yaml-flow 8.6.1 → 8.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/asset-integrity.json +3 -3
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/board-server.js +544 -45
- package/examples/board/server-config.json +2 -1
- package/examples/board/test/server-http-test.js +12 -4
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/{artifacts-store-lib-CLOtsiav.d.cts → artifacts-store-lib-BR-Samty.d.cts} +1 -1
- package/lib/{artifacts-store-lib-C1rtrkxm.d.ts → artifacts-store-lib-DT7XlWUL.d.ts} +1 -1
- package/lib/artifacts-store-public.d.cts +3 -3
- package/lib/artifacts-store-public.d.ts +3 -3
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.d.cts +56 -23
- package/lib/board-live-cards-mcp.d.ts +56 -23
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +8 -8
- package/lib/board-live-cards-node.d.cts +39 -21
- package/lib/board-live-cards-node.d.ts +39 -21
- package/lib/board-live-cards-node.js +8 -8
- package/lib/{board-live-cards-public-CBVjm327.d.ts → board-live-cards-public-BMUIPOrc.d.ts} +67 -42
- package/lib/board-live-cards-public-async-DKZqbJVU.d.ts +256 -0
- package/lib/board-live-cards-public-async-dMWNbWq6.d.cts +256 -0
- package/lib/{board-live-cards-public-CPJy-aGW.d.cts → board-live-cards-public-wkNmBIRC.d.cts} +67 -42
- package/lib/board-live-cards-public.cjs +1 -1
- package/lib/board-live-cards-public.d.cts +2 -2
- package/lib/board-live-cards-public.d.ts +2 -2
- package/lib/board-live-cards-public.js +1 -1
- package/lib/board-live-cards-server-runtime.cjs +1 -1
- package/lib/board-live-cards-server-runtime.d.cts +7 -6
- package/lib/board-live-cards-server-runtime.d.ts +7 -6
- package/lib/board-live-cards-server-runtime.js +1 -1
- package/lib/board-worker-adapter.cjs +4 -3
- package/lib/board-worker-adapter.d.cts +24 -14
- package/lib/board-worker-adapter.d.ts +24 -14
- package/lib/board-worker-adapter.js +4 -3
- package/lib/card-store-public.d.cts +2 -2
- package/lib/card-store-public.d.ts +2 -2
- package/lib/{chat-storage-lib-CKylihjm.d.cts → chat-storage-lib-BIUbE-fM.d.cts} +1 -1
- package/lib/{chat-storage-lib-Bce-xx6l.d.ts → chat-storage-lib-BlG-sobS.d.ts} +1 -1
- package/lib/chat-store-public.d.cts +3 -3
- package/lib/chat-store-public.d.ts +3 -3
- package/lib/{chunk-CWREBRXS.js → chunk-BQS3EIEK.js} +3 -3
- package/lib/{chunk-LDAP75GN.js → chunk-CIAJNUR4.js} +2 -2
- package/lib/chunk-GJJMEAVN.cjs +2 -0
- package/lib/chunk-GLIX37VG.cjs +8 -0
- package/lib/chunk-H5HBXPOI.cjs +3 -0
- package/lib/chunk-HEEDJEKM.js +2 -0
- package/lib/chunk-LRVAVWAG.js +8 -0
- package/lib/chunk-MLVTJASJ.js +2 -0
- package/lib/chunk-N6P2JW4W.js +3 -0
- package/lib/chunk-OEFTOO47.cjs +3 -0
- package/lib/chunk-PBCDDO4V.cjs +2 -0
- package/lib/{chunk-I4WH5U5D.cjs → chunk-PMUSJQSR.cjs} +2 -2
- package/lib/chunk-SCWHDI3I.js +2 -0
- package/lib/{chunk-UVE65IPR.cjs → chunk-SFVO2LB2.cjs} +3 -3
- package/lib/{chunk-5DB54ZX2.cjs → chunk-U2N6MCD5.cjs} +2 -2
- package/lib/chunk-VMW4Z6EF.js +3 -0
- package/lib/chunk-WOALA3V5.cjs +2 -0
- package/lib/{chunk-LBMEVV4U.js → chunk-XQRNDX4Q.js} +2 -2
- package/lib/cloud-storage.cjs +2 -0
- package/lib/cloud-storage.d.cts +177 -0
- package/lib/cloud-storage.d.ts +177 -0
- package/lib/cloud-storage.js +2 -0
- package/lib/execution-refs.cjs +1 -1
- package/lib/execution-refs.js +1 -1
- package/lib/index.cjs +2 -2
- package/lib/index.d.cts +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/{types-DRl0Hy_p.d.cts → queue-lane-registry-BPKWWgd4.d.cts} +66 -14
- package/lib/{types-BuK2UMxk.d.ts → queue-lane-registry-Be6c0ftj.d.ts} +66 -14
- package/lib/server-runtime/index.cjs +1 -1
- package/lib/server-runtime/index.d.cts +18 -7
- package/lib/server-runtime/index.d.ts +18 -7
- package/lib/server-runtime/index.js +1 -1
- package/lib/step-machine-public/index.cjs +1 -1
- package/lib/step-machine-public/index.d.cts +1 -1
- package/lib/step-machine-public/index.d.ts +1 -1
- package/lib/step-machine-public/index.js +1 -1
- package/lib/{storage-interface-Ct-C4tlz.d.cts → storage-interface-BFiD3kyB.d.cts} +11 -1
- package/lib/{storage-interface-Ct-C4tlz.d.ts → storage-interface-BFiD3kyB.d.ts} +11 -1
- package/lib/stores/index.cjs +1 -1
- package/lib/stores/index.d.cts +1 -1
- package/lib/stores/index.d.ts +1 -1
- package/lib/stores/index.js +1 -1
- package/lib/stores/kv.d.cts +1 -1
- package/lib/stores/kv.d.ts +1 -1
- package/package.json +6 -1
- package/lib/chunk-6APH25VI.js +0 -2
- package/lib/chunk-KNFFDVLD.cjs +0 -2
- package/lib/chunk-LVNQCE5X.cjs +0 -3
- package/lib/chunk-M7EQRS6W.js +0 -3
- package/lib/chunk-NJJ7WEDT.cjs +0 -2
- package/lib/chunk-P64UKI3L.cjs +0 -8
- package/lib/chunk-Q6VSL327.js +0 -8
- package/lib/chunk-VCCTAUIG.js +0 -2
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';var chunkWOALA3V5_cjs=require('./chunk-WOALA3V5.cjs'),chunkH5HBXPOI_cjs=require('./chunk-H5HBXPOI.cjs'),chunkOEFTOO47_cjs=require('./chunk-OEFTOO47.cjs'),chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),chunkGJJMEAVN_cjs=require('./chunk-GJJMEAVN.cjs'),chunkYMEIPKLW_cjs=require('./chunk-YMEIPKLW.cjs'),chunkGYQXDNNI_cjs=require('./chunk-GYQXDNNI.cjs');function wt(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Qe(r){if(!r||typeof r!="object")return false;let t=r.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function ze(r,t){if(!t||typeof t!="object")return;let s=t;if(s.kind==="notification-batch"&&Array.isArray(s.notifications)){for(let o of s.notifications)ze(r,o);return}s.kind==="status"&&Qe(s.status)&&(r.status=s.status),s.kind==="computed_values"&&s.cardId&&(r.computedValues[s.cardId]=s.values),s.kind==="data_object"&&s.key&&(r.dataObjects[s.key]=s.payload),s.kind==="card_refreshed"&&s.cardId&&(r.cards[s.cardId]=s.card),s.kind==="card_removed"&&s.cardId&&(delete r.cards[s.cardId],delete r.computedValues[s.cardId]);}function ge(r){return typeof r.journalStorage=="function"}function Ct(r){return typeof r.whatToRun=="string"?r.whatToRun.startsWith("b64:")?chunkSFVO2LB2_cjs.b(r.whatToRun).value:r.whatToRun:r.whatToRun.value}function se(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(r){let t=r.reduce((u,p)=>u+p.length,0),s=new Uint8Array(t),o=0;for(let u of r)s.set(u,o),o+=u.length;return s}function ht(r){let t=new Map,s=new Map,o=new Map,u=0,p=null;function R(i){let m=JSON.stringify(i);return u++,`id: ${u}
|
|
2
|
+
data: ${m}
|
|
3
|
+
|
|
4
|
+
`}function C(i){let m=i;try{m.flushHeaders?.();}catch{}try{m.flush?.();}catch{}try{m.socket?.setNoDelay?.(!0);}catch{}try{m.socket?.uncork?.();}catch{}}function F(i,m){let A=t.get(i);if(A&&!(m&&A.res!==m)){t.delete(i),j();try{r.onSseClientDisconnected?.(i);}catch{}try{A.res.end();}catch{}}}function T(i,m,A){let P=t.get(i);P&&F(i,P.res),t.set(i,{res:m,subscribedChatCardIds:A??new Set});}function g(i,m){let A=t.get(i);if(!A)return;let P=R(m);try{A.res.write(P),C(A.res);}catch{F(i,A.res);}}function b(){let i=new Set;for(let m of t.values())for(let A of m.subscribedChatCardIds)i.add(A);return Array.from(i)}function S(i){let m=s.has(i)?s.get(i):null,{cursor:A}=r.chatStorage.readAfter(i,m),P=r.chatStorage.isProcessing(i),G=P!==(o.get(i)??false),ue=A!==m;return ue&&s.set(i,A),o.set(i,P),ue||G}function O(i,m){let A=r.readChatRecords(i),P=Date.now();return {kind:"card_chats",cardId:i,sentAt:new Date(P).toISOString(),sentAtMs:P,messages:A.map(G=>({role:String(G.role||"system"),text:String(G.text||""),files:Array.isArray(G.files)?G.files:[]})),receiving:m,processing:r.chatStorage.isProcessing(i)}}function x(i,m=true){let A={kind:"notification-batch",notifications:[O(i,m)]};for(let[P,G]of t.entries())G.subscribedChatCardIds.has(i)&&g(P,A);}function j(){b().length>0||(p&&(clearInterval(p),p=null),s.clear(),o.clear());}function w(){if(p)return;let i=()=>{let m=b();if(m.length===0){j();return}let A=new Set(m);for(let P of Array.from(s.keys()))A.has(P)||s.delete(P);for(let P of Array.from(o.keys()))A.has(P)||o.delete(P);for(let P of m)S(P)&&x(P,true);};i(),p=setInterval(i,1e3);}function v(i,m){let A=t.get(i);if(!A)return false;A.subscribedChatCardIds.add(m);let{cursor:P}=r.chatStorage.readAfter(m,null);return s.set(m,P),o.set(m,r.chatStorage.isProcessing(m)),w(),g(i,{kind:"notification-batch",notifications:[O(m,true)]}),true}function L(i,m){let A=t.get(i);return A?(A.subscribedChatCardIds.delete(m),b().includes(m)||(s.delete(m),o.delete(m)),j(),true):false}function d(i){if(!i||typeof i!="object")return false;let m=i.kind;return m==="card_chats"||m==="chat_messages"}function l(i){if(!i||i.length===0)return;let m=[],A=new Set;for(let P of i)d(P)&&typeof P.cardId=="string"?A.add(String(P.cardId)):m.push(P);if(m.length>0){let P={kind:"notification-batch",notifications:m};for(let G of t.keys())g(G,P);}for(let P of A)x(P,true);}return {size:()=>t.size,has:i=>t.has(i),get:i=>t.get(i),buildFrame:R,flushTransport:C,register:T,disconnect:F,writeFrame:g,subscribeChat:v,unsubscribeChat:L,broadcastNotificationBatch:l,broadcastCardChats:x}}function z(r,...t){for(let s of t)if(typeof r[s]=="string")return String(r[s]);return ""}function ye(r,...t){for(let s of t)if(r[s]!==void 0)return Number(r[s])}function _e(r,...t){for(let s of t){let o=r[s];if(o&&typeof o=="object"&&!Array.isArray(o))return o}return {}}function he(r,t,...s){for(let o of s){let u=r[o];if(u&&typeof u=="object"&&!Array.isArray(u))return u}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function We(r,t,...s){for(let o of s){let u=r[o];if(u!==void 0){let p=Number(u);if(Number.isFinite(p))return p}}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function Rt(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(t=>Math.max(0,Math.min(255,Number(t)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let t=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),s=t+"=".repeat((4-t.length%4)%4),o=atob(s);return Uint8Array.from(o,u=>u.charCodeAt(0))}return null}function Je(r,t){if(r?.status==="success")return Object.prototype.hasOwnProperty.call(r,"data")?r.data:void 0;throw r?.status==="fail"||r?.status==="error"?Object.assign(new Error(r.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function Ke(r,t){return Je(await r,t)}function Ge(r){let t=z(r,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let s=t.split(".");if(!(s.length>=2&&s[0]==="chat"&&s.every(u=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return t}function Ze(r,t){let s=r.meta;for(let o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,o))return {exists:false,value:null};s=s[o];}return {exists:true,value:s}}function kt(r){let{boardId:t,getMcpFacade:s,getMcpCardStoreFacade:o}=r;function u(T){let g=z(T,"board_id"),b=z(T,"card_id");if(!g)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!b)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(g!==t)throw Object.assign(new Error(`Unknown board_id: ${g}`),{statusCode:400});return {cardId:b}}function p(T,g){let{cardId:b}=u(T);return s().setChatProcessing({cardId:b,active:g}),{status:"success",data:{boardId:t,cardId:b,active:g}}}function R(T){let{cardId:g}=u(T),b=s().getChatProcessing({cardId:g});return {status:"success",data:{boardId:t,cardId:g,active:b.active}}}async function C(T){let{cardId:g}=u(T),b=Ge(T);if(!Object.prototype.hasOwnProperty.call(T,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(b.split(".").includes("__visible_controlplane_only")){let S=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(S.cards)&&S.cards.length>0&&typeof S.cards[0]=="object"&&!Array.isArray(S.cards[0])?S.cards[0]:null,x=O?Ze(O,"__visible_controlplane_only").value:void 0;if(T.value!==x)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:g,key:b}}}return Je(await o().patch({params:{id:g,path:`meta.${b}`},body:{value:T.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:g,key:b}}}async function F(T){let{cardId:g}=u(T),b=Ge(T),S=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(S.cards)&&S.cards.length>0&&S.cards[0]&&typeof S.cards[0]=="object"&&!Array.isArray(S.cards[0])?S.cards[0]:null;if(!O)throw Object.assign(new Error(`Card "${g}" not found`),{statusCode:404});let x=Ze(O,b);return {status:"success",data:{boardId:t,cardId:g,key:b,exists:x.exists,value:x.value}}}return {requireCardArgs:u,setChatProcessing:p,getChatProcessing:R,setCardMeta:C,getCardMeta:F}}function St(r){let{boardId:t,boardContexts:s,readCardDefinitions:o,readChatRecords:u,getChatProcessing:p}=r;async function R(){let g=(await Promise.all(s.map(async j=>{try{let w=j.boardAdapter.kvStorageForRef(j.outputsStoreRef),v=await Promise.resolve(w.read("status"));if(v!=null)return v}catch{}return j.notification.status}))).filter(Boolean);if(g.length===0)return null;if(g.length===1)return g[0];let b=[],S=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],O={};for(let j of S)O[j]=0;for(let j of g){let w=j,v=Array.isArray(w.cards)?w.cards:[];b.push(...v);for(let L of S)O[L]+=Number(w?.summary?.[L]||0);}let x=g[0];return {...x,cards:b,summary:{...x.summary||{},card_count:b.length,...O}}}async function C(){let g={},b=async S=>{try{let O=await S.boardOps.getAllOutputsComputedValues({});if(O.status==="success"&&O.data&&typeof O.data=="object"){for(let[x,j]of Object.entries(O.data)){let w=S.notification.cards[x];g[x]={schema_version:"v1",card_id:x,card_data:w?.card_data??{},computed_values:j??{}};}return}}catch{}for(let[O,x]of Object.entries(S.notification.computedValues)){let j=S.notification.cards[O];g[O]={schema_version:"v1",card_id:O,card_data:j?.card_data??{},computed_values:x??{}};}};for(let S of s)await b(S);return g}async function F(){let g={};for(let b of s){try{let S=await b.boardOps.getAllOutputsDataObjects({});if(S.status==="success"&&S.data&&typeof S.data=="object"){Object.assign(g,S.data);continue}}catch{}Object.assign(g,b.notification.dataObjects||{});}return g}async function T(){let g=await o(),b=await C(),S=await F(),O={};for(let j of g){if(!j?.id)continue;let w=j.id,v=b[w]||{},L={...v.card_data&&typeof v.card_data=="object"?v.card_data:j.card_data&&typeof j.card_data=="object"?j.card_data:{}};O[w]={schema_version:v.schema_version||"v1",card_id:v.card_id||w,card_data:L,computed_values:v.computed_values&&typeof v.computed_values=="object"?v.computed_values:{}};}let x={};for(let j of g){if(!j?.id)continue;let w=j.id;try{let v=u(w),L=p(w);(v.length>0||L)&&(x[w]={messages:v.map(d=>({role:String(d.role||"system"),text:String(d.text||""),files:Array.isArray(d.files)?d.files:[]})),receiving:!1,processing:L});}catch{}}return {boardId:t,cardDefinitions:g,statusSnapshot:await R(),dataObjectsByToken:S,cardRuntimeById:O,cardChatsByCardId:x}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:C,readDataObjectsByToken:F,buildPublishedRuntimePayload:T}}function Ht(r){let t=String(r||"").trim();if(!t)return "upload.bin";let s=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (s>=0?t.slice(s+1):t)||"upload.bin"}function At(r){let{safeCardId:t,artifactsStores:s,cardFileMetadataStore:o,readCardFromStore:u,updateCardLocalOnly:p,writeChatRecord:R}=r;async function C(g){let b=[];try{let S=await u(g);if(!S)return b;let O=o().read(S.card_data&&typeof S.card_data=="object"?S.card_data:null);for(let x of O)b.push(String(x.stored_name??""));}catch{}return b}async function F(g,b,S,O){let x=t(g),j=s(g),w=Ht(b),v=await C(g),d=`${String(v.length+1).padStart(3,"0")}-${w}`.slice(-36);return j.files&&await j.files.putBytes(`${x}/${d}`,new Uint8Array(O),S||"application/octet-stream"),{name:w,stored_name:d,size:O.length,mime_type:S||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function T(g,b,S,O,x){if(!O.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let j=x?.inChat===true,w=await F(g,b,S,O),v=null;if(await p(g,L=>{let d=new Date().toISOString(),l=L.card_data&&typeof L.card_data=="object"?L.card_data:{};L.card_data=l;let i=o().normalizeIncoming([{name:w.name,stored_name:w.stored_name,size:w.size,mime_type:w.mime_type,uploaded_at:w.uploaded_at||d,chat:j}],d);return v=o().merge(l,i).findIndex(A=>A.stored_name===w.stored_name),L}),j){let L=typeof v=="number"&&v>=0?` #${v}`:"";R(g,"system",`file uploaded: ${w.name} as ${w.stored_name}${L}`,[],x?.turnId??"");}return {ok:true,file:w}}return {uploadCardFile:T,readCardStoredFileNames:C}}function vt(r){return {"discover.source-kinds":()=>r.discoverSourceKinds(),"inspect.board-runtime-status":()=>r.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>r.inspectCardDefinitionAndRuntime({cardId:z(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let s=ye(t,"tail_turns"),o=ye(t,"tail"),u=z(t,"turn_id"),p=t.all_turns===true,R=z(t,"tail_turns_before_id");return r.inspectChatMessagesOnCards({cardId:z(t,"card_id"),...s!==void 0?{lastUserTurns:s}:{},...o!==void 0?{tail:o}:{},...u?{turnId:u}:{},...p?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":t=>r.inspectFileContents({cardId:z(t,"card_id"),fileIdx:Number(ye(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>r.preflightValidateCandidateCardDefinition({candidateCardContent:he(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>r.preflightMaterializeCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:he(t,"mock_requires","mock_requires"),mockFetchedSources:he(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>r.preflightProbeSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>r.preflightRunSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>r.preflightRunSingleSourceInLiveCard({cardId:z(t,"card_id"),sourceIdx:We(t,"source_idx","source_idx"),mockRequires:he(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>r.preflightRunOneCycleWithCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:_e(t,"mock_requires")}),"manage.read-card":t=>r.manageReadCard({cardId:z(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let s=z(t,"turn_id");if(!s)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return r.manageAddChatEntryAndAnyAttachments({cardId:z(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...s?{turn:s}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.upsert-card":t=>r.manageUpsertCard({cardId:z(t,"card_id"),candidateCardContent:_e(t,"candidate_card_content")}),"manage.remove-card":t=>r.manageRemoveCard({cardId:z(t,"card_id")})}}function Pt(r){let{boardId:t,uploadCardFile:s,getMcpFacade:o,controlplane:u}=r;return {"getstate.is-chat-processing":p=>u.getChatProcessing(p),"setstate.chat-processing-started":p=>u.setChatProcessing(p,true),"setstate.chat-processing-done":p=>u.setChatProcessing(p,false),"getstate.card-meta":p=>u.getCardMeta(p),"setstate.card-meta":p=>u.setCardMeta(p),"manage.upload-card-file":p=>{let R=z(p,"board_id"),C=z(p,"card_id"),F=z(p,"file_name"),T=z(p,"content_type")||"application/octet-stream",g=Rt(p);if(!R)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});if(!C)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(!g)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return s(C,F,T,g,{inChat:false})},"manage.admin-read-card":async p=>{let{cardId:R}=u.requireCardArgs(p);return {status:"success",data:{cards:await o().adminReadCard({cardId:R})}}},"manage.admin-upsert-card":p=>{let R=z(p,"board_id"),C=z(p,"card_id");if(!R)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});return o().adminUpsertCard({cardId:C,candidateCardContent:_e(p,"candidate_card_content")})}}}function Bt(r){let{boardContexts:t,cardOwnerIndex:s,cardContextForCard:o,readStatusSnapshot:u,readDataObjectsByToken:p,readCardRuntimeArtifacts:R,readCardFromStore:C,readCardDefinitions:F,processAccumulatedLaneInternal:T,uploadCardFile:g,chatStorePublic:b,serverUrl:S,apiBasePath:O}=r;function x(){return t[0]??null}function j(){return {async status(){let d=await u();return d==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:d}},async getOutputsDataObject(d){let l=d?.params?.key;return l?{status:"success",data:(await p())[l]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(d){let l=d?.params?.key;return l?{status:"success",data:(await R())[l]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(d){let l=d?.params?.key;if(!l)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let i=o(l)??x();return i?i.boardOps.getOutputsFetchedSources({params:{key:l}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(d){let l=d?.params?.id;if(!l)return {status:"fail",error:"removeCard requires params.id"};let i=o(l)??x();return i?i.boardOps.removeCard({params:{id:l}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let i=o(l)??x();return i?i.boardOps.cardRefreshedNotify({params:{cardId:l}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"upsertCard requires params.cardId"};let i=o(l)??x();if(!i)return {status:"fail",error:"Board context is unavailable"};let m=await i.boardOps.upsertCard({params:{cardId:l,restart:d.params.restart===true}});if(m.status!=="success")return m;if(ge(i.boardAdapter)){let A=await T(true);if(A.status!=="success")return A}return m}}}function w(){let d=()=>{let l=x();if(!l?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return l.nonCore};return {describeTaskExecutorCapabilities(l){return d().describeTaskExecutorCapabilities(l)},validateCardPreflight(l){return d().validateCardPreflight(l)},evalCardCompute(l){return d().evalCardCompute(l)},probeSourcePreflight(l){return d().probeSourcePreflight(l)},runSourcePreflight(l){return d().runSourcePreflight(l)},simulateCardCycle(l){return d().simulateCardCycle(l)}}}function v(){return {async get(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(l){let i=await C(l);return i?{status:"success",data:{cards:[i]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await F()}}},async set(d){let l=d.body;if(l==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let i=Array.isArray(l)?l:[l];for(let m of i){let A=m,P=typeof A.id=="string"?A.id:"";if(!P)return {status:"fail",error:"each card must have a string `id` field"};let G=s.get(P)??0,ue=t[G]??x();if(!ue)return {status:"fail",error:"Board context is unavailable"};let fe=await ue.cardStoreOps.set({body:A});if(fe.status!=="success")return fe;s.set(P,G);}return {status:"success",data:{count:i.length}}},async del(d){let l=[d.params?.id,...d.body?.ids??[]].filter(i=>typeof i=="string"&&!!i);if(l.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let i of l){let m=o(i)??x();if(!m)return {status:"fail",error:"Board context is unavailable"};let A=await m.cardStoreOps.del({params:{id:i}});if(A.status!=="success")return A;s.delete(i);}return {status:"success",data:{count:l.length}}},async patch(d){let l=typeof d.params?.id=="string"?d.params.id:void 0,i=typeof d.params?.path=="string"?d.params.path:void 0;if(!l||!i)return {status:"fail",error:"patch requires params.id and params.path"};let m=o(l)??x();return m?m.cardStoreOps.patch(d):{status:"fail",error:"Board context is unavailable"}},async appendFiles(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(!l)return {status:"fail",error:"appendFiles requires params.id"};let i=o(l)??x();return i?i.cardStoreOps.appendFiles(d):{status:"fail",error:"Board context is unavailable"}}}}function L(){return chunkGJJMEAVN_cjs.a({board:j(),nonCore:w(),cardStore:v(),chatStore:b,uploadCardFile({cardId:d,fileName:l,contentType:i,bytes:m}){return g(d,l,i,m,{inChat:false})},buildFileDownloadUrl({cardId:d,fileIdx:l,storedName:i}){let m=`${S||""}${O}/cards/${encodeURIComponent(d)}/files/${l}`;return i?`${m}?sn=${encodeURIComponent(i)}`:m},readFetchedSourceJsonByRef({cardId:d,ref:l}){let i=o(d)??x();if(!i||ge(i.boardAdapter))return null;let P=i.boardAdapter.resolveBlob(chunkSFVO2LB2_cjs.b(l)).trim();return P?JSON.parse(P):null}})}return {mcpBoardFacade:j,mcpNonCoreFacade:w,mcpCardStoreFacade:v,createMcpFacade:L}}function It(r){let{sseHub:t,corsHeaders:s,json:o,buildPublishedRuntimePayload:u,onSseClientConnected:p,onChannelSubscribed:R,onChannelUnsubscribed:C}=r;function F(g,b,S,O,x){if(!t.has(b)){o(g,404,{error:`SSE client not connected: ${b}`});return}x?R?.(b,S,O):C?.(b,S,O),o(g,200,{ok:true,clientId:b,channelName:S,...O.cardId?{cardId:O.cardId}:{},subscribed:x});}async function T(g,b,S){let O=t.get(S),x=O?new Set(O.subscribedChatCardIds):new Set;b.writeHead(200,{...s,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),t.flushTransport(b),t.register(S,b,x);let j=await u(),w=t.buildFrame(j);b.write(w);try{p?.(S,L=>{t.writeFrame(S,L);});}catch{}let v=setInterval(()=>{try{b.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);g.on("close",()=>{clearInterval(v),t.disconnect(S,b);});}return {handleChannelSubscription:F,handleSse:T}}async function Xe(r,t,s){let o=s[r];if(!o)throw Object.assign(new Error(`Unknown MCP tool: ${r}`),{statusCode:400});let u=await o(t);if(u&&typeof u=="object"&&!Array.isArray(u)){let p=u,R=p.status;if(R==="success")return Object.prototype.hasOwnProperty.call(p,"data")?u:{status:"success",data:{}};if(R==="fail"||R==="error")return u}return {status:"success",data:u}}function Me(r,t){if(!r||typeof r!="object"||Array.isArray(r))return t;let s=r;if(typeof s.error=="string"&&s.error.trim())return s.error;if(s.step==="validate"){let o=s.validation;if(o&&typeof o=="object"&&!Array.isArray(o)){let p=o.data;if(p&&typeof p=="object"&&!Array.isArray(p)){let R=p.issues;if(Array.isArray(R)){let F=R.find(T=>typeof T=="string"&&T.trim());if(typeof F=="string")return `Validation failed: ${F}`}let C=p.errors;if(Array.isArray(C)&&C.length>0)return "Validation failed"}}return "Validation failed"}return t}function xt(r){let{apiBasePath:t,boardContexts:s,json:o,readJsonBody:u,readRawBody:p,initBoardAndSetup:R,bootstrapBoard:C,buildPublishedRuntimePayload:F,publishPersistedStateSnapshot:T,upsertCardsFromSource:g,applyBoardWorkerCallback:b,handleSse:S,handleChannelSubscription:O,createMcpFacade:x,createMcpToolRegistry:j,createMcpControlplaneToolRegistry:w,readCardFromStore:v,patchCard:L,retriggerCard:d,applyCardAction:l,resolveChatHandlerTarget:i,chatStorePublic:m,chatStorage:A,sseHub:P,uploadCardFile:G,sendCardFileDownloadResponse:ue,resolveCardFileDownloadPayload:fe,isLikelyTextMimeType:ie,sliceTextByLines:be}=r;async function Se(ee,I,Ve){let W=ee.method||"GET",te=Ve,Y=te.pathname;try{if(W==="GET"&&Y===`${t}/init-board`)return await R(),o(I,200,await F()),!0;if(W==="GET"&&Y===`${t}/sse`){await R();let k=String(te.searchParams.get("clientId")||"").trim();if(!k)return o(I,400,{error:"clientId query param is required for SSE"}),!0;await S(ee,I,k);for(let h=0;h<s.length;h++)await T(s[h]),await g(s[h],h),await T(s[h]);return !0}if(W==="GET"&&Y===`${t}/board-status`)return o(I,200,await F()),!0;let we=Y.match(new RegExp(`^${se(t)}/callback/board-worker/([^/]+)/(success|failure)$`));if(W==="POST"&&we){await R();let k=decodeURIComponent(we[1]),h=we[2],M=await u(ee),B=await b(k,h,M);return o(I,B.statusCode,B.body),!0}if(W==="POST"&&Y===`${t}/mcp`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;if(h==="inspect.file-contents")return o(I,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let B=await Xe(h,M,j(x()));if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(I,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(I,500,{error:Me(B,"Internal error")}),!0}o(I,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(I,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-controlplane`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;try{let B=await Xe(h,M,w());if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(I,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(I,500,{error:Me(B,"Internal error")}),!0}o(I,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(I,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-raw`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;if(h!=="inspect.file-contents")return o(I,400,{error:`Tool does not support raw response: ${h}`}),!0;let B=z(M,"card_id","cardId"),q=ye(M,"file_idx","fileIdx"),Z=ye(M,"head-lines","headLines"),Q=ye(M,"tail-lines","tailLines"),ne=ye(M,"head-bytes","headBytes"),le=ye(M,"tail-bytes","tailBytes");if(!B)return o(I,400,{error:"inspect.file-contents requires card_id"}),!0;if(q===void 0||!Number.isInteger(q)||q<0)return o(I,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([Z,Q,ne,le].filter(ce=>ce!==void 0).length>1)return o(I,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[ce,ke]of [["head-lines",Z],["tail-lines",Q],["head-bytes",ne],["tail-bytes",le]])if(ke!==void 0&&(!Number.isInteger(ke)||ke<0))return o(I,400,{error:`inspect.file-contents requires ${ce} to be a non-negative integer`}),!0;let Ie=await x().inspectFileContents({cardId:B,fileIdx:q}),$e=typeof Ie?.stored_name=="string"?Ie.stored_name:null,{fileRecord:Fe,bytes:Ae}=await fe(B,q,$e),qe=String(Fe.name||Fe.stored_name||"download.bin"),Te=String(Fe.mime_type||"application/octet-stream"),ve=(te.searchParams.get("resp")||"").trim().toLowerCase();if(ve&&ve!=="json-b64")return o(I,400,{error:`unsupported resp mode: ${ve}`}),!0;let Ne=ve==="json-b64",me;if(Z!==void 0||Q!==void 0){if(!ie(Te))return o(I,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let ce=new TextDecoder().decode(Ae),ke=Z!==void 0?be(ce,"head",Z):be(ce,"tail",Q);me=typeof Buffer<"u"?Buffer.from(ke,"utf8"):new TextEncoder().encode(ke);}else if(ne!==void 0||le!==void 0){let ce=ne??le;me=ne!==void 0?Ae.slice(0,ce):Ae.slice(Math.max(0,Ae.length-ce));}else me=Ae;if(Ne){let ce=typeof Buffer<"u"?Buffer.from(me).toString("base64"):btoa(String.fromCharCode(...me));return o(I,200,{bodyBase64:ce,mimeType:Te,filename:qe,byteLength:me.length}),!0}return I.writeHead(200,{"Content-Type":Te,"Content-Disposition":`attachment; filename="${qe}"`,"Content-Length":me.length}),I.end(me),!0}let Ce=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)$`));if(W==="GET"&&Ce){await C();let k=decodeURIComponent(Ce[1]),h=await v(k);return h?(o(I,200,h),!0):(o(I,404,{error:`card not found: ${k}`}),!0)}if(W==="PATCH"&&Ce){await C();let k=decodeURIComponent(Ce[1]),h=await u(ee);return await L(k,h),o(I,200,{ok:!0}),!0}let je=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/retrigger$`));if(W==="POST"&&je){await C();let k=decodeURIComponent(je[1]);return await d(k),o(I,200,{ok:!0}),!0}let pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/actions$`));if(W==="POST"&&pe){await C();let k=decodeURIComponent(pe[1]),h=Date.now(),M=new Date(h).toISOString(),B=await u(ee),q=B?.actionType;if(q==="chat-send"&&!await i(k)){let Q=Date.now();return o(I,409,{error:`chat handler is not configured for card: ${k}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Q).toISOString(),responseSentAtMs:Q,responseStatus:409}),!0}if(q==="chat-send"){let Q=B?.payload??{},ne=typeof Q["turn-id"]=="string"?Q["turn-id"]:typeof Q.turnId=="string"?Q.turnId:typeof Q.turn=="string"?Q.turn:"";if(!ne||!String(ne).trim()){let le=Date.now();return o(I,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${k}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(le).toISOString(),responseSentAtMs:le,responseStatus:400}),!0}}await l(k,q,B?.payload);let Z=Date.now();return o(I,200,{ok:!0,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Z).toISOString(),responseSentAtMs:Z,responseStatus:200}),!0}let Pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats$`));if(W==="GET"&&Pe){await C();let k=decodeURIComponent(Pe[1]),h=String(te.searchParams.get("turn-id")||""),M=String(te.searchParams.get("all-turns")||"").toLowerCase()==="true",B=String(te.searchParams.get("tail-turns-before-id")||""),q=te.searchParams.get("tail-turns"),Z=q==null||q===""?M||h?void 0:1:Number.parseInt(q,10),Q=m.readAll({params:{cardId:k},body:{...Z===void 0?{}:{tailTurns:Z},...h?{turnId:h}:{},...M?{allTurns:!0}:{},...B?{tailTurnsBeforeId:B}:{}}});if(Q.status!=="success")return o(I,400,{error:Q.error||"Failed to read chats"}),!0;let ne=Q.data.records;return o(I,200,{ok:!0,messages:ne}),!0}if(W==="POST"&&Pe){await C();let k=decodeURIComponent(Pe[1]),h=await u(ee),M=typeof h?.role=="string"?h.role:"assistant",B=typeof h?.text=="string"?h.text:"",q=Array.isArray(h?.files)?h.files:[],Z=typeof h?.turn=="string"?h.turn:typeof h?.["turn-id"]=="string"?h["turn-id"]:typeof h?.turnId=="string"?h.turnId:"",Q=h?.done===!0,ne=A.append(k,M,B,q,Z);return Q&&A.setProcessing(k,!1),P.broadcastCardChats(k,!Q),o(I,200,{ok:!0,id:ne}),!0}let Ee=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(W==="POST"&&Ee){await C();let k=decodeURIComponent(Ee[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.subscribeChat(M,k)?(o(I,200,{ok:!0,clientId:M,cardId:k,subscribed:!0}),!0):(o(I,404,{error:`SSE client not connected: ${M}`}),!0):(o(I,400,{error:"clientId is required"}),!0)}let Le=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(W==="POST"&&Le){await C();let k=decodeURIComponent(Le[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.unsubscribeChat(M,k)?(o(I,200,{ok:!0,clientId:M,cardId:k,subscribed:!1}),!0):(o(I,404,{error:`SSE client not connected: ${M}`}),!0):(o(I,400,{error:"clientId is required"}),!0)}let Re=Y.match(new RegExp(`^${se(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Re){await C();let k=decodeURIComponent(Re[1]),h=Re[2]==="subscribe",M=await u(ee),B=typeof M?.clientId=="string"?M.clientId.trim():"";return B?(O(I,B,k,{},h),!0):(o(I,400,{error:"clientId is required"}),!0)}let Be=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Be){await C();let k=decodeURIComponent(Be[1]),h=decodeURIComponent(Be[2]),M=Be[3]==="subscribe",B=await u(ee),q=typeof B?.clientId=="string"?B.clientId.trim():"";return q?(O(I,q,h,{cardId:k},M),!0):(o(I,400,{error:"clientId is required"}),!0)}let De=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files$`));if(W==="POST"&&De){await C();let k=decodeURIComponent(De[1]),h=String(te.searchParams.get("inChat")||"").toLowerCase()==="true",M=String(te.searchParams.get("turn-id")||"").trim();if(h&&!M)return o(I,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${k}`}),!0;let B=ee.headers["x-file-name"],q=String(ee.headers["content-type"]||"application/octet-stream"),Z=Array.isArray(B)?B[0]:B,Q=Z?decodeURIComponent(String(Z)):"upload.bin",ne=await p(ee);return o(I,200,await G(k,Q,q,ne,{inChat:h,turnId:M})),!0}let Oe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files/(\\d+)$`));if(W==="GET"&&Oe){let k=decodeURIComponent(Oe[1]),h=parseInt(Oe[2],10),M=te.searchParams.get("sn");return await ue(I,k,h,M),!0}return !1}catch(we){let Ce=we?.statusCode||500;return o(I,Ce,{error:String(we?.message||we)}),true}}return {handleRuntimeApi:Se}}function Ye(r,t){return t?{...r,...t.pollIntervalMs!=null?{pollIntervalMs:t.pollIntervalMs}:{},...t.visibilityMs!=null?{visibilityMs:t.visibilityMs}:{},...t.concurrency!=null?{concurrency:t.concurrency}:{},...t.maxAttempts!=null?{maxAttempts:t.maxAttempts}:{}}:r}function _t(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.leaseRequests(u))).map(R=>({id:R.messageId,attempt:R.attempt,message:R.request,ack:()=>Promise.resolve(t.ackRequest(R.messageId,R.leaseToken)),nack:C=>Promise.resolve(t.nackRequest(R.messageId,R.leaseToken,C))}))},async handle(u){await s(u.args,u);},onError:o?(u,p)=>o(u,p.attempt,p.message):void 0}}function Wt(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.lease(u))).map(R=>({id:R.id,attempt:R.attempt,message:R.body,ack:()=>Promise.resolve(t.ack(R.id,R.leaseToken)),nack:C=>Promise.resolve(t.nack(R.id,R.leaseToken,C))}))},async handle(){await s();},onError:o?(u,p)=>o(u,p.attempt):void 0}}function br(r){let t=r.logger??{info(){},warn(){},error(){}},s=r.boardAdapter,o=r.runtime.queueLaneTuning??{},u=s.processAccumulatedStore(),p=s.chatAgentStore(),R=[];if(R.push(Ye(Wt("process-accumulated",u,async()=>{let C=await r.runtime.processAccumulatedLane();if(C.status!=="success")throw new Error(C.error||`processAccumulatedLane returned ${C.status}`)},(C,F)=>{t.error(`[board-server] queued process-accumulated failed for ${r.boardId} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.processAccumulated)),R.push(Ye(_t("chat-agent",p,async(C,F)=>{await r.runtime.handleChatAgentRequest(F);},(C,F,T)=>{let g=typeof T.args?.cardId=="string"?T.args.cardId:"";t.error(`[board-server] queued chat-agent failed for ${r.boardId}${g?`/${g}`:""} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.chatAgent)),r.executeTaskExecutorRequest){let C=s.boardWorkerStore();R.push(Ye(_t("task-executor",C,r.executeTaskExecutorRequest,(F,T)=>{t.error(`[board-server] queued board-worker failed for ${r.boardId} (attempt ${T}): ${String(F&&F.message||F)}`);}),o.taskExecutor));}return chunkWOALA3V5_cjs.f(R)}var Ft={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ot="chat-handler-flow-queue";function Lr(r){let t=String(r.apiBasePath||"/api/board").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.queueLaneTuning??{},u=r.boardId||"",p=r.logger||{info:console.log,warn:console.warn,error:console.error},R=r.invocationAdapter,C=r.chatFlowRunner||null,F=r.chatStorage??chunkWOALA3V5_cjs.b(),T=chunkGYQXDNNI_cjs.a(F),g=r.notificationTransport||null,b=r.serverUrl||null,S=r.executionExtra||{},O=r.onSseClientConnected,x=r.onSseClientDisconnected,j=r.onChannelSubscribed,w=r.onChannelUnsubscribed,v=ht({chatStorage:F,readChatRecords:e=>le(e),onSseClientDisconnected:x});function L(e){function n(y){if(Array.isArray(y))return y;if(y&&typeof y=="object"){let E=y;return Array.isArray(E.files)?E.files:[y]}return null}function a(y){return {async get(E){return y.get(E)},async set(E){return y.set(E)},async del(E){return y.del(E)},async patch(E){return y.patch(E)},async appendFiles(E){return y.appendFiles(E)}}}function f(y){function E(V){return {status:"success",data:V}}function $(V){return {status:"fail",error:V}}function D(V){return {status:"error",error:V instanceof Error?V.message:String(V)}}return {async get(V){try{let U=V.params?.id;if(U){let re=await y.readCard(U);return re?E({cards:[re]}):$(`card "${U}" not found`)}return E({cards:await y.readAllCards()})}catch(U){return D(U)}},async set(V){try{let U=V.body;if(U==null)return $("set requires a body (card object or array of cards)");let re=Array.isArray(U)?U:[U];for(let ae of re){if(typeof ae.id!="string")return $("each card must have a string `id` field");await y.writeCard(ae.id,ae);}return E({count:re.length})}catch(U){return D(U)}},async del(V){try{let U=V.body?.ids??[],re=V.params?.id,ae=re?[...U,re]:U;if(ae.length===0)return $("del requires body.ids (string[]) or params.id");for(let xe of ae)await y.removeCard(xe);return E({count:ae.length})}catch(U){return D(U)}},async patch(V){try{let U=V.params?.id,re=V.params?.path;if(!U)return $("patch requires params.id");if(!re)return $("patch requires params.path");let ae=V.body,xe=ae&&Object.prototype.hasOwnProperty.call(ae,"value")?ae.value:V.body;return await y.patchCard(U,re,xe),E({count:1})}catch(U){return D(U)}},async appendFiles(V){try{let U=V.params?.id;if(!U)return $("appendFiles requires params.id");let re=await y.readCard(U);if(!re)return $(`card "${U}" not found`);let ae=n(V.body);if(!ae||ae.length===0)return $("appendFiles requires a file metadata object, array, or body.files array");let xe=re.card_data&&typeof re.card_data=="object"&&!Array.isArray(re.card_data)?re.card_data:{},nt=Array.isArray(xe.files)?xe.files:[],qt=[...nt,...ae];return await y.patchCard(U,"card_data.files",qt),E({files_added:ae.map((Nt,Ut)=>({idx:nt.length+Ut,entry:Nt}))})}catch(U){return D(U)}}}}let c=ge(e.boardAdapter)?chunkH5HBXPOI_cjs.j(e.baseRef,e.boardAdapter):chunkOEFTOO47_cjs.y(e.baseRef,e.boardAdapter),_=e.nonCoreAdapter??(!ge(e.boardAdapter)&&m(e.boardAdapter)?e.boardAdapter:null),N=_?chunkOEFTOO47_cjs.z(e.baseRef,_):null,K,H=ge(e.boardAdapter)?(()=>{let y=chunkH5HBXPOI_cjs.d(chunkH5HBXPOI_cjs.c(chunkH5HBXPOI_cjs.b(e.boardAdapter.kvStorageForRef(e.cardStoreRef)),e.boardAdapter.hashFn),p.warn),E=f(y);return K={get($){return E.get($)},set($){return E.set($)}},E})():(()=>{let y=e.boardAdapter.kvStorageForRef(e.cardStoreRef),$=chunkYMEIPKLW_cjs.a(chunkOEFTOO47_cjs.l({readIndex:()=>y.read("_index"),writeIndex:D=>y.write("_index",D),readCard:D=>y.read(D),writeCard:(D,V)=>(y.write(D,V),D),removeCard:D=>{y.delete(D);},cardExists:D=>y.read(D)!==null,defaultCardKey:D=>D},p.warn));return K=$,a($)})(),X=e.artifactsAdapter||e.boardAdapter,J=e.filesArtifactsStore??null,oe=J?{putBytes(y,E,$){J.putBytes(y,E,$);},getBytes(y){return J.getBytes(y)},listKeys(y){return J.list(y).map(E=>E.key)}}:null;if(!oe&&!ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files"),E=chunkWOALA3V5_cjs.c(y);oe={putBytes($,D,V){E.putBytes($,D,V);},getBytes($){return E.getBytes($)},listKeys($){return E.list($).map(D=>D.key)}};}else if(!oe&&ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files");oe={async putBytes(E,$){if(y.writeBytes){await y.writeBytes(E,$);return}let D=JSON.stringify({__kind:"bytes-array",data:[...$]});await y.write(E,D);},async getBytes(E){if(y.readBytes){let D=await y.readBytes(E);if(D!==null)return D}let $=await y.read(E);if($===null)return null;try{let D=JSON.parse($);if(D&&D.__kind==="bytes-array"&&Array.isArray(D.data))return new Uint8Array(D.data)}catch{}return new TextEncoder().encode($)},async listKeys(E){return await y.listKeys(E)}};}let de={async init(y){return c.init(y)},async status(y){return c.status(y)},async getConfig(y){return c.getConfig(y)},async getAllOutputsDataObjects(y){return c.getAllOutputsDataObjects(y)},async getAllOutputsComputedValues(y){return c.getAllOutputsComputedValues(y)},async getOutputsFetchedSources(y){return c.getOutputsFetchedSources(y)},async upsertCard(y){return c.upsertCard(y)},async removeCard(y){return c.removeCard(y)},async cardRefreshedNotify(y){return c.cardRefreshedNotify(y)},async sourceDataFetched(y){return c.sourceDataFetched(y)},async sourceDataFetchFailure(y){return c.sourceDataFetchFailure(y)}};return {label:e.label,board:c,nonCore:N,publicCardStore:K,boardOps:de,cardStoreOps:H,get filesArtifacts(){return oe},boardAdapter:e.boardAdapter,cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef,artifactsStoreRef:e.artifactsStoreRef,scratchStoreRef:e.scratchStoreRef,archiveStoreRef:e.archiveStoreRef,notifyRef:e.notifyRef,taskExecutorRef:e.taskExecutorRef,chatHandlerRef:e.chatHandlerRef,chatHandlerFlow:e.chatHandlerFlow,inferenceAdapterRef:e.inferenceAdapterRef,notification:wt(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d=r.boards.map(L),l=new Map;function i(e){return l.get(e)??0}function m(e){let n=e;return typeof n.invokeExecutor=="function"&&typeof n.validateSchema=="function"}function A(e){let n=d[i(e)];return {files:n?n.filesArtifacts:null}}function P(){return chunkWOALA3V5_cjs.e()}function G(e){return String(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ue(e){if(!e||e.notificationTeardown||!g||!e.notifyRef)return;let n=await g.subscribe(e.notifyRef,a=>{ze(e.notification,a);let f=a.kind==="notification-batch"?a.notifications:[a];v.broadcastNotificationBatch(f);});e.notificationTeardown=n;}async function fe(e){if(!e||e.initialized)return;let n={cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef};e.artifactsStoreRef&&(n.artifactsStoreRef=e.artifactsStoreRef),e.scratchStoreRef&&(n.scratchStoreRef=e.scratchStoreRef),e.archiveStoreRef&&(n.archiveStoreRef=e.archiveStoreRef);let a={};e.taskExecutorRef&&(a["task-executor-ref"]=e.taskExecutorRef),e.chatHandlerFlow!==void 0&&(a["chat-handler-flow"]=e.chatHandlerFlow),e.inferenceAdapterRef&&(a["inference-adapter-ref"]=e.inferenceAdapterRef);let f=await e.boardOps.init({params:n,body:a});if(f.status!=="success")throw Object.assign(new Error(f.error||`init failed for ${e.label}`),{statusCode:500});if(await ue(e),!e.chatHandlerFlow&&e.chatHandlerRef&&R.describe)try{let c=await R.describe(e.chatHandlerRef);c&&c.kind!=="chat-handler"?p.warn(`[init] chat-handler describe returned kind="${c.kind}", expected "chat-handler" for ${e.label}`):c&&p.info(`[init] chat-handler validated: ${c.name} (protocol ${c.protocolVersion}) for ${e.label}`);}catch(c){p.warn(`[init] chat-handler describe failed for ${e.label}: ${c?.message||String(c)}`);}e.initialized=true;}async function ie(e){if(!e.boardAdapter.publishBoardChangeNotifications)return;let n=[],a=await e.boardOps.status({});a.status==="success"&&a.data!=null&&Qe(a.data)&&n.push({kind:"status",status:a.data});let f=await e.boardOps.getAllOutputsDataObjects({});if(f.status==="success"&&f.data!=null)for(let[_,N]of Object.entries(f.data))_&&n.push({kind:"data_object",key:_,payload:N});let c=await e.boardOps.getAllOutputsComputedValues({});if(c.status==="success"&&c.data!=null)for(let[_,N]of Object.entries(c.data))_&&n.push({kind:"computed_values",cardId:_,values:N});n.length>0&&e.boardAdapter.publishBoardChangeNotifications(n);}async function be(e,n){if(!e||e.cardsBootstrapped)return;let a=await e.cardStoreOps.get({}),f=a.status==="success"&&Array.isArray(a.data?.cards)?a.data.cards:[];for(let c of f)typeof c.id=="string"&&(l.set(c.id,n),await e.boardOps.upsertCard({params:{cardId:c.id}}));e.cardsBootstrapped=true;}async function Se(){for(let e of d)await fe(e);}async function ee(){await Se();for(let e=0;e<d.length;e++)await ie(d[e]),await be(d[e],e),await ie(d[e]);}async function I(e=false){e||await Se();for(let n of d){let a=await n.board.processAccumulatedEvents({});if(a.status!=="success")return a}return {status:"success"}}async function Ve(){return await Se(),I(true)}function W(e){return d[i(e)]??null}async function te(e){let n=W(e);if(!n)return null;let a=await n.cardStoreOps.get({params:{id:e}});if(a.status!=="success")return null;let f=Array.isArray(a.data?.cards)?a.data.cards:[];return f.length>0?f[0]:null}async function Y(){let e=async a=>{if(!a)return [];let f=await a.cardStoreOps.get({});return f.status!=="success"||!Array.isArray(f.data?.cards)?[]:f.data.cards},n=[];for(let a of d)n.push(...await e(a));return n}function we(){return d[0]??null}let Ce=Bt({boardContexts:d,cardOwnerIndex:l,cardContextForCard:e=>W(e),readStatusSnapshot:()=>Be(),readDataObjectsByToken:()=>Oe(),readCardRuntimeArtifacts:()=>De(),readCardFromStore:e=>te(e),readCardDefinitions:()=>Y(),processAccumulatedLaneInternal:e=>I(e),uploadCardFile:(e,n,a,f,c)=>Ie(e,n,a,f,c),chatStorePublic:T,serverUrl:b,apiBasePath:t}),je=Ce.mcpCardStoreFacade,pe=Ce.createMcpFacade,Pe=kt({boardId:u,getMcpFacade:()=>pe(),getMcpCardStoreFacade:()=>je()});function Ee(e){return vt(e)}function Le(){return Pt({boardId:u,uploadCardFile:Ie,getMcpFacade:()=>pe(),controlplane:Pe})}let Re=St({boardId:u,boardContexts:d,readCardDefinitions:()=>Y(),readChatRecords:e=>le(e),getChatProcessing:e=>pe().getChatProcessing({cardId:e}).active}),Be=Re.readStatusSnapshot,De=Re.readCardRuntimeArtifacts,Oe=Re.readDataObjectsByToken,k=Re.buildPublishedRuntimePayload;async function h(e,n,a){let f=a?.syncBoard!==false,c=a?.restartOnlyIfChanged===true,_=W(e);if(!_)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let N=await te(e);if(!N)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let K=c?JSON.stringify(N):null,H=n(N)||N;if(c&&JSON.stringify(H)===K)return;let X=await _.cardStoreOps.set({body:H});if(X.status!=="success")throw Object.assign(new Error(X.error||`Failed to persist card: ${e}`),{statusCode:500});if(f){let J=await _.boardOps.upsertCard({params:{cardId:e,restart:true}});if(J.status!=="success")throw Object.assign(new Error(J.error||`Failed to upsert card: ${e}`),{statusCode:500})}}async function M(e,n){await h(e,n,{syncBoard:true});}async function B(e,n){await h(e,n,{syncBoard:false});}async function q(e){let n=W(e);if(!n)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});if(!await te(e))throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let f=await n.boardOps.upsertCard({params:{cardId:e,restart:true}});if(f.status!=="success")throw Object.assign(new Error(f.error||`Failed to retrigger card: ${e}`),{statusCode:500})}async function Z(e,n){await h(e,a=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return a;function f(c,_,N){let K=String(_||"").split(".").filter(Boolean);if(!K.length)return;let H=c;for(let X=0;X<K.length-1;X++){let J=K[X];(!H[J]||typeof H[J]!="object")&&(H[J]={}),H=H[J];}H[K[K.length-1]]=N;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let c=null,_=a.view;if(_&&Array.isArray(_.elements)){for(let N of _.elements)if(N?.data&&N.data.writeTo){c=N.data.writeTo;break}}c?f(a,c,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(a.card_data={...a.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return a;for(let[c,_]of Object.entries(n))c!=="_stagedFiles"&&(_!==null&&typeof _=="object"&&!Array.isArray(_)&&a[c]!==null&&typeof a[c]=="object"&&!Array.isArray(a[c])?a[c]={...a[c],..._}:a[c]=_);}return a},{syncBoard:true,restartOnlyIfChanged:true});}function Q(e){F.clear(e);try{pe().setChatProcessing({cardId:e,active:!1});}catch{}}function ne(e,n,a,f,c=""){let _=typeof a=="string"?a.trim():"";return F.append(e,n||"system",_,f,c)}function le(e){return F.readAll(e)}let Ie=At({safeCardId:e=>G(e),artifactsStores:e=>A(e),cardFileMetadataStore:()=>P(),readCardFromStore:e=>te(e),updateCardLocalOnly:(e,n)=>B(e,n),writeChatRecord:(e,n,a,f,c)=>ne(e,n,a,f,c)}).uploadCardFile;async function $e(e){let n=W(e);if(!n)return null;let a=await n.boardOps.getConfig({params:{key:"chat-handler-flow"}}),f=a.status==="success"?a.data?.value:null,c=n.chatHandlerRef;return f==null&&(!c||typeof c!="object")?null:{ctx:n,handlerFlow:f,handlerRef:c}}async function Fe(e,n,a=false,f=""){let c=await $e(e);if(!c)return;let{ctx:_,handlerFlow:N,handlerRef:K}=c;if(!a)try{pe().setChatProcessing({cardId:e,active:!0});}catch{}let H={boardId:u,cardId:String(e),lastChatEntryId:n,...f?{turnId:f}:{},...S,...b?{serverUrl:b}:{}},X=N!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:Ot}}:K;try{ge(_.boardAdapter)?await _.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}):_.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}),await Promise.resolve(_.boardAdapter.requestProcessAccumulated?.());}catch(J){try{pe().setChatProcessing({cardId:e,active:!1});}catch{}p.warn(`[chat-handler] queue failed for card "${e}": ${J instanceof Error?J.message:String(J)}`);}}async function Ae(e,n,a){if(n.howToRun==="built-in"&&Ct(n)===Ot){let f=C,c=a.__chatHandlerFlow,_={...a};return delete _.__chatHandlerFlow,f?f.run(c,_,{boardId:u,cardId:String(_.cardId||""),label:e.label,logger:p,serverUrl:b,executionExtra:S}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return R.invoke(n,a)}async function qe(e,n=false){n||await Se();let a=typeof e.args?.cardId=="string"?e.args.cardId:"",f=a?W(a):we();if(!f)throw new Error(a?`Board context is unavailable for chat-agent request: ${a}`:"Board context is unavailable for chat-agent request");let c=await Ae(f,e.ref,e.args);if(!c.dispatched){if(a)try{F.setProcessing(a,!1);}catch{}throw new Error(c.error||`chat-agent dispatch failed for card "${a||"unknown"}"`)}}async function Te(e,n,a){let f=n==="chat-send"?B:M,c;await f(e,_=>{let N=new Date().toISOString(),K=_.card_data&&typeof _.card_data=="object"?_.card_data:{};if(_.card_data=K,n==="chat-send"){let H=a&&typeof a.text=="string"?a.text.trim():"",X=a&&typeof a["turn-id"]=="string"?a["turn-id"]:a&&typeof a.turnId=="string"?a.turnId:a&&typeof a.turn=="string"?a.turn:"",J=[];if(Array.isArray(a?.files)){for(let oe of a.files)if(oe){if(typeof oe=="string"){J.push({name:oe});continue}if(typeof oe=="object"){let de=oe;typeof de.name=="string"&&J.push({name:de.name,size:de.size,mime_type:de.mime_type,uploaded_at:de.uploaded_at,stored_name:de.stored_name,chat:de.chat===true});}}}if(H||J.length>0){let oe=T.runBatch({cardId:e,commands:[{command:"append",role:"user",text:H,files:J,turn:X},{command:"set-processing",active:true}]});if(oe.status!=="success")throw new Error(oe.error);let de=oe.data.results[0]?.data?.id;if(typeof de!="string"||!de)throw new Error(`chat-send did not return an append id for card ${e}`);c={cardId:e,lastEntryId:de,processingAlreadySet:true,turnId:X};try{let $=le(e);v.broadcastNotificationBatch([{kind:"card_chats",cardId:e,messages:$.map(D=>({role:String(D.role||"system"),text:String(D.text||""),files:Array.isArray(D.files)?D.files:[]})),receiving:!0,processing:F.isProcessing(e)}]);}catch{}}return _}if(n==="file-upload"){let H=P().normalizeIncoming(a?.files,N);return H.length>0&&P().merge(K,H),_}if(n==="action"){let H=a&&typeof a.buttonId=="string"?a.buttonId:"";if(!H)return _;K.lastAction={buttonId:H,at:N},K.lastActionText=`${H} @ ${N}`;}return _}),c&&Fe(c.cardId,c.lastEntryId,c.processingAlreadySet,c.turnId??"");}function ve(e,n,a){let f=JSON.stringify(a),c=typeof Buffer<"u"?Buffer.byteLength(f):new TextEncoder().encode(f).length;e.writeHead(n,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":c}),e.end(f);}async function Ne(e,n,a){let f=await te(e);if(!f)throw Object.assign(new Error("Card not found"),{statusCode:404});let c=P().resolve(f.card_data,n,a);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 _=c.file,N=G(e),K=A(e),H=String(_.stored_name||""),X=`${N}/${H}`,J=K.files?await K.files.getBytes(X):null;if(!J)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:_,bytes:J}}async function me(e,n,a,f){let{fileRecord:c,bytes:_}=await Ne(n,a,f),N=String(c.name||c.stored_name||"download.bin"),K=String(c.mime_type||"application/octet-stream");e.writeHead(200,{"Content-Type":K,"Content-Disposition":`attachment; filename="${N}"`,"Content-Length":_.length}),e.end(_);}function ce(e){let n=String(e||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function ke(e,n,a){let f=e.split(/\r?\n/);return (n==="head"?f.slice(0,a):f.slice(-a)).join(`
|
|
7
|
+
`)}async function Mt(e){let n=[];for await(let f of e)n.push(f);let a=typeof Buffer<"u"?Buffer.concat(n).toString("utf-8").trim():new TextDecoder().decode(He(n)).trim();return a?JSON.parse(a):{}}async function jt(e){let n=[];for await(let a of e)n.push(a);return typeof Buffer<"u"?Buffer.concat(n):He(n)}async function et(e,n){let a=typeof n.ref=="string"?n.ref.trim():"";if(!a)return {status:"fail",error:"board-worker success callback requires body.ref"};let f=d[0];return f?f.boardOps.sourceDataFetched({params:{token:e,ref:a}}):{status:"fail",error:"no board context"}}async function tt(e,n){let a=typeof n.reason=="string"&&n.reason.trim()?n.reason:"unknown",f=d[0];return f?f.boardOps.sourceDataFetchFailure({params:{token:e,reason:a}}):{status:"fail",error:"no board context"}}async function Et(e,n,a){let f=String(e||"").trim();if(!f)return {statusCode:400,body:{error:"callback token is required"}};let c=n==="success"?await et(f,a):await tt(f,a);return c.status==="success"?{statusCode:200,body:c}:c.status==="fail"?{statusCode:400,body:{error:c.error}}:{statusCode:500,body:{error:c.error}}}let rt=It({sseHub:v,corsHeaders:s,json:ve,buildPublishedRuntimePayload:()=>k(),onSseClientConnected:O,onChannelSubscribed:j,onChannelUnsubscribed:w}),Lt=rt.handleChannelSubscription,Dt=rt.handleSse,$t=xt({apiBasePath:t,boardContexts:d,json:ve,readJsonBody:e=>Mt(e),readRawBody:e=>jt(e),initBoardAndSetup:()=>Se(),bootstrapBoard:()=>ee(),buildPublishedRuntimePayload:()=>k(),publishPersistedStateSnapshot:e=>ie(e),upsertCardsFromSource:(e,n)=>be(e,n),applyBoardWorkerCallback:(e,n,a)=>Et(e,n,a),handleSse:(e,n,a)=>Dt(e,n,a),handleChannelSubscription:(e,n,a,f,c)=>Lt(e,n,a,f,c),createMcpFacade:()=>pe(),createMcpToolRegistry:e=>Ee(e),createMcpControlplaneToolRegistry:()=>Le(),readCardFromStore:e=>te(e),patchCard:(e,n)=>Z(e,n),retriggerCard:e=>q(e),applyCardAction:(e,n,a)=>Te(e,n,a),resolveChatHandlerTarget:e=>$e(e),chatStorePublic:T,chatStorage:{append:(e,n,a,f,c)=>F.append(e,n,a,f,c),setProcessing:(e,n)=>F.setProcessing(e,n)},sseHub:v,uploadCardFile:(e,n,a,f,c)=>Ie(e,n,a,f,c),sendCardFileDownloadResponse:(e,n,a,f)=>me(e,n,a,f),resolveCardFileDownloadPayload:(e,n,a)=>Ne(e,n,a),isLikelyTextMimeType:e=>ce(e),sliceTextByLines:(e,n,a)=>ke(e,n,a)}).handleRuntimeApi;return {get apiBasePath(){return t},get corsHeaders(){return s},get queueLaneTuning(){return o},handleRuntimeApi:$t,buildPublishedRuntimePayload:k,processAccumulatedEvents:Ve,processAccumulatedLane:I,handleChatAgentRequest:qe,clearChatRecords:Q,reportSourceFetched(e,n){return et(e,{ref:n})},reportSourceFetchFailure(e,n){return tt(e,{reason:n})},get cardStore(){return d[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Dr(r){let t=String(r.apiBasePath||"/api/boards").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.serverMetaStore,u=r.boardRuntimeFactory,p=new Map,R="boards-config.json";function C(){let w=o.getText(R);if(!w)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(w)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function F(w){o.putText(R,JSON.stringify(w,null,2));}function T(w){let v=String(w||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return v.length>0&&v.length<=64?v:null}function g(w){if(p.has(w))return p.get(w);let L=C().boards.find(l=>l.id===w)||{},d=u(w,L);return p.set(w,d),d}function b(w,v,L){let d=JSON.stringify(L),l=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;w.writeHead(v,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":l}),w.end(d);}async function S(w,v,L){let d=w.method||"GET",l=L.pathname;if(d==="GET"&&l===t)return b(v,200,{ok:true,boards:C().boards}),true;if(d==="POST"&&l===t){let i=[];for await(let ie of w)i.push(ie);let m=typeof Buffer<"u"?Buffer.concat(i).toString("utf-8").trim():new TextDecoder().decode(He(i)).trim(),A={};try{A=m?JSON.parse(m):{};}catch{A={};}let P=T(A.id);if(!P)return b(v,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let G=C();if(G.boards.some(ie=>ie.id===P))return b(v,409,{error:`Board "${P}" is already registered`}),true;let ue=typeof A.label=="string"&&A.label.trim()?A.label.trim():P,fe={id:P,label:ue};for(let[ie,be]of Object.entries(A))ie==="id"||ie==="label"||be!=null&&(fe[ie]=be);return G.boards.push(fe),F(G),b(v,200,{ok:true,board:fe}),true}return false}async function O(w,v,L){let l=L.pathname.match(new RegExp(`^${se(t)}/([^/]+)(/|$)`));if(!l)return false;let i=T(decodeURIComponent(l[1]));return i?C().boards.some(P=>P.id===i)?!!await g(i).handleRuntimeApi(w,v,L):(b(v,404,{error:`Board "${i}" not registered. POST ${t} with {id} to register it first.`}),true):(b(v,400,{error:"Invalid board id"}),true)}async function x(w,v,L){return !!(await S(w,v,L)||await O(w,v,L))}function j(w){if(!C().boards.some(L=>L.id===w))throw Object.assign(new Error(`Board "${w}" not registered`),{statusCode:404});return {service:g(w)}}return {get apiBasePath(){return t},get corsHeaders(){return s},handleApi:x,requireBoardService:j}}exports.a=br;exports.b=Lr;exports.c=Dr;//# sourceMappingURL=chunk-GLIX37VG.cjs.map
|
|
8
|
+
//# sourceMappingURL=chunk-GLIX37VG.cjs.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkPBCDDO4V_cjs=require('./chunk-PBCDDO4V.cjs'),chunkOEFTOO47_cjs=require('./chunk-OEFTOO47.cjs'),chunkU2N6MCD5_cjs=require('./chunk-U2N6MCD5.cjs'),chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),chunkG4XXRHL2_cjs=require('./chunk-G4XXRHL2.cjs'),chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');async function $e(e,t,a){let u=await e.tryAcquire();if(!u)return false;try{await t();}finally{await u();}return await a?.(),true}function We(e){return chunkPBCDDO4V_cjs.b(e)}function Le(e,t){return {async readIndex(){return await e.read("_index")},writeIndex(a){return e.write("_index",a)},async readCard(a){return await e.read(a)},async writeCard(a,u){return await e.write(a,u),t(u)},removeCard(a){return e.delete(a)},async cardExists(a){return await e.read(a)!==null},defaultCardKey(a){return a}}}function Je(e,t){async function a(){return await e.readIndex()??{}}return {async readCard(u){let p=(await a())[u];return !p||!await e.cardExists(p.key)?null:await e.readCard(p.key)},async readCardKey(u){return (await a())[u]?.key??null},async readAllCards(){let u=[];for(let[p,S]of Object.entries(await a())){if(!await e.cardExists(S.key))continue;let f=await e.readCard(S.key);f?u.push(f):t?.(`[card-store] could not read card "${p}" at key "${S.key}"`);}return u},async readChecksumIndex(){let u={};for(let[p,S]of Object.entries(await a()))u[p]=S.checksum;return u},async changedSince(u){let p=await a(),S=[];for(let[f,l]of Object.entries(p))u[f]!==l.checksum&&S.push(f);for(let f of Object.keys(u))p[f]||S.push(f);return S},async validateUpsert(u,p){let S=await a(),f=S[u],l=Object.entries(S).find(([,k])=>k.key===p);return f&&f.key!==p?{ok:false,error:`Card id "${u}" is already mapped to key "${f.key}", cannot remap to "${p}"`}:l&&l[0]!==u?{ok:false,error:`Key "${p}" is already mapped to card id "${l[0]}", cannot remap to "${u}"`}:{ok:true}},async writeCard(u,p,S){let f=await a(),l=S??f[u]?.key??e.defaultCardKey(u),k=await e.writeCard(l,p);f[u]={key:l,checksum:k,updatedAt:new Date().toISOString()},await e.writeIndex(f);},async patchCard(u,p,S){let f=await a(),l=f[u];if(!l||!await e.cardExists(l.key))throw new Error(`card "${u}" not found`);let k=await e.readCard(l.key);if(!k||typeof k!="object"||Array.isArray(k))throw new Error(`card "${u}" is not patchable`);let v=String(p||"").split(".").filter(Boolean),q=chunkPBCDDO4V_cjs.a(k,v,S),P=await e.writeCard(l.key,q);f[u]={key:l.key,checksum:P,updatedAt:new Date().toISOString()},await e.writeIndex(f);},async removeCard(u){let p=await a(),S=p[u];S&&(await e.removeCard(S.key),delete p[u],await e.writeIndex(p));},readIndex(){return a()}}}function cr(e,t){return chunkOEFTOO47_cjs.a(e,t)}function dr(e,t,a){return {blob:e,kv:t,journal:a}}function Se(e){return {messageId:e.id,enqueuedAt:e.enqueuedAt,attempt:e.attempt,request:e.body}}function Xe(e){return typeof e=="string"?e.startsWith("b64:")?chunkSFVO2LB2_cjs.b(e).value:e:e.value}function ie(e){return {async enqueueRequest(t){return (await e.enqueue(t)).id},async leaseRequests(t){return (await e.lease(t)).map(a=>({...Se(a),leaseToken:a.leaseToken,leaseExpiresAt:a.leaseExpiresAt}))},ackRequest(t,a){return e.ack(t,a)},nackRequest(t,a,u){return e.nack(t,a,u)},async peekActive(){return (await e.peekActive()).map(Se)},async peekDeadLetter(){return (await e.peekDeadLetter()).map(t=>({...Se(t),reason:t.reason}))}}}function Qe(e){async function t(a){let u=await e.read(a);return u==null?null:typeof u=="string"?u:JSON.stringify(u)}return {async readTaskExecutorRef(){let a=await t("task-executor");if(a?.trim())return chunkU2N6MCD5_cjs.c(a.trim())},writeTaskExecutorRef(a){return e.write("task-executor",chunkU2N6MCD5_cjs.b(a))},readChatHandlerFlow(){return e.read("chat-handler-flow")},writeChatHandlerFlow(a){return e.write("chat-handler-flow",a)},readCardStoreRef(){return t("card-store-ref")},writeCardStoreRef(a){return e.write("card-store-ref",a)},readOutputsStoreRef(){return t("outputs-store-ref")},writeOutputsStoreRef(a){return e.write("outputs-store-ref",a)},readScratchStoreRef(){return t("scratch-store-ref")},writeScratchStoreRef(a){return e.write("scratch-store-ref",a)},readArchiveStoreRef(){return t("archive-store-ref")},writeArchiveStoreRef(a){return e.write("archive-store-ref",a)},readChatStoreRef(){return t("chat-store-ref")},writeChatStoreRef(a){return e.write("chat-store-ref",a)},readArtifactsStoreRef(){return t("artifacts-store-ref")},writeArtifactsStoreRef(a){return e.write("artifacts-store-ref",a)}}}function gr(e){let t,a,u,p=e.callbackTransport,S=e.resolveBlob??(async l=>{let k=await e.blobStorage("").read(l.value);if(k==null)throw new Error(`Blob not found for ref ${l.kind}:${l.value}`);return k});async function f(l,k){if(l.howToRun==="queue-storage"){let v=e.boardWorkerStore??t??(e.queueStorage?ie(e.queueStorage):void 0);return v?(t||(t=v),await v.enqueueRequest({boardId:typeof l.extra?.boardId=="string"?l.extra.boardId:e.boardId,ref:l,args:k}),{dispatched:true}):{dispatched:false,error:"queue-storage dispatch requires queueStorage or boardWorkerStore"}}if(l.howToRun==="http:post"){let v=e.fetch??globalThis.fetch;if(!v)return {dispatched:false,error:"http:post dispatch requires fetch support"};let q=await v(Xe(l.whatToRun),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...k,...l.extra?{extra:l.extra}:{}})});if(!q.ok){let P=await q.text().catch(()=>"");return {dispatched:false,error:`HTTP ${q.status}: ${P}`}}return {dispatched:true}}return {dispatched:false,error:`Unsupported hosted async transport "${l.howToRun}"`}}return {kvStorage:e.kvStorage,kvStorageForRef:e.kvStorageForRef,blobStorage:e.blobStorage,scratchStorage:e.scratchStorage,scratchStorageForRef:e.scratchStorageForRef,archiveFactory:e.archiveFactory,archiveFactoryForRef:e.archiveFactoryForRef,journalStorage:e.journalStorage,boardWorkerStore:()=>{if(!t)if(e.boardWorkerStore)t=e.boardWorkerStore;else if(e.queueStorage)t=ie(e.queueStorage);else throw new Error("Hosted async board adapter requires queueStorage or boardWorkerStore");return t},chatAgentStore:()=>{if(!a)if(e.chatAgentStore)a=e.chatAgentStore;else if(e.chatAgentQueueStorage)a=ie(e.chatAgentQueueStorage);else if(e.boardWorkerStore)a=e.boardWorkerStore;else if(e.queueStorage)a=ie(e.queueStorage);else throw new Error("Hosted async board adapter requires chatAgentStore, chatAgentQueueStorage, queueStorage, or boardWorkerStore");return a},processAccumulatedStore:()=>{if(u||(u=e.processAccumulatedStore??e.processAccumulatedQueueStorage??e.queueStorage),!u)throw new Error("Hosted async board adapter requires processAccumulatedStore, processAccumulatedQueueStorage, or queueStorage");return u},lock:e.lock,get callbackTransport(){return p},set callbackTransport(l){p=l;},dispatchExecution:(l,k)=>e.dispatchExecution?.(l,k)??f(l,k),supportsDirectSourceOutput:e.supportsDirectSourceOutput,resolveBlob:S,hashFn:e.hashFn,genId:e.genId,requestProcessAccumulated:e.requestProcessAccumulated,publishBoardChangeNotifications:e.publishBoardChangeNotifications,warn:e.onWarn}}function C(e){return e!==void 0?{status:"success",data:e}:{status:"success"}}function R(e){return {status:"fail",error:e}}function w(e){return {status:"error",error:e instanceof Error?e.message:String(e)}}function I(){return new Date().toISOString()}function Ze(e){let t=new TextEncoder().encode(e),a=Array.from(t,u=>String.fromCharCode(u)).join("");return btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Me(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),a=t+"=".repeat((4-t.length%4)%4),u=atob(a),p=Uint8Array.from(u,S=>S.charCodeAt(0));return new TextDecoder().decode(p)}function ue(e){try{let t=JSON.parse(Me(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function er(e){return Ze(JSON.stringify(e))}function He(e){try{let t=JSON.parse(Me(e));return typeof t?.cbk=="string"&&typeof t?.cid=="string"&&typeof t?.b=="string"&&typeof t?.d=="string"?t:null}catch{return null}}function rr(e){return chunkOEFTOO47_cjs.j(e,chunkOEFTOO47_cjs.o,()=>({_sources:{}}))}function tr(e,t){return chunkOEFTOO47_cjs.h(e,t)}function nr(e){return chunkOEFTOO47_cjs.k(e)}function ar(e,t){return chunkOEFTOO47_cjs.i(e,t)}function or(e,t,a,u,p,S){return async f=>{let l=[],k=await a.cardStore.readCard(f.nodeId);if(!k)return "task-initiate-failure";let v=k.id,q=k.card_data??{},P=k.source_defs??[],N=P.filter(s=>s.optionalForCompletionGating!==true),V=await a.cardRuntimeStore.readRuntime(v),K=false,L=async()=>{K&&(await a.cardRuntimeStore.writeRuntime(v,V),K=false);},j=s=>chunkOEFTOO47_cjs.p(V._sources[s]),b=(s,i)=>{V._sources[s]=chunkOEFTOO47_cjs.p(i),K=true;},$=f.taskState?.executionCount??0;if(V._lastExecutionCount!==$&&(V._sources={},V._lastExecutionCount=$,K=true),f.update){let s=f.update.outputFile;if(s){let i=j(s);if(f.update.failure){let m=f.update.rqt??i.lastRequestedToken??i.queueRequestedToken;m&&b(s,chunkOEFTOO47_cjs.s(i,m));}else {let m=f.update.rqt;if(!i.lastCompletedToken||m>i.lastCompletedToken){let h=typeof f.update.deliveryToken=="string"?f.update.deliveryToken:void 0,x=h?await a.fetchedSourcesStore.commitSourceData(v,s,h):false;b(s,x?chunkOEFTOO47_cjs.r(i,m):chunkOEFTOO47_cjs.s(i,m));}}await L();}}let J={};for(let s of P){if(!s.outputFile)continue;let i=await a.fetchedSourcesStore.readSourceData(v,s.outputFile);i!==null&&(J[s.bindTo]=i);}let Q={};for(let[s,i]of Object.entries(f.state??{}))if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let m=i[s];Q[s]=m!==void 0?m:i;}else Q[s]=i;let H={id:v,card_data:{...q},requires:Q,source_defs:P,compute:k.compute};H._sourcesData=J,k.compute&&chunkIXZG74EW_cjs.a.runSync(H,{sourcesData:J}),(p??(()=>{}))(v,H.computed_values??{});let G=chunkIXZG74EW_cjs.a.enrichSourcesSync(Array.isArray(k.source_defs)?k.source_defs:void 0,{card_data:k.card_data,requires:Q}),z={...k,source_defs:Array.isArray(G)?G.map(s=>({...s,boardDir:typeof s.boardDir=="string"&&s.boardDir?s.boardDir:e.value})):G},_=I(),O=f.update?void 0:_,n=N.filter(s=>{let i=s.outputFile;if(typeof i!="string"||!i)return true;let m=j(i);O&&(m={...m,queueRequestedToken:O},b(i,m));let h=m.queueRequestedToken??m.lastRequestedToken??_;return chunkOEFTOO47_cjs.q(m,h)==="dispatch"});if(await L(),n.length>0){let s=false,i=_;for(let m of n){let h=m.outputFile;if(typeof h!="string"||!h)continue;let x=j(h),F=x.queueRequestedToken??_;b(h,{...x,lastRequestedToken:F}),i=F,s=true;}return s&&await L(),s&&(l.push({taskKind:"source-fetch",payload:{boardRef:chunkSFVO2LB2_cjs.a(e),enrichedCard:z,callbackToken:f.callbackToken,rqt:i}}),await a.executionRequestStore.appendEntries(t,l)),"task-initiated"}if(N.some(s=>{let i=s.outputFile;if(typeof i!="string"||!i)return false;let m=j(i),h=m.queueRequestedToken??m.lastRequestedToken??_;return chunkOEFTOO47_cjs.q(m,h)==="in-flight"}))return "task-initiated";let d=k.provides??[],o={};for(let{bindTo:s,ref:i}of d)o[s]=chunkIXZG74EW_cjs.a.resolve(H,i);return (S??(()=>{}))(o),P.filter(s=>{if(s.optionalForCompletionGating!==true)return false;let i=j(s.outputFile);return !i.lastRequestedToken||!i.lastCompletedToken?true:i.lastCompletedToken<=i.lastRequestedToken}).length>0&&l.push({taskKind:"source-fetch",payload:{boardRef:chunkSFVO2LB2_cjs.a(e),enrichedCard:z,callbackToken:f.callbackToken,rqt:_}}),u(f.nodeId,o),l.length>0&&await a.executionRequestStore.appendEntries(t,l),"task-initiated"}}function Ir(e,t){chunkOEFTOO47_cjs.d(t.callbackTransport,"createAsyncBoardLiveCardsPublic");let a=t.callbackTransport,u=t.warn??(()=>{}),p=chunkSFVO2LB2_cjs.a(e),S=null;function f(n){if(n.length!==0)try{return Promise.resolve(t.publishBoardChangeNotifications?.(n)).catch(r=>{u(`[async-board-live-cards-public] publishBoardChangeNotifications failed: ${r instanceof Error?r.message:String(r)}`);})}catch(r){u(`[async-board-live-cards-public] publishBoardChangeNotifications failed: ${r instanceof Error?r.message:String(r)}`);return}}let l=()=>Qe(t.kvStorage("config")),k=()=>t.kvStorage("state-snapshot"),v=e.value,q=()=>chunkOEFTOO47_cjs.b(chunkOEFTOO47_cjs.a(()=>k(),t.hashFn),"v1"),P=async()=>{let n=await l().readOutputsStoreRef();if(!n)throw new Error(`Board at ${e.value} has no outputs store configured.`);return nr(t.kvStorageForRef(n))},N=async()=>{let n=await l().readCardStoreRef();if(!n)throw new Error(`Board at ${e.value} has no card store configured.`);let r=t.kvStorageForRef(n);return Je(Le(We(r),t.hashFn),u)};async function V(){return !!(await q().readSnapshot(v)).values[chunkOEFTOO47_cjs.n]}async function K(){let n=await q().readSnapshot(v);if(!n.values[chunkOEFTOO47_cjs.n])throw new Error(`Board not initialized at ${e.value}`);return chunkOEFTOO47_cjs.w(n.values)}async function L(n,r){let d=await q().commitSnapshot(v,{schemaVersion:"v1",expectedVersion:r,deleteKeys:[],shallowMerge:chunkOEFTOO47_cjs.v(n)});if(!d.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${r??"null"} current=${d.currentVersion??"null"}`)}let j=()=>chunkOEFTOO47_cjs.c(t.journalStorage());async function b(n){await j().appendEvent(n);}function $(){return tr(t.blobStorage("sources"),n=>t.resolveBlob(n))}async function J(n){let r=await Promise.resolve(t.blobStorage("sources").keyRef?.(n));return r?chunkSFVO2LB2_cjs.a(r):n}async function Q(){let n=ar(t.kvStorage("execution-requests"),async(c,g)=>{let A=c.payload,T=(A.enrichedCard??{}).id??A.cardId??"unknown";await b({type:"task-failed",taskName:T,error:g,timestamp:I()});}),r=rr(t.kvStorage("card-runtime")),d=$(),o=await N(),y=await P(),s=new Map,i=new Map,m=[],h=[],x=[],F=new Map,W=new Set,M={async readRuntime(c){return s.get(c)??await r.readRuntime(c)},async writeRuntime(c,g){s.set(c,g);}},ce={async readSourceData(c,g){let A=`${c}/${g}`;return i.has(A)?i.get(A):await d.readSourceData(c,g)},ingestSourceDataStaged(c,g,A,B){return d.ingestSourceDataStaged(c,g,A,B)},async commitSourceData(c,g,A){let B=`${c}/.staged/${A}/${g}`,T=t.blobStorage("sources"),D=await T.read(B);if(D==null){let X=await T.keyRef?.(B);X&&(D=await t.resolveBlob(X));}if(D==null)return false;let re=`${c}/${g}`,Y=D.trim();try{i.set(re,JSON.parse(Y));}catch{i.set(re,Y);}return m.push({cardId:c,outputFile:g,deliveryToken:A}),true},async hasSource(c,g){let A=`${c}/${g}`;return i.has(A)||await d.hasSource(c,g)},async listSources(c){let g=await d.listSources(c),A=[...i.keys()].filter(B=>B.startsWith(`${c}/`)).map(B=>B.slice(`${c}/`.length));return [...new Set([...g,...A])]}},ke=await K(),Ue=chunkG4XXRHL2_cjs.q(ke.graph),{events:Ge,newCursor:de}=await j().readEntriesAfterCursor(ke.lastDrainedJournalId),Z=Ge,ee=chunkG4XXRHL2_cjs.u(Ue,{handlers:{"card-handler":or(e,de,{cardStore:o,cardRuntimeStore:M,fetchedSourcesStore:ce,executionRequestStore:n},(c,g)=>{Z.push({type:"task-completed",taskName:c,data:g,timestamp:I()});},(c,g)=>{h.push({cardId:c,values:g});},c=>{x.push(c);})},onNodeRemoved:c=>{F.delete(c),s.delete(c),W.add(c);}});for(;Z.length>0;){let c=Z;Z=[];for(let g of c)if(g.type==="task-restart"){let A=await o.readCard(g.taskName);A&&F.set(g.taskName,A);}ee.pushAll(c),await ee.waitForHandlers();}let Re=ee.getState();await ee.dispose({wait:true}),await L({lastDrainedJournalId:de,graph:chunkG4XXRHL2_cjs.p(Re)},(await q().readSnapshot(v)).version);for(let{cardId:c,values:g}of h)await y.writeComputedValues(c,g);for(let c of x)await y.writeDataObjects(c);for(let[c,g]of s)await r.writeRuntime(c,g);for(let c of m)await d.commitSourceData(c.cardId,c.outputFile,c.deliveryToken);let he=chunkOEFTOO47_cjs.t(p,Re);await y.writeStatusSnapshot(he);let U=[];for(let{cardId:c,values:g}of h)U.push({kind:"computed_values",cardId:c,values:g});for(let c of x)for(let[g,A]of Object.entries(c))U.push({kind:"data_object",key:g,payload:A});for(let[c,g]of F)U.push({kind:"card_refreshed",cardId:c,card:g});for(let c of W)U.push({kind:"card_removed",cardId:c});U.push({kind:"status",status:he}),await f(U);let le=await l().readTaskExecutorRef();if(!le)return;let ze=t.supportsDirectSourceOutput?.(le)===true;await n.dispatchEntriesForJournalId(de,async c=>{if(c.taskKind!=="source-fetch"){u(`[async-process-accumulated-events] unknown taskKind "${c.taskKind}" \u2014 skipping`);return}let g=c.payload,A=g.enrichedCard?.id??"unknown",B=g.enrichedCard?.source_defs??[];for(let T of B){if(!T.outputFile)continue;let D;if(ze){let X=t.genId(),Ye=`${A}/.staged/${X}/${T.outputFile}`,Ce=await Promise.resolve(t.blobStorage("sources").keyRef?.(Ye));Ce&&(D={ref:chunkSFVO2LB2_cjs.a(Ce),deliveryToken:X,outputFile:T.outputFile,cardId:A});}let re=er({cbk:g.callbackToken,rg:e.value,br:chunkSFVO2LB2_cjs.a(e),cid:A,b:T.bindTo,d:T.outputFile,cs:void 0,rqt:g.rqt,...D?{dt:D.deliveryToken}:{}}),Y=await t.dispatchExecution(le,{source_def:T,base_ref:chunkSFVO2LB2_cjs.a(e),callback:a.createCallback(re),...D?{output:D}:{}});Y.dispatched||await b({type:"task-failed",taskName:A,error:Y.error??"dispatch failed",timestamp:I()});}});}async function H(){try{let n=async()=>{let d=await K(),{events:o}=await j().readEntriesAfterCursor(d.lastDrainedJournalId);o.length>0&&await z();},r=await $e(t.lock,Q,n);return C({ran:r!==!1})}catch(n){return w(n)}}async function G(){return S||(S=H().finally(()=>{S=null;}),S)}async function z(){let n=t.processAccumulatedStore();n.enqueueIfAbsent?await n.enqueueIfAbsent({boardRef:chunkSFVO2LB2_cjs.a(e)},`process-accumulated:${chunkSFVO2LB2_cjs.a(e)}`):await n.enqueue({boardRef:chunkSFVO2LB2_cjs.a(e)}),await t.requestProcessAccumulated?.();}async function _(){let n=t.processAccumulatedStore();for(;;){let r=await n.lease({max:64,visibilityMs:1e3});if(r.length<=0)return;for(let d of r)await n.ack(d.id,d.leaseToken);if(r.length<64)return}}function O(){z();}return {async init(n){try{let r=n.params?.cardStoreRef;if(!r)return R("init requires params.cardStoreRef");let d=n.params?.outputsStoreRef;if(!d)return R("init requires params.outputsStoreRef");await V()||await L({lastDrainedJournalId:"",graph:chunkG4XXRHL2_cjs.p(chunkG4XXRHL2_cjs.a(chunkOEFTOO47_cjs.u))},null);let o=l();await o.writeCardStoreRef(r),await o.writeOutputsStoreRef(d);let y=n.params?.scratchStoreRef,s=n.params?.archiveStoreRef,i=n.params?.chatStoreRef,m=n.params?.artifactsStoreRef;y&&await o.writeScratchStoreRef(y),s&&await o.writeArchiveStoreRef(s),i&&await o.writeChatStoreRef(i),m&&await o.writeArtifactsStoreRef(m);let h=n.body??{};return h["task-executor-ref"]&&await o.writeTaskExecutorRef(h["task-executor-ref"]),Object.prototype.hasOwnProperty.call(h,"chat-handler-flow")&&await o.writeChatHandlerFlow(h["chat-handler-flow"]),await(await P()).writeStatusSnapshot(chunkOEFTOO47_cjs.t(p,chunkG4XXRHL2_cjs.q((await K()).graph))),C()}catch(r){return w(r)}},async status(n){try{let r=await P(),d=await r.readStatusSnapshot();return d||(d=chunkOEFTOO47_cjs.t(p,chunkG4XXRHL2_cjs.q((await K()).graph)),await r.writeStatusSnapshot(d)),C(d)}catch(r){return w(r)}},async getCardStoreRef(n){try{let r=await l().readCardStoreRef();return r?C({storeRef:r}):R(`Board at ${e.value} has no card store configured`)}catch(r){return w(r)}},async getOutputsStoreRef(n){try{let r=await l().readOutputsStoreRef();return r?C({storeRef:r}):R(`Board at ${e.value} has no outputs store configured`)}catch(r){return w(r)}},async getScratchStoreRef(n){try{return C({storeRef:await l().readScratchStoreRef()})}catch(r){return w(r)}},async getArchiveStoreRef(n){try{return C({storeRef:await l().readArchiveStoreRef()})}catch(r){return w(r)}},async getChatStoreRef(n){try{return C({storeRef:await l().readChatStoreRef()})}catch(r){return w(r)}},async getArtifactsStoreRef(n){try{return C({storeRef:await l().readArtifactsStoreRef()})}catch(r){return w(r)}},async getConfig(n){try{let r=n.params?.key;if(!r)return R("getConfig requires params.key");let d=l(),o;switch(r){case "task-executor":o=await d.readTaskExecutorRef()??null;break;case "chat-handler-flow":o=await d.readChatHandlerFlow()??null;break;case "card-store-ref":o=await d.readCardStoreRef();break;case "outputs-store-ref":o=await d.readOutputsStoreRef();break;case "scratch-store-ref":o=await d.readScratchStoreRef();break;case "archive-store-ref":o=await d.readArchiveStoreRef();break;case "chat-store-ref":o=await d.readChatStoreRef();break;case "artifacts-store-ref":o=await d.readArtifactsStoreRef();break;default:return R(`getConfig: unknown key "${r}"`)}return C({value:o})}catch(r){return w(r)}},async getOutputsDataObject(n){try{let r=n.params?.key;return r?C(await(await P()).readDataObject(r)):R("getOutputsDataObject requires params.key")}catch(r){return w(r)}},async getAllOutputsDataObjects(n){try{return C(await(await P()).readAllDataObjects())}catch(r){return w(r)}},async getOutputsComputedValues(n){try{let r=n.params?.key;return r?C(await(await P()).readComputedValues(r)):R("getOutputsComputedValues requires params.key")}catch(r){return w(r)}},async getAllOutputsComputedValues(n){try{return C(await(await P()).readAllComputedValues())}catch(r){return w(r)}},async getOutputsFetchedSources(n){try{let r=n.params?.key;if(!r)return R("getOutputsFetchedSources requires params.key");let d=await $().listSources(r),o={};for(let y of d)o[y]=await J(`${r}/${y}`);return C(o)}catch(r){return w(r)}},async getAllOutputsFetchedSources(n){try{let r=$(),d=await t.blobStorage("sources").listKeys(),o=new Set;for(let s of d){let i=s.indexOf("/");i>0&&!s.includes("/.staged/")&&o.add(s.slice(0,i));}let y={};for(let s of o){let i=await r.listSources(s);if(i.length!==0){y[s]={};for(let m of i)y[s][m]=await J(`${s}/${m}`);}}return C(y)}catch(r){return w(r)}},async addCardFiles(n){try{let r=n.params?.cardId;if(!r)return R("addCardFiles requires params.cardId");let d=await N(),o=await d.readCard(r);if(!o)return R(`card "${r}" not found`);let y=n.body,s=Array.isArray(y)?y:y&&typeof y=="object"&&Array.isArray(y.files)?y.files:y!=null?[y]:null;if(!s||s.length===0)return R("addCardFiles requires a file metadata object, array, or body.files array");let i=o.card_data&&typeof o.card_data=="object"&&!Array.isArray(o.card_data)?o.card_data:{},m=Array.isArray(i.files)?i.files:[],h=[...m,...s],x=s.map((W,M)=>({idx:m.length+M,entry:W}));await d.writeCard(r,{...o,card_data:{...i,files:h}});let F=await this.cardRefreshedNotify({params:{cardId:r}});return F.status!=="success"?F:C({cardId:r,files_added:x,notified:!0})}catch(r){return w(r)}},async cardRefreshedNotify(n){try{let r=n.params?.cardId;if(!r)return R("cardRefreshedNotify requires params.cardId");let d=await(await N()).readCard(r);return d?(await f([{kind:"card_refreshed",cardId:r,card:d}]),C({cardId:r,notified:!0})):R(`Card "${r}" not found in board at ${e.value}`)}catch(r){return w(r)}},async removeCard(n){try{let r=n.params?.id;if(!r)return R("removeCard requires params.id");try{await t.kvStorage("card-upsert").delete(r);}catch{}return await b({type:"task-removal",taskName:r,timestamp:I()}),O(),C()}catch(r){return w(r)}},async retrigger(n){try{let r=n.params?.id;return r?(await b({type:"task-restart",taskName:r,timestamp:I()}),O(),C()):R("retrigger requires params.id")}catch(r){return w(r)}},async processAccumulatedEvents(n){return await _(),G()},async upsertCard(n){try{let r=n.params?.cardId,d=n.params?.all,o=!!n.params?.restart;if(!r&&!d)return R("upsertCard requires --card-id <id> or --all");let y=await N(),s=d?(await y.readAllCards()).map(m=>m.id):[r];for(let m of s)if(!await y.readCard(m))return R(`Card "${m}" not found in board at ${e.value}`);let i=t.kvStorage("card-upsert");for(let m of s){let h=await y.readCard(m);if(!h)continue;let x=chunkOEFTOO47_cjs.x(h),F=t.hashFn(x),W=await i.read(m),M=W?.taskConfigHash!==F;if(!(!M&&!o)){if(M){let ce=W?.blobRef??await y.readCardKey(m)??m;await b({type:"task-upsert",taskName:m,taskConfig:x,timestamp:I()}),await i.write(m,{blobRef:ce,taskConfigHash:F,updatedAt:I()});}o&&await b({type:"task-restart",taskName:m,timestamp:I()});}}return O(),C()}catch(r){return w(r)}},async taskFailed(n){try{let r=n.params?.token;if(!r)return R("taskFailed requires params.token");let d=n.params?.error??"unknown error",o=ue(r);return o?(await b({type:"task-failed",taskName:o.taskName,error:d,timestamp:I()}),O(),C()):R("Invalid callback token")}catch(r){return w(r)}},async taskProgress(n){try{let r=n.params?.token;if(!r)return R("taskProgress requires params.token");let d=(n.body??{}).update??{},o=ue(r);return o?(await b({type:"task-progress",taskName:o.taskName,update:d,timestamp:I()}),O(),C()):R("Invalid callback token")}catch(r){return w(r)}},async sourceDataFetched(n){try{let r=n.params?.token,d=n.params?.ref;if(!r)return R("sourceDataFetched requires params.token");if(!d)return R("sourceDataFetched requires params.ref");let o=He(r);if(!o)return R("Invalid source token");let y=$(),s=o.dt||t.genId();o.dt||await y.ingestSourceDataStaged(o.cid,o.d,chunkSFVO2LB2_cjs.b(d),s);let i=ue(o.cbk);return i?(await b({type:"task-progress",taskName:i.taskName,update:{bindTo:o.b,outputFile:o.d,fetchedAt:I(),deliveryToken:s,sourceChecksum:o.cs,rqt:o.rqt},timestamp:I()}),O(),C()):R("Invalid callback token embedded in source token")}catch(r){return w(r)}},async sourceDataFetchFailure(n){try{let r=n.params?.token,d=n.params?.reason??"unknown";if(!r)return R("sourceDataFetchFailure requires params.token");let o=He(r);if(!o)return R("Invalid source token");let y=ue(o.cbk);return y?(await b({type:"task-progress",taskName:y.taskName,update:{bindTo:o.b,outputFile:o.d,failure:!0,reason:d,sourceChecksum:o.cs,rqt:o.rqt},timestamp:I()}),O(),C()):R("Invalid callback token embedded in source token")}catch(r){return w(r)}}}}
|
|
2
|
+
exports.a=$e;exports.b=We;exports.c=Le;exports.d=Je;exports.e=cr;exports.f=dr;exports.g=ie;exports.h=Qe;exports.i=gr;exports.j=Ir;//# sourceMappingURL=chunk-H5HBXPOI.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-H5HBXPOI.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function g(n){return typeof n=="object"&&n!==null&&"then"in n&&typeof n.then=="function"}function i(n,s){return g(n)?n.then(s):s(n)}function u(n,s){let r={...n};for(let[e,t]of Object.entries(s))t!==null&&typeof t=="object"&&!Array.isArray(t)&&r[e]!==null&&typeof r[e]=="object"&&!Array.isArray(r[e])?r[e]=u(r[e],t):r[e]=t;return r}function c(n,s,r){if(s.length===0)return n;let[e,...t]=s;if(t.length===0)return {...n,[e]:r};let o=n[e]!==null&&typeof n[e]=="object"&&!Array.isArray(n[e])?n[e]:{};return {...n,[e]:c(o,t,r)}}function l(n){return {read:r=>n.read(r),get(r,e){return i(n.read(r),t=>{if(t===null)return null;let o=t;for(let a of e.split(".").filter(Boolean)){if(o===null||typeof o!="object"||Array.isArray(o))return null;o=o[a]??null;}return o??null})},write:(r,e)=>n.write(r,e),delete:r=>n.delete(r),listKeys:r=>n.listKeys(r),shallowMerge(r,e){return i(n.read(r),t=>n.write(r,{...t??{},...e}))},deepMerge(r,e){return i(n.read(r),t=>n.write(r,u(t??{},e)))},patch(r,e,t){return i(n.read(r),o=>{let a=e.split(".").filter(Boolean);return n.write(r,c(o??{},a,t))})}}}export{c as a,l as b};//# sourceMappingURL=chunk-HEEDJEKM.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-HEEDJEKM.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {f,b,c as c$1,e}from'./chunk-MLVTJASJ.js';import {j,d,c,b as b$1}from'./chunk-VMW4Z6EF.js';import {y,z as z$1,l}from'./chunk-N6P2JW4W.js';import {b as b$2}from'./chunk-BQS3EIEK.js';import {a as a$2}from'./chunk-SCWHDI3I.js';import {a as a$1}from'./chunk-KBELAKIY.js';import {a}from'./chunk-76ON3V7R.js';function wt(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Qe(r){if(!r||typeof r!="object")return false;let t=r.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function ze(r,t){if(!t||typeof t!="object")return;let s=t;if(s.kind==="notification-batch"&&Array.isArray(s.notifications)){for(let o of s.notifications)ze(r,o);return}s.kind==="status"&&Qe(s.status)&&(r.status=s.status),s.kind==="computed_values"&&s.cardId&&(r.computedValues[s.cardId]=s.values),s.kind==="data_object"&&s.key&&(r.dataObjects[s.key]=s.payload),s.kind==="card_refreshed"&&s.cardId&&(r.cards[s.cardId]=s.card),s.kind==="card_removed"&&s.cardId&&(delete r.cards[s.cardId],delete r.computedValues[s.cardId]);}function ge(r){return typeof r.journalStorage=="function"}function Ct(r){return typeof r.whatToRun=="string"?r.whatToRun.startsWith("b64:")?b$2(r.whatToRun).value:r.whatToRun:r.whatToRun.value}function se(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(r){let t=r.reduce((u,p)=>u+p.length,0),s=new Uint8Array(t),o=0;for(let u of r)s.set(u,o),o+=u.length;return s}function ht(r){let t=new Map,s=new Map,o=new Map,u=0,p=null;function R(i){let m=JSON.stringify(i);return u++,`id: ${u}
|
|
2
|
+
data: ${m}
|
|
3
|
+
|
|
4
|
+
`}function C(i){let m=i;try{m.flushHeaders?.();}catch{}try{m.flush?.();}catch{}try{m.socket?.setNoDelay?.(!0);}catch{}try{m.socket?.uncork?.();}catch{}}function F(i,m){let A=t.get(i);if(A&&!(m&&A.res!==m)){t.delete(i),j();try{r.onSseClientDisconnected?.(i);}catch{}try{A.res.end();}catch{}}}function T(i,m,A){let P=t.get(i);P&&F(i,P.res),t.set(i,{res:m,subscribedChatCardIds:A??new Set});}function g(i,m){let A=t.get(i);if(!A)return;let P=R(m);try{A.res.write(P),C(A.res);}catch{F(i,A.res);}}function b(){let i=new Set;for(let m of t.values())for(let A of m.subscribedChatCardIds)i.add(A);return Array.from(i)}function S(i){let m=s.has(i)?s.get(i):null,{cursor:A}=r.chatStorage.readAfter(i,m),P=r.chatStorage.isProcessing(i),G=P!==(o.get(i)??false),ue=A!==m;return ue&&s.set(i,A),o.set(i,P),ue||G}function O(i,m){let A=r.readChatRecords(i),P=Date.now();return {kind:"card_chats",cardId:i,sentAt:new Date(P).toISOString(),sentAtMs:P,messages:A.map(G=>({role:String(G.role||"system"),text:String(G.text||""),files:Array.isArray(G.files)?G.files:[]})),receiving:m,processing:r.chatStorage.isProcessing(i)}}function x(i,m=true){let A={kind:"notification-batch",notifications:[O(i,m)]};for(let[P,G]of t.entries())G.subscribedChatCardIds.has(i)&&g(P,A);}function j(){b().length>0||(p&&(clearInterval(p),p=null),s.clear(),o.clear());}function w(){if(p)return;let i=()=>{let m=b();if(m.length===0){j();return}let A=new Set(m);for(let P of Array.from(s.keys()))A.has(P)||s.delete(P);for(let P of Array.from(o.keys()))A.has(P)||o.delete(P);for(let P of m)S(P)&&x(P,true);};i(),p=setInterval(i,1e3);}function v(i,m){let A=t.get(i);if(!A)return false;A.subscribedChatCardIds.add(m);let{cursor:P}=r.chatStorage.readAfter(m,null);return s.set(m,P),o.set(m,r.chatStorage.isProcessing(m)),w(),g(i,{kind:"notification-batch",notifications:[O(m,true)]}),true}function L(i,m){let A=t.get(i);return A?(A.subscribedChatCardIds.delete(m),b().includes(m)||(s.delete(m),o.delete(m)),j(),true):false}function d(i){if(!i||typeof i!="object")return false;let m=i.kind;return m==="card_chats"||m==="chat_messages"}function l(i){if(!i||i.length===0)return;let m=[],A=new Set;for(let P of i)d(P)&&typeof P.cardId=="string"?A.add(String(P.cardId)):m.push(P);if(m.length>0){let P={kind:"notification-batch",notifications:m};for(let G of t.keys())g(G,P);}for(let P of A)x(P,true);}return {size:()=>t.size,has:i=>t.has(i),get:i=>t.get(i),buildFrame:R,flushTransport:C,register:T,disconnect:F,writeFrame:g,subscribeChat:v,unsubscribeChat:L,broadcastNotificationBatch:l,broadcastCardChats:x}}function z(r,...t){for(let s of t)if(typeof r[s]=="string")return String(r[s]);return ""}function ye(r,...t){for(let s of t)if(r[s]!==void 0)return Number(r[s])}function _e(r,...t){for(let s of t){let o=r[s];if(o&&typeof o=="object"&&!Array.isArray(o))return o}return {}}function he(r,t,...s){for(let o of s){let u=r[o];if(u&&typeof u=="object"&&!Array.isArray(u))return u}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function We(r,t,...s){for(let o of s){let u=r[o];if(u!==void 0){let p=Number(u);if(Number.isFinite(p))return p}}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function Rt(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(t=>Math.max(0,Math.min(255,Number(t)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let t=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),s=t+"=".repeat((4-t.length%4)%4),o=atob(s);return Uint8Array.from(o,u=>u.charCodeAt(0))}return null}function Je(r,t){if(r?.status==="success")return Object.prototype.hasOwnProperty.call(r,"data")?r.data:void 0;throw r?.status==="fail"||r?.status==="error"?Object.assign(new Error(r.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function Ke(r,t){return Je(await r,t)}function Ge(r){let t=z(r,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let s=t.split(".");if(!(s.length>=2&&s[0]==="chat"&&s.every(u=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return t}function Ze(r,t){let s=r.meta;for(let o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,o))return {exists:false,value:null};s=s[o];}return {exists:true,value:s}}function kt(r){let{boardId:t,getMcpFacade:s,getMcpCardStoreFacade:o}=r;function u(T){let g=z(T,"board_id"),b=z(T,"card_id");if(!g)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!b)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(g!==t)throw Object.assign(new Error(`Unknown board_id: ${g}`),{statusCode:400});return {cardId:b}}function p(T,g){let{cardId:b}=u(T);return s().setChatProcessing({cardId:b,active:g}),{status:"success",data:{boardId:t,cardId:b,active:g}}}function R(T){let{cardId:g}=u(T),b=s().getChatProcessing({cardId:g});return {status:"success",data:{boardId:t,cardId:g,active:b.active}}}async function C(T){let{cardId:g}=u(T),b=Ge(T);if(!Object.prototype.hasOwnProperty.call(T,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(b.split(".").includes("__visible_controlplane_only")){let S=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(S.cards)&&S.cards.length>0&&typeof S.cards[0]=="object"&&!Array.isArray(S.cards[0])?S.cards[0]:null,x=O?Ze(O,"__visible_controlplane_only").value:void 0;if(T.value!==x)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:g,key:b}}}return Je(await o().patch({params:{id:g,path:`meta.${b}`},body:{value:T.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:g,key:b}}}async function F(T){let{cardId:g}=u(T),b=Ge(T),S=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(S.cards)&&S.cards.length>0&&S.cards[0]&&typeof S.cards[0]=="object"&&!Array.isArray(S.cards[0])?S.cards[0]:null;if(!O)throw Object.assign(new Error(`Card "${g}" not found`),{statusCode:404});let x=Ze(O,b);return {status:"success",data:{boardId:t,cardId:g,key:b,exists:x.exists,value:x.value}}}return {requireCardArgs:u,setChatProcessing:p,getChatProcessing:R,setCardMeta:C,getCardMeta:F}}function St(r){let{boardId:t,boardContexts:s,readCardDefinitions:o,readChatRecords:u,getChatProcessing:p}=r;async function R(){let g=(await Promise.all(s.map(async j=>{try{let w=j.boardAdapter.kvStorageForRef(j.outputsStoreRef),v=await Promise.resolve(w.read("status"));if(v!=null)return v}catch{}return j.notification.status}))).filter(Boolean);if(g.length===0)return null;if(g.length===1)return g[0];let b=[],S=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],O={};for(let j of S)O[j]=0;for(let j of g){let w=j,v=Array.isArray(w.cards)?w.cards:[];b.push(...v);for(let L of S)O[L]+=Number(w?.summary?.[L]||0);}let x=g[0];return {...x,cards:b,summary:{...x.summary||{},card_count:b.length,...O}}}async function C(){let g={},b=async S=>{try{let O=await S.boardOps.getAllOutputsComputedValues({});if(O.status==="success"&&O.data&&typeof O.data=="object"){for(let[x,j]of Object.entries(O.data)){let w=S.notification.cards[x];g[x]={schema_version:"v1",card_id:x,card_data:w?.card_data??{},computed_values:j??{}};}return}}catch{}for(let[O,x]of Object.entries(S.notification.computedValues)){let j=S.notification.cards[O];g[O]={schema_version:"v1",card_id:O,card_data:j?.card_data??{},computed_values:x??{}};}};for(let S of s)await b(S);return g}async function F(){let g={};for(let b of s){try{let S=await b.boardOps.getAllOutputsDataObjects({});if(S.status==="success"&&S.data&&typeof S.data=="object"){Object.assign(g,S.data);continue}}catch{}Object.assign(g,b.notification.dataObjects||{});}return g}async function T(){let g=await o(),b=await C(),S=await F(),O={};for(let j of g){if(!j?.id)continue;let w=j.id,v=b[w]||{},L={...v.card_data&&typeof v.card_data=="object"?v.card_data:j.card_data&&typeof j.card_data=="object"?j.card_data:{}};O[w]={schema_version:v.schema_version||"v1",card_id:v.card_id||w,card_data:L,computed_values:v.computed_values&&typeof v.computed_values=="object"?v.computed_values:{}};}let x={};for(let j of g){if(!j?.id)continue;let w=j.id;try{let v=u(w),L=p(w);(v.length>0||L)&&(x[w]={messages:v.map(d=>({role:String(d.role||"system"),text:String(d.text||""),files:Array.isArray(d.files)?d.files:[]})),receiving:!1,processing:L});}catch{}}return {boardId:t,cardDefinitions:g,statusSnapshot:await R(),dataObjectsByToken:S,cardRuntimeById:O,cardChatsByCardId:x}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:C,readDataObjectsByToken:F,buildPublishedRuntimePayload:T}}function Ht(r){let t=String(r||"").trim();if(!t)return "upload.bin";let s=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (s>=0?t.slice(s+1):t)||"upload.bin"}function At(r){let{safeCardId:t,artifactsStores:s,cardFileMetadataStore:o,readCardFromStore:u,updateCardLocalOnly:p,writeChatRecord:R}=r;async function C(g){let b=[];try{let S=await u(g);if(!S)return b;let O=o().read(S.card_data&&typeof S.card_data=="object"?S.card_data:null);for(let x of O)b.push(String(x.stored_name??""));}catch{}return b}async function F(g,b,S,O){let x=t(g),j=s(g),w=Ht(b),v=await C(g),d=`${String(v.length+1).padStart(3,"0")}-${w}`.slice(-36);return j.files&&await j.files.putBytes(`${x}/${d}`,new Uint8Array(O),S||"application/octet-stream"),{name:w,stored_name:d,size:O.length,mime_type:S||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function T(g,b,S,O,x){if(!O.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let j=x?.inChat===true,w=await F(g,b,S,O),v=null;if(await p(g,L=>{let d=new Date().toISOString(),l=L.card_data&&typeof L.card_data=="object"?L.card_data:{};L.card_data=l;let i=o().normalizeIncoming([{name:w.name,stored_name:w.stored_name,size:w.size,mime_type:w.mime_type,uploaded_at:w.uploaded_at||d,chat:j}],d);return v=o().merge(l,i).findIndex(A=>A.stored_name===w.stored_name),L}),j){let L=typeof v=="number"&&v>=0?` #${v}`:"";R(g,"system",`file uploaded: ${w.name} as ${w.stored_name}${L}`,[],x?.turnId??"");}return {ok:true,file:w}}return {uploadCardFile:T,readCardStoredFileNames:C}}function vt(r){return {"discover.source-kinds":()=>r.discoverSourceKinds(),"inspect.board-runtime-status":()=>r.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>r.inspectCardDefinitionAndRuntime({cardId:z(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let s=ye(t,"tail_turns"),o=ye(t,"tail"),u=z(t,"turn_id"),p=t.all_turns===true,R=z(t,"tail_turns_before_id");return r.inspectChatMessagesOnCards({cardId:z(t,"card_id"),...s!==void 0?{lastUserTurns:s}:{},...o!==void 0?{tail:o}:{},...u?{turnId:u}:{},...p?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":t=>r.inspectFileContents({cardId:z(t,"card_id"),fileIdx:Number(ye(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>r.preflightValidateCandidateCardDefinition({candidateCardContent:he(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>r.preflightMaterializeCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:he(t,"mock_requires","mock_requires"),mockFetchedSources:he(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>r.preflightProbeSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>r.preflightRunSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>r.preflightRunSingleSourceInLiveCard({cardId:z(t,"card_id"),sourceIdx:We(t,"source_idx","source_idx"),mockRequires:he(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>r.preflightRunOneCycleWithCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:_e(t,"mock_requires")}),"manage.read-card":t=>r.manageReadCard({cardId:z(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let s=z(t,"turn_id");if(!s)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return r.manageAddChatEntryAndAnyAttachments({cardId:z(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...s?{turn:s}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.upsert-card":t=>r.manageUpsertCard({cardId:z(t,"card_id"),candidateCardContent:_e(t,"candidate_card_content")}),"manage.remove-card":t=>r.manageRemoveCard({cardId:z(t,"card_id")})}}function Pt(r){let{boardId:t,uploadCardFile:s,getMcpFacade:o,controlplane:u}=r;return {"getstate.is-chat-processing":p=>u.getChatProcessing(p),"setstate.chat-processing-started":p=>u.setChatProcessing(p,true),"setstate.chat-processing-done":p=>u.setChatProcessing(p,false),"getstate.card-meta":p=>u.getCardMeta(p),"setstate.card-meta":p=>u.setCardMeta(p),"manage.upload-card-file":p=>{let R=z(p,"board_id"),C=z(p,"card_id"),F=z(p,"file_name"),T=z(p,"content_type")||"application/octet-stream",g=Rt(p);if(!R)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});if(!C)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(!g)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return s(C,F,T,g,{inChat:false})},"manage.admin-read-card":async p=>{let{cardId:R}=u.requireCardArgs(p);return {status:"success",data:{cards:await o().adminReadCard({cardId:R})}}},"manage.admin-upsert-card":p=>{let R=z(p,"board_id"),C=z(p,"card_id");if(!R)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});return o().adminUpsertCard({cardId:C,candidateCardContent:_e(p,"candidate_card_content")})}}}function Bt(r){let{boardContexts:t,cardOwnerIndex:s,cardContextForCard:o,readStatusSnapshot:u,readDataObjectsByToken:p,readCardRuntimeArtifacts:R,readCardFromStore:C,readCardDefinitions:F,processAccumulatedLaneInternal:T,uploadCardFile:g,chatStorePublic:b,serverUrl:S,apiBasePath:O}=r;function x(){return t[0]??null}function j(){return {async status(){let d=await u();return d==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:d}},async getOutputsDataObject(d){let l=d?.params?.key;return l?{status:"success",data:(await p())[l]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(d){let l=d?.params?.key;return l?{status:"success",data:(await R())[l]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(d){let l=d?.params?.key;if(!l)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let i=o(l)??x();return i?i.boardOps.getOutputsFetchedSources({params:{key:l}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(d){let l=d?.params?.id;if(!l)return {status:"fail",error:"removeCard requires params.id"};let i=o(l)??x();return i?i.boardOps.removeCard({params:{id:l}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let i=o(l)??x();return i?i.boardOps.cardRefreshedNotify({params:{cardId:l}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"upsertCard requires params.cardId"};let i=o(l)??x();if(!i)return {status:"fail",error:"Board context is unavailable"};let m=await i.boardOps.upsertCard({params:{cardId:l,restart:d.params.restart===true}});if(m.status!=="success")return m;if(ge(i.boardAdapter)){let A=await T(true);if(A.status!=="success")return A}return m}}}function w(){let d=()=>{let l=x();if(!l?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return l.nonCore};return {describeTaskExecutorCapabilities(l){return d().describeTaskExecutorCapabilities(l)},validateCardPreflight(l){return d().validateCardPreflight(l)},evalCardCompute(l){return d().evalCardCompute(l)},probeSourcePreflight(l){return d().probeSourcePreflight(l)},runSourcePreflight(l){return d().runSourcePreflight(l)},simulateCardCycle(l){return d().simulateCardCycle(l)}}}function v(){return {async get(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(l){let i=await C(l);return i?{status:"success",data:{cards:[i]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await F()}}},async set(d){let l=d.body;if(l==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let i=Array.isArray(l)?l:[l];for(let m of i){let A=m,P=typeof A.id=="string"?A.id:"";if(!P)return {status:"fail",error:"each card must have a string `id` field"};let G=s.get(P)??0,ue=t[G]??x();if(!ue)return {status:"fail",error:"Board context is unavailable"};let fe=await ue.cardStoreOps.set({body:A});if(fe.status!=="success")return fe;s.set(P,G);}return {status:"success",data:{count:i.length}}},async del(d){let l=[d.params?.id,...d.body?.ids??[]].filter(i=>typeof i=="string"&&!!i);if(l.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let i of l){let m=o(i)??x();if(!m)return {status:"fail",error:"Board context is unavailable"};let A=await m.cardStoreOps.del({params:{id:i}});if(A.status!=="success")return A;s.delete(i);}return {status:"success",data:{count:l.length}}},async patch(d){let l=typeof d.params?.id=="string"?d.params.id:void 0,i=typeof d.params?.path=="string"?d.params.path:void 0;if(!l||!i)return {status:"fail",error:"patch requires params.id and params.path"};let m=o(l)??x();return m?m.cardStoreOps.patch(d):{status:"fail",error:"Board context is unavailable"}},async appendFiles(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(!l)return {status:"fail",error:"appendFiles requires params.id"};let i=o(l)??x();return i?i.cardStoreOps.appendFiles(d):{status:"fail",error:"Board context is unavailable"}}}}function L(){return a$2({board:j(),nonCore:w(),cardStore:v(),chatStore:b,uploadCardFile({cardId:d,fileName:l,contentType:i,bytes:m}){return g(d,l,i,m,{inChat:false})},buildFileDownloadUrl({cardId:d,fileIdx:l,storedName:i}){let m=`${S||""}${O}/cards/${encodeURIComponent(d)}/files/${l}`;return i?`${m}?sn=${encodeURIComponent(i)}`:m},readFetchedSourceJsonByRef({cardId:d,ref:l}){let i=o(d)??x();if(!i||ge(i.boardAdapter))return null;let P=i.boardAdapter.resolveBlob(b$2(l)).trim();return P?JSON.parse(P):null}})}return {mcpBoardFacade:j,mcpNonCoreFacade:w,mcpCardStoreFacade:v,createMcpFacade:L}}function It(r){let{sseHub:t,corsHeaders:s,json:o,buildPublishedRuntimePayload:u,onSseClientConnected:p,onChannelSubscribed:R,onChannelUnsubscribed:C}=r;function F(g,b,S,O,x){if(!t.has(b)){o(g,404,{error:`SSE client not connected: ${b}`});return}x?R?.(b,S,O):C?.(b,S,O),o(g,200,{ok:true,clientId:b,channelName:S,...O.cardId?{cardId:O.cardId}:{},subscribed:x});}async function T(g,b,S){let O=t.get(S),x=O?new Set(O.subscribedChatCardIds):new Set;b.writeHead(200,{...s,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),t.flushTransport(b),t.register(S,b,x);let j=await u(),w=t.buildFrame(j);b.write(w);try{p?.(S,L=>{t.writeFrame(S,L);});}catch{}let v=setInterval(()=>{try{b.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);g.on("close",()=>{clearInterval(v),t.disconnect(S,b);});}return {handleChannelSubscription:F,handleSse:T}}async function Xe(r,t,s){let o=s[r];if(!o)throw Object.assign(new Error(`Unknown MCP tool: ${r}`),{statusCode:400});let u=await o(t);if(u&&typeof u=="object"&&!Array.isArray(u)){let p=u,R=p.status;if(R==="success")return Object.prototype.hasOwnProperty.call(p,"data")?u:{status:"success",data:{}};if(R==="fail"||R==="error")return u}return {status:"success",data:u}}function Me(r,t){if(!r||typeof r!="object"||Array.isArray(r))return t;let s=r;if(typeof s.error=="string"&&s.error.trim())return s.error;if(s.step==="validate"){let o=s.validation;if(o&&typeof o=="object"&&!Array.isArray(o)){let p=o.data;if(p&&typeof p=="object"&&!Array.isArray(p)){let R=p.issues;if(Array.isArray(R)){let F=R.find(T=>typeof T=="string"&&T.trim());if(typeof F=="string")return `Validation failed: ${F}`}let C=p.errors;if(Array.isArray(C)&&C.length>0)return "Validation failed"}}return "Validation failed"}return t}function xt(r){let{apiBasePath:t,boardContexts:s,json:o,readJsonBody:u,readRawBody:p,initBoardAndSetup:R,bootstrapBoard:C,buildPublishedRuntimePayload:F,publishPersistedStateSnapshot:T,upsertCardsFromSource:g,applyBoardWorkerCallback:b,handleSse:S,handleChannelSubscription:O,createMcpFacade:x,createMcpToolRegistry:j,createMcpControlplaneToolRegistry:w,readCardFromStore:v,patchCard:L,retriggerCard:d,applyCardAction:l,resolveChatHandlerTarget:i,chatStorePublic:m,chatStorage:A,sseHub:P,uploadCardFile:G,sendCardFileDownloadResponse:ue,resolveCardFileDownloadPayload:fe,isLikelyTextMimeType:ie,sliceTextByLines:be}=r;async function Se(ee,I,Ve){let W=ee.method||"GET",te=Ve,Y=te.pathname;try{if(W==="GET"&&Y===`${t}/init-board`)return await R(),o(I,200,await F()),!0;if(W==="GET"&&Y===`${t}/sse`){await R();let k=String(te.searchParams.get("clientId")||"").trim();if(!k)return o(I,400,{error:"clientId query param is required for SSE"}),!0;await S(ee,I,k);for(let h=0;h<s.length;h++)await T(s[h]),await g(s[h],h),await T(s[h]);return !0}if(W==="GET"&&Y===`${t}/board-status`)return o(I,200,await F()),!0;let we=Y.match(new RegExp(`^${se(t)}/callback/board-worker/([^/]+)/(success|failure)$`));if(W==="POST"&&we){await R();let k=decodeURIComponent(we[1]),h=we[2],M=await u(ee),B=await b(k,h,M);return o(I,B.statusCode,B.body),!0}if(W==="POST"&&Y===`${t}/mcp`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;if(h==="inspect.file-contents")return o(I,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let B=await Xe(h,M,j(x()));if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(I,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(I,500,{error:Me(B,"Internal error")}),!0}o(I,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(I,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-controlplane`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;try{let B=await Xe(h,M,w());if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(I,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(I,500,{error:Me(B,"Internal error")}),!0}o(I,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(I,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-raw`){await C();let k=await u(ee),h=typeof k.tool=="string"?k.tool.trim():"",M=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!h)return o(I,400,{error:"tool is required"}),!0;if(h!=="inspect.file-contents")return o(I,400,{error:`Tool does not support raw response: ${h}`}),!0;let B=z(M,"card_id","cardId"),q=ye(M,"file_idx","fileIdx"),Z=ye(M,"head-lines","headLines"),Q=ye(M,"tail-lines","tailLines"),ne=ye(M,"head-bytes","headBytes"),le=ye(M,"tail-bytes","tailBytes");if(!B)return o(I,400,{error:"inspect.file-contents requires card_id"}),!0;if(q===void 0||!Number.isInteger(q)||q<0)return o(I,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([Z,Q,ne,le].filter(ce=>ce!==void 0).length>1)return o(I,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[ce,ke]of [["head-lines",Z],["tail-lines",Q],["head-bytes",ne],["tail-bytes",le]])if(ke!==void 0&&(!Number.isInteger(ke)||ke<0))return o(I,400,{error:`inspect.file-contents requires ${ce} to be a non-negative integer`}),!0;let Ie=await x().inspectFileContents({cardId:B,fileIdx:q}),$e=typeof Ie?.stored_name=="string"?Ie.stored_name:null,{fileRecord:Fe,bytes:Ae}=await fe(B,q,$e),qe=String(Fe.name||Fe.stored_name||"download.bin"),Te=String(Fe.mime_type||"application/octet-stream"),ve=(te.searchParams.get("resp")||"").trim().toLowerCase();if(ve&&ve!=="json-b64")return o(I,400,{error:`unsupported resp mode: ${ve}`}),!0;let Ne=ve==="json-b64",me;if(Z!==void 0||Q!==void 0){if(!ie(Te))return o(I,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let ce=new TextDecoder().decode(Ae),ke=Z!==void 0?be(ce,"head",Z):be(ce,"tail",Q);me=typeof Buffer<"u"?Buffer.from(ke,"utf8"):new TextEncoder().encode(ke);}else if(ne!==void 0||le!==void 0){let ce=ne??le;me=ne!==void 0?Ae.slice(0,ce):Ae.slice(Math.max(0,Ae.length-ce));}else me=Ae;if(Ne){let ce=typeof Buffer<"u"?Buffer.from(me).toString("base64"):btoa(String.fromCharCode(...me));return o(I,200,{bodyBase64:ce,mimeType:Te,filename:qe,byteLength:me.length}),!0}return I.writeHead(200,{"Content-Type":Te,"Content-Disposition":`attachment; filename="${qe}"`,"Content-Length":me.length}),I.end(me),!0}let Ce=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)$`));if(W==="GET"&&Ce){await C();let k=decodeURIComponent(Ce[1]),h=await v(k);return h?(o(I,200,h),!0):(o(I,404,{error:`card not found: ${k}`}),!0)}if(W==="PATCH"&&Ce){await C();let k=decodeURIComponent(Ce[1]),h=await u(ee);return await L(k,h),o(I,200,{ok:!0}),!0}let je=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/retrigger$`));if(W==="POST"&&je){await C();let k=decodeURIComponent(je[1]);return await d(k),o(I,200,{ok:!0}),!0}let pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/actions$`));if(W==="POST"&&pe){await C();let k=decodeURIComponent(pe[1]),h=Date.now(),M=new Date(h).toISOString(),B=await u(ee),q=B?.actionType;if(q==="chat-send"&&!await i(k)){let Q=Date.now();return o(I,409,{error:`chat handler is not configured for card: ${k}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Q).toISOString(),responseSentAtMs:Q,responseStatus:409}),!0}if(q==="chat-send"){let Q=B?.payload??{},ne=typeof Q["turn-id"]=="string"?Q["turn-id"]:typeof Q.turnId=="string"?Q.turnId:typeof Q.turn=="string"?Q.turn:"";if(!ne||!String(ne).trim()){let le=Date.now();return o(I,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${k}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(le).toISOString(),responseSentAtMs:le,responseStatus:400}),!0}}await l(k,q,B?.payload);let Z=Date.now();return o(I,200,{ok:!0,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Z).toISOString(),responseSentAtMs:Z,responseStatus:200}),!0}let Pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats$`));if(W==="GET"&&Pe){await C();let k=decodeURIComponent(Pe[1]),h=String(te.searchParams.get("turn-id")||""),M=String(te.searchParams.get("all-turns")||"").toLowerCase()==="true",B=String(te.searchParams.get("tail-turns-before-id")||""),q=te.searchParams.get("tail-turns"),Z=q==null||q===""?M||h?void 0:1:Number.parseInt(q,10),Q=m.readAll({params:{cardId:k},body:{...Z===void 0?{}:{tailTurns:Z},...h?{turnId:h}:{},...M?{allTurns:!0}:{},...B?{tailTurnsBeforeId:B}:{}}});if(Q.status!=="success")return o(I,400,{error:Q.error||"Failed to read chats"}),!0;let ne=Q.data.records;return o(I,200,{ok:!0,messages:ne}),!0}if(W==="POST"&&Pe){await C();let k=decodeURIComponent(Pe[1]),h=await u(ee),M=typeof h?.role=="string"?h.role:"assistant",B=typeof h?.text=="string"?h.text:"",q=Array.isArray(h?.files)?h.files:[],Z=typeof h?.turn=="string"?h.turn:typeof h?.["turn-id"]=="string"?h["turn-id"]:typeof h?.turnId=="string"?h.turnId:"",Q=h?.done===!0,ne=A.append(k,M,B,q,Z);return Q&&A.setProcessing(k,!1),P.broadcastCardChats(k,!Q),o(I,200,{ok:!0,id:ne}),!0}let Ee=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(W==="POST"&&Ee){await C();let k=decodeURIComponent(Ee[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.subscribeChat(M,k)?(o(I,200,{ok:!0,clientId:M,cardId:k,subscribed:!0}),!0):(o(I,404,{error:`SSE client not connected: ${M}`}),!0):(o(I,400,{error:"clientId is required"}),!0)}let Le=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(W==="POST"&&Le){await C();let k=decodeURIComponent(Le[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.unsubscribeChat(M,k)?(o(I,200,{ok:!0,clientId:M,cardId:k,subscribed:!1}),!0):(o(I,404,{error:`SSE client not connected: ${M}`}),!0):(o(I,400,{error:"clientId is required"}),!0)}let Re=Y.match(new RegExp(`^${se(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Re){await C();let k=decodeURIComponent(Re[1]),h=Re[2]==="subscribe",M=await u(ee),B=typeof M?.clientId=="string"?M.clientId.trim():"";return B?(O(I,B,k,{},h),!0):(o(I,400,{error:"clientId is required"}),!0)}let Be=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Be){await C();let k=decodeURIComponent(Be[1]),h=decodeURIComponent(Be[2]),M=Be[3]==="subscribe",B=await u(ee),q=typeof B?.clientId=="string"?B.clientId.trim():"";return q?(O(I,q,h,{cardId:k},M),!0):(o(I,400,{error:"clientId is required"}),!0)}let De=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files$`));if(W==="POST"&&De){await C();let k=decodeURIComponent(De[1]),h=String(te.searchParams.get("inChat")||"").toLowerCase()==="true",M=String(te.searchParams.get("turn-id")||"").trim();if(h&&!M)return o(I,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${k}`}),!0;let B=ee.headers["x-file-name"],q=String(ee.headers["content-type"]||"application/octet-stream"),Z=Array.isArray(B)?B[0]:B,Q=Z?decodeURIComponent(String(Z)):"upload.bin",ne=await p(ee);return o(I,200,await G(k,Q,q,ne,{inChat:h,turnId:M})),!0}let Oe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files/(\\d+)$`));if(W==="GET"&&Oe){let k=decodeURIComponent(Oe[1]),h=parseInt(Oe[2],10),M=te.searchParams.get("sn");return await ue(I,k,h,M),!0}return !1}catch(we){let Ce=we?.statusCode||500;return o(I,Ce,{error:String(we?.message||we)}),true}}return {handleRuntimeApi:Se}}function Ye(r,t){return t?{...r,...t.pollIntervalMs!=null?{pollIntervalMs:t.pollIntervalMs}:{},...t.visibilityMs!=null?{visibilityMs:t.visibilityMs}:{},...t.concurrency!=null?{concurrency:t.concurrency}:{},...t.maxAttempts!=null?{maxAttempts:t.maxAttempts}:{}}:r}function _t(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.leaseRequests(u))).map(R=>({id:R.messageId,attempt:R.attempt,message:R.request,ack:()=>Promise.resolve(t.ackRequest(R.messageId,R.leaseToken)),nack:C=>Promise.resolve(t.nackRequest(R.messageId,R.leaseToken,C))}))},async handle(u){await s(u.args,u);},onError:o?(u,p)=>o(u,p.attempt,p.message):void 0}}function Wt(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.lease(u))).map(R=>({id:R.id,attempt:R.attempt,message:R.body,ack:()=>Promise.resolve(t.ack(R.id,R.leaseToken)),nack:C=>Promise.resolve(t.nack(R.id,R.leaseToken,C))}))},async handle(){await s();},onError:o?(u,p)=>o(u,p.attempt):void 0}}function br(r){let t=r.logger??{info(){},warn(){},error(){}},s=r.boardAdapter,o=r.runtime.queueLaneTuning??{},u=s.processAccumulatedStore(),p=s.chatAgentStore(),R=[];if(R.push(Ye(Wt("process-accumulated",u,async()=>{let C=await r.runtime.processAccumulatedLane();if(C.status!=="success")throw new Error(C.error||`processAccumulatedLane returned ${C.status}`)},(C,F)=>{t.error(`[board-server] queued process-accumulated failed for ${r.boardId} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.processAccumulated)),R.push(Ye(_t("chat-agent",p,async(C,F)=>{await r.runtime.handleChatAgentRequest(F);},(C,F,T)=>{let g=typeof T.args?.cardId=="string"?T.args.cardId:"";t.error(`[board-server] queued chat-agent failed for ${r.boardId}${g?`/${g}`:""} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.chatAgent)),r.executeTaskExecutorRequest){let C=s.boardWorkerStore();R.push(Ye(_t("task-executor",C,r.executeTaskExecutorRequest,(F,T)=>{t.error(`[board-server] queued board-worker failed for ${r.boardId} (attempt ${T}): ${String(F&&F.message||F)}`);}),o.taskExecutor));}return f(R)}var Ft={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ot="chat-handler-flow-queue";function Lr(r){let t=String(r.apiBasePath||"/api/board").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.queueLaneTuning??{},u=r.boardId||"",p=r.logger||{info:console.log,warn:console.warn,error:console.error},R=r.invocationAdapter,C=r.chatFlowRunner||null,F=r.chatStorage??b(),T=a(F),g=r.notificationTransport||null,b$2=r.serverUrl||null,S=r.executionExtra||{},O=r.onSseClientConnected,x=r.onSseClientDisconnected,j$1=r.onChannelSubscribed,w=r.onChannelUnsubscribed,v=ht({chatStorage:F,readChatRecords:e=>le(e),onSseClientDisconnected:x});function L(e){function n(y){if(Array.isArray(y))return y;if(y&&typeof y=="object"){let E=y;return Array.isArray(E.files)?E.files:[y]}return null}function a(y){return {async get(E){return y.get(E)},async set(E){return y.set(E)},async del(E){return y.del(E)},async patch(E){return y.patch(E)},async appendFiles(E){return y.appendFiles(E)}}}function f(y){function E(V){return {status:"success",data:V}}function $(V){return {status:"fail",error:V}}function D(V){return {status:"error",error:V instanceof Error?V.message:String(V)}}return {async get(V){try{let U=V.params?.id;if(U){let re=await y.readCard(U);return re?E({cards:[re]}):$(`card "${U}" not found`)}return E({cards:await y.readAllCards()})}catch(U){return D(U)}},async set(V){try{let U=V.body;if(U==null)return $("set requires a body (card object or array of cards)");let re=Array.isArray(U)?U:[U];for(let ae of re){if(typeof ae.id!="string")return $("each card must have a string `id` field");await y.writeCard(ae.id,ae);}return E({count:re.length})}catch(U){return D(U)}},async del(V){try{let U=V.body?.ids??[],re=V.params?.id,ae=re?[...U,re]:U;if(ae.length===0)return $("del requires body.ids (string[]) or params.id");for(let xe of ae)await y.removeCard(xe);return E({count:ae.length})}catch(U){return D(U)}},async patch(V){try{let U=V.params?.id,re=V.params?.path;if(!U)return $("patch requires params.id");if(!re)return $("patch requires params.path");let ae=V.body,xe=ae&&Object.prototype.hasOwnProperty.call(ae,"value")?ae.value:V.body;return await y.patchCard(U,re,xe),E({count:1})}catch(U){return D(U)}},async appendFiles(V){try{let U=V.params?.id;if(!U)return $("appendFiles requires params.id");let re=await y.readCard(U);if(!re)return $(`card "${U}" not found`);let ae=n(V.body);if(!ae||ae.length===0)return $("appendFiles requires a file metadata object, array, or body.files array");let xe=re.card_data&&typeof re.card_data=="object"&&!Array.isArray(re.card_data)?re.card_data:{},nt=Array.isArray(xe.files)?xe.files:[],qt=[...nt,...ae];return await y.patchCard(U,"card_data.files",qt),E({files_added:ae.map((Nt,Ut)=>({idx:nt.length+Ut,entry:Nt}))})}catch(U){return D(U)}}}}let c$2=ge(e.boardAdapter)?j(e.baseRef,e.boardAdapter):y(e.baseRef,e.boardAdapter),_=e.nonCoreAdapter??(!ge(e.boardAdapter)&&m(e.boardAdapter)?e.boardAdapter:null),N=_?z$1(e.baseRef,_):null,K,H=ge(e.boardAdapter)?(()=>{let y=d(c(b$1(e.boardAdapter.kvStorageForRef(e.cardStoreRef)),e.boardAdapter.hashFn),p.warn),E=f(y);return K={get($){return E.get($)},set($){return E.set($)}},E})():(()=>{let y=e.boardAdapter.kvStorageForRef(e.cardStoreRef),$=a$1(l({readIndex:()=>y.read("_index"),writeIndex:D=>y.write("_index",D),readCard:D=>y.read(D),writeCard:(D,V)=>(y.write(D,V),D),removeCard:D=>{y.delete(D);},cardExists:D=>y.read(D)!==null,defaultCardKey:D=>D},p.warn));return K=$,a($)})(),X=e.artifactsAdapter||e.boardAdapter,J=e.filesArtifactsStore??null,oe=J?{putBytes(y,E,$){J.putBytes(y,E,$);},getBytes(y){return J.getBytes(y)},listKeys(y){return J.list(y).map(E=>E.key)}}:null;if(!oe&&!ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files"),E=c$1(y);oe={putBytes($,D,V){E.putBytes($,D,V);},getBytes($){return E.getBytes($)},listKeys($){return E.list($).map(D=>D.key)}};}else if(!oe&&ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files");oe={async putBytes(E,$){if(y.writeBytes){await y.writeBytes(E,$);return}let D=JSON.stringify({__kind:"bytes-array",data:[...$]});await y.write(E,D);},async getBytes(E){if(y.readBytes){let D=await y.readBytes(E);if(D!==null)return D}let $=await y.read(E);if($===null)return null;try{let D=JSON.parse($);if(D&&D.__kind==="bytes-array"&&Array.isArray(D.data))return new Uint8Array(D.data)}catch{}return new TextEncoder().encode($)},async listKeys(E){return await y.listKeys(E)}};}let de={async init(y){return c$2.init(y)},async status(y){return c$2.status(y)},async getConfig(y){return c$2.getConfig(y)},async getAllOutputsDataObjects(y){return c$2.getAllOutputsDataObjects(y)},async getAllOutputsComputedValues(y){return c$2.getAllOutputsComputedValues(y)},async getOutputsFetchedSources(y){return c$2.getOutputsFetchedSources(y)},async upsertCard(y){return c$2.upsertCard(y)},async removeCard(y){return c$2.removeCard(y)},async cardRefreshedNotify(y){return c$2.cardRefreshedNotify(y)},async sourceDataFetched(y){return c$2.sourceDataFetched(y)},async sourceDataFetchFailure(y){return c$2.sourceDataFetchFailure(y)}};return {label:e.label,board:c$2,nonCore:N,publicCardStore:K,boardOps:de,cardStoreOps:H,get filesArtifacts(){return oe},boardAdapter:e.boardAdapter,cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef,artifactsStoreRef:e.artifactsStoreRef,scratchStoreRef:e.scratchStoreRef,archiveStoreRef:e.archiveStoreRef,notifyRef:e.notifyRef,taskExecutorRef:e.taskExecutorRef,chatHandlerRef:e.chatHandlerRef,chatHandlerFlow:e.chatHandlerFlow,inferenceAdapterRef:e.inferenceAdapterRef,notification:wt(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d$1=r.boards.map(L),l$1=new Map;function i(e){return l$1.get(e)??0}function m(e){let n=e;return typeof n.invokeExecutor=="function"&&typeof n.validateSchema=="function"}function A(e){let n=d$1[i(e)];return {files:n?n.filesArtifacts:null}}function P(){return e()}function G(e){return String(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ue(e){if(!e||e.notificationTeardown||!g||!e.notifyRef)return;let n=await g.subscribe(e.notifyRef,a=>{ze(e.notification,a);let f=a.kind==="notification-batch"?a.notifications:[a];v.broadcastNotificationBatch(f);});e.notificationTeardown=n;}async function fe(e){if(!e||e.initialized)return;let n={cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef};e.artifactsStoreRef&&(n.artifactsStoreRef=e.artifactsStoreRef),e.scratchStoreRef&&(n.scratchStoreRef=e.scratchStoreRef),e.archiveStoreRef&&(n.archiveStoreRef=e.archiveStoreRef);let a={};e.taskExecutorRef&&(a["task-executor-ref"]=e.taskExecutorRef),e.chatHandlerFlow!==void 0&&(a["chat-handler-flow"]=e.chatHandlerFlow),e.inferenceAdapterRef&&(a["inference-adapter-ref"]=e.inferenceAdapterRef);let f=await e.boardOps.init({params:n,body:a});if(f.status!=="success")throw Object.assign(new Error(f.error||`init failed for ${e.label}`),{statusCode:500});if(await ue(e),!e.chatHandlerFlow&&e.chatHandlerRef&&R.describe)try{let c=await R.describe(e.chatHandlerRef);c&&c.kind!=="chat-handler"?p.warn(`[init] chat-handler describe returned kind="${c.kind}", expected "chat-handler" for ${e.label}`):c&&p.info(`[init] chat-handler validated: ${c.name} (protocol ${c.protocolVersion}) for ${e.label}`);}catch(c){p.warn(`[init] chat-handler describe failed for ${e.label}: ${c?.message||String(c)}`);}e.initialized=true;}async function ie(e){if(!e.boardAdapter.publishBoardChangeNotifications)return;let n=[],a=await e.boardOps.status({});a.status==="success"&&a.data!=null&&Qe(a.data)&&n.push({kind:"status",status:a.data});let f=await e.boardOps.getAllOutputsDataObjects({});if(f.status==="success"&&f.data!=null)for(let[_,N]of Object.entries(f.data))_&&n.push({kind:"data_object",key:_,payload:N});let c=await e.boardOps.getAllOutputsComputedValues({});if(c.status==="success"&&c.data!=null)for(let[_,N]of Object.entries(c.data))_&&n.push({kind:"computed_values",cardId:_,values:N});n.length>0&&e.boardAdapter.publishBoardChangeNotifications(n);}async function be(e,n){if(!e||e.cardsBootstrapped)return;let a=await e.cardStoreOps.get({}),f=a.status==="success"&&Array.isArray(a.data?.cards)?a.data.cards:[];for(let c of f)typeof c.id=="string"&&(l$1.set(c.id,n),await e.boardOps.upsertCard({params:{cardId:c.id}}));e.cardsBootstrapped=true;}async function Se(){for(let e of d$1)await fe(e);}async function ee(){await Se();for(let e=0;e<d$1.length;e++)await ie(d$1[e]),await be(d$1[e],e),await ie(d$1[e]);}async function I(e=false){e||await Se();for(let n of d$1){let a=await n.board.processAccumulatedEvents({});if(a.status!=="success")return a}return {status:"success"}}async function Ve(){return await Se(),I(true)}function W(e){return d$1[i(e)]??null}async function te(e){let n=W(e);if(!n)return null;let a=await n.cardStoreOps.get({params:{id:e}});if(a.status!=="success")return null;let f=Array.isArray(a.data?.cards)?a.data.cards:[];return f.length>0?f[0]:null}async function Y(){let e=async a=>{if(!a)return [];let f=await a.cardStoreOps.get({});return f.status!=="success"||!Array.isArray(f.data?.cards)?[]:f.data.cards},n=[];for(let a of d$1)n.push(...await e(a));return n}function we(){return d$1[0]??null}let Ce=Bt({boardContexts:d$1,cardOwnerIndex:l$1,cardContextForCard:e=>W(e),readStatusSnapshot:()=>Be(),readDataObjectsByToken:()=>Oe(),readCardRuntimeArtifacts:()=>De(),readCardFromStore:e=>te(e),readCardDefinitions:()=>Y(),processAccumulatedLaneInternal:e=>I(e),uploadCardFile:(e,n,a,f,c)=>Ie(e,n,a,f,c),chatStorePublic:T,serverUrl:b$2,apiBasePath:t}),je=Ce.mcpCardStoreFacade,pe=Ce.createMcpFacade,Pe=kt({boardId:u,getMcpFacade:()=>pe(),getMcpCardStoreFacade:()=>je()});function Ee(e){return vt(e)}function Le(){return Pt({boardId:u,uploadCardFile:Ie,getMcpFacade:()=>pe(),controlplane:Pe})}let Re=St({boardId:u,boardContexts:d$1,readCardDefinitions:()=>Y(),readChatRecords:e=>le(e),getChatProcessing:e=>pe().getChatProcessing({cardId:e}).active}),Be=Re.readStatusSnapshot,De=Re.readCardRuntimeArtifacts,Oe=Re.readDataObjectsByToken,k=Re.buildPublishedRuntimePayload;async function h(e,n,a){let f=a?.syncBoard!==false,c=a?.restartOnlyIfChanged===true,_=W(e);if(!_)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let N=await te(e);if(!N)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let K=c?JSON.stringify(N):null,H=n(N)||N;if(c&&JSON.stringify(H)===K)return;let X=await _.cardStoreOps.set({body:H});if(X.status!=="success")throw Object.assign(new Error(X.error||`Failed to persist card: ${e}`),{statusCode:500});if(f){let J=await _.boardOps.upsertCard({params:{cardId:e,restart:true}});if(J.status!=="success")throw Object.assign(new Error(J.error||`Failed to upsert card: ${e}`),{statusCode:500})}}async function M(e,n){await h(e,n,{syncBoard:true});}async function B(e,n){await h(e,n,{syncBoard:false});}async function q(e){let n=W(e);if(!n)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});if(!await te(e))throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let f=await n.boardOps.upsertCard({params:{cardId:e,restart:true}});if(f.status!=="success")throw Object.assign(new Error(f.error||`Failed to retrigger card: ${e}`),{statusCode:500})}async function Z(e,n){await h(e,a=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return a;function f(c,_,N){let K=String(_||"").split(".").filter(Boolean);if(!K.length)return;let H=c;for(let X=0;X<K.length-1;X++){let J=K[X];(!H[J]||typeof H[J]!="object")&&(H[J]={}),H=H[J];}H[K[K.length-1]]=N;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let c=null,_=a.view;if(_&&Array.isArray(_.elements)){for(let N of _.elements)if(N?.data&&N.data.writeTo){c=N.data.writeTo;break}}c?f(a,c,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(a.card_data={...a.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return a;for(let[c,_]of Object.entries(n))c!=="_stagedFiles"&&(_!==null&&typeof _=="object"&&!Array.isArray(_)&&a[c]!==null&&typeof a[c]=="object"&&!Array.isArray(a[c])?a[c]={...a[c],..._}:a[c]=_);}return a},{syncBoard:true,restartOnlyIfChanged:true});}function Q(e){F.clear(e);try{pe().setChatProcessing({cardId:e,active:!1});}catch{}}function ne(e,n,a,f,c=""){let _=typeof a=="string"?a.trim():"";return F.append(e,n||"system",_,f,c)}function le(e){return F.readAll(e)}let Ie=At({safeCardId:e=>G(e),artifactsStores:e=>A(e),cardFileMetadataStore:()=>P(),readCardFromStore:e=>te(e),updateCardLocalOnly:(e,n)=>B(e,n),writeChatRecord:(e,n,a,f,c)=>ne(e,n,a,f,c)}).uploadCardFile;async function $e(e){let n=W(e);if(!n)return null;let a=await n.boardOps.getConfig({params:{key:"chat-handler-flow"}}),f=a.status==="success"?a.data?.value:null,c=n.chatHandlerRef;return f==null&&(!c||typeof c!="object")?null:{ctx:n,handlerFlow:f,handlerRef:c}}async function Fe(e,n,a=false,f=""){let c=await $e(e);if(!c)return;let{ctx:_,handlerFlow:N,handlerRef:K}=c;if(!a)try{pe().setChatProcessing({cardId:e,active:!0});}catch{}let H={boardId:u,cardId:String(e),lastChatEntryId:n,...f?{turnId:f}:{},...S,...b$2?{serverUrl:b$2}:{}},X=N!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:Ot}}:K;try{ge(_.boardAdapter)?await _.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}):_.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}),await Promise.resolve(_.boardAdapter.requestProcessAccumulated?.());}catch(J){try{pe().setChatProcessing({cardId:e,active:!1});}catch{}p.warn(`[chat-handler] queue failed for card "${e}": ${J instanceof Error?J.message:String(J)}`);}}async function Ae(e,n,a){if(n.howToRun==="built-in"&&Ct(n)===Ot){let f=C,c=a.__chatHandlerFlow,_={...a};return delete _.__chatHandlerFlow,f?f.run(c,_,{boardId:u,cardId:String(_.cardId||""),label:e.label,logger:p,serverUrl:b$2,executionExtra:S}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return R.invoke(n,a)}async function qe(e,n=false){n||await Se();let a=typeof e.args?.cardId=="string"?e.args.cardId:"",f=a?W(a):we();if(!f)throw new Error(a?`Board context is unavailable for chat-agent request: ${a}`:"Board context is unavailable for chat-agent request");let c=await Ae(f,e.ref,e.args);if(!c.dispatched){if(a)try{F.setProcessing(a,!1);}catch{}throw new Error(c.error||`chat-agent dispatch failed for card "${a||"unknown"}"`)}}async function Te(e,n,a){let f=n==="chat-send"?B:M,c;await f(e,_=>{let N=new Date().toISOString(),K=_.card_data&&typeof _.card_data=="object"?_.card_data:{};if(_.card_data=K,n==="chat-send"){let H=a&&typeof a.text=="string"?a.text.trim():"",X=a&&typeof a["turn-id"]=="string"?a["turn-id"]:a&&typeof a.turnId=="string"?a.turnId:a&&typeof a.turn=="string"?a.turn:"",J=[];if(Array.isArray(a?.files)){for(let oe of a.files)if(oe){if(typeof oe=="string"){J.push({name:oe});continue}if(typeof oe=="object"){let de=oe;typeof de.name=="string"&&J.push({name:de.name,size:de.size,mime_type:de.mime_type,uploaded_at:de.uploaded_at,stored_name:de.stored_name,chat:de.chat===true});}}}if(H||J.length>0){let oe=T.runBatch({cardId:e,commands:[{command:"append",role:"user",text:H,files:J,turn:X},{command:"set-processing",active:true}]});if(oe.status!=="success")throw new Error(oe.error);let de=oe.data.results[0]?.data?.id;if(typeof de!="string"||!de)throw new Error(`chat-send did not return an append id for card ${e}`);c={cardId:e,lastEntryId:de,processingAlreadySet:true,turnId:X};try{let $=le(e);v.broadcastNotificationBatch([{kind:"card_chats",cardId:e,messages:$.map(D=>({role:String(D.role||"system"),text:String(D.text||""),files:Array.isArray(D.files)?D.files:[]})),receiving:!0,processing:F.isProcessing(e)}]);}catch{}}return _}if(n==="file-upload"){let H=P().normalizeIncoming(a?.files,N);return H.length>0&&P().merge(K,H),_}if(n==="action"){let H=a&&typeof a.buttonId=="string"?a.buttonId:"";if(!H)return _;K.lastAction={buttonId:H,at:N},K.lastActionText=`${H} @ ${N}`;}return _}),c&&Fe(c.cardId,c.lastEntryId,c.processingAlreadySet,c.turnId??"");}function ve(e,n,a){let f=JSON.stringify(a),c=typeof Buffer<"u"?Buffer.byteLength(f):new TextEncoder().encode(f).length;e.writeHead(n,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":c}),e.end(f);}async function Ne(e,n,a){let f=await te(e);if(!f)throw Object.assign(new Error("Card not found"),{statusCode:404});let c=P().resolve(f.card_data,n,a);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 _=c.file,N=G(e),K=A(e),H=String(_.stored_name||""),X=`${N}/${H}`,J=K.files?await K.files.getBytes(X):null;if(!J)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:_,bytes:J}}async function me(e,n,a,f){let{fileRecord:c,bytes:_}=await Ne(n,a,f),N=String(c.name||c.stored_name||"download.bin"),K=String(c.mime_type||"application/octet-stream");e.writeHead(200,{"Content-Type":K,"Content-Disposition":`attachment; filename="${N}"`,"Content-Length":_.length}),e.end(_);}function ce(e){let n=String(e||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function ke(e,n,a){let f=e.split(/\r?\n/);return (n==="head"?f.slice(0,a):f.slice(-a)).join(`
|
|
7
|
+
`)}async function Mt(e){let n=[];for await(let f of e)n.push(f);let a=typeof Buffer<"u"?Buffer.concat(n).toString("utf-8").trim():new TextDecoder().decode(He(n)).trim();return a?JSON.parse(a):{}}async function jt(e){let n=[];for await(let a of e)n.push(a);return typeof Buffer<"u"?Buffer.concat(n):He(n)}async function et(e,n){let a=typeof n.ref=="string"?n.ref.trim():"";if(!a)return {status:"fail",error:"board-worker success callback requires body.ref"};let f=d$1[0];return f?f.boardOps.sourceDataFetched({params:{token:e,ref:a}}):{status:"fail",error:"no board context"}}async function tt(e,n){let a=typeof n.reason=="string"&&n.reason.trim()?n.reason:"unknown",f=d$1[0];return f?f.boardOps.sourceDataFetchFailure({params:{token:e,reason:a}}):{status:"fail",error:"no board context"}}async function Et(e,n,a){let f=String(e||"").trim();if(!f)return {statusCode:400,body:{error:"callback token is required"}};let c=n==="success"?await et(f,a):await tt(f,a);return c.status==="success"?{statusCode:200,body:c}:c.status==="fail"?{statusCode:400,body:{error:c.error}}:{statusCode:500,body:{error:c.error}}}let rt=It({sseHub:v,corsHeaders:s,json:ve,buildPublishedRuntimePayload:()=>k(),onSseClientConnected:O,onChannelSubscribed:j$1,onChannelUnsubscribed:w}),Lt=rt.handleChannelSubscription,Dt=rt.handleSse,$t=xt({apiBasePath:t,boardContexts:d$1,json:ve,readJsonBody:e=>Mt(e),readRawBody:e=>jt(e),initBoardAndSetup:()=>Se(),bootstrapBoard:()=>ee(),buildPublishedRuntimePayload:()=>k(),publishPersistedStateSnapshot:e=>ie(e),upsertCardsFromSource:(e,n)=>be(e,n),applyBoardWorkerCallback:(e,n,a)=>Et(e,n,a),handleSse:(e,n,a)=>Dt(e,n,a),handleChannelSubscription:(e,n,a,f,c)=>Lt(e,n,a,f,c),createMcpFacade:()=>pe(),createMcpToolRegistry:e=>Ee(e),createMcpControlplaneToolRegistry:()=>Le(),readCardFromStore:e=>te(e),patchCard:(e,n)=>Z(e,n),retriggerCard:e=>q(e),applyCardAction:(e,n,a)=>Te(e,n,a),resolveChatHandlerTarget:e=>$e(e),chatStorePublic:T,chatStorage:{append:(e,n,a,f,c)=>F.append(e,n,a,f,c),setProcessing:(e,n)=>F.setProcessing(e,n)},sseHub:v,uploadCardFile:(e,n,a,f,c)=>Ie(e,n,a,f,c),sendCardFileDownloadResponse:(e,n,a,f)=>me(e,n,a,f),resolveCardFileDownloadPayload:(e,n,a)=>Ne(e,n,a),isLikelyTextMimeType:e=>ce(e),sliceTextByLines:(e,n,a)=>ke(e,n,a)}).handleRuntimeApi;return {get apiBasePath(){return t},get corsHeaders(){return s},get queueLaneTuning(){return o},handleRuntimeApi:$t,buildPublishedRuntimePayload:k,processAccumulatedEvents:Ve,processAccumulatedLane:I,handleChatAgentRequest:qe,clearChatRecords:Q,reportSourceFetched(e,n){return et(e,{ref:n})},reportSourceFetchFailure(e,n){return tt(e,{reason:n})},get cardStore(){return d$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Dr(r){let t=String(r.apiBasePath||"/api/boards").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.serverMetaStore,u=r.boardRuntimeFactory,p=new Map,R="boards-config.json";function C(){let w=o.getText(R);if(!w)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(w)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function F(w){o.putText(R,JSON.stringify(w,null,2));}function T(w){let v=String(w||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return v.length>0&&v.length<=64?v:null}function g(w){if(p.has(w))return p.get(w);let L=C().boards.find(l=>l.id===w)||{},d=u(w,L);return p.set(w,d),d}function b(w,v,L){let d=JSON.stringify(L),l=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;w.writeHead(v,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":l}),w.end(d);}async function S(w,v,L){let d=w.method||"GET",l=L.pathname;if(d==="GET"&&l===t)return b(v,200,{ok:true,boards:C().boards}),true;if(d==="POST"&&l===t){let i=[];for await(let ie of w)i.push(ie);let m=typeof Buffer<"u"?Buffer.concat(i).toString("utf-8").trim():new TextDecoder().decode(He(i)).trim(),A={};try{A=m?JSON.parse(m):{};}catch{A={};}let P=T(A.id);if(!P)return b(v,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let G=C();if(G.boards.some(ie=>ie.id===P))return b(v,409,{error:`Board "${P}" is already registered`}),true;let ue=typeof A.label=="string"&&A.label.trim()?A.label.trim():P,fe={id:P,label:ue};for(let[ie,be]of Object.entries(A))ie==="id"||ie==="label"||be!=null&&(fe[ie]=be);return G.boards.push(fe),F(G),b(v,200,{ok:true,board:fe}),true}return false}async function O(w,v,L){let l=L.pathname.match(new RegExp(`^${se(t)}/([^/]+)(/|$)`));if(!l)return false;let i=T(decodeURIComponent(l[1]));return i?C().boards.some(P=>P.id===i)?!!await g(i).handleRuntimeApi(w,v,L):(b(v,404,{error:`Board "${i}" not registered. POST ${t} with {id} to register it first.`}),true):(b(v,400,{error:"Invalid board id"}),true)}async function x(w,v,L){return !!(await S(w,v,L)||await O(w,v,L))}function j(w){if(!C().boards.some(L=>L.id===w))throw Object.assign(new Error(`Board "${w}" not registered`),{statusCode:404});return {service:g(w)}}return {get apiBasePath(){return t},get corsHeaders(){return s},handleApi:x,requireBoardService:j}}export{br as a,Lr as b,Dr as c};//# sourceMappingURL=chunk-LRVAVWAG.js.map
|
|
8
|
+
//# sourceMappingURL=chunk-LRVAVWAG.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function p(t){return String(t).replace(/[^a-zA-Z0-9_-]/g,"_")}function m(t){let n=t.payload??{};return {id:t.id,role:typeof n.role=="string"?n.role:"system",text:typeof n.text=="string"?n.text:"",files:Array.isArray(n.files)?n.files:[],turn:typeof n.turn=="string"?n.turn:"",updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function T(t,n){let i=e=>`chats/${p(e)}/processing`,r=e=>`chats/${p(e)}/config`;return {append(e,a,o,u=[],s=""){return t(e).append({role:a,text:o,files:u,turn:s,updated_at:new Date().toISOString()}).id},readAll(e){return t(e).readAll().map(m)},readAfter(e,a){let o=t(e).readAfter(a);return {records:o.entries.map(m),cursor:o.newCursor}},clear(e){t(e).clear?.();},setProcessing(e,a){a?n.write(i(e),true):n.delete(i(e));},isProcessing(e){return n.read(i(e))===true},getConfig(e){return n.read(r(e))??{}},setConfig(e,a){let o=n.read(r(e))??{};n.write(r(e),{...o,...a});}}}function _(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?String(t.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function z(){let t=new Map,n=new Map;function i(r){return t.has(r)||t.set(r,[]),t.get(r)}return {append(r,e,a,o=[],u=""){let s={id:_(),role:e,text:a,files:o,turn:u,updated_at:new Date().toISOString()};return i(r).push(s),s.id},readAll(r){return i(r).slice()},readAfter(r,e){let a=i(r);if(!e)return {records:a.slice(),cursor:a.length>0?a[a.length-1].id:null};let o=a.findIndex(s=>s.id===e),u=o===-1?a.slice():a.slice(o+1);return {records:u,cursor:u.length>0?u[u.length-1].id:e}},clear(r){t.set(r,[]);},setProcessing(r,e){e?n.set(`p:${r}`,true):n.delete(`p:${r}`);},isProcessing(r){return n.get(`p:${r}`)===true},getConfig(r){return n.get(`c:${r}`)??{}},setConfig(r,e){let a=n.get(`c:${r}`)??{};n.set(`c:${r}`,{...a,...e});}}}function y(){return new Date().toISOString()}function x(t){return new TextEncoder().encode(t).byteLength}function S(t){return t?{key:t.key,size:t.size,updatedAt:t.updatedAt,contentType:t.contentType}:null}function w(t){let n=String(t||"").match(/^(\d+)[-_]/);return n?parseInt(n[1],10):0}function L(t){let n=String(t||"").trim();if(!n)return "upload.bin";let i=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (i>=0?n.slice(i+1):n)||"upload.bin"}function b(t){return String(t||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function I(t){if(!t||t===".")return "";let n=String(t).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return n?`.${n}`:""}function k(t){let n=L(t),i=n.lastIndexOf(".");return i<=0||i===n.length-1?{stem:n,ext:""}:{stem:n.slice(0,i),ext:n.slice(i)}}function M(t){let n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function F(t){function n(i){let r=t.stat?S(t.stat(i)):null;if(r)return r;if(!t.exists(i))return null;let e=t.read(i);return e===null?{key:i}:{key:i,size:x(e)}}return {exists(i){return t.exists(i)},putText(i,r,e="text/plain; charset=utf-8"){t.write(i,r);let a=n(i)??{key:i};return a.contentType=e,a.updatedAt=a.updatedAt??y(),a.size=a.size??x(r),a},putBytes(i,r,e="application/octet-stream"){if(t.writeBytes)t.writeBytes(i,r);else {let o=JSON.stringify({__kind:"bytes-array",data:[...r]});t.write(i,o);}let a=n(i)??{key:i};return a.contentType=e,a.updatedAt=a.updatedAt??y(),a.size=a.size??r.byteLength,a},getText(i){let r=t.read(i);if(r===null){if(!t.readBytes)return null;let e=t.readBytes(i);return e===null?null:Buffer.from(e).toString("utf-8")}try{let e=JSON.parse(r);if(e&&e.__kind==="bytes-array"&&Array.isArray(e.data))return new TextDecoder("utf-8").decode(new Uint8Array(e.data))}catch{}return r},getBytes(i){if(t.readBytes){let e=t.readBytes(i);if(e!==null)return e}let r=t.read(i);if(r===null)return null;try{let e=JSON.parse(r);if(e&&e.__kind==="bytes-array"&&Array.isArray(e.data))return new Uint8Array(e.data)}catch{}return new TextEncoder().encode(r)},head:n,list(i=""){return t.listKeys(i).map(r=>n(r)??{key:r}).sort((r,e)=>r.key.localeCompare(e.key))},remove(i){t.remove(i);}}}function $(t){function n(e,a){let o=0,u=[];Array.isArray(a)&&u.push(...a);for(let s of t.list(`${e}/`))u.push(M(s.key));for(let s of u){let l=w(s);Number.isFinite(l)&&l>o&&(o=l);}return o+1}function i(e,a,o){let u=Number(o?.maxLen||32),{stem:s,ext:l}=k(e),h=I(l),A=b(s),g=`${String(a).padStart(3,"0")}-`,d=h,f=u-g.length-d.length;f<1&&(d="",f=u-g.length);let C=A.slice(0,Math.max(1,f)),c=`${g}${C}${d}`;return c.length>u&&(c=c.slice(0,u).replace(/\.$/,"")),c}function r(e,a,o){let u=n(e,o?.seedNames),s=i(a,u,{maxLen:o?.maxLen});for(;t.exists(`${e}/${s}`);)u+=1,s=i(a,u,{maxLen:o?.maxLen});return s}return {nextSerial:n,buildStoredName:i,allocateStoredName:r}}function B(){function t(e,a){if(!Array.isArray(e))return [];let o=[];for(let u of e){if(!u||typeof u!="object")continue;let s=u;typeof s.stored_name=="string"&&o.push({name:typeof s.name=="string"?s.name:s.stored_name,stored_name:s.stored_name,size:typeof s.size=="number"&&Number.isFinite(s.size)?s.size:null,mime_type:typeof s.mime_type=="string"?s.mime_type:null,uploaded_at:typeof s.uploaded_at=="string"?s.uploaded_at:a||null,chat:s.chat===true});}return o}function n(e){return !e||typeof e!="object"?[]:t(e.files,void 0)}function i(e,a){let o=n(e);if(a.length===0)return e.files=o,o;let u=new Set(o.map(s=>s.stored_name));for(let s of a)u.has(s.stored_name)||(o.push(s),u.add(s.stored_name));return e.files=o,o}function r(e,a,o){let u=n(e);if(!Number.isInteger(a)||a<0||a>=u.length)return {ok:false,reason:"index_out_of_range"};let s=u[a];return !s||!s.stored_name?{ok:false,reason:"missing_stored_name"}:o&&o!==s.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:s}}return {read:n,normalizeIncoming:t,merge:i,resolve:r}}function Q(t){return {lanes:t}}export{T as a,z as b,F as c,$ as d,B as e,Q as f};//# sourceMappingURL=chunk-MLVTJASJ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-MLVTJASJ.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {b as b$1,c as c$1}from'./chunk-XQRNDX4Q.js';import {a,b,c}from'./chunk-BQS3EIEK.js';import {r,a as a$1,p,q,u}from'./chunk-VGT3TRQG.js';import {a as a$3}from'./chunk-JMDHDY6M.js';import {a as a$2}from'./chunk-KBELAKIY.js';function et(e){return typeof e=="string"&&e.trim().length>0}function tt(e,t){if(!e||typeof e!="object")throw new Error(`${t}: adapter.selfRef is required`);if(!et(e.howToRun))throw new Error(`${t}: adapter.selfRef.howToRun is required`);if(!et(e.whatToRun))throw new Error(`${t}: adapter.selfRef.whatToRun is required`)}function rt(e,t){if(!e||typeof e!="object")throw new Error(`${t}: adapter.callbackTransport is required`);if(typeof e.createCallback!="function")throw new Error(`${t}: adapter.callbackTransport.createCallback is required`)}function jt(e,t="callbackTransport"){return {createCallback(n){let o=e();return tt(o,t),{token:n,via:o}}}}function Ve(e){return jt(()=>e,"createStaticExecutionRefCallbackTransport")}function Qt(e){return Ve({meta:"board-live-cards",howToRun:"http:post",whatToRun:a({kind:"http-url",value:String(e||"").trim()})})}function Zt(e){return Ve({meta:"board-live-cards",howToRun:"in-process-loop",whatToRun:a({kind:"in-process-loop",value:String(e||"").trim()})})}function er(e){return Ve({meta:"board-live-cards",howToRun:"local-node",whatToRun:a({kind:"yaml-flow-cli",value:"board-live-cards-cli.js"}),...e?{extra:{notifyChannel:e}}:{}})}function we(e){return typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"}function qe(e,t){return we(e)?e.then(t):t(e)}function ot(e,t){let n={...e};for(let o of t.deleteKeys)delete n[o];return {...n,...t.shallowMerge}}function rr(e,t){return {readValues(o){let i=e(o);return qe(i.listKeys(),u=>{let c=[...u].sort();if(c.length===0)return {version:null,values:{}};let f={},S=null;for(let y of c){let P=i.read(y);we(P)?S=(S??Promise.resolve()).then(async()=>{f[y]=await P;}):f[y]=P;}return S?S.then(()=>({version:t(f),values:f})):{version:t(f),values:f}})},writeValues(o,i,u){let c=e(o),f=null;for(let S of u){let y=c.delete(S);we(y)&&(f=(f??Promise.resolve()).then(()=>y).then(()=>{}));}for(let[S,y]of Object.entries(i)){let P=c.write(S,y);we(P)&&(f=(f??Promise.resolve()).then(()=>P).then(()=>{}));}return f?f.then(()=>t(i)):t(i)}}}function st(e,t){return {readSnapshot(n){return e.readValues(n)},commitSnapshot(n,o){if(o.schemaVersion!==t)throw new Error(`Unsupported snapshot schema version: ${o.schemaVersion}`);return qe(e.readValues(n),i=>{if(i.version!==o.expectedVersion)return {ok:false,reason:"version-mismatch",currentVersion:i.version};let u=ot(i.values,o);return qe(e.writeValues(n,u,o.deleteKeys),c=>({ok:true,newVersion:c}))})}}}function nt(e,t){if(!t)return e;let n=e.findIndex(o=>o.id===t);return n===-1?e:e.slice(n+1)}function at(e){return {readEntriesAfterCursor(t){let n=nt(e.readAllEntries(),t);return n.length===0?{events:[],newCursor:t}:{events:n.map(o=>o.event),newCursor:n[n.length-1].id}},pendingCount(t){return nt(e.readAllEntries(),t).length},appendEvent(t){e.appendEntry({id:e.generateId(),event:t});}}}function nr(e){return {appendEvent(t){return e.append(t).then(()=>{})},async readEntriesAfterCursor(t){let n=await e.readAfter(t||null);return {events:n.entries.map(o=>o.payload),newCursor:n.newCursor??t}}}}function xe(e){return typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"}function G(e,t){return xe(e)?e.then(t):t(e)}function Be(e,t){let n=null;for(let o of e){if(n){n=n.then(()=>t(o)).then(()=>{});continue}let i=t(o);xe(i)&&(n=Promise.resolve(i).then(()=>{}));}return n??void 0}function Kt(e){if(e==null)return null;let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Dt(e,t){let n=e.match(t);return n?n[1]:null}function it(e,t,n){let o={},i=Be(e,u=>{let c=n(u);if(c)return G(t(u),f=>{o[c]=f;})});return xe(i)?i.then(()=>o):o}function ut(e,t){let n=o=>G(e.read(o),i=>i??(e.keyRef?G(e.keyRef(o),u=>u?G(t(u),c=>c??null):null):null));return {readSourceData(o,i){return G(e.read(`${o}/${i}`),Kt)},ingestSourceDataStaged(o,i,u,c){return G(t(u),f=>e.write(`${o}/.staged/${c}/${i}`,f))},commitSourceData(o,i,u){let c=`${o}/.staged/${u}/${i}`;return G(n(c),f=>f==null?false:G(e.write(`${o}/${i}`,f),()=>G(e.remove(c),()=>true)))},hasSource(o,i){return e.exists(`${o}/${i}`)},listSources(o){return G(e.listKeys(`${o}/`),i=>i.filter(u=>!u.includes("/.staged/")).map(u=>u.slice(`${o}/`.length)))}}}function dt(e,t){let n=(o,i)=>{try{let u=i(o);return xe(u)?u.catch(c=>t(o,c instanceof Error?c.message:String(c))):void 0}catch(u){try{return t(o,u instanceof Error?u.message:String(u))}catch{return}}};return {appendEntries(o,i){if(!(!o||i.length===0))return G(e.read(o),u=>e.write(o,[...u??[],...i]))},dispatchEntriesForJournalId(o,i){if(o)return G(e.read(o),u=>{let c=u;if(!(!c||c.length===0))return G(Be(c,f=>n(f,i)),()=>e.delete(o))})}}}function ct(e,t,n){return {readRuntime(o){return G(e.read(t(o)),i=>i??n())},writeRuntime(o,i){return e.write(t(o),i)}}}function lt(e){return {writeComputedValues(t,n){return e.write(`cards/${t}/computed_values`,n)},readComputedValues(t){return e.read(`cards/${t}/computed_values`)},readAllComputedValues(){return G(e.listKeys("cards/"),t=>it(t,n=>e.read(n),n=>Dt(n,/^cards\/([^/]+)\/computed_values$/)))},writeDataObjects(t){return Be(Object.entries(t),([n,o])=>{if(n)return e.write(`data-objects/${n}`,o)})},readDataObject(t){return e.read(`data-objects/${t}`)},readAllDataObjects(){return G(e.listKeys("data-objects/"),t=>it(t,n=>e.read(n),n=>n.slice(13)))},writeStatusSnapshot(t){return e.write("status",t)},readStatusSnapshot(){return e.read("status")}}}function je(e,t){function n(){return e.readIndex()??{}}function o(i,u,c){let f=String(u||"").split(".").filter(Boolean);if(f.length===0)return c&&typeof c=="object"&&!Array.isArray(c)?c:{value:c};let S={...i},y=S;for(let P=0;P<f.length-1;P++){let L=f[P],j=y[L],Y=j&&typeof j=="object"&&!Array.isArray(j)?{...j}:{};y[L]=Y,y=Y;}return y[f[f.length-1]]=c,S}return {readCard(i){let u=n()[i];return !u||!e.cardExists(u.key)?null:e.readCard(u.key)},readCardKey(i){return n()[i]?.key??null},readAllCards(){let i=[];for(let[u,c]of Object.entries(n())){if(!e.cardExists(c.key))continue;let f=e.readCard(c.key);f?i.push(f):t?.(`[card-store] could not read card "${u}" at key "${c.key}"`);}return i},readChecksumIndex(){let i={};for(let[u,c]of Object.entries(n()))i[u]=c.checksum;return i},changedSince(i){let u=n(),c=[];for(let[f,S]of Object.entries(u))i[f]!==S.checksum&&c.push(f);for(let f of Object.keys(i))u[f]||c.push(f);return c},validateUpsert(i,u){let c=n(),f=c[i],S=Object.entries(c).find(([,y])=>y.key===u);return f&&f.key!==u?{ok:false,error:`Card id "${i}" is already mapped to key "${f.key}", cannot remap to "${u}"`}:S&&S[0]!==i?{ok:false,error:`Key "${u}" is already mapped to card id "${S[0]}", cannot remap to "${i}"`}:{ok:true}},writeCard(i,u,c){let f=n(),S=c??f[i]?.key??e.defaultCardKey(i),y=e.writeCard(S,u);f[i]={key:S,checksum:y,updatedAt:new Date().toISOString()},e.writeIndex(f);},patchCard(i,u,c){let f=n(),S=f[i];if(!S||!e.cardExists(S.key))throw new Error(`card "${i}" not found`);let y=e.readCard(S.key);if(!y||typeof y!="object"||Array.isArray(y))throw new Error(`card "${i}" is not patchable`);let P=o(y,u,c),L=e.writeCard(S.key,P);f[i]={key:S.key,checksum:L,updatedAt:new Date().toISOString()},e.writeIndex(f);},removeCard(i){let u=n(),c=u[i];c&&(e.removeCard(c.key),delete u[i],e.writeIndex(u));},readIndex(){return n()}}}function Te(e,t){return ut(e,t)}function gt(e){return at(e)}function kt(e,t){return dt(e,t)}var Ee="v1",le="board/graph",St="board/lastJournalProcessedId";function Lt(e){return `cards/${e}/runtime`}function ht(e){return ct(e,Lt,()=>({_sources:{}}))}function yt(e){return st(e,Ee)}function Ke(e){function t(n){let o=e.read(n);return o==null?null:typeof o=="string"?o:JSON.stringify(o)}return {readTaskExecutorRef(){let n=t("task-executor");if(n?.trim())return c$1(n.trim())},writeTaskExecutorRef(n){e.write("task-executor",b$1(n));},readChatHandlerFlow(){return e.read("chat-handler-flow")},writeChatHandlerFlow(n){e.write("chat-handler-flow",n);},readCardStoreRef(){return t("card-store-ref")},writeCardStoreRef(n){e.write("card-store-ref",n);},readOutputsStoreRef(){return t("outputs-store-ref")},writeOutputsStoreRef(n){e.write("outputs-store-ref",n);},readScratchStoreRef(){return t("scratch-store-ref")},writeScratchStoreRef(n){e.write("scratch-store-ref",n);},readArchiveStoreRef(){return t("archive-store-ref")},writeArchiveStoreRef(n){e.write("archive-store-ref",n);},readChatStoreRef(){return t("chat-store-ref")},writeChatStoreRef(n){e.write("chat-store-ref",n);},readArtifactsStoreRef(){return t("artifacts-store-ref")},writeArtifactsStoreRef(n){e.write("artifacts-store-ref",n);}}}function Ct(e){return lt(e)}function pt(e){return e?{lastRequestedToken:e.lastRequestedToken,lastCompletedToken:e.lastCompletedToken,lastCompletionStatus:e.lastCompletionStatus??(e.lastCompletedToken?"success":"not-started"),queueRequestedToken:e.queueRequestedToken}:{lastCompletionStatus:"not-started"}}function Nt(e){return e?.lastRequestedToken?e.lastCompletedToken!==e.lastRequestedToken:false}function ft(e,t){return e?.lastRequestedToken?Nt(e)?"in-flight":!e.lastCompletedToken||e.lastCompletedToken<t?"dispatch":"idle":"dispatch"}function $t(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"success"}}function mt(e,t){return {...e,lastCompletedToken:t,lastCompletionStatus:"failure"}}function Ae(e,t){let n=t.state.tasks,o=t.config.tasks,i=Object.keys(n),u=r(t),c={completed:0,failed:0,in_progress:0,pending:0,blocked:0,unresolved:0},f=new Map;for(let v of u.pending)f.set(v.taskName,v.waitingOn);for(let v of u.unresolved)f.set(v.taskName,v.missingTokens);for(let v of u.blocked)f.set(v.taskName,v.failedTokens);let S=new Map;for(let[v,l]of Object.entries(o))for(let a of l.requires??[]){let d=S.get(a)??[];d.push(v),S.set(a,d);}let y=i.sort().map(v=>{let l=n[v],a=o[v]??{requires:[],provides:[]};l.status==="completed"?c.completed+=1:l.status==="failed"?c.failed+=1:l.status==="in-progress"&&(c.in_progress+=1);let d=a.requires??[],C=a.provides??[],A=Object.keys(l.data??{}).sort(),E=d.filter(M=>t.state.availableOutputs.includes(M)),_=d.filter(M=>!t.state.availableOutputs.includes(M)),F=f.get(v)??_,V=new Set;for(let M of C)for(let $ of S.get(M)??[])$!==v&&V.add($);let N=l.failedAt,D=l.error?{message:l.error,code:"TASK_FAILED",at:N,source:"task-runtime"}:void 0;return {name:v,status:l.status,error:D,requires:d,requires_satisfied:E,requires_missing:_,provides_declared:C,provides_runtime:A,blocked_by:F,unblocks:Array.from(V).sort(),runtime:{attempt_count:l.executionCount??0,restart_count:l.retryCount??0,in_progress_since:l.status==="in-progress"?l.startedAt??null:null,last_transition_at:l.lastUpdated??null,last_completed_at:l.completedAt??null,last_restarted_at:l.startedAt??null,status_age_ms:l.lastUpdated?0:null}}});c.pending=u.pending.length,c.blocked=u.blocked.length,c.unresolved=u.unresolved.length;let P=y.map(v=>({name:v.name,fanOut:v.unblocks.length})).sort((v,l)=>l.fanOut-v.fanOut||v.name.localeCompare(l.name)),L=P.length>0?P[0]:{name:null,fanOut:0},j=new Set;for(let v of Object.values(o))for(let l of v.requires??[])j.add(l);let Y=0;for(let[v,l]of Object.entries(o)){let a=(l.requires??[]).length===0,C=(l.provides??[]).some(A=>(S.get(A)??[]).some(E=>E!==v));a&&!C&&(Y+=1);}return {schema_version:"v1",meta:{board:{path:e}},summary:{card_count:i.length,completed:c.completed,eligible:u.eligible.length,pending:c.pending,blocked:c.blocked,unresolved:c.unresolved,failed:c.failed,in_progress:c.in_progress,orphan_cards:Y,topology:{edge_count:Array.from(j).length,max_fan_out_card:L.name,max_fan_out:L.fanOut}},cards:y}}function Jt(){return new Date().toISOString()}function Rt(e,t,n,o,i,u,c){return async f=>{let S=[],y=n.cardStore.readCard(f.nodeId);if(!y)return "task-initiate-failure";let P=y.id,L=y.card_data??{},j=y.source_defs??[],Y=j.filter(b=>b.optionalForCompletionGating!==true),v=n.cardRuntimeStore.readRuntime(P),l=false,a$1=()=>{l&&(n.cardRuntimeStore.writeRuntime(P,v),l=false);},d=b=>pt(v._sources[b]),C=(b,k)=>{v._sources[b]=pt(k),l=true;},A=f.taskState?.executionCount??0;if(v._lastExecutionCount!==A&&(v._sources={},v._lastExecutionCount=A,l=true),f.update){let b=f.update,k=b.outputFile;if(k){let w=d(k);if(b.failure){let B=b.rqt??w.lastRequestedToken??w.queueRequestedToken;B&&C(k,mt(w,B));}else {let B=b.rqt;if(!w.lastCompletedToken||B>w.lastCompletedToken){let H=typeof b.deliveryToken=="string"?b.deliveryToken:void 0,Z=false;H&&(Z=n.fetchedSourcesStore.commitSourceData(P,k,H)),Z?C(k,$t(w,B)):C(k,mt(w,B));}}a$1();}}let _={};for(let b of j)if(b.outputFile){let k=n.fetchedSourcesStore.readSourceData(P,b.outputFile);k!==null&&(_[b.bindTo]=k);}let F={};for(let[b,k]of Object.entries(f.state??{}))if(k!==null&&typeof k=="object"&&!Array.isArray(k)){let w=k[b];F[b]=w!==void 0?w:k;}else F[b]=k;let V={id:P,card_data:{...L},requires:F,source_defs:j,compute:y.compute};V._sourcesData=_,y.compute&&a$3.runSync(V,{sourcesData:_}),(u??n.outputStore.writeComputedValues.bind(n.outputStore))(P,V.computed_values??{});let N={...y},D=a$3.enrichSourcesSync(Array.isArray(y.source_defs)?y.source_defs:void 0,{card_data:y.card_data,requires:F}),M=e.value;N.source_defs=Array.isArray(D)?D.map(b=>({...b,boardDir:typeof b.boardDir=="string"&&b.boardDir?b.boardDir:M})):D;let $=Jt(),oe=f.update?void 0:$,se=Y.filter(b=>{let k=b.outputFile;if(typeof k!="string"||!k)return true;let w=d(k);oe&&(w={...w,queueRequestedToken:oe},C(k,w));let B=w.queueRequestedToken??w.lastRequestedToken??$,H=ft(w,B);return H==="in-flight"?false:H==="dispatch"});if(a$1(),se.length>0){let b=false,k=$;for(let w of se){let B=w.outputFile;if(typeof B!="string"||!B)continue;let H=d(B),Z=H.queueRequestedToken??$;C(B,{...H,lastRequestedToken:Z}),k=Z,b=true;}return b&&a$1(),b&&(S.push({taskKind:"source-fetch",payload:{boardRef:a(e),enrichedCard:N,callbackToken:f.callbackToken,rqt:k}}),n.executionRequestStore.appendEntries(t,S)),"task-initiated"}if(Y.some(b=>{let k=b.outputFile;if(typeof k!="string"||!k)return false;let w=d(k),B=w.queueRequestedToken??w.lastRequestedToken??$;return ft(w,B)==="in-flight"}))return "task-initiated";let ae=y.provides??[],ie={};for(let{bindTo:b,ref:k}of ae)ie[b]=a$3.resolve(V,k);return (c??n.outputStore.writeDataObjects.bind(n.outputStore))(ie),j.filter(b=>{if(b.optionalForCompletionGating!==true)return false;let k=d(b.outputFile);return !k.lastRequestedToken||!k.lastCompletedToken?true:k.lastCompletedToken<=k.lastRequestedToken}).length>0&&S.push({taskKind:"source-fetch",payload:{boardRef:a(e),enrichedCard:N,callbackToken:f.callbackToken,rqt:$}}),o(f.nodeId,ie),S.length>0&&n.executionRequestStore.appendEntries(t,S),"task-initiated"}}var De={settings:{completion:"manual",refreshStrategy:"data-changed"},tasks:{}};function bt(e){return {[le]:e.graph,[St]:e.lastDrainedJournalId}}function vt(e){let t=e[le],n=e[St];if(!t||typeof t!="object")throw new Error(`State snapshot is missing required key: ${le}`);return {graph:t,lastDrainedJournalId:typeof n=="string"?n:""}}function wt(e){let t=e.requires,n=e.provides?.map(o=>o.bindTo)??[];return {requires:t&&t.length>0?t:void 0,provides:n,taskHandlers:["card-handler"],description:e.meta?.title??e.id}}function T(e){return e!==void 0?{status:"success",data:e}:{status:"success"}}function R(e){return {status:"fail",error:e}}function I(e){return {status:"error",error:e instanceof Error?e.message:String(e)}}function Mt(e){let t=new TextEncoder().encode(e),n=Array.from(t,o=>String.fromCharCode(o)).join("");return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Tt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),o=atob(n),i=Uint8Array.from(o,u=>u.charCodeAt(0));return new TextDecoder().decode(i)}function Ie(e){try{let t=JSON.parse(Tt(e));return typeof t?.t=="string"?{taskName:t.t}:null}catch{return null}}function Ht(e){return Mt(JSON.stringify(e))}function xt(e){try{let t=JSON.parse(Tt(e));return typeof t?.cbk=="string"&&typeof t?.cid=="string"&&typeof t?.b=="string"&&typeof t?.d=="string"?t:null}catch{return null}}function U(){return new Date().toISOString()}function Cr(e,t){rt(t.callbackTransport,"createBoardLiveCardsPublic");let n=t.callbackTransport,o=t.onWarn??(()=>{}),i=a(e);function u$1(s){if(s.length!==0)try{let r=t.publishBoardChangeNotifications?.(s);r&&typeof r.catch=="function"&&r.catch(p=>o(`[board-live-cards-public] publishBoardChangeNotifications failed: ${p instanceof Error?p.message:String(p)}`));}catch(r){o(`[board-live-cards-public] publishBoardChangeNotifications failed: ${r instanceof Error?r.message:String(r)}`);}}function c$1(){let s=S().readCardStoreRef();if(!s)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let r=t.kvStorageForRef(s);return {readIndex(){return r.read("_index")},writeIndex(p){r.write("_index",p);},readCard(p){return r.read(p)},writeCard(p,g){return r.write(p,g),t.hashFn(g)},removeCard(p){r.delete(p);},cardExists(p){return r.read(p)!==null},defaultCardKey(p){return p}}}let f={readValues(s){let r=t.kvStorage("state-snapshot"),p=r.listKeys().sort();if(p.length===0)return {version:null,values:{}};let g={};for(let x of p)g[x]=r.read(x);return {version:t.hashFn(g),values:g}},writeValues(s,r,p){let g=t.kvStorage("state-snapshot");for(let x of p)g.delete(x);for(let[x,O]of Object.entries(r))g.write(x,O);return t.hashFn(r)}},S=()=>Ke(t.kvStorage("config")),y=()=>yt(f),P=()=>gt(t.journalAdapter()),L=()=>je(c$1(),o),j=()=>{let s=S().readOutputsStoreRef();if(!s)throw new Error(`Board at ${e.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return Ct(t.kvStorageForRef(s))},Y=()=>{let s=S().readArchiveStoreRef();return s?t.archiveFactoryForRef(s):t.archiveFactory()};function v(){return !!y().readSnapshot(e.value).values[le]}function l(){let s=y().readSnapshot(e.value);if(!s.values[le])throw new Error(`Board not initialized at ${e.value}`);return vt(s.values)}function a$3(s,r){let p=y().commitSnapshot(e.value,{schemaVersion:Ee,expectedVersion:r,commitId:t.genId(),committedAt:U(),deleteKeys:[],shallowMerge:bt(s)});if(!p.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${r??"null"} current=${p.currentVersion??"null"}`)}function d(s){P().appendEvent(s);}async function C(){let s=(m,h)=>{let q=m.payload,z=(q?.enrichedCard??{}).id??q?.cardId??"unknown";d({type:"task-failed",taskName:z,error:h,timestamp:U()});},r=kt(t.kvStorage("execution-requests"),s),p$1=ht(t.kvStorage("card-runtime")),g=Te(t.blobStorage("sources"),m=>t.resolveBlob(m)),x=new Map,O={readRuntime(m){return x.get(m)??p$1.readRuntime(m)},writeRuntime(m,h){x.set(m,h);}},X=[],K=new Map,Q={readSourceData(m,h){let q=`${m}/${h}`;return K.has(q)?K.get(q):g.readSourceData(m,h)},ingestSourceDataStaged(m,h,q,re){g.ingestSourceDataStaged(m,h,q,re);},commitSourceData(m,h,q){let re=`${m}/.staged/${q}/${h}`,z=t.blobStorage("sources"),ee=z.read(re);if(ee==null){let be=z.keyRef?.(re);be&&(ee=t.resolveBlob(be));}if(ee==null)return false;let Re=`${m}/${h}`,ne=ee.trim();try{K.set(Re,JSON.parse(ne));}catch{K.set(Re,ne);}return X.push({cardId:m,outputFile:h,deliveryToken:q}),true},hasSource(m,h){let q=`${m}/${h}`;return K.has(q)?true:g.hasSource(m,h)},listSources(m){let h=g.listSources(m),q=new Set;for(let z of K.keys())z.startsWith(`${m}/`)&&q.add(z.slice(`${m}/`.length));let re=new Set([...h,...q]);return Array.from(re)}},W={cardStore:L(),cardRuntimeStore:O,fetchedSourcesStore:Q,outputStore:j(),executionRequestStore:r},ue=l(),fe=q(ue.graph),{events:me,newCursor:ge}=P().readEntriesAfterCursor(ue.lastDrainedJournalId),de=[],he=[],_e=[],Fe=new Map,$e=new Set,Vt=(m,h)=>{de.push({type:"task-completed",taskName:m,data:h,timestamp:U()});try{Y().stream("exec-history").append({taskName:m,status:"completed",completedAt:U()});}catch{}},Je=(m,h)=>{d({type:"task-failed",taskName:m,error:h,timestamp:U()});try{Y().stream("exec-history").append({taskName:m,status:"failed",error:h,completedAt:U()});}catch{}},ye=u(fe,{handlers:{"card-handler":Rt(e,ge,W,Vt,Je,(m,h)=>{he.push({cardId:m,values:h});},m=>{_e.push(m);})},onNodeRemoved:m=>{Fe.delete(m),x.delete(m),$e.add(m);}});for(de=me;de.length>0;){let m=de;de=[];for(let h of m)if(h.type==="task-restart"){let q=W.cardStore.readCard(h.taskName);q&&Fe.set(h.taskName,q);}ye.pushAll(m),await ye.waitForHandlers();}let Me=ye.getState();await ye.dispose({wait:true});let qt=y().readSnapshot(e.value).version;a$3({lastDrainedJournalId:ge,graph:p(Me)},qt);for(let{cardId:m,values:h}of he)W.outputStore.writeComputedValues(m,h);for(let m of _e)W.outputStore.writeDataObjects(m);for(let[m,h]of x)p$1.writeRuntime(m,h);for(let{cardId:m,outputFile:h,deliveryToken:q}of X)g.commitSourceData(m,h,q);let Ce;try{Ce=Ae(i,Me),W.outputStore.writeStatusSnapshot(Ce);}catch(m){o(`[board-live-cards-public] status publish failed: ${m instanceof Error?m.message:String(m)}`);}let ke=[];for(let{cardId:m,values:h}of he)ke.push({kind:"computed_values",cardId:m,values:h});for(let m of _e)for(let[h,q]of Object.entries(m))h&&ke.push({kind:"data_object",key:h,payload:q});for(let[m,h]of Fe)ke.push({kind:"card_refreshed",cardId:m,card:h});for(let m of $e)ke.push({kind:"card_removed",cardId:m});Ce!==void 0&&ke.push({kind:"status",status:Ce}),u$1(ke);let He=S().readTaskExecutorRef()??{howToRun:"built-in",whatToRun:a({kind:"built-in",value:"source-cli-task-executor"})},Bt=t.supportsDirectSourceOutput?.(He)===true;r.dispatchEntriesForJournalId(ge,m=>{if(m.taskKind!=="source-fetch"){o(`[process-accumulated-events] unknown taskKind "${m.taskKind}" \u2014 skipping`);return}let h=m.payload,q=h.enrichedCard?.id??"unknown",re=h.enrichedCard?.source_defs??[];for(let z of re){if(!z.outputFile){o(`[dispatch] source "${z.bindTo}" has no outputFile \u2014 skipping`);continue}let ee;if(Bt){let ne=t.genId(),be=`${q}/.staged/${ne}/${z.outputFile}`,Ge=t.blobStorage("sources").keyRef?.(be);Ge?ee={ref:a(Ge),deliveryToken:ne,outputFile:z.outputFile,cardId:q}:o("[dispatch] hosted board-worker requested but sources BlobStorage cannot produce portable refs; falling back to scratch protocol");}let Re=Ht({cbk:h.callbackToken,rg:e.value,br:a(e),cid:q,b:z.bindTo,d:z.outputFile,cs:void 0,rqt:h.rqt,...ee?{dt:ee.deliveryToken}:{}});t.dispatchExecution(He,{source_def:z,base_ref:a(e),callback:n.createCallback(Re),...ee?{output:ee}:{}}).catch(ne=>Je(q,ne instanceof Error?ne.message:String(ne)));}});}function A(){let s=t.processAccumulatedStore();s.enqueueIfAbsent?s.enqueueIfAbsent({boardRef:a(e)},`process-accumulated:${a(e)}`):s.enqueue({boardRef:a(e)}),t.requestProcessAccumulated?.();}function E(){let s=t.processAccumulatedStore();for(;;){let r=s.lease({max:64,visibilityMs:1e3});if(r.length<=0)return;for(let p of r)s.ack(p.id,p.leaseToken);if(r.length<64)return}}async function _(){try{let s=()=>{let p=l(),{events:g}=P().readEntriesAfterCursor(p.lastDrainedJournalId);g.length<=0||A();},r=await c(t.lock,C,s);return T({ran:r!==!1})}catch(s){return I(s)}}function F(){A();}function V(s){try{let r=s.params?.cardStoreRef;if(!r)return R("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(!v()){let W=a$1(De);a$3({lastDrainedJournalId:"",graph:p(W)},null);}let p$1=s.params?.outputsStoreRef;if(!p$1)return R("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let g=s.params?.scratchStoreRef,x=s.params?.archiveStoreRef,O=s.params?.chatStoreRef,X=s.params?.artifactsStoreRef,K=S();K.writeCardStoreRef(r),K.writeOutputsStoreRef(p$1),g&&K.writeScratchStoreRef(g),x&&K.writeArchiveStoreRef(x),O&&K.writeChatStoreRef(O),X&&K.writeArtifactsStoreRef(X);let Q=s.body??{};Q["task-executor-ref"]&&K.writeTaskExecutorRef(Q["task-executor-ref"]),Object.prototype.hasOwnProperty.call(Q,"chat-handler-flow")&&K.writeChatHandlerFlow(Q["chat-handler-flow"]);try{j().writeStatusSnapshot(Ae(i,q(l().graph)));}catch{}return T()}catch(r){return I(r)}}function N(s){try{let r=j().readStatusSnapshot();if(!r){r=Ae(i,q(l().graph));try{j().writeStatusSnapshot(r);}catch{}}return T(r)}catch(r){return I(r)}}function D(s){try{let r=s.params?.id;if(!r)return R("removeCard requires params.id");try{t.kvStorage("card-upsert").delete(r);}catch{}return d({type:"task-removal",taskName:r,timestamp:U()}),F(),T()}catch(r){return I(r)}}function M(s){try{let r=s.params?.cardId;if(!r)return R("addCardFiles requires params.cardId");let p=a$2(L()).appendFiles({params:{id:r},body:s.body});if(p.status!=="success")return p;let g=$({params:{cardId:r}});return g.status!=="success"?g:T({cardId:r,files_added:p.data.files_added,notified:!0})}catch(r){return I(r)}}function $(s){try{let r=s.params?.cardId;if(!r)return R("cardRefreshedNotify requires params.cardId");let p=L().readCard(r);return p?(u$1([{kind:"card_refreshed",cardId:r,card:p}]),T({cardId:r,notified:!0})):R(`Card "${r}" not found in board at ${e.value}`)}catch(r){return I(r)}}function oe(s){try{let r=s.params?.id;return r?(d({type:"task-restart",taskName:r,timestamp:U()}),F(),T()):R("retrigger requires params.id")}catch(r){return I(r)}}async function se(s){return E(),_()}function Se(s){try{let r=s.params?.cardId,p=s.params?.all,g=!!s.params?.restart;if(!r&&!p)return R("upsertCard requires --card-id <id> or --all");let x=p?L().readAllCards().map(O=>O.id):[r];for(let O of x)if(!L().readCard(O))return R(`Card "${O}" not found in board at ${e.value}`);for(let O of x){let X=L().readCard(O),K=wt(X),Q=t.hashFn(K),W=t.kvStorage("card-upsert"),ue=W.read(O),fe=ue?.taskConfigHash!==Q;if(!(!fe&&!g)){if(fe){let me=ue?.blobRef??L().readCardKey(O)??O;d({type:"task-upsert",taskName:O,taskConfig:K,timestamp:U()}),W.write(O,{blobRef:me,taskConfigHash:Q,updatedAt:U()});}g&&d({type:"task-restart",taskName:O,timestamp:U()});}}return F(),T()}catch(r){return I(r)}}function ae(s){try{let r=s.params?.token;if(!r)return R("taskFailed requires params.token");let p=s.params?.error??"unknown error",g=Ie(r);if(!g)return R("Invalid callback token");d({type:"task-failed",taskName:g.taskName,error:p,timestamp:U()});try{Y().stream("exec-history").append({taskName:g.taskName,status:"failed",error:p,completedAt:U()});}catch{}return F(),T()}catch(r){return I(r)}}function ie(s){try{let r=s.params?.token;if(!r)return R("taskProgress requires params.token");let g=(s.body??{}).update??{},x=Ie(r);return x?(d({type:"task-progress",taskName:x.taskName,update:g,timestamp:U()}),F(),T()):R("Invalid callback token")}catch(r){return I(r)}}function pe(s){try{let r=s.params?.token,p=s.params?.ref;if(!r)return R("sourceDataFetched requires params.token");if(!p)return R("sourceDataFetched requires params.ref");let g=xt(r);if(!g)return R("Invalid source token");let{cbk:x,cid:O,b:X,d:K,cs:Q,rqt:W,dt:ue}=g,fe=Te(t.blobStorage("sources"),he=>t.resolveBlob(he)),me=ue||t.genId();ue||fe.ingestSourceDataStaged(O,K,b(p),me);let ge=Ie(x);if(!ge)return R("Invalid callback token embedded in source token");let de=U();return d({type:"task-progress",taskName:ge.taskName,update:{bindTo:X,outputFile:K,fetchedAt:de,deliveryToken:me,sourceChecksum:Q,rqt:W},timestamp:de}),F(),T()}catch(r){return I(r)}}function b$1(s){try{let r=s.params?.token,p=s.params?.reason??"unknown";if(!r)return R("sourceDataFetchFailure requires params.token");let g=xt(r);if(!g)return R("Invalid source token");let{cbk:x,b:O,d:X,cs:K,rqt:Q}=g,W=Ie(x);return W?(d({type:"task-progress",taskName:W.taskName,update:{bindTo:O,outputFile:X,failure:!0,reason:p,sourceChecksum:K,rqt:Q},timestamp:U()}),F(),T()):R("Invalid callback token embedded in source token")}catch(r){return I(r)}}function k(s){try{let r=S().readCardStoreRef();return r?T({storeRef:r}):R(`Board at ${e.value} has no card store configured`)}catch(r){return I(r)}}function w(s){try{let r=S().readOutputsStoreRef();return r?T({storeRef:r}):R(`Board at ${e.value} has no outputs store configured`)}catch(r){return I(r)}}function B(s){try{let r=S().readScratchStoreRef();return T({storeRef:r})}catch(r){return I(r)}}function H(s){try{let r=S().readArchiveStoreRef();return T({storeRef:r})}catch(r){return I(r)}}function Z(s){try{let r=S().readChatStoreRef();return T({storeRef:r})}catch(r){return I(r)}}function te(s){try{let r=S().readArtifactsStoreRef();return T({storeRef:r})}catch(r){return I(r)}}function Et(s){try{let r=s.params?.key;if(!r)return R("getConfig requires params.key");let p=S(),g;switch(r){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 R(`getConfig: unknown key "${r}"`)}return T({value:g})}catch(r){return I(r)}}function At(s){try{let r=s.params?.key;if(!r)return R("getOutputsDataObject requires params.key");let p=j().readDataObject(r);return T(p)}catch(r){return I(r)}}function It(s){try{return T(j().readAllDataObjects())}catch(r){return I(r)}}function _t(s){try{let r=s.params?.key;if(!r)return R("getOutputsComputedValues requires params.key");let p=j().readComputedValues(r);return T(p)}catch(r){return I(r)}}function Ft(s){try{return T(j().readAllComputedValues())}catch(r){return I(r)}}function Le(){return Te(t.blobStorage("sources"),s=>t.resolveBlob(s))}function Ne(s){let r=t.blobStorage("sources").keyRef?.(s);return r?a(r):s}function Ot(s){try{let r=s.params?.key;if(!r)return R("getOutputsFetchedSources requires params.key");let p=Le().listSources(r),g={};for(let x of p)g[x]=Ne(`${r}/${x}`);return T(g)}catch(r){return I(r)}}function Pt(s){try{let r=Le(),p=new Set;for(let x of t.blobStorage("sources").listKeys()){let O=x.indexOf("/");O>0&&!x.includes("/.staged/")&&p.add(x.slice(0,O));}let g={};for(let x of p){let O=r.listSources(x);if(O.length>0){g[x]={};for(let X of O)g[x][X]=Ne(`${x}/${X}`);}}return T(g)}catch(r){return I(r)}}return {init:V,status:N,getCardStoreRef:k,getOutputsStoreRef:w,getScratchStoreRef:B,getArchiveStoreRef:H,getChatStoreRef:Z,getArtifactsStoreRef:te,getConfig:Et,getOutputsDataObject:At,getAllOutputsDataObjects:It,getOutputsComputedValues:_t,getAllOutputsComputedValues:Ft,getOutputsFetchedSources:Ot,getAllOutputsFetchedSources:Pt,removeCard:D,addCardFiles:M,cardRefreshedNotify:$,retrigger:oe,processAccumulatedEvents:se,upsertCard:Se,taskFailed:ae,taskProgress:ie,sourceDataFetched:pe,sourceDataFetchFailure:b$1}}function Rr(e,t){let n=()=>Ke(t.kvStorage("config"));function o(){let l=n().readCardStoreRef();if(!l)throw new Error(`Board at ${e.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let a=t.kvStorageForRef(l);return {readIndex(){return a.read("_index")},writeIndex(d){a.write("_index",d);},readCard(d){return a.read(d)},writeCard(d,C){return a.write(d,C),t.hashFn(C)},removeCard(d){a.delete(d);},cardExists(d){return a.read(d)!==null},defaultCardKey(d){return d}}}let i=()=>je(o(),t.onWarn??(()=>{}));async function u(l,a){let d=t.validateSchema(a),C=[],A=n().readTaskExecutorRef();if(A&&Array.isArray(a.source_defs))for(let _ of a.source_defs){let F=typeof _.bindTo=="string"?_.bindTo:"(unknown)";try{let V;try{V=await t.invokeExecutor(A,"validate-source-def",{timeout:t.executorTimeouts?.validationMs??1e4,input:JSON.stringify(_)});}catch(D){let M=D;if(V=typeof M?.stdout=="string"?M.stdout:"",!V.trim()){C.push(`source "${F}": executor validate-source-def failed \u2014 ${D instanceof Error?D.message:String(D)}`);continue}}let N=JSON.parse(V.trim());if(!N.ok&&Array.isArray(N.errors))for(let D of N.errors)C.push(`source "${F}": ${D}`);}catch(V){C.push(`source "${F}": executor validate-source-def failed \u2014 ${V instanceof Error?V.message:String(V)}`);}}let E=[...d.errors,...C];return T({cardId:l,isValid:E.length===0,issues:E})}function c(l,a){let d=l.params?.sourceIdx,C=l.params?.outRef;if(d===void 0)return R(`${a} requires params.sourceIdx`);if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return R(`${a} requires card JSON object in body`);let A=l.body,E=A["card-content"]??A,_=A["mock-projections"]??{},F=E.source_defs??[];if(d<0||d>=F.length)return R(`sourceIdx ${d} out of range (card has ${F.length} source(s))`);let V=F[d],N=typeof V.bindTo=="string"?V.bindTo:"source";return {src:V,bindTo:N,outRef:C,mockProjections:_}}async function f(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return R("validateCardPreflight requires card JSON object in body");let a=l.body,d=a["card-content"]??a,C=typeof d.id=="string"?d.id:"(unknown)";return await u(C,d)}catch(a){return I(a)}}async function S(l){try{let a=c(l,"probeSourcePreflight");if("status"in a)return a;let d=n().readTaskExecutorRef();if(!d)return R("No task-executor registered for this board");try{let C={...a.src,_projections:a.mockProjections},A=await t.invokeExecutor(d,"probe-source-preflight",{timeout:a.src.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(C)}),E=JSON.parse(A.trim());return E.ok?T({bindTo:a.bindTo,reachable:E.reachable,latencyMs:E.latencyMs,note:E.note}):R(E.error??"Preflight probe failed")}catch{return R("Executor does not support probe-source-preflight")}}catch(a){return I(a)}}async function y(l){try{let a=c(l,"runSourcePreflight");if("status"in a)return a;let d=n().readTaskExecutorRef();if(!d)return R("No task-executor registered for this board");try{let C={...a.src,_projections:a.mockProjections},A=await t.invokeExecutor(d,"run-source-preflight",{timeout:a.src.timeout??t.executorTimeouts?.probeMs??6e4,input:JSON.stringify(C)}),E=JSON.parse(A.trim());if(!E.ok)return T({bindTo:a.bindTo,ok:!1,result:null,issues:[E.error??"Preflight run failed"]});if(a.outRef){let _=b(a.outRef);t.absoluteBlob.write(_.value,JSON.stringify(E.resultValue,null,2));}return T({bindTo:typeof E.bindTo=="string"?E.bindTo:a.bindTo,ok:!0,result:E.resultValue??null,issues:[]})}catch(C){let A=C instanceof Error?C.message:String(C);return T({bindTo:a.bindTo,ok:!1,result:null,issues:[A]})}}catch(a){return I(a)}}async function P(l){try{let a=n().readTaskExecutorRef();if(!a)return R("No task-executor registered for this board");let d=await t.invokeExecutor(a,"describe-capabilities",{timeout:t.executorTimeouts?.describeMs??1e4});return T(JSON.parse(d.trim()))}catch(a){return I(a)}}function L(l){try{let a=l.body;if(!a||!Array.isArray(a.ops))return R("updatesInCardStore requires body.ops array");let d=a.ops,C=i();for(let A of d){let E=A.op,_=A.id;if(!_)return R('op is missing "id"');if(E==="update"){let F=A["card-content"];if(!F)return R(`update op for "${_}" is missing "card-content"`);C.writeCard(_,F);}else return R(`Unknown op type: "${E??"(none)"}"`)}return T()}catch(a){return I(a)}}function j(l){try{let a=l.body;if(!a||!Array.isArray(a.ids))return R("readFromCardStore requires body.ids array");let d=a.ids,C=i(),A=d.map(E=>({id:E,"card-content":C.readCard(E)}));return T({cards:A})}catch(a){return I(a)}}function Y(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return R("evalCardCompute requires a JSON object in body");let a=l.body,d=a["card-content"]??a,C=typeof d.id=="string"?d.id:"(unknown)",A=a["mock-fetched-sources"]??{},E=a["mock-requires"]??{},_=d.compute;if(!_||!Array.isArray(_)||_.length===0)return T({cardId:C,ok:!0,computed_values:{},errors:[]});let F={id:C,card_data:d.card_data??{},requires:E,source_defs:d.source_defs,compute:_},V=a$3.runSync(F,{sourcesData:A}),N=V.node.computed_values??{},D=V.errors??[];return T({cardId:C,ok:D.length===0,computed_values:N,errors:D})}catch(a){return I(a)}}async function v(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return R("simulateCardCycle requires a JSON object in body");let a=l.body,d=a["card-content"]??a,C=typeof d.id=="string"?d.id:"(unknown)",A=a["mock-fetched-sources"]??{},E=a["mock-requires"]??{},_=await u(C,d),F=_.status==="success"?{isValid:_.data.isValid,issues:_.data.issues}:{isValid:!1,issues:[_.status==="fail"?_.error:"internal error"]},V=d.source_defs??[],N=d.card_data??{},D=[],M=[];if(V.length>0){D=a$3.enrichSourcesSync(V,{card_data:N,requires:E});for(let k of D){let w=k.projections,B=k._projections;if(w&&B){for(let H of Object.keys(w))if(B[H]===void 0){let Z=typeof k.bindTo=="string"?k.bindTo:"(unknown)";M.push({bindTo:Z,key:H,error:`Projection "${H}" resolved to undefined`});}}}}let $=[],oe={...A},se=a["task-executor-ref"],Se=(se?.howToRun&&se?.whatToRun?se:void 0)??n().readTaskExecutorRef();for(let k=0;k<D.length;k++){let w=D[k],B=typeof w.bindTo=="string"?w.bindTo:`source_${k}`;if(!Se){$.push({bindTo:B,skipped:!0,error:"No task executor configured"});continue}try{let H={...w},Z=await t.invokeExecutor(Se,"run-source-preflight",{timeout:w.timeout??t.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(H)}),te=JSON.parse(Z.trim());te.ok&&!Object.prototype.hasOwnProperty.call(A,B)&&Object.prototype.hasOwnProperty.call(te,"resultValue")&&(oe[B]=te.resultValue),$.push({bindTo:B,reachable:te.reachable,latencyMs:te.latencyMs,error:te.ok?void 0:te.error});}catch{$.push({bindTo:B,skipped:!0,error:"Executor does not support run-source-preflight"});}}let ae=d.compute,ie={},pe=[];if(ae&&Array.isArray(ae)&&ae.length>0){let k={id:C,card_data:N,requires:E,source_defs:d.source_defs,compute:ae},w=a$3.runSync(k,{sourcesData:oe});ie=w.node.computed_values??{},pe=w.errors??[];}let b=F.isValid&&M.length===0&&pe.length===0&&$.every(k=>k.reachable!==!1);return T({cardId:C,ok:b,validation:F,source_probes:$,projection_errors:M,fetched_sources:oe,computed_values:ie,compute_errors:pe})}catch(a){return I(a)}}return {validateCardPreflight:f,probeSourcePreflight:S,runSourcePreflight:y,evalCardCompute:Y,simulateCardCycle:v,describeTaskExecutorCapabilities:P,updatesInCardStore:L,readFromCardStore:j}}
|
|
2
|
+
export{rr as a,st as b,nr as c,rt as d,Qt as e,Zt as f,er as g,ut as h,dt as i,ct as j,lt as k,je as l,Ee as m,le as n,Lt as o,pt as p,ft as q,$t as r,mt as s,Ae as t,De as u,bt as v,vt as w,wt as x,Cr as y,Rr as z};//# sourceMappingURL=chunk-N6P2JW4W.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-N6P2JW4W.js.map
|