yaml-flow 8.11.8 → 8.11.10
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 +5 -5
- package/browser/live-cards.schema.json +807 -151
- package/browser/server-runtime-controlface.js +5 -5
- package/examples/board/cards/card-rebalance-sim.json +7 -5
- package/examples/board/cards/cardT-market-prices.json +3 -1
- package/examples/board/cards/cardT-portfolio-value.json +3 -1
- package/examples/board/cards/cardT-portfolio.json +4 -2
- package/examples/board/test/server-http-test-browser.ts +3 -1
- package/examples/board/test/server-http-test.js +3 -1
- package/examples/portfolio-tracker/portfolio-tracker.js +2 -2
- package/examples/portfolio-tracker/test/portfolio-t4.js +2 -2
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +2 -2
- package/lib/board-live-cards-node.js +1 -1
- package/lib/board-live-cards-public.cjs +1 -1
- 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.js +1 -1
- package/lib/board-livegraph-runtime/index.cjs +1 -1
- package/lib/board-livegraph-runtime/index.d.cts +1 -1
- package/lib/board-livegraph-runtime/index.d.ts +1 -1
- package/lib/board-livegraph-runtime/index.js +1 -1
- package/lib/card-compute/index.cjs +1 -1
- package/lib/card-compute/index.js +1 -1
- package/lib/card-store-public.cjs +1 -1
- package/lib/card-store-public.js +1 -1
- package/lib/card-validation.cjs +1 -1
- package/lib/card-validation.js +1 -1
- package/lib/chunk-23X3V5FR.cjs +2 -0
- package/lib/{chunk-OR6B2H2Y.cjs → chunk-2AIIEBBL.cjs} +3 -3
- package/lib/chunk-3EITX4IQ.cjs +3 -0
- package/lib/chunk-4P52IVQN.cjs +2 -0
- package/lib/chunk-66ZZIF2L.cjs +2 -0
- package/lib/{chunk-4NWVZ7AW.js → chunk-72FB4M6P.js} +2 -2
- package/lib/{chunk-BRYV6CDD.js → chunk-C7OY3PYL.js} +3 -3
- package/lib/{chunk-EGZPROOH.cjs → chunk-C7RR2JCL.cjs} +3 -3
- package/lib/{chunk-JOQWJ3VR.cjs → chunk-CAID4CGO.cjs} +2 -2
- package/lib/{chunk-REZO2QJD.js → chunk-E7SDEZSI.js} +3 -3
- package/lib/chunk-G5UUXBIB.cjs +2 -0
- package/lib/chunk-JQALMLNI.js +2 -0
- package/lib/{chunk-ROIYEFSE.js → chunk-K2VRX4TC.js} +2 -2
- package/lib/chunk-NJCDHKPX.js +3 -0
- package/lib/chunk-ONJG6QW6.js +2 -0
- package/lib/{chunk-HOS2ZUFZ.cjs → chunk-P4WQJ7LA.cjs} +2 -2
- package/lib/{chunk-6SPWFJRG.cjs → chunk-PYYRDOD5.cjs} +2 -2
- package/lib/chunk-QE3QXEHI.js +2 -0
- package/lib/{chunk-MRESV3MD.js → chunk-QJQ53PLM.js} +2 -2
- package/lib/{chunk-BA25VGJP.js → chunk-QOOIN523.js} +3 -3
- package/lib/{chunk-MRIFSG7L.cjs → chunk-TIQ775WI.cjs} +3 -3
- package/lib/chunk-WFMVZ3LO.js +2 -0
- package/lib/cloud-storage.cjs +1 -1
- package/lib/cloud-storage.js +1 -1
- package/lib/continuous-event-graph/index.cjs +1 -1
- package/lib/continuous-event-graph/index.d.cts +2 -2
- package/lib/continuous-event-graph/index.d.ts +2 -2
- package/lib/continuous-event-graph/index.js +1 -1
- package/lib/firestore-storage/index.cjs +1 -1
- package/lib/firestore-storage/index.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/{live-cards-bridge-Bwi-lbBT.d.cts → live-cards-bridge-D8kP3uog.d.cts} +2 -2
- package/lib/{live-cards-bridge-YL6AWawT.d.ts → live-cards-bridge-DMBSDgpk.d.ts} +2 -2
- package/lib/localstorage-storage/index.cjs +1 -1
- package/lib/localstorage-storage/index.js +1 -1
- package/lib/{mcp-tool-registries-CRtea2x4.d.cts → mcp-tool-registries-B6KrbGuh.d.cts} +9 -0
- package/lib/{mcp-tool-registries-D3rWSppt.d.ts → mcp-tool-registries-BbxbZCbF.d.ts} +9 -0
- package/lib/server-runtime/index.cjs +1 -1
- package/lib/server-runtime/index.js +1 -1
- package/lib/server-runtime-agentface/index.d.cts +1 -1
- package/lib/server-runtime-agentface/index.d.ts +1 -1
- package/lib/server-runtime-controlface/index.cjs +1 -1
- package/lib/server-runtime-controlface/index.js +1 -1
- package/lib/server-runtime-core/index.cjs +1 -1
- package/lib/server-runtime-core/index.d.cts +14 -1
- package/lib/server-runtime-core/index.d.ts +14 -1
- package/lib/server-runtime-core/index.js +1 -1
- package/lib/server-runtime-webhooks/index.d.cts +1 -1
- package/lib/server-runtime-webhooks/index.d.ts +1 -1
- package/package.json +2 -1
- package/schema/live-cards.schema.json +807 -151
- package/browser/live-cards.js +0 -108
- package/lib/chunk-36KKCQVE.cjs +0 -2
- package/lib/chunk-3DWVFRQD.cjs +0 -3
- package/lib/chunk-3SLSRX6Q.js +0 -3
- package/lib/chunk-543ZEGP7.cjs +0 -2
- package/lib/chunk-ESTFYRHF.cjs +0 -2
- package/lib/chunk-NN52BT3Q.js +0 -2
- package/lib/chunk-PIPXFUEA.js +0 -2
- package/lib/chunk-UJQ7IML5.js +0 -2
- package/lib/chunk-YOY2JM5N.js +0 -2
- package/lib/chunk-ZV35WD6K.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkBQUQTOPB_cjs=require('./chunk-BQUQTOPB.cjs'),chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunkG5UUXBIB_cjs=require('./chunk-G5UUXBIB.cjs'),chunkVQCIOKJV_cjs=require('./chunk-VQCIOKJV.cjs');function F(a){if(!a||typeof a!="object")return false;let e=a;return typeof e.kind=="string"&&e.kind.length>0}function J(a){if(!a||typeof a!="object")return [];let e=a;return e.kind==="notification-batch"?Array.isArray(e.notifications)?e.notifications.filter(F):[]:F(a)?[a]:[]}function X(a,e,c){let m=0;return {accepted:a.filter(h=>{if(!F(h))return m++,false;let R=h;return typeof R.sentAtMs=="number"&&e-R.sentAtMs>c?(m++,false):true}),rejected:m}}function Q(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function V(a){if(!a||typeof a!="object")return false;let e=a.summary;return !e||typeof e!="object"?false:Number(e.card_count||0)>0}function W(a){if(!a||typeof a!="object")return false;let e=a;return e.kind==="notification-batch"&&Array.isArray(e.notifications)}function H(a,e){if(e.kind==="status"){V(e.status)&&(a.status=e.status);return}if(e.kind==="computed_values"){a.computedValues[e.cardId]=e.values;return}if(e.kind==="data_object"){a.dataObjects[e.key]=e.payload;return}if(e.kind==="card_refreshed"){a.cards[e.cardId]=e.card;return}e.kind==="card_removed"&&(delete a.cards[e.cardId],delete a.computedValues[e.cardId]);}function Y(a,e){if(W(e)){for(let c of e.notifications)F(c)&&H(a,c);return}F(e)&&H(a,e);}function q(a,e){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?Object.assign(new Error(a.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function T(a,e){return q(await a,e)}function E(a){let e=chunkLPXVVMQT_cjs.a(a,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let c=e.split(".");if(!(c.length>=2&&c.every(I=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(I))))throw Object.assign(new Error("MCP tool requires a card private key with at least two identifier segments (e.g. chat.foundry_thread_id)"),{statusCode:400});return e}function D(a,e){let c=a.__private;for(let m of e.split(".")){if(!c||typeof c!="object"||Array.isArray(c)||!Object.prototype.hasOwnProperty.call(c,m))return {exists:false,value:null};c=c[m];}return {exists:true,value:c}}function se(a){let{boardId:e,bootstrapBoard:c,sseHub:m,onChannelSubscribed:I,onChannelUnsubscribed:h,getMcpFacade:R,getMcpCardStoreFacade:S}=a;function n(o){let s=chunkLPXVVMQT_cjs.a(o,"board_id");if(!s)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(s!==e)throw Object.assign(new Error(`Unknown board_id: ${s}`),{statusCode:400})}function C(o){let s=chunkLPXVVMQT_cjs.a(o,"client_id");if(!s)throw Object.assign(new Error("MCP tool requires client_id"),{statusCode:400});return s}function k(o){n(o);let s=C(o),t=chunkLPXVVMQT_cjs.a(o,"channel_name"),r=chunkLPXVVMQT_cjs.a(o,"card_id")||void 0;if(!t)throw Object.assign(new Error("MCP tool requires channel_name"),{statusCode:400});return {clientId:s,channelName:t,...r?{cardId:r}:{}}}function g(o){n(o);let s=chunkLPXVVMQT_cjs.a(o,"card_id");if(!s)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});return {cardId:s}}async function _(o){await c();let{cardId:s}=g(o),t=C(o);if(!await m.subscribeChat(t,s))throw Object.assign(new Error(`SSE client not connected: ${t}`),{statusCode:404});return {status:"success",data:{boardId:e,cardId:s,clientId:t,subscribed:true}}}async function d(o){await c();let{cardId:s}=g(o),t=C(o);if(!m.unsubscribeChat(t,s))throw Object.assign(new Error(`SSE client not connected: ${t}`),{statusCode:404});return {status:"success",data:{boardId:e,cardId:s,clientId:t,subscribed:false}}}async function b(o,s){await c();let{clientId:t,channelName:r,cardId:i}=k(o);if(!m.has(t))throw Object.assign(new Error(`SSE client not connected: ${t}`),{statusCode:404});return s?(m.subscribeChannel(t,r,i),I?.(t,r,i?{cardId:i}:{})):(m.unsubscribeChannel(t,r,i),h?.(t,r,i?{cardId:i}:{})),{status:"success",data:{boardId:e,clientId:t,channelName:r,subscribed:s,...i?{cardId:i}:{}}}}async function l(o,s){let{cardId:t}=g(o);return await R().setChatProcessing({cardId:t,active:s}),{status:"success",data:{boardId:e,cardId:t,active:s}}}async function f(o){let{cardId:s}=g(o),t=await R().getChatProcessing({cardId:s});return {status:"success",data:{boardId:e,cardId:s,active:t.active}}}async function y(o){let{cardId:s}=g(o),t=E(o);if(!Object.prototype.hasOwnProperty.call(o,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(t.split(".").includes("visible_controlplane_only")){let r=await T(S().get({params:{id:s}}),"cardStore.get"),i=Array.isArray(r.cards)&&r.cards.length>0&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null,w=i?D(i,"visible_controlplane_only").value:void 0;if(o.value!==w)throw Object.assign(new Error("MCP tool cannot change the reserved private flag visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:e,cardId:s,key:t}}}return q(await S().patch({params:{id:s,path:`__private.${t}`},body:{value:o.value}}),"cardStore.patch"),{status:"success",data:{boardId:e,cardId:s,key:t}}}async function p(o){let{cardId:s}=g(o),t=E(o),r=await T(S().get({params:{id:s}}),"cardStore.get"),i=Array.isArray(r.cards)&&r.cards.length>0&&r.cards[0]&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null;if(!i)throw Object.assign(new Error(`Card "${s}" not found`),{statusCode:404});let w=D(i,t);return {status:"success",data:{boardId:e,cardId:s,key:t,exists:w.exists,value:w.value}}}return {requireCardArgs:g,subscribeChat:_,unsubscribeChat:d,watchChannel:b,setChatProcessing:l,getChatProcessing:f,setCardMeta:y,getCardMeta:p}}function ie(a){let{boardId:e,boardContexts:c,readChatRecords:m,getChatProcessing:I}=a,h=Number.isInteger(a.chatBootstrapTailTurns)&&a.chatBootstrapTailTurns>0?a.chatBootstrapTailTurns:1;function R(d){return {role:String(d.role||"system"),text:String(d.text||""),files:Array.isArray(d.files)?d.files:[],...typeof d.turn=="string"&&d.turn?{turn:d.turn}:{}}}function S(d){if(d.length===0)return null;if(d.length===1)return d[0];let b=[],l=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],f={};for(let p of l)f[p]=0;for(let p of d){let o=p,s=Array.isArray(o.cards)?o.cards:[];b.push(...s);for(let t of l)f[t]+=Number(o?.summary?.[t]||0);}let y=d[0];return {...y,cards:b,summary:{...y.summary||{},card_count:b.length,...f}}}async function n(){let d=[];for(let b of c)try{let l=await b.boardOps.buildSseOneShotPayload({});l.status==="success"&&l.data&&d.push(l.data);}catch{}return d}async function C(){let b=(await n()).map(l=>l.statusSnapshot).filter(Boolean);if(b.length===0){let l=c.map(f=>f.notification.status).filter(Boolean);return S(l)}return S(b)}async function k(){let d={},b=await n();for(let l of b)Object.assign(d,l.cardRuntimeById||{});if(Object.keys(d).length>0)return d;for(let l of c)for(let[f,y]of Object.entries(l.notification.computedValues)){let p=l.notification.cards[f];d[f]={schema_version:"v1",card_id:f,card_data:p?.card_data??{},computed_values:y??{}};}return d}async function g(){let d={},b=await n();for(let l of b)Object.assign(d,l.dataObjectsByToken||{});if(Object.keys(d).length===0)for(let l of c)Object.assign(d,l.notification.dataObjects||{});return d}async function _(){let d=await n(),b=d.flatMap(p=>Array.isArray(p.cardDefinitions)?p.cardDefinitions:[]),l={},f={};for(let p of d)Object.assign(l,p.dataObjectsByToken||{}),Object.assign(f,p.cardRuntimeById||{});let y={};for(let p of b){if(!p?.id)continue;let o=p.id;try{let s=await m(o,{tailTurns:h}),t=await I(o);(s.length>0||t)&&(y[o]={messages:s.map(r=>R(r)),receiving:!1,processing:t});}catch{}}return {boardId:e,cardDefinitions:b,statusSnapshot:await C(),dataObjectsByToken:l,cardRuntimeById:f,cardChatsByCardId:y}}return {readStatusSnapshot:C,readCardRuntimeArtifacts:k,readDataObjectsByToken:g,buildPublishedRuntimePayload:_}}function K(a){let e=String(a||"").trim();if(!e)return "upload.bin";let c=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (c>=0?e.slice(c+1):e)||"upload.bin"}function ce(a){let{safeCardId:e,artifactsStores:c,cardFileMetadataStore:m,readCardFromStore:I,updateCardLocalOnly:h,writeChatRecord:R}=a;async function S(g){let _=[];try{let d=await I(g);if(!d)return _;let b=m().read(d.card_data&&typeof d.card_data=="object"?d.card_data:null);for(let l of b)_.push(String(l.stored_name??""));}catch{}return _}async function n(g,_,d,b,l){let f=e(g),y=c(g),p=K(_),o=typeof l=="number"?l:(await S(g)).length,t=`${String(o+1).padStart(3,"0")}-${p}`.slice(-36);if(!y.files)throw Object.assign(new Error(`artifactsStoreRef is not configured for card uploads: ${g}`),{statusCode:500});return await y.files.putBytes(`${f}/${t}`,new Uint8Array(b),d||"application/octet-stream"),{name:p,stored_name:t,size:b.length,mime_type:d||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function C(g,_,d,b,l){if(!b.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let f=l?.inChat===true,y=await n(g,_,d,b),p=null;if(await h(g,o=>{let s=new Date().toISOString(),t=o.card_data&&typeof o.card_data=="object"?o.card_data:{};o.card_data=t;let r=m().normalizeIncoming([{name:y.name,stored_name:y.stored_name,size:y.size,mime_type:y.mime_type,uploaded_at:y.uploaded_at||s,chat:f}],s);return p=m().merge(t,r).findIndex(w=>w.stored_name===y.stored_name),o}),f&&l?.suppressChatRecordWrite!==true){let o=typeof p=="number"&&p>=0?` #${p}`:"";await R(g,"system",`file uploaded: ${y.name} as ${y.stored_name}${o}`,[],l?.turnId??"");}return {ok:true,file:{...y,...typeof p=="number"&&p>=0?{file_idx:p}:{},chat:f},...typeof p=="number"&&p>=0?{file_idx:p}:{}}}async function k(g,_,d){if(!Array.isArray(_)||_.length===0)throw Object.assign(new Error("uploadCardFilesMultiple requires at least one file"),{statusCode:400});for(let s of _)if(!s.buffer.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let l=(await S(g)).length,f=[];for(let s of _){let t=await n(g,s.requestedName,s.contentType,s.buffer,l);f.push(t),l+=1;}let y=typeof d?.message=="string"?d.message:"",p=[],o={};return await h(g,s=>{let t=new Date().toISOString(),r=s.card_data&&typeof s.card_data=="object"?s.card_data:{};s.card_data=r;let i=m().normalizeIncoming(f.map(P=>({name:P.name,stored_name:P.stored_name,size:P.size,mime_type:P.mime_type,uploaded_at:P.uploaded_at||t,chat:false})),t),w=m().merge(r,i);p.length=0;for(let P of f)p.push(w.findIndex(M=>M.stored_name===P.stored_name));let x=Array.isArray(r.filegroups)?r.filegroups:[];return o={message:y,file_idxs:p.slice(),created_at:t},x.push(o),r.filegroups=x,s}),{ok:true,files:f.map((s,t)=>({...s,file_idx:p[t],chat:false})),file_idxs:p.slice(),filegroup:o}}return {uploadCardFile:C,uploadCardFilesMultiple:k,readCardStoredFileNames:S}}function pe(a){return {"discover.source-kinds":()=>a.discoverSourceKinds(),"inspect.board-runtime-status":()=>a.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>a.inspectCardDefinitionAndRuntime({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let c=chunkLPXVVMQT_cjs.b(e,"tail_turns"),m=chunkLPXVVMQT_cjs.b(e,"tail"),I=chunkLPXVVMQT_cjs.a(e,"turn_id"),h=e.all_turns===true,R=chunkLPXVVMQT_cjs.a(e,"tail_turns_before_id");return a.inspectChatMessagesOnCards({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),...c!==void 0?{lastUserTurns:c}:{},...m!==void 0?{tail:m}:{},...I?{turnId:I}:{},...h?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":e=>a.inspectFileContents({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),fileIdx:Number(chunkLPXVVMQT_cjs.b(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>a.preflightValidateCandidateCardDefinition({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>a.preflightMaterializeCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires"),mockFetchedSources:chunkLPXVVMQT_cjs.d(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>a.preflightProbeSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>a.preflightRunSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>a.preflightRunSingleSourceInLiveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>a.preflightRunOneCycleWithCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.c(e,"mock_requires")}),"manage.read-card":e=>a.manageReadCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let c=chunkLPXVVMQT_cjs.a(e,"turn_id");if(!c)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return a.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...c?{turn:c}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"stage-ai-failure-message":e=>{let c=chunkLPXVVMQT_cjs.a(e,"turn_id"),m=chunkLPXVVMQT_cjs.a(e,"failure");if(!c)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty turn_id"),{statusCode:400});if(!m)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty failure"),{statusCode:400});return a.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),role:"system",text:m,turn:c})},"manage.upsert-card":e=>a.manageUpsertCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),candidateCardContent:chunkLPXVVMQT_cjs.c(e,"candidate_card_content")}),"manage.remove-card":e=>a.manageRemoveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")})}}function me(a){return {"webhook.process-accumulated":()=>a.webhookProcessAccumulated(),"webhook.source-fetch-done":e=>a.webhookSourceFetchDone({token:chunkLPXVVMQT_cjs.a(e,"token"),ref:chunkLPXVVMQT_cjs.a(e,"ref")}),"webhook.source-fetch-failed":e=>a.webhookSourceFetchFailed({token:chunkLPXVVMQT_cjs.a(e,"token"),reason:chunkLPXVVMQT_cjs.a(e,"reason")})}}function fe(a){let{boardId:e,uploadCardFile:c,uploadCardFilesMultiple:m,getMcpFacade:I,controlplane:h}=a;function R(n,C){let k=chunkLPXVVMQT_cjs.a(n,"board_id");if(!k)throw Object.assign(new Error(`${C} requires board_id`),{statusCode:400});if(k!==e)throw Object.assign(new Error(`Unknown board_id: ${k}`),{statusCode:400})}function S(n,C){let{cardId:k}=h.requireCardArgs(n),g=chunkLPXVVMQT_cjs.a(n,"turn_id");return R(n,C),I().manageAddChatAttachment({cardId:k,role:chunkLPXVVMQT_cjs.a(n,"role")||"user",...g?{turn:g}:{},files:[{file_name:chunkLPXVVMQT_cjs.a(n,"file_name"),content_type:chunkLPXVVMQT_cjs.a(n,"content_type")||"application/octet-stream",...typeof n.text=="string"?{text:n.text}:{},...typeof n.base64=="string"?{base64:n.base64}:{},...Array.isArray(n.bytes)?{bytes:n.bytes}:{}}]})}return {"list-runtime-cards":n=>(R(n,"list-runtime-cards"),I().listRuntimeCards()),"sse.subscribe-chat":n=>h.subscribeChat(n),"sse.unsubscribe-chat":n=>h.unsubscribeChat(n),"sse.watch-channel":n=>h.watchChannel(n,true),"sse.unwatch-channel":n=>h.watchChannel(n,false),"getstate.is-chat-processing":n=>h.getChatProcessing(n),"setstate.chat-processing-started":n=>h.setChatProcessing(n,true),"setstate.chat-processing-done":n=>h.setChatProcessing(n,false),"getstate.card-private":n=>h.getCardMeta(n),"setstate.card-private":n=>h.setCardMeta(n),"manage.upload-card-file":n=>{let C=chunkLPXVVMQT_cjs.a(n,"card_id"),k=chunkLPXVVMQT_cjs.a(n,"file_name"),g=chunkLPXVVMQT_cjs.a(n,"content_type")||"application/octet-stream",_=chunkLPXVVMQT_cjs.f(n);if(R(n,"manage.upload-card-file"),!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!k)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!_)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return c(C,k,g,_,{inChat:false})},"manage.upload-card-file-multiple":n=>{let C=chunkLPXVVMQT_cjs.a(n,"card_id"),k=chunkLPXVVMQT_cjs.a(n,"message"),g=Array.isArray(n.files)?n.files:[];if(R(n,"manage.upload-card-file-multiple"),!C)throw Object.assign(new Error("manage.upload-card-file-multiple requires card_id"),{statusCode:400});if(g.length===0)throw Object.assign(new Error("manage.upload-card-file-multiple requires a non-empty files array"),{statusCode:400});let _=g.map((d,b)=>{let l=d&&typeof d=="object"?d:{},f=chunkLPXVVMQT_cjs.a(l,"file_name");if(!f)throw Object.assign(new Error(`manage.upload-card-file-multiple files[${b}] requires file_name`),{statusCode:400});let y=chunkLPXVVMQT_cjs.f(l);if(!y)throw Object.assign(new Error(`manage.upload-card-file-multiple files[${b}] requires bytes, text, or base64`),{statusCode:400});return {requestedName:f,contentType:chunkLPXVVMQT_cjs.a(l,"content_type")||"application/octet-stream",buffer:y}});return m(C,_,k?{message:k}:void 0)},"manage.add-chat-attachment":n=>S(n,"manage.add-chat-attachment"),"manage.add-chat-attachement":n=>S(n,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":n=>{let{cardId:C}=h.requireCardArgs(n),k=chunkLPXVVMQT_cjs.a(n,"role")||"user",g=chunkLPXVVMQT_cjs.a(n,"turn_id");return R(n,"manage.add-chat-entry-and-any-attachments"),I().manageAddChatEntryAndAnyAttachments({cardId:C,role:k,...typeof n.text=="string"?{text:n.text}:{},...g?{turn:g}:{},...Array.isArray(n.files)?{files:n.files}:{}})},"manage.patch-card":n=>{let{cardId:C}=h.requireCardArgs(n);return R(n,"manage.patch-card"),I().managePatchCard({cardId:C,patch:chunkLPXVVMQT_cjs.c(n,"patch")},{allowControlplaneOnlyCards:true})},"manage.upsert-card":n=>{let{cardId:C}=h.requireCardArgs(n);return R(n,"manage.upsert-card"),I().manageUpsertCard({cardId:C,candidateCardContent:chunkLPXVVMQT_cjs.c(n,"candidate_card_content")},{allowControlplaneOnlyCards:true})},"manage.remove-card":n=>{let{cardId:C}=h.requireCardArgs(n);return R(n,"manage.remove-card"),I().manageRemoveCard({cardId:C},{allowControlplaneOnlyCards:true})},"manage.admin-read-card":async n=>{let{cardId:C}=h.requireCardArgs(n);return {status:"success",data:{cards:await I().adminReadCard({cardId:C})}}},"manage.admin-upsert-card":n=>{let C=chunkLPXVVMQT_cjs.a(n,"board_id"),k=chunkLPXVVMQT_cjs.a(n,"card_id");if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!k)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(C!==e)throw Object.assign(new Error(`Unknown board_id: ${C}`),{statusCode:400});return I().adminUpsertCard({cardId:k,candidateCardContent:chunkLPXVVMQT_cjs.c(n,"candidate_card_content")})}}}function he(a){let{boardContexts:e,cardOwnerIndex:c,cardContextForCard:m,readStatusSnapshot:I,readDataObjectsByToken:h,readCardRuntimeArtifacts:R,readCardFromStore:S,readCardDefinitions:n,processAccumulatedLaneInternal:C,reportSourceFetched:k,reportSourceFetchFailure:g,uploadCardFile:_,chatStorePublic:d,serverUrl:b,apiBasePath:l}=a;function f(){return e[0]??null}function y(){return {async status(){let t=await I();return t==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:t}},async getOutputsDataObject(t){let r=t?.params?.key;return r?{status:"success",data:(await h())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(t){let r=t?.params?.key;return r?{status:"success",data:(await R())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(t){let r=t?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let i=m(r)??f();return i?i.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(t){let r=t?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let i=m(r)??f();return i?i.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(t){let r=t?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let i=m(r)??f();if(!i)return {status:"fail",error:"Board context is unavailable"};let w=await i.boardOps.upsertCard({params:{cardId:r,restart:t.params.restart===true}});if(w.status!=="success")return w;if(chunkBQUQTOPB_cjs.a(i.boardAdapter)){let x=await C(true);if(x.status!=="success")return x}return w}}}function p(){let t=()=>{let r=f();if(!r?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return r.nonCore};return {describeTaskExecutorCapabilities(r){return t().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return t().validateCardPreflight(r)},evalCardCompute(r){return t().evalCardCompute(r)},probeSourcePreflight(r){return t().probeSourcePreflight(r)},runSourcePreflight(r){return t().runSourcePreflight(r)},simulateCardCycle(r){return t().simulateCardCycle(r)}}}function o(){return {async get(t){let r=typeof t.params?.id=="string"?t.params.id:void 0;if(r){let i=await S(r);return i?{status:"success",data:{cards:[i]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await n()}}},async set(t){let r=t.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let i=Array.isArray(r)?r:[r];for(let w of i){let x=w,P=typeof x.id=="string"?x.id:"";if(!P)return {status:"fail",error:"each card must have a string `id` field"};let M=c.get(P)??0,L=e[M]??f();if(!L)return {status:"fail",error:"Board context is unavailable"};let U=await L.cardStoreOps.set({body:x});if(U.status!=="success")return U;c.set(P,M);}return {status:"success",data:{count:i.length}}},async del(t){let r=[t.params?.id,...t.body?.ids??[]].filter(i=>typeof i=="string"&&!!i);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let i of r){let w=m(i)??f();if(!w)return {status:"fail",error:"Board context is unavailable"};let x=await w.cardStoreOps.del({params:{id:i}});if(x.status!=="success")return x;c.delete(i);}return {status:"success",data:{count:r.length}}},async patch(t){let r=typeof t.params?.id=="string"?t.params.id:void 0,i=typeof t.params?.path=="string"?t.params.path:void 0;if(!r||!i)return {status:"fail",error:"patch requires params.id and params.path"};let w=m(r)??f();return w?w.cardStoreOps.patch(t):{status:"fail",error:"Board context is unavailable"}},async appendFiles(t){let r=typeof t.params?.id=="string"?t.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let i=m(r)??f();return i?i.cardStoreOps.appendFiles(t):{status:"fail",error:"Board context is unavailable"}}}}function s(){return chunkG5UUXBIB_cjs.a({board:y(),nonCore:p(),cardStore:o(),chatStore:d,processAccumulated:()=>C(true),sourceFetchDone:({token:t,ref:r})=>k(t,r),sourceFetchFailed:({token:t,reason:r})=>g(t,r),uploadCardFile({cardId:t,fileName:r,contentType:i,bytes:w,suppressChatRecordWrite:x}){return _(t,r,i,w,{inChat:true,...x===true?{suppressChatRecordWrite:true}:{}})},buildFileDownloadUrl({cardId:t,fileIdx:r,storedName:i}){let w=`${b||""}${l}/cards/${encodeURIComponent(t)}/files/${r}`;return i?`${w}?sn=${encodeURIComponent(i)}`:w},readFetchedSourceJsonByRef({cardId:t,ref:r}){let i=m(t)??f();if(!i||chunkBQUQTOPB_cjs.a(i.boardAdapter))return null;let P=i.boardAdapter.resolveBlob(chunkVQCIOKJV_cjs.b(r)).trim();return P?JSON.parse(P):null}})}return {mcpBoardFacade:y,mcpNonCoreFacade:p,mcpCardStoreFacade:o,createMcpFacade:s}}exports.a=J;exports.b=X;exports.c=Q;exports.d=V;exports.e=Y;exports.f=q;exports.g=T;exports.h=E;exports.i=D;exports.j=se;exports.k=ie;exports.l=ce;exports.m=pe;exports.n=me;exports.o=fe;exports.p=he;//# sourceMappingURL=chunk-23X3V5FR.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-23X3V5FR.cjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkLFVMX23W_cjs=require('./chunk-LFVMX23W.cjs'),chunkNM6O35RY_cjs=require('./chunk-NM6O35RY.cjs'),chunkNBJTYAYN_cjs=require('./chunk-NBJTYAYN.cjs'),chunk36KKCQVE_cjs=require('./chunk-36KKCQVE.cjs'),chunkBQUQTOPB_cjs=require('./chunk-BQUQTOPB.cjs'),chunkGPCMBPLK_cjs=require('./chunk-GPCMBPLK.cjs'),chunk7FGPOGRV_cjs=require('./chunk-7FGPOGRV.cjs'),chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs'),chunkMRIFSG7L_cjs=require('./chunk-MRIFSG7L.cjs'),chunkCSHNTZW4_cjs=require('./chunk-CSHNTZW4.cjs'),chunkEGZPROOH_cjs=require('./chunk-EGZPROOH.cjs'),chunkJOQWJ3VR_cjs=require('./chunk-JOQWJ3VR.cjs'),chunkSDJ3747Q_cjs=require('./chunk-SDJ3747Q.cjs'),chunkOF4FPYNI_cjs=require('./chunk-OF4FPYNI.cjs'),chunk2RIHC5TZ_cjs=require('./chunk-2RIHC5TZ.cjs');function ce(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=chunkLPXVVMQT_cjs.a(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=chunkLPXVVMQT_cjs.c(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await chunk272IYUKT_cjs.a(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:chunk272IYUKT_cjs.b(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:chunk272IYUKT_cjs.b(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ke=3e4;function Ve(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function ue(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Ve(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=chunk36KKCQVE_cjs.b(T,Date.now(),Ke);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var le={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},de="chat-handler-flow-queue",ot="__probe__echo__probe__";function Mr(g){let w=String(g.apiBasePath||"/api/board").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.queueLaneTuning??{},B=g.boardId||"",$=Number.isInteger(g.chatBootstrapTailTurns)&&g.chatBootstrapTailTurns>0?g.chatBootstrapTailTurns:1,N=g.logger||{info:console.log,warn:console.warn,error:console.error},x=g.invocationAdapter,_=g.chatFlowRunner||null,H=g.notificationTransport||null,E=g.serverUrl||null,T=g.executionExtra||{},S=g.onSseClientConnected,z=g.onSseClientDisconnected,q=g.onChannelSubscribed,K=g.onChannelUnsubscribed,l=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F(t){function e(a){return {...a,queueStorageForRef(d,C){return chunkSDJ3747Q_cjs.a(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function r(a){return {...a,queueStorageForRef(d,C){return chunkMRIFSG7L_cjs.h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c=chunkBQUQTOPB_cjs.a(t.boardAdapter)?r(t.boardAdapter):e(t.boardAdapter),j=t.nonCoreAdapter??(!chunkBQUQTOPB_cjs.a(c)&&P(c)?c:null),h=chunkBQUQTOPB_cjs.a(c)?chunkMRIFSG7L_cjs.i(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}):chunkEGZPROOH_cjs.e(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}),M=t.nonCore??(j?chunkEGZPROOH_cjs.f(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),We=c.chatStorageForRef(t.chatStoreRef),lt,Je=chunkBQUQTOPB_cjs.a(c)?(()=>{let a=chunkMRIFSG7L_cjs.d(chunkMRIFSG7L_cjs.c(chunkMRIFSG7L_cjs.b(c.kvStorageForRef(t.cardStoreRef)),c.hashFn),N.warn),d=chunkMRIFSG7L_cjs.g(a,{emitNotification:i}),C=o(d);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c.kvStorageForRef(t.cardStoreRef),C=chunkJOQWJ3VR_cjs.H(chunkJOQWJ3VR_cjs.m({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i});return lt=C,n(C)})(),ft;if(chunkBQUQTOPB_cjs.a(c)){let a=c.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c.blobStorageForRef(t.artifactsStoreRef),d=chunkNBJTYAYN_cjs.a(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let ze={async init(a){return h.init(a)},async status(a){return h.status(a)},async getConfig(a){return h.getConfig(a)},async getAllOutputsDataObjects(a){return h.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h.buildSseOneShotPayload(a)},async upsertCard(a){return h.upsertCard(a)},async removeCard(a){return h.removeCard(a)},async sourceDataFetched(a){return h.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h.sourceDataFetchFailure(a)}};return s={label:t.label,board:h,nonCore:M,publicCardStore:lt,boardOps:ze,cardStoreOps:Je,get filesArtifacts(){return ft},get chatStorage(){return We},boardAdapter:c,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:chunk36KKCQVE_cjs.c(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p=g.boards.map(F),f=new Map;function y(t){return f.get(t)??0}function k(t){return t.queueStoreRef}function u(t,e){if(chunkBQUQTOPB_cjs.a(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k(t),e);return chunkCSHNTZW4_cjs.a(n)}let r=t.boardAdapter.queueStorageForRef(k(t),e);return chunkGPCMBPLK_cjs.a(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return chunkNBJTYAYN_cjs.c()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p[0]??void 0}function ct(t,e={}){if(!t||t.length===0)return;let r=chunk2RIHC5TZ_cjs.e(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e.ctx??U(r);if(e.appendState!==false&&o&&chunk36KKCQVE_cjs.e(o.notification,n),e.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store"||i.category==="chat-store"||i.category==="hosted-runtime");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function fe(t){if(!t||t.notificationTeardown||!H||!t.notifyRef)return;let e=await H.subscribe(t.notifyRef,r=>{let n=chunk36KKCQVE_cjs.a(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function pe(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await fe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&chunk36KKCQVE_cjs.d(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G(){for(let t of p)await pe(t);}async function at(){await G();for(let t=0;t<p.length;t++)await ut(p[t]),await Rt(p[t],t),await ut(p[t]);}async function yt(t=false){t||await G();for(let e of p){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function me(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p)e.push(...await t(r));return e}function ht(){return p[0]??null}function ge(t){return W(t)??ht()}function L(t){let e=ge(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function Re(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=chunkOF4FPYNI_cjs.a({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=chunk36KKCQVE_cjs.p({boardContexts:p,cardOwnerIndex:f,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Se(),readDataObjectsByToken:()=>Ae(),readCardRuntimeArtifacts:()=>Ce(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>me(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>kt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Pt(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>Ct(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),ye=wt.mcpCardStoreFacade,st=wt.createMcpFacade,he=chunk36KKCQVE_cjs.j({boardId:B,bootstrapBoard:()=>at(),sseHub:l,onChannelSubscribed:q,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>ye()});function we(t){return chunk36KKCQVE_cjs.m(t)}function be(){return chunk36KKCQVE_cjs.n(st())}function bt(){return chunk36KKCQVE_cjs.o({boardId:B,uploadCardFile:Ct,getMcpFacade:()=>st(),controlplane:he})}let it=chunk36KKCQVE_cjs.k({boardId:B,boardContexts:p,readChatRecords:(t,e)=>ve(t,e),getChatProcessing:t=>Re(t),chatBootstrapTailTurns:$}),Se=it.readStatusSnapshot,Ce=it.readCardRuntimeArtifacts,Ae=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function Be(t,e){await St(t,e,{syncBoard:true});}async function ke(t,e){await St(t,e,{syncBoard:false});}async function Pe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Oe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function Fe(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function ve(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=chunk36KKCQVE_cjs.l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>ke(t,e),writeChatRecord:(t,e,r,n,o)=>Fe(t,e,r,n,o)}).uploadCardFile;async function At(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function xe(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Te(t,e,r=false,n="",o=""){try{let s=await At(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:de}}:j;chunkBQUQTOPB_cjs.a(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function Ne(t,e,r){if(e.howToRun==="built-in"&&chunkBQUQTOPB_cjs.b(e)===de){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Ee(t,e=false){e||await G();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await Ne(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function je(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=xe(r?.text),c=i?i.text:r?.text,j=await chunk272IYUKT_cjs.a("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await chunk272IYUKT_cjs.a("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(M,`chat-send processing update failed for card ${t}`));Te(t,h,true,o,i?.assistant||"");return}await Be(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function Bt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function Me(t,e,r,n){let{fileRecord:o,bytes:s}=await Bt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function _e(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function De(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
|
|
2
|
-
`)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(chunkBQUQTOPB_cjs.d(e)).trim();return r?JSON.parse(r):{}}async function
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkLFVMX23W_cjs=require('./chunk-LFVMX23W.cjs'),chunkNM6O35RY_cjs=require('./chunk-NM6O35RY.cjs'),chunkNBJTYAYN_cjs=require('./chunk-NBJTYAYN.cjs'),chunk23X3V5FR_cjs=require('./chunk-23X3V5FR.cjs'),chunkBQUQTOPB_cjs=require('./chunk-BQUQTOPB.cjs'),chunkGPCMBPLK_cjs=require('./chunk-GPCMBPLK.cjs'),chunk7FGPOGRV_cjs=require('./chunk-7FGPOGRV.cjs'),chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs'),chunkTIQ775WI_cjs=require('./chunk-TIQ775WI.cjs'),chunkCSHNTZW4_cjs=require('./chunk-CSHNTZW4.cjs'),chunkC7RR2JCL_cjs=require('./chunk-C7RR2JCL.cjs'),chunkCAID4CGO_cjs=require('./chunk-CAID4CGO.cjs'),chunkSDJ3747Q_cjs=require('./chunk-SDJ3747Q.cjs'),chunkOF4FPYNI_cjs=require('./chunk-OF4FPYNI.cjs'),chunk2RIHC5TZ_cjs=require('./chunk-2RIHC5TZ.cjs');function ue(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=chunkLPXVVMQT_cjs.a(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=chunkLPXVVMQT_cjs.c(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await chunk272IYUKT_cjs.a(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:chunk272IYUKT_cjs.b(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:chunk272IYUKT_cjs.b(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ge=3e4;function Qe(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function de(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Qe(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=chunk23X3V5FR_cjs.b(T,Date.now(),Ge);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var fe={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},le="chat-handler-flow-queue",ot="__probe__echo__probe__";function _r(g){let w=String(g.apiBasePath||"/api/board").replace(/\/$/,""),b={...fe,...g.corsHeaders||{}},I=g.queueLaneTuning??{},B=g.boardId||"",$=Number.isInteger(g.chatBootstrapTailTurns)&&g.chatBootstrapTailTurns>0?g.chatBootstrapTailTurns:1,N=g.logger||{info:console.log,warn:console.warn,error:console.error},x=g.invocationAdapter,_=g.chatFlowRunner||null,H=g.notificationTransport||null,E=g.serverUrl||null,T=g.executionExtra||{},S=g.onSseClientConnected,z=g.onSseClientDisconnected,q=g.onChannelSubscribed,K=g.onChannelUnsubscribed,l=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F(t){function e(a){return {...a,queueStorageForRef(d,C){return chunkSDJ3747Q_cjs.a(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function r(a){return {...a,queueStorageForRef(d,C){return chunkTIQ775WI_cjs.h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c=chunkBQUQTOPB_cjs.a(t.boardAdapter)?r(t.boardAdapter):e(t.boardAdapter),j=t.nonCoreAdapter??(!chunkBQUQTOPB_cjs.a(c)&&P(c)?c:null),h=chunkBQUQTOPB_cjs.a(c)?chunkTIQ775WI_cjs.i(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}):chunkC7RR2JCL_cjs.e(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}),M=t.nonCore??(j?chunkC7RR2JCL_cjs.f(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),ze=c.chatStorageForRef(t.chatStoreRef),lt,Ke=chunkBQUQTOPB_cjs.a(c)?(()=>{let a=chunkTIQ775WI_cjs.d(chunkTIQ775WI_cjs.c(chunkTIQ775WI_cjs.b(c.kvStorageForRef(t.cardStoreRef)),c.hashFn),N.warn),d=chunkTIQ775WI_cjs.g(a,{emitNotification:i}),C=o(d);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c.kvStorageForRef(t.cardStoreRef),C=chunkCAID4CGO_cjs.H(chunkCAID4CGO_cjs.m({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i});return lt=C,n(C)})(),ft;if(chunkBQUQTOPB_cjs.a(c)){let a=c.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c.blobStorageForRef(t.artifactsStoreRef),d=chunkNBJTYAYN_cjs.a(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let Ve={async init(a){return h.init(a)},async status(a){return h.status(a)},async getConfig(a){return h.getConfig(a)},async getAllOutputsDataObjects(a){return h.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h.buildSseOneShotPayload(a)},async upsertCard(a){return h.upsertCard(a)},async removeCard(a){return h.removeCard(a)},async sourceDataFetched(a){return h.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h.sourceDataFetchFailure(a)}};return s={label:t.label,board:h,nonCore:M,publicCardStore:lt,boardOps:Ve,cardStoreOps:Ke,get filesArtifacts(){return ft},get chatStorage(){return ze},boardAdapter:c,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:chunk23X3V5FR_cjs.c(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p=g.boards.map(F),f=new Map;function y(t){return f.get(t)??0}function k(t){return t.queueStoreRef}function u(t,e){if(chunkBQUQTOPB_cjs.a(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k(t),e);return chunkCSHNTZW4_cjs.a(n)}let r=t.boardAdapter.queueStorageForRef(k(t),e);return chunkGPCMBPLK_cjs.a(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return chunkNBJTYAYN_cjs.c()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p[0]??void 0}function ct(t,e={}){if(!t||t.length===0)return;let r=chunk2RIHC5TZ_cjs.e(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e.ctx??U(r);if(e.appendState!==false&&o&&chunk23X3V5FR_cjs.e(o.notification,n),e.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store"||i.category==="chat-store"||i.category==="hosted-runtime");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function pe(t){if(!t||t.notificationTeardown||!H||!t.notifyRef)return;let e=await H.subscribe(t.notifyRef,r=>{let n=chunk23X3V5FR_cjs.a(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function me(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await pe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&chunk23X3V5FR_cjs.d(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G(){for(let t of p)await me(t);}async function at(){await G();for(let t=0;t<p.length;t++)await ut(p[t]),await Rt(p[t],t),await ut(p[t]);}async function yt(t=false){t||await G();for(let e of p){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function ge(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p)e.push(...await t(r));return e}function ht(){return p[0]??null}function Re(t){return W(t)??ht()}function L(t){let e=Re(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function ye(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=chunkOF4FPYNI_cjs.a({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=chunk23X3V5FR_cjs.p({boardContexts:p,cardOwnerIndex:f,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Ce(),readDataObjectsByToken:()=>Be(),readCardRuntimeArtifacts:()=>Ae(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>ge(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>Pt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Ot(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>At(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),he=wt.mcpCardStoreFacade,st=wt.createMcpFacade,we=chunk23X3V5FR_cjs.j({boardId:B,bootstrapBoard:()=>at(),sseHub:l,onChannelSubscribed:q,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>he()});function be(t){return chunk23X3V5FR_cjs.m(t)}function Se(){return chunk23X3V5FR_cjs.n(st())}function bt(){return chunk23X3V5FR_cjs.o({boardId:B,uploadCardFile:At,uploadCardFilesMultiple:Te,getMcpFacade:()=>st(),controlplane:we})}let it=chunk23X3V5FR_cjs.k({boardId:B,boardContexts:p,readChatRecords:(t,e)=>xe(t,e),getChatProcessing:t=>ye(t),chatBootstrapTailTurns:$}),Ce=it.readStatusSnapshot,Ae=it.readCardRuntimeArtifacts,Be=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function ke(t,e){await St(t,e,{syncBoard:true});}async function Pe(t,e){await St(t,e,{syncBoard:false});}async function Oe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Fe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function ve(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function xe(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=chunk23X3V5FR_cjs.l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>Pe(t,e),writeChatRecord:(t,e,r,n,o)=>ve(t,e,r,n,o)}),At=Ct.uploadCardFile,Te=Ct.uploadCardFilesMultiple;async function Bt(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function Ne(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Ee(t,e,r=false,n="",o=""){try{let s=await Bt(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:le}}:j;chunkBQUQTOPB_cjs.a(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function je(t,e,r){if(e.howToRun==="built-in"&&chunkBQUQTOPB_cjs.b(e)===le){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Me(t,e=false){e||await G();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await je(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function _e(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=Ne(r?.text),c=i?i.text:r?.text,j=await chunk272IYUKT_cjs.a("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await chunk272IYUKT_cjs.a("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(M,`chat-send processing update failed for card ${t}`));Ee(t,h,true,o,i?.assistant||"");return}await ke(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function kt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function De(t,e,r,n){let{fileRecord:o,bytes:s}=await kt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function Ie(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function qe(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
|
|
2
|
+
`)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(chunkBQUQTOPB_cjs.d(e)).trim();return r?JSON.parse(r):{}}async function Pt(t,e){let r=typeof e.ref=="string"?e.ref.trim():"";if(!r)return {status:"fail",error:"board-worker success callback requires body.ref"};let n=p[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function Ot(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=p[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let $e=chunkLFVMX23W_cjs.b({sseHub:l,queueSseHub:R,corsHeaders:b,json:et,buildPublishedRuntimePayload:()=>dt(),onSseClientConnected:S,onChannelSubscribed:q,onChannelUnsubscribed:K,apiBasePath:w,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),bootstrapBoard:()=>at(),boardContexts:p,publishPersistedStateSnapshot:t=>ut(t),upsertCardsFromSource:(t,e)=>Rt(t,e)}).handleWatchersRoutes,He=chunk7FGPOGRV_cjs.a({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpFacade:()=>st(),createMcpToolRegistry:t=>be(t),resolveCardFileDownloadPayload:(t,e,r)=>kt(t,e,r),isLikelyTextMimeType:t=>Ie(t),sliceTextByLines:(t,e,r)=>qe(t,e,r)}).handleAgentfaceApi,Le=chunkNM6O35RY_cjs.a({apiBasePath:w,json:et,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),createMcpWebhookToolRegistry:()=>Se()}).handleWebhooksApi,Ue=ue({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpControlplaneToolRegistry:()=>bt(),retriggerCard:t=>Oe(t),applyCardAction:(t,e,r)=>_e(t,e,r),resolveChatHandlerTarget:t=>Bt(t),sendCardFileDownloadResponse:(t,e,r,n)=>De(t,e,r,n)}).handleRuntimeApi,We=de({apiBasePath:w,emitNotifications:t=>V(t),readJsonBody:t=>rt(t),json:(t,e,r)=>et(t,e,r)}).handleNotifyRoute;async function Je(t,e,r){return !!(await He(t,e,r)||await Le(t,e,r)||await $e(t,e,r)||await We(t,e,r)||await Ue(t,e,r))}return {get apiBasePath(){return w},get corsHeaders(){return b},get queueLaneTuning(){return I},handleRuntimeApi:Je,emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);},buildPublishedRuntimePayload:dt,__drainProcessAccumulatedLane:yt,handleChatAgentRequest:Me,clearChatRecords:Fe,reportSourceFetched(t,e){return Pt(t,{ref:e})},reportSourceFetchFailure(t,e){return Ot(t,{reason:e})},get cardStore(){return p[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Dr(g){let w=String(g.apiBasePath||"/api/boards").replace(/\/$/,""),b={...fe,...g.corsHeaders||{}},I=g.serverMetaStore,B=g.boardRuntimeFactory,$=new Map,N="boards-config.json";function x(){let l=I.getText(N);if(!l)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(l)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function _(l){I.putText(N,JSON.stringify(l,null,2));}function H(l){let R=String(l||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return R.length>0&&R.length<=64?R:null}function E(l){if($.has(l))return $.get(l);let F=x().boards.find(f=>f.id===l)||{},p=B(l,F);return $.set(l,p),p}function T(l,R,F){let p=JSON.stringify(F),f=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;l.writeHead(R,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":f}),l.end(p);}async function S(l,R,F){let p=l.method||"GET",f=F.pathname;if(p==="GET"&&f===w)return T(R,200,{ok:true,boards:x().boards}),true;if(p==="POST"&&f===w){let y=[];for await(let O of l)y.push(O);let k=typeof Buffer<"u"?Buffer.concat(y).toString("utf-8").trim():new TextDecoder().decode(chunkBQUQTOPB_cjs.d(y)).trim(),u={};try{u=k?JSON.parse(k):{};}catch{u={};}let P=H(u.id);if(!P)return T(R,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let v=x();if(v.boards.some(O=>O.id===P))return T(R,409,{error:`Board "${P}" is already registered`}),true;let A=typeof u.label=="string"&&u.label.trim()?u.label.trim():P,D={id:P,label:A};for(let[O,U]of Object.entries(u))O==="id"||O==="label"||U!=null&&(D[O]=U);return v.boards.push(D),_(v),T(R,200,{ok:true,board:D}),true}return false}async function z(l,R,F){let f=F.pathname.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/([^/]+)(/|$)`));if(!f)return false;let y=H(decodeURIComponent(f[1]));return y?x().boards.some(P=>P.id===y)?!!await E(y).handleRuntimeApi(l,R,F):(T(R,404,{error:`Board "${y}" not registered. POST ${w} with {id} to register it first.`}),true):(T(R,400,{error:"Invalid board id"}),true)}async function q(l,R,F){return !!(await S(l,R,F)||await z(l,R,F))}function K(l){if(!x().boards.some(F=>F.id===l))throw Object.assign(new Error(`Board "${l}" not registered`),{statusCode:404});return {service:E(l)}}return {get apiBasePath(){return w},get corsHeaders(){return b},handleApi:q,requireBoardService:K}}exports.a=_r;exports.b=Dr;//# sourceMappingURL=chunk-2AIIEBBL.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-2AIIEBBL.cjs.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkUJ7ZTV4J_cjs=require('./chunk-UJ7ZTV4J.cjs'),chunkGNFE24S7_cjs=require('./chunk-GNFE24S7.cjs'),$=require('ajv-formats'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var $__default=/*#__PURE__*/_interopDefault($);var g={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://nsreehari.github.io/boards/live-cards.schema.json",definitions:{bind_ref:{description:"A card data path reference, e.g. 'card_data.raw_quotes' or 'requires.upstream'",type:"string",pattern:"^(card_data|requires|fetched_sources|computed_values)(\\.|$)"},compute_expr:{description:"A declarative JSON compute expression",type:"object",required:["fn"],properties:{fn:{type:"string",description:"Function name from the built-in vocabulary",enum:["sum","avg","min","max","count","first","last","add","sub","mul","div","round","abs","mod","gt","gte","lt","lte","eq","neq","if","and","or","not","concat","upper","lower","template","filter","pluck","map","sort","slice","flat","unique","group","get","default","now","diff_days","format_date"]},input:{description:"card_data.path, literal, array of inputs, or nested compute_expr",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/definitions/compute_expr"}]},field:{type:"string",description:"For pluck/sum/group \u2014 the object key to extract"},where:{$ref:"#/definitions/compute_expr",description:"For filter \u2014 predicate expression ($ = current item)"},cond:{$ref:"#/definitions/compute_expr",description:"For if \u2014 condition expression"},then:{description:"For if \u2014 value when cond is truthy"},else:{description:"For if \u2014 value when cond is falsy"},format:{type:"string",description:"For format_date \u2014 date format string"}}},meta:{type:"object",properties:{title:{type:"string"},presentation:{type:"object",description:"Semantic presentation hints authored on the card, expressed from the user's perception of the card on the Main Canvas. Content shape is inferred from view.elements[].kind; runtime placement and live drag/resize coordinates are frontend-managed and must not be authored into card JSON.",properties:{prominence:{type:"string",default:"standard",description:"How much the user should care about this card / how much attention it earns. Default: standard; omit unless a non-standard value is needed.",enum:["glance","standard","feature","spotlight"]},footprint:{type:"string",default:"standard",description:"How much room the card wants to render well, independent of attention. Default: standard; omit unless a non-standard value is needed.",enum:["compact","standard","wide","large"]},resizable:{type:"boolean",default:true,description:"Whether the user may resize this card at runtime. Default: true; omit unless it must be false."}},additionalProperties:true},tags:{type:"array",items:{type:"string"}}},additionalProperties:true},__private:{description:"Control-plane-owned private state. Stripped entirely from all regular /mcp read responses. Writable only via 'setstate.card-private' and 'manage.admin-upsert-card'. Agents must never author this field. Keys inside use plain names (no leading underscores).",type:"object",additionalProperties:true},requires:{type:"array",items:{type:"string"},description:"IDs of upstream nodes this node depends on"},provides:{type:"array",items:{type:"object",required:["bindTo","ref"],properties:{bindTo:{type:"string",description:"Token name published downstream"},ref:{type:"string",description:"Path to read value from (card_data.*, requires.*, fetched_sources.*, computed_values.*)"}}},description:"Explicit bindings exposing computed or card_data values downstream as named tokens"},compute_step:{description:"A single ordered compute step: reads card_data.*/requires.*/computed_values.*, writes to computed_values[bindTo]",type:"object",required:["bindTo","expr"],properties:{bindTo:{type:"string",description:"Key in computed_values to write result"},expr:{type:"string",description:"JSONata expression evaluated against { card_data, requires, fetched_sources, computed_values }"}}},source_def:{description:"One source entry. The engine requires 'bindTo' (compute namespace key) and 'outputFile' (delivery signal path). bindTo and outputFile must be unique across all source_defs in a card. Every other property is yours \u2014 add whatever your task-executor needs: kind, url, headers, mailbox, channel, model, query, etc. The full object is passed verbatim as the --in JSON to the executor.",type:"object",required:["bindTo","outputFile"],additionalProperties:true,properties:{bindTo:{type:"string",description:"Key under fetched_sources.* available in compute expressions"},outputFile:{type:"string",description:"Board-relative path the executor writes its JSON result to. Presence of this file signals delivery."},projections:{type:"object",description:"Named data projections from card_data or requires, evaluated before the executor is called. Each key is a ref name; each value is a JSONata expression rooted at card_data or requires. The resolved values are passed to the executor as _projections. fetched_sources, computed_values, and source_defs are not accessible here \u2014 sources run before those exist.",additionalProperties:{type:"string"}},skip_when:{type:"string",description:"JSONata over card_data/requires. Truthy skips this source."},timeout:{type:"integer",minimum:0,default:12e4,description:"Executor/script timeout in ms. Default: 120 000 (2 min)."},script:{type:"string",description:"Legacy direct-run: shell command executed when no .task-executor is registered. stdout is captured as the result."}}},render_element:{type:"object",required:["kind"],additionalProperties:false,properties:{kind:{enum:["metric","table","editable-table","chart","form","list","notes","todo","alert","narrative","badge","text","markdown","markup","selection","searchbox","query","ref","custom","actions","multi-file-upload"]},id:{type:"string",description:"Optional element ID for targeted updates and action routing"},label:{type:"string",description:"Heading above this element (also the metric/alert title)"},className:{type:"string",description:"Bootstrap grid class, e.g. 'col-12 col-md-6'"},containerStyle:{type:"object",description:"Inline style applied to the element container"},visible:{type:"string",description:"card_data/requires/fetched_sources/computed_values path \u2014 element shown only if truthy"},data:{allOf:[{$ref:"#/definitions/value_source"}],description:"The element value: { bind } (dynamic) or { value } (static literal)"},writeTo:{$ref:"#/definitions/write_ref"},spec:{type:"object",description:"Per-kind static configuration (constrained per kind below)"}},allOf:[{if:{properties:{kind:{const:"metric"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"table"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_table"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"list"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_table"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"chart"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_chart"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"alert"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_alert"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"badge"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_badge"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"narrative"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"text"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_text"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"markdown"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"markup"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"},writeTo:false},required:["data"]}},{if:{properties:{kind:{const:"actions"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_actions"},data:false,writeTo:false}}},{if:{properties:{kind:{const:"selection"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_single_field"}}}},{if:{properties:{kind:{const:"searchbox"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_searchbox"}}}},{if:{properties:{kind:{const:"query"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_searchbox"}}}},{if:{properties:{kind:{const:"form"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_form"}}}},{if:{properties:{kind:{const:"notes"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"}}}},{if:{properties:{kind:{const:"todo"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_empty"}}}},{if:{properties:{kind:{const:"editable-table"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_editable_table"}}}},{if:{properties:{kind:{const:"ref"}},required:["kind"]},then:{properties:{spec:{$ref:"#/definitions/spec_ref"}}}}]},view:{type:"object",required:["elements"],properties:{elements:{type:"array",minItems:1,items:{$ref:"#/definitions/render_element"}}}},value_source:{description:"Element value source. Exactly one of `bind` (dynamic path) or `value` (static inline literal).",type:"object",oneOf:[{required:["bind"],additionalProperties:false,properties:{bind:{$ref:"#/definitions/bind_ref",description:"card_data/requires/fetched_sources/computed_values path to read the value from"}}},{required:["value"],additionalProperties:false,properties:{value:{description:"Static inline literal value (no binding)."}}}]},write_ref:{type:"string",pattern:"^card_data(\\.|$)",description:"card_data path the element writes user input to (input kinds only)"},spec_empty:{type:"object",additionalProperties:false,properties:{}},spec_table:{type:"object",additionalProperties:false,properties:{columns:{type:"array",items:{type:"string"},description:"Visible columns, in order"},maxRows:{type:"integer",description:"Max rows to display"},sortable:{type:"boolean",default:true,description:"Enable click-to-sort"},placeholder:{type:"string",description:"Empty-state message"}}},spec_chart:{type:"object",additionalProperties:false,properties:{chartType:{enum:["bar","line","area","scatter","pie","doughnut"],description:"Explicit chart type (else auto-detected)"},columns:{type:"array",items:{type:"string"},description:"First column is the label/x axis; rest are series"},labelKey:{type:"string",description:"Row key to use as the category/x label"},xKey:{type:"string",description:"Row key to use as the x axis (line charts)"},series:{type:"array",items:{type:"string"},description:"Row keys to plot as series"},stacked:{type:"boolean",description:"Stack bar/area series"},legend:{type:"boolean",default:true,description:"Show the legend"},grid:{type:"boolean",default:true,description:"Show the cartesian grid"},height:{type:"integer",default:220,description:"Chart height in pixels"}}},spec_alert:{type:"object",additionalProperties:false,properties:{thresholds:{type:"object",additionalProperties:false,properties:{green:{type:"string",description:"Comparison expr, e.g. '>=80'"},amber:{type:"string",description:"Comparison expr, e.g. '>=50'"}}}}},spec_badge:{type:"object",additionalProperties:false,properties:{colorMap:{type:"object",additionalProperties:{type:"string"},description:"value \u2192 tone/Bootstrap color"}}},spec_text:{type:"object",additionalProperties:false,properties:{format:{enum:["default","file-links"],description:"'file-links' renders the bound file array as download links"},style:{enum:["default","muted","muted-italic","heading"],description:"Display style"},hideIfEmpty:{type:"boolean",description:"Render nothing when the value is empty"}}},spec_actions:{type:"object",additionalProperties:false,required:["buttons"],properties:{buttons:{type:"array",description:"Button definitions; clicks emit an action save keyed by element id + button id",items:{type:"object",required:["id","label"],additionalProperties:false,properties:{id:{type:"string"},label:{type:"string"},style:{type:"string",description:"Bootstrap button variant, e.g. 'success', 'outline-danger'"},size:{type:"string",default:"sm"},disabled:{oneOf:[{type:"boolean"},{type:"string",description:"card_data/requires/fetched_sources/computed_values path \u2014 truthy = disabled"}]}}}}}},spec_form:{type:"object",additionalProperties:false,required:["fields"],properties:{fields:{type:"object",description:"JSON-Schema-ish { properties, required } describing the form fields"},discardLabel:{type:"string"},saveLabel:{type:"string"},validators:{type:"array",description:"Cross-field validation rules. Each item is a [jsonataExpr, errorMessage] pair; the expr is evaluated against { data: <current field values> } and must return true to pass. Required-field emptiness is already handled by fields.required, so validators are for format/relationship rules. Runs on blur and submit.",items:{type:"array",minItems:2,maxItems:2,items:{type:"string"}}}}},spec_single_field:{type:"object",additionalProperties:false,required:["fields"],properties:{fields:{type:"object",description:"Single-property JSON-Schema-ish { properties, required } for the control"}}},spec_searchbox:{type:"object",additionalProperties:false,required:["fields"],properties:{fields:{type:"object",description:"Single-property JSON-Schema-ish { properties, required } for the query field"},actionLabel:{type:"string",description:"Submit button label (default 'Search')"}}},spec_editable_table:{type:"object",additionalProperties:false,properties:{schema:{type:"object",description:"JSON-Schema-ish { properties } describing per-column cell types"},columns:{type:"array",items:{type:"string"},description:"Explicit column order"},addRow:{type:"boolean",default:true},deleteRow:{type:"boolean",default:true},placeholder:{type:"string"}}},spec_ref:{type:"object",additionalProperties:true,required:["viewBind"],properties:{viewBind:{$ref:"#/definitions/bind_ref",description:"Path to a computed view descriptor { kind, data?, spec? } selecting the effective kind at runtime"},fallbackKind:{enum:["metric","table","editable-table","chart","form","list","notes","todo","alert","narrative","badge","text","markdown","markup","selection","searchbox","query","ref","custom","actions","multi-file-upload"],description:"Kind to use when viewBind is absent/unresolved"},columns:{type:"array",items:{type:"string"},description:"Columns to forward to the resolved table/list view"}}}},title:"LiveCard",description:"A unified card node. Behavior depends on which sections are present (source_defs, compute, view, etc.)",type:"object",required:["id"],additionalProperties:false,properties:{id:{type:"string"},requires:{$ref:"#/definitions/requires"},provides:{$ref:"#/definitions/provides"},meta:{$ref:"#/definitions/meta"},__private:{$ref:"#/definitions/__private"},view:{$ref:"#/definitions/view"},card_data:{type:"object",description:"User editable data on card. Includes uploaded-file metadata maintained by host handlers. Not to be used for card static content.",properties:{files:{type:"array",description:"Optional uploaded-file metadata maintained by host handlers. Stored name is normalized and serial-prefixed (for example 001-my_file.pdf).",items:{type:"object",required:["name","stored_name"],properties:{name:{type:"string",minLength:1},stored_name:{type:"string",minLength:5,maxLength:32,pattern:"^[0-9]{3,}-[a-z0-9._-]+$"},size:{oneOf:[{type:"integer",minimum:0},{type:"null"}]},mime_type:{type:"string"},path:{type:"string",pattern:"^[^\\s]+/files/[0-9]{3,}-[a-z0-9._-]+$"},uploaded_at:{type:"string",format:"date-time"},chat:{type:"boolean",description:"Whether this file entry is associated with a chat interaction"}},additionalProperties:false}},filegroups:{type:"array",description:"Optional grouped multi-file upload submissions maintained by host handlers. Each entry references files in card_data.files by index and carries an optional message. Identified by array position.",items:{type:"object",required:["file_idxs"],properties:{message:{type:"string",description:"Optional message associated with the upload group; empty string when none."},file_idxs:{type:"array",description:"Indexes into card_data.files identifying the files in this group, in upload order.",items:{type:"integer",minimum:0}},created_at:{type:"string",format:"date-time"}},additionalProperties:false}}},additionalProperties:true},source_defs:{type:"array",description:"Source entries. Each entry is passed verbatim to the board's .task-executor (registered via init --task-executor) as the --in JSON file. The executor fetches/generates the data and writes JSON to --out. If no executor is registered, the built-in executor runs the entry's 'cli' command directly. Sources gate completion.",items:{$ref:"#/definitions/source_def"}},compute:{type:"array",description:"Ordered array of compute steps. Each reads card_data.*/requires.*/fetched_sources.*/computed_values.* and writes to ephemeral computed_values[bindTo].",items:{$ref:"#/definitions/compute_step"}}}};var v=chunkGNFE24S7_cjs.b(chunkUJ7ZTV4J_cjs.q(),1);var A=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-3EITX4IQ.cjs', document.baseURI).href))),E=A("./jsonata-sync.cjs"),m=null;var _=/\b(card_data|requires|fetched_sources|computed_values|source_defs)\b/g,N=/^\s*(card_data|requires|fetched_sources|computed_values|source_defs)(\.|$)/;function P(e){let t=new Set,s;for(_.lastIndex=0;(s=_.exec(e))!==null;)t.add(s[1]);return t}function w(e){let t=N.exec(e);return t?t[1]:null}function h(e,t,s,o){try{E(e);}catch(n){let d=n instanceof Error?n.message:String(n);o.push(`${t}: invalid JSONata expression (${d})`);return}let i=P(e);for(let n of i)s.has(n)||o.push(`${t}: disallowed namespace "${n}" in expression`);}function b(e,t,s){if(Array.isArray(e)){e.forEach((i,n)=>{b(i,`${t}/${n}`,s);});return}if(typeof e=="string"){let i=w(e);if(!i)return;new Set(["card_data","requires","computed_values"]).has(i)||s.push(`${t}: disallowed namespace "${i}" in view reference`);return}if(!e||typeof e!="object")return;let o=e;for(let[i,n]of Object.entries(o))b(n,`${t}/${i}`,s);}function T(){if(m)return m;let e=new v.default({allErrors:true});return $__default.default(e),m=e.compile(g),m}function R(e){let t=T(),s=t(e),o=(t.errors??[]).map(i=>`${i.instancePath||"/"}: ${i.message??"unknown error"}`);if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.source_defs;if(Array.isArray(i)){let n=new Set,d=new Set;i.forEach((p,l)=>{if(!p||typeof p!="object"||Array.isArray(p))return;let r=p;typeof r.bindTo=="string"&&r.bindTo&&(n.has(r.bindTo)&&o.push(`/source_defs/${l}/bindTo: bindTo "${r.bindTo}" must be unique across all source_defs`),n.add(r.bindTo)),typeof r.outputFile=="string"&&r.outputFile&&(d.has(r.outputFile)&&o.push(`/source_defs/${l}/outputFile: outputFile "${r.outputFile}" must be unique across all source_defs`),d.add(r.outputFile));});}}return !s||o.length>0?{ok:false,errors:o}:{ok:true,errors:[]}}function O(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return {ok:true,errors:[]};let s=e,o=s.compute;Array.isArray(o)&&o.forEach((r,c)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r.expr;typeof a!="string"||a.trim().length===0||h(a,`/compute/${c}/expr`,new Set(["card_data","requires","fetched_sources","computed_values"]),t);});let i=new Set(["card_data","requires","fetched_sources","computed_values"]),n=s.provides;Array.isArray(n)&&n.forEach((r,c)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r.ref;if(typeof a!="string"||a.trim().length===0)return;let u=w(a);u===null?t.push(`/provides/${c}/ref: path "${a}" must start with a valid namespace (${[...i].join(", ")})`):i.has(u)||t.push(`/provides/${c}/ref: disallowed namespace "${u}" in path "${a}" (valid: ${[...i].join(", ")})`);});let d=s.view;d&&typeof d=="object"&&!Array.isArray(d)&&b(d,"/view",t);let p=new Set(["card_data","requires"]),l=s.source_defs;return Array.isArray(l)&&l.forEach((r,c)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r,u=a.skip_when;typeof u=="string"&&u.trim().length>0&&h(u,`/source_defs/${c}/skip_when`,p,t);let f=a.projections;if(!(!f||typeof f!="object"||Array.isArray(f)))for(let[k,y]of Object.entries(f))typeof y!="string"||y.trim().length===0||h(y,`/source_defs/${c}/projections/${k}`,p,t);}),{ok:t.length===0,errors:t}}function V(e){return F(e)}function F(e){let t=R(e);if(!t.ok)return t;let s=O(e);return s.ok?{ok:true,errors:[]}:{ok:false,errors:s.errors}}
|
|
2
|
+
exports.a=R;exports.b=O;exports.c=V;exports.d=F;//# sourceMappingURL=chunk-3EITX4IQ.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-3EITX4IQ.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var g=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-66ZZIF2L.cjs', document.baseURI).href))),u=g("./jsonata-sync.cjs"),c=u;function d(t,r){if(!r||!t)return;let s=r.split("."),e=t;for(let n=0;n<s.length;n++){if(e==null)return;e=e[s[n]];}return e}function f(t,r,s){let e=r.split("."),n=t;for(let o=0;o<e.length-1;o++)(n[e[o]]==null||typeof n[e[o]]!="object")&&(n[e[o]]={}),n=n[e[o]];n[e[e.length-1]]=s;}async function m(t,r){if(!t?.compute?.length)return t;t.card_data||(t.card_data={}),t.computed_values={},t._sourcesData=r?.sourcesData??{};let s=t.requires??{},e={card_data:t.card_data,requires:s,expects_data:s,fetched_sources:t._sourcesData,data:t.computed_values,computed_values:t.computed_values};for(let n of t.compute)try{let o=await u(n.expr).evaluate(e);f(t.computed_values,n.bindTo,o),e.computed_values=t.computed_values;}catch{}return t}function y(t,r){if(!t?.compute?.length)return {ok:true,node:t};t.card_data||(t.card_data={}),t.computed_values={},t._sourcesData=r?.sourcesData??{};let s=t.requires??{},e={card_data:t.card_data,requires:s,expects_data:s,fetched_sources:t._sourcesData,data:t.computed_values,computed_values:t.computed_values},n=[];for(let o of t.compute)try{let a=c(o.expr).evaluate(e);f(t.computed_values,o.bindTo,a),e.computed_values=t.computed_values;}catch(a){let i=a instanceof Error?a.message:String(a);n.push({bindTo:o.bindTo,error:i});}return n.length>0?{ok:true,node:t,errors:n}:{ok:true,node:t}}async function _(t,r,s){let e={...s??{},card_data:r.card_data??{},requires:r.requires??{},fetched_sources:r._sourcesData??{},computed_values:r.computed_values??{}};return u(t).evaluate(e)}function b(t,r){return r.startsWith("fetched_sources.")?d(t._sourcesData??{},r.slice(16)):d(t,r)}var p=new Set(["metric","table","editable-table","chart","form","list","notes","todo","alert","narrative","badge","text","markdown","markup","selection","searchbox","query","ref","custom","actions"]),h=new Set(["id","meta","requires","provides","view","card_data","compute","source_defs"]);function k(t){let r=[];if(!t||typeof t!="object"||Array.isArray(t))return {ok:false,errors:["Node must be a non-null object"]};let s=t;(typeof s.id!="string"||!s.id)&&r.push("id: required, must be a non-empty string");for(let e of Object.keys(s))h.has(e)||r.push(`Unknown top-level key: "${e}"`);if((s.card_data==null||typeof s.card_data!="object"||Array.isArray(s.card_data))&&r.push("card_data: required, must be an object"),s.meta!=null)if(typeof s.meta!="object"||Array.isArray(s.meta))r.push("meta: must be an object");else {let e=s.meta;e.title!=null&&typeof e.title!="string"&&r.push("meta.title: must be a string"),e.tags!=null&&!Array.isArray(e.tags)&&r.push("meta.tags: must be an array");}if(s.requires!=null&&!Array.isArray(s.requires)&&r.push("requires: must be an array of strings"),s.provides!=null&&(Array.isArray(s.provides)?s.provides.forEach((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))r.push(`provides[${n}]: must be an object with bindTo and ref`);else {let o=e;(typeof o.bindTo!="string"||!o.bindTo)&&r.push(`provides[${n}]: missing required "bindTo" string`),(typeof o.ref!="string"||!o.ref)&&r.push(`provides[${n}]: missing required "ref" string`);}}):r.push("provides: must be an array of { bindTo, ref } bindings")),s.compute!=null&&(Array.isArray(s.compute)?s.compute.forEach((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))r.push(`compute[${n}]: must be a compute step object`);else {let o=e;(typeof o.bindTo!="string"||!o.bindTo)&&r.push(`compute[${n}]: missing required "bindTo" property`),(typeof o.expr!="string"||!o.expr)&&r.push(`compute[${n}]: missing required "expr" string (JSONata expression)`);}}):r.push("compute: must be an array of compute steps")),s.source_defs!=null)if(!Array.isArray(s.source_defs))r.push("source_defs: must be an array");else {let e=new Set,n=new Set;s.source_defs.forEach((o,a)=>{if(!o||typeof o!="object"||Array.isArray(o))r.push(`source_defs[${a}]: must be an object`);else {let i=o;typeof i.bindTo!="string"||!i.bindTo?r.push(`source_defs[${a}]: missing required "bindTo" property`):(e.has(i.bindTo)&&r.push(`source_defs[${a}]: bindTo "${i.bindTo}" is not unique across source_defs`),e.add(i.bindTo)),typeof i.outputFile!="string"||!i.outputFile?r.push(`source_defs[${a}]: missing required "outputFile" property`):(n.has(i.outputFile)&&r.push(`source_defs[${a}]: outputFile "${i.outputFile}" is not unique across source_defs`),n.add(i.outputFile));}});}if(s.view!=null)if(typeof s.view!="object"||Array.isArray(s.view))r.push("view: must be an object");else {let e=s.view;!Array.isArray(e.elements)||e.elements.length===0?r.push("view.elements: required, must be a non-empty array"):e.elements.forEach((n,o)=>{if(!n||typeof n!="object"){r.push(`view.elements[${o}]: must be an object`);return}!n.kind||typeof n.kind!="string"?r.push(`view.elements[${o}].kind: required, must be a string`):p.has(n.kind)||r.push(`view.elements[${o}].kind: unknown kind "${n.kind}". Valid: ${[...p].join(", ")}`),n.data!=null&&(typeof n.data!="object"||Array.isArray(n.data))&&r.push(`view.elements[${o}].data: must be an object`);});}return {ok:r.length===0,errors:r}}async function w(t,r){if(!t||t.length===0)return [];let s={card_data:r.card_data??{},requires:r.requires??{}};return Promise.all(t.map(async e=>{let n=false;if(typeof e.skip_when=="string"&&e.skip_when.trim().length>0)try{n=!!await u(e.skip_when).evaluate(s);}catch{n=false;}let o={};if(!n&&e.projections&&typeof e.projections=="object"&&!Array.isArray(e.projections)){for(let[a,i]of Object.entries(e.projections))if(typeof i=="string"&&i.trim().length>0)try{o[a]=await u(i).evaluate(s);}catch{o[a]=void 0;}}return {...e,_projections:o,_skip:n}}))}function v(t,r){if(!t||t.length===0)return [];let s={card_data:r.card_data??{},requires:r.requires??{}};return t.map(e=>{let n=false;if(typeof e.skip_when=="string"&&e.skip_when.trim().length>0)try{n=!!c(e.skip_when).evaluate(s);}catch{n=false;}let o={};if(!n&&e.projections&&typeof e.projections=="object"&&!Array.isArray(e.projections)){for(let[a,i]of Object.entries(e.projections))if(typeof i=="string"&&i.trim().length>0)try{o[a]=c(i).evaluate(s);}catch{o[a]=void 0;}}return {...e,_projections:o,_skip:n}})}var j={run:m,runSync:y,eval:_,resolve:b,validate:k,enrichSources:w,enrichSourcesSync:v},$=j;exports.a=j;exports.b=$;//# sourceMappingURL=chunk-66ZZIF2L.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-66ZZIF2L.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {t}from'./chunk-FULAMLUU.js';import {a}from'./chunk-YOY2JM5N.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-4NWVZ7AW.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {t}from'./chunk-FULAMLUU.js';import {a}from'./chunk-QE3QXEHI.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-72FB4M6P.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-72FB4M6P.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$1,p,q,t as t$1}from'./chunk-FULAMLUU.js';import {D,l,z,B,i,H,G,n,h,A,q as q$1,p as p$1,E,t,m as m$1,u,F,s,o,C}from'./chunk-MRESV3MD.js';import {a,b,c}from'./chunk-44L64VQ2.js';import {a as a$2}from'./chunk-YOY2JM5N.js';import {e,f}from'./chunk-UGB7PC4P.js';function Ct(o){return typeof o=="string"&&o.trim().length>0}function ht(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.selfRef is required`);if(!Ct(o.howToRun))throw new Error(`${r}: adapter.selfRef.howToRun is required`);if(!Ct(o.whatToRun))throw new Error(`${r}: adapter.selfRef.whatToRun is required`)}function St(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.callbackTransport is required`);if(typeof o.createCallback!="function")throw new Error(`${r}: adapter.callbackTransport.createCallback is required`)}function $t(o,r="callbackTransport"){return {createCallback(S){let _=o();return ht(_,r),{token:S,via:_}}}}function Ye(o){return $t(()=>o,"createStaticExecutionRefCallbackTransport")}function Yt(o){return Ye({meta:"board-live-cards",howToRun:"http:post",whatToRun:a({kind:"http-url",value:String(o||"").trim()})})}function Ut(o){return Ye({meta:"board-live-cards",howToRun:"in-process-loop",whatToRun:a({kind:"in-process-loop",value:String(o||"").trim()})})}function Xt(o){let r=typeof o=="string"?{notifyChannel:o}:o??{},S={};return r.notifyChannel&&(S.notifyChannel=r.notifyChannel),r.boardRuntimeStoreRef&&(S.boardRuntimeStoreRef=r.boardRuntimeStoreRef),r.queueStoreRef&&(S.queueStoreRef=r.queueStoreRef),Ye({meta:"board-live-cards",howToRun:"built-in",whatToRun:a({kind:"built-in",value:"board-live-cards"}),...Object.keys(S).length>0?{extra:S}:{}})}function m(o){return o!==void 0?{status:"success",data:o}:{status:"success"}}function d(o){return {status:"fail",error:o}}function g(o){return {status:"error",error:o instanceof Error?o.message:String(o)}}function Dt(o){let r=new TextEncoder().encode(o),S=Array.from(r,_=>String.fromCharCode(_)).join("");return btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(o){let r=o.replace(/-/g,"+").replace(/_/g,"/"),S=r+"=".repeat((4-r.length%4)%4),_=atob(S),E=Uint8Array.from(_,K=>K.charCodeAt(0));return new TextDecoder().decode(E)}function Pe(o){try{let r=JSON.parse(vt(o));return typeof r?.t=="string"?{taskName:r.t}:null}catch{return null}}function bt(o){return Dt(JSON.stringify(o))}function yt(o){try{let r=JSON.parse(vt(o));return typeof r?.cbk=="string"&&typeof r?.cid=="string"&&typeof r?.b=="string"&&typeof r?.d=="string"?r:null}catch{return null}}function N(){return new Date().toISOString()}function Vt(o){let r=new Map;return {appendEntries(S,_){if(!S||_.length===0)return;let E=r.get(S)??[];r.set(S,[...E,..._]);},dispatchEntriesForJournalId(S,_){if(!S)return;let E=r.get(S);if(!(!E||E.length===0)){for(let K of E)try{_(K);}catch(j){try{o(K,j instanceof Error?j.message:String(j));}catch{}}r.delete(S);}}}}function sr(o$1,r,S={}){St(r.callbackTransport,"createBoardLiveCardsPublic");let _=r.callbackTransport,E$1=r.onWarn??(()=>{}),K=a(o$1),j=S.boardRuntimeStoreRef,G$1=S.scratchStoreRef,ce=S.taskExecutorRef,ke=S.chatHandlerFlow,Ce=S.emitNotification??(t=>{if(!r.publishBoardChangeNotifications)return;let e=t.kind==="notification-batch"?t.notifications:[t];return r.publishBoardChangeNotifications(e)});function ne(){if(!j)throw new Error(`Board at ${o$1.value} has no board runtime store configured. Pass boardRuntimeStoreRef at construction or init.`);return j}function Ne(t){if(t.length!==0)try{let e$1=e(t),s=f({kind:"notification-batch",notifications:e$1}),i=Ce(s);i&&typeof i.catch=="function"&&i.catch(f=>E$1(`[board-live-cards-public] emitNotification failed: ${f instanceof Error?f.message:String(f)}`));}catch(e){E$1(`[board-live-cards-public] emitNotification failed: ${e instanceof Error?e.message:String(e)}`);}}function qe(){let t=q$2().readCardStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let e=r.kvStorageForRef(t);return {readIndex(){return e.read("_index")},writeIndex(s){e.write("_index",s);},readCard(s){return e.read(s)},writeCard(s,i){return e.write(s,i),r.hashFn(i)},removeCard(s){e.delete(s);},cardExists(s){return e.read(s)!==null},defaultCardKey(s){return s}}}let je={readValues(t){let e=r.kvStorageForRef(ne()),s=e.listKeys().sort();if(s.length===0)return {version:null,values:{}};let i={};for(let f of s)i[f]=e.read(f);return {version:r.hashFn(i),values:i}},writeValues(t,e,s){let i=r.kvStorageForRef(ne());for(let f of s)i.delete(f);for(let[f,v]of Object.entries(e))i.write(f,v);return r.hashFn(e)}},q$2=()=>t(r.kvStorageForRef(ne())),oe=()=>s(je),de=()=>o(r.journalAdapterForRef(ne())),l$1=()=>m$1(qe(),E$1),n$1=()=>{let t=q$2().readOutputsStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return u(r.kvStorageForRef(t))};function u$1(){return ce??q$2().readTaskExecutorRef()}function R(){return !!oe().readSnapshot(o$1.value).values[q$1]}function y(){let t=oe().readSnapshot(o$1.value);if(!t.values[q$1])throw new Error(`Board not initialized at ${o$1.value}`);return F(t.values)}function C$1(t,e){let s=oe().commitSnapshot(o$1.value,{schemaVersion:p$1,expectedVersion:e,commitId:r.genId(),committedAt:N(),deleteKeys:[],shallowMerge:E(t)});if(!s.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${e??"null"} current=${s.currentVersion??"null"}`)}function p$2(t){de().appendEvent(t);}async function A$1(){let e=Vt((a,c)=>{let h=a.payload,w=(h?.enrichedCard??{}).id??h?.cardId??"unknown";p$2({type:"task-failed",taskName:w,error:c,timestamp:N()});}),s=y(),i$1=q(s.graph),{events:f,newCursor:v}=de().readEntriesAfterCursor(s.lastDrainedJournalId),k=Y(),b=n(k,a=>r.resolveBlob(a)),x={...s.runtimeByCardId},P=new Map,Z={readRuntime(a){return P.get(a)??x[a]??{_sources:{}}},writeRuntime(a,c){P.set(a,c),x[a]=c;}},ee=[],V=new Map,ae={readSourceData(a,c){let h=`${a}/${c}`;return V.has(h)?V.get(h):b.readSourceData(a,c)},ingestSourceDataStaged(a,c,h,H){b.ingestSourceDataStaged(a,c,h,H);},commitSourceData(a,c,h){let H=`${a}/.staged/${h}/${c}`,w=k.read(H);if(w==null){let B=k.keyRef?.(H);B&&(w=r.resolveBlob(B));}if(w==null)return false;let M=`${a}/${c}`,Q=w.trim();try{V.set(M,JSON.parse(Q));}catch{V.set(M,Q);}return ee.push({cardId:a,outputFile:c,deliveryToken:h}),true},hasSource(a,c){let h=`${a}/${c}`;return V.has(h)?true:b.hasSource(a,c)},listSources(a){let c=b.listSources(a),h=new Set;for(let w of V.keys())w.startsWith(`${a}/`)&&h.add(w.slice(`${a}/`.length));let H=new Set([...c,...h]);return Array.from(H)}},pe=()=>i$1.config.tasks,te={cardStore:l$1(),cardRuntimeStore:Z,fetchedSourcesStore:ae,outputStore:n$1(),executionRequestStore:e,activeTaskConfigs:()=>pe()},ge=[],$e=[],De=[],Ve=new Map,We=new Set,Nt=(a,c)=>{ge.push({type:"task-completed",taskName:a,data:c,timestamp:N()});},Je=(a,c)=>{p$2({type:"task-failed",taskName:a,error:c,timestamp:N()});},Re=t$1(i$1,{handlers:{"card-handler":C(o$1,v,te,Nt,Je,(a,c)=>{$e.push({cardId:a,values:c});},a=>{De.push(a);})},onNodeRemoved:a=>{Ve.delete(a),P.delete(a),delete x[a],We.add(a);}});for(pe=()=>Re.getState().config.tasks,ge=f;ge.length>0;){let a=ge;ge=[];for(let c of a)if(c.type==="task-restart"){let h=te.cardStore.readCard(c.taskName);h&&Ve.set(c.taskName,h);}Re.pushAll(a),await Re.waitForHandlers();}let Ze=Re.getState();await Re.dispose({wait:true});let qt=oe().readSnapshot(o$1.value).version;C$1({lastDrainedJournalId:v,graph:p(Ze),runtimeByCardId:x},qt);for(let{cardId:a,values:c}of $e)te.outputStore.writeComputedValues(a,c);for(let a of De)te.outputStore.writeDataObjects(a);for(let{cardId:a,outputFile:c,deliveryToken:h}of ee)b.commitSourceData(a,c,h);let ve;try{ve=z(B(K,Ze)),te.outputStore.writeStatusSnapshot(ve);}catch(a){E$1(`[board-live-cards-public] status publish failed: ${a instanceof Error?a.message:String(a)}`);}let ie=[];for(let{cardId:a,values:c}of $e)ie.push({kind:"computed_values",cardId:a,values:c});for(let a of De)for(let[c,h]of Object.entries(a))c&&ie.push({kind:"data_object",key:c,payload:h});for(let[a,c]of Ve)a!==i&&ie.push({kind:"card_refreshed",cardId:a,card:c});for(let a of We)ie.push({kind:"card_removed",cardId:a});ve!==void 0&&ie.push({kind:"status",status:ve}),Ne(ie);let ue=u$1()??{howToRun:"built-in",whatToRun:a({kind:"built-in",value:"source-cli-task-executor"})},et=r.supportsDirectSourceOutput?.(ue)===true;e.dispatchEntriesForJournalId(v,a$1=>{if(a$1.taskKind!=="source-fetch"){E$1(`[process-accumulated-events] unknown taskKind "${a$1.taskKind}" \u2014 skipping`);return}let c=a$1.payload,h=c.enrichedCard?.id??"unknown",H=c.enrichedCard?.source_defs??[];if(ue.howToRun==="queue-storage"&&et){try{let w=r.queueStorageForRef(T(),"task-executor"),M=typeof ue.extra?.boardId=="string"?ue.extra.boardId:void 0,Q=[];for(let B of H){if(!B.outputFile){E$1(`[dispatch] source "${B.bindTo}" has no outputFile \u2014 skipping`);continue}let we=r.genId(),Te=`${h}/.staged/${we}/${B.outputFile}`,tt=k.keyRef?.(Te);if(!tt)continue;let rt={ref:a(tt),deliveryToken:we,outputFile:B.outputFile,cardId:h},jt=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:B.bindTo,d:B.outputFile,cs:void 0,rqt:c.rqt,dt:rt.deliveryToken});Q.push({...M?{boardId:M}:{},ref:ue,args:{source_def:B,base_ref:a(o$1),callback:_.createCallback(jt),output:rt}});}Q.length>0&&w.enqueueMany(Q);}catch(w){Je(h,w instanceof Error?w.message:String(w));}return}for(let w of H){if(!w.outputFile){E$1(`[dispatch] source "${w.bindTo}" has no outputFile \u2014 skipping`);continue}let M;if(et){let B=r.genId(),we=`${h}/.staged/${B}/${w.outputFile}`,Te=k.keyRef?.(we);Te&&(M={ref:a(Te),deliveryToken:B,outputFile:w.outputFile,cardId:h});}let Q=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:w.bindTo,d:w.outputFile,cs:void 0,rqt:c.rqt,...M?{dt:M.deliveryToken}:{}});r.dispatchExecution(ue,{source_def:w,base_ref:a(o$1),callback:_.createCallback(Q),...M?{output:M}:{}}).catch(B=>Je(h,B instanceof Error?B.message:String(B)));}});}function T(){let t=q$2().readQueueStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);return t}function $(){r.queueStorageForRef(T(),"process-accumulated").enqueue({boardRef:a(o$1)}),r.requestProcessAccumulated?.();}function F$1(){let t=r.queueStorageForRef(T(),"process-accumulated");for(;;){let e=t.lease({max:64,visibilityMs:1e3});if(e.length<=0)return;for(let s of e)t.ack(s.id,s.leaseToken);if(e.length<64)return}}async function X(){try{let t=()=>{let s=y(),{events:i}=de().readEntriesAfterCursor(s.lastDrainedJournalId);i.length<=0||$();},e=await c(r.lock,A$1,t);return m({ran:e!==!1})}catch(t){return g(t)}}function J(){$();}function z$1(t){try{let e=t.params?.cardStoreRef;if(!e)return d("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(j=t.params?.boardRuntimeStoreRef,!j)return d("init requires params.boardRuntimeStoreRef \u2014 pass the board runtime store ref here");if(!R()){let P=a$1(D);C$1({lastDrainedJournalId:"",graph:p(P),runtimeByCardId:{}},null);}let s=t.params?.outputsStoreRef;if(!s)return d("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let i=t.params?.queueStoreRef;if(!i)return d("init requires params.queueStoreRef \u2014 pass the queue store ref here");let f=t.params?.fetchedSourcesStoreRef;if(!f)return d("init requires params.fetchedSourcesStoreRef \u2014 pass the fetched sources store ref here");G$1=t.params?.scratchStoreRef;let v=t.params?.chatStoreRef;if(!v)return d("init requires params.chatStoreRef \u2014 pass the chat store ref here");let k=t.params?.artifactsStoreRef;if(!k)return d("init requires params.artifactsStoreRef \u2014 pass the artifacts store ref here");let b=q$2();b.writeBoardRuntimeStoreRef(j),b.writeCardStoreRef(e),b.writeOutputsStoreRef(s),b.writeQueueStoreRef(i),b.writeFetchedSourcesStoreRef(f),b.writeChatStoreRef(v),b.writeArtifactsStoreRef(k),l$1().writeCard(l().id,l());let x=ye({params:{cardId:l().id,restart:!0}});if(x.status!=="success")return x;try{n$1().writeStatusSnapshot(z(B(K,q(y().graph))));}catch{}return m()}catch(e){return g(e)}}function he(t){try{let e=n$1().readStatusSnapshot();if(!e){e=z(B(K,q(y().graph)));try{n$1().writeStatusSnapshot(e);}catch{}}return m(e)}catch(e){return g(e)}}function le(t){try{let e=t.params?.id;if(!e)return d("removeCard requires params.id");try{r.kvStorage("card-upsert").delete(e);}catch{}return p$2({type:"task-removal",taskName:e,timestamp:N()}),e!==i&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function fe(t){try{let e=t.params?.cardId;if(!e)return d("addCardFiles requires params.cardId");let s=H(l$1(),{emitNotification:Ce}).appendFiles({params:{id:e},body:t.body});return s.status!=="success"?s:m({cardId:e,files_added:s.data.files_added,notified:!0})}catch(e){return g(e)}}function Se(t){try{let e=t.params?.id;return e?(p$2({type:"task-restart",taskName:e,timestamp:N()}),J(),m()):d("retrigger requires params.id")}catch(e){return g(e)}}async function se(t){return F$1(),X()}function be(){let t=q$2().readFetchedSourcesStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no fetched sources store configured. Run: init --fetched-sources-store-ref <b64-ref>`);return t}function Y(){return r.blobStorageForRef(be())}function ye(t){try{let e=t.params?.cardId,s=t.params?.all,i$1=!!t.params?.restart;if(!e&&!s)return d("upsertCard requires --card-id <id> or --all");let f=s?l$1().readAllCards().map(k=>k.id):[e];for(let k of f)if(!l$1().readCard(k))return d(`Card "${k}" not found in board at ${o$1.value}`);let v=!1;for(let k of f){let b=l$1().readCard(k),x=G(b),P=r.hashFn(x),Z=r.kvStorage("card-upsert"),ee=Z.read(k),V=ee?.taskConfigHash!==P;if(!(!V&&!i$1)){if(V){let ae=ee?.blobRef??l$1().readCardKey(k)??k;p$2({type:"task-upsert",taskName:k,taskConfig:x,timestamp:N()}),Z.write(k,{blobRef:ae,taskConfigHash:P,updatedAt:N()}),v=v||k!==i;}i$1&&p$2({type:"task-restart",taskName:k,timestamp:N()});}}return v&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function I(t){try{let e=t.params?.token;if(!e)return d("taskFailed requires params.token");let s=t.params?.error??"unknown error",i=Pe(e);return i?(p$2({type:"task-failed",taskName:i.taskName,error:s,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function D$1(t){try{let e=t.params?.token;if(!e)return d("taskProgress requires params.token");let i=(t.body??{}).update??{},f=Pe(e);return f?(p$2({type:"task-progress",taskName:f.taskName,update:i,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function L(t){try{let e=t.params?.token,s=t.params?.ref;if(!e)return d("sourceDataFetched requires params.token");if(!s)return d("sourceDataFetched requires params.ref");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,cid:v,b:k,d:b$1,cs:x,rqt:P,dt:Z}=i,ee=n(Y(),te=>r.resolveBlob(te)),V=Z||r.genId();Z||ee.ingestSourceDataStaged(v,b$1,b(s),V);let ae=Pe(f);if(!ae)return d("Invalid callback token embedded in source token");let pe=N();return p$2({type:"task-progress",taskName:ae.taskName,update:{bindTo:k,outputFile:b$1,fetchedAt:pe,deliveryToken:V,sourceChecksum:x,rqt:P},timestamp:pe}),J(),m()}catch(e){return g(e)}}function W(t){try{let e=t.params?.token,s=t.params?.reason??"unknown";if(!e)return d("sourceDataFetchFailure requires params.token");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,b:v,d:k,cs:b,rqt:x}=i,P=Pe(f);return P?(p$2({type:"task-progress",taskName:P.taskName,update:{bindTo:v,outputFile:k,failure:!0,reason:s,sourceChecksum:b,rqt:x},timestamp:N()}),J(),m()):d("Invalid callback token embedded in source token")}catch(e){return g(e)}}function me(t){try{let e=q$2().readCardStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no card store configured`)}catch(e){return g(e)}}function U(t){try{return m({storeRef:j??null})}catch(e){return g(e)}}function wt(t){try{let e=q$2().readOutputsStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no outputs store configured`)}catch(e){return g(e)}}function Tt(t){try{return m({storeRef:G$1??null})}catch(e){return g(e)}}function It(t){try{let e=q$2().readChatStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function xt(t){try{let e=q$2().readArtifactsStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function Et(t){try{let e=q$2().readFetchedSourcesStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function At(t){try{let e=t.params?.key;if(!e)return d("getConfig requires params.key");let s=q$2(),i;switch(e){case "task-executor":i=ce??null;break;case "chat-handler-flow":i=ke??null;break;case "board-runtime-store-ref":i=s.readBoardRuntimeStoreRef();break;case "card-store-ref":i=s.readCardStoreRef();break;case "outputs-store-ref":i=s.readOutputsStoreRef();break;case "scratch-store-ref":i=G$1??null;break;case "chat-store-ref":i=s.readChatStoreRef();break;case "artifacts-store-ref":i=s.readArtifactsStoreRef();break;case "fetched-sources-store-ref":i=s.readFetchedSourcesStoreRef();break;default:return d(`getConfig: unknown key "${e}"`)}return m({value:i})}catch(e){return g(e)}}function Bt(t){try{let e=t.params?.key;if(!e)return d("getOutputsDataObject requires params.key");if(e===h)return m(null);let s=n$1().readDataObject(e);return m(s)}catch(e){return g(e)}}function Ue(t){try{return m(A(n$1().readAllDataObjects()))}catch(e){return g(e)}}function _t(t){try{let e=t.params?.key;if(!e)return d("getOutputsComputedValues requires params.key");let s=n$1().readComputedValues(e);return m(s)}catch(e){return g(e)}}function Xe(t){try{return m(n$1().readAllComputedValues())}catch(e){return g(e)}}function ze(){return n(Y(),t=>r.resolveBlob(t))}function Qe(t){let e=Y().keyRef?.(t);if(!e)throw new Error("configured fetched-sources store does not support keyRef");return a(e)}function Ft(t){try{let e=t.params?.key;if(!e)return d("getOutputsFetchedSources requires params.key");let s=ze().listSources(e),i={};for(let f of s)i[f]=Qe(`${e}/${f}`);return m(i)}catch(e){return g(e)}}function Ot(t){try{let e=ze(),s=new Set;for(let f of Y().listKeys()){let v=f.indexOf("/");v>0&&!f.includes("/.staged/")&&s.add(f.slice(0,v));}let i={};for(let f of s){let v=e.listSources(f);if(v.length>0){i[f]={};for(let k of v)i[f][k]=Qe(`${f}/${k}`);}}return m(i)}catch(e){return g(e)}}function Pt(t){try{let e=l$1().readAllCards().filter(b=>b.id!==i),s=he({});if(s.status!=="success")return s;let i$1=Ue({});if(i$1.status!=="success")return i$1;let f=Xe({});if(f.status!=="success")return f;let v=f.data,k={};for(let b of e){let x=typeof b?.id=="string"?b.id:null;if(!x)continue;let P=b.card_data&&typeof b.card_data=="object"&&!Array.isArray(b.card_data)?b.card_data:{};k[x]={schema_version:"v1",card_id:x,card_data:{...P},computed_values:v[x]&&typeof v[x]=="object"?v[x]:{}};}return m({cardDefinitions:e,statusSnapshot:s.data,dataObjectsByToken:i$1.data,cardRuntimeById:k})}catch(e){return g(e)}}return {init:z$1,status:he,getBoardRuntimeStoreRef:U,getCardStoreRef:me,getOutputsStoreRef:wt,getScratchStoreRef:Tt,getChatStoreRef:It,getArtifactsStoreRef:xt,getFetchedSourcesStoreRef:Et,getConfig:At,getOutputsDataObject:Bt,getAllOutputsDataObjects:Ue,getOutputsComputedValues:_t,getAllOutputsComputedValues:Xe,getOutputsFetchedSources:Ft,getAllOutputsFetchedSources:Ot,buildSseOneShotPayload:Pt,removeCard:le,addCardFiles:fe,retrigger:Se,processAccumulatedEvents:se,upsertCard:ye,taskFailed:I,taskProgress:D$1,sourceDataFetched:L,sourceDataFetchFailure:W}}function ar(o,r,S){let _=S?.taskExecutorRef,E=()=>{if(S){if(!S.boardRuntimeStoreRef)throw new Error(`Board at ${o.value} requires boardRuntimeStoreRef for non-core runtime operations.`);return t(r.kvStorageForRef(S.boardRuntimeStoreRef))}return t(r.kvStorage("config"))};function K(){let l=E().readCardStoreRef();if(!l)throw new Error(`Board at ${o.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let n=r.kvStorageForRef(l);return {readIndex(){return n.read("_index")},writeIndex(u){n.write("_index",u);},readCard(u){return n.read(u)},writeCard(u,R){return n.write(u,R),r.hashFn(R)},removeCard(u){n.delete(u);},cardExists(u){return n.read(u)!==null},defaultCardKey(u){return u}}}let j=()=>m$1(K(),r.onWarn??(()=>{}));function G(){return _??E().readTaskExecutorRef()}async function ce(l,n){let u=r.validateSchema(n),R=[],y=G();if(y&&Array.isArray(n.source_defs))for(let p of n.source_defs){let A=typeof p.bindTo=="string"?p.bindTo:"(unknown)";try{let T;try{T=await r.invokeExecutor(y,"validate-source-def",{timeout:r.executorTimeouts?.validationMs??1e4,input:JSON.stringify(p)});}catch(F){let X=F;if(T=typeof X?.stdout=="string"?X.stdout:"",!T.trim()){R.push(`source "${A}": executor validate-source-def failed \u2014 ${F instanceof Error?F.message:String(F)}`);continue}}let $=JSON.parse(T.trim());if(!$.ok&&Array.isArray($.errors))for(let F of $.errors)R.push(`source "${A}": ${F}`);}catch(T){R.push(`source "${A}": executor validate-source-def failed \u2014 ${T instanceof Error?T.message:String(T)}`);}}let C=[...u.errors,...R];return m({cardId:l,isValid:C.length===0,issues:C})}function ke(l,n){let u=l.params?.sourceIdx,R=l.params?.outRef;if(u===void 0)return d(`${n} requires params.sourceIdx`);if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d(`${n} requires card JSON object in body`);let y=l.body,C=y["card-content"]??y,p=y["mock-projections"]??{},A=C.source_defs??[];if(u<0||u>=A.length)return d(`sourceIdx ${u} out of range (card has ${A.length} source(s))`);let T=A[u],$=typeof T.bindTo=="string"?T.bindTo:"source";return {src:T,bindTo:$,outRef:R,mockProjections:p}}async function Ce(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("validateCardPreflight requires card JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)";return await ce(R,u)}catch(n){return g(n)}}async function ne(l){try{let n=ke(l,"probeSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"probe-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());return C.ok?m({bindTo:n.bindTo,reachable:C.reachable,latencyMs:C.latencyMs,note:C.note}):d(C.error??"Preflight probe failed")}catch{return d("Executor does not support probe-source-preflight")}}catch(n){return g(n)}}async function Ne(l){try{let n=ke(l,"runSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"run-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.probeMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());if(!C.ok)return m({bindTo:n.bindTo,ok:!1,result:null,issues:[C.error??"Preflight run failed"]});if(n.outRef){let p=b(n.outRef);r.absoluteBlob.write(p.value,JSON.stringify(C.resultValue,null,2));}return m({bindTo:typeof C.bindTo=="string"?C.bindTo:n.bindTo,ok:!0,result:C.resultValue??null,issues:[]})}catch(R){let y=R instanceof Error?R.message:String(R);return m({bindTo:n.bindTo,ok:!1,result:null,issues:[y]})}}catch(n){return g(n)}}async function qe(l){try{let n=G();if(!n)return d("No task-executor registered for this board");let u=await r.invokeExecutor(n,"describe-capabilities",{timeout:r.executorTimeouts?.describeMs??1e4});return m(JSON.parse(u.trim()))}catch(n){return g(n)}}function je(l){try{let n=l.body;if(!n||!Array.isArray(n.ops))return d("updatesInCardStore requires body.ops array");let u=n.ops,R=j();for(let y of u){let C=y.op,p=y.id;if(!p)return d('op is missing "id"');if(C==="update"){let A=y["card-content"];if(!A)return d(`update op for "${p}" is missing "card-content"`);R.writeCard(p,A);}else return d(`Unknown op type: "${C??"(none)"}"`)}return m()}catch(n){return g(n)}}function q(l){try{let n=l.body;if(!n||!Array.isArray(n.ids))return d("readFromCardStore requires body.ids array");let u=n.ids,R=j(),y=u.map(C=>({id:C,"card-content":R.readCard(C)}));return m({cards:y})}catch(n){return g(n)}}function oe(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("evalCardCompute requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=u.compute;if(!p||!Array.isArray(p)||p.length===0)return m({cardId:R,ok:!0,computed_values:{},errors:[]});let A={id:R,card_data:u.card_data??{},requires:C,source_defs:u.source_defs,compute:p},T=a$2.runSync(A,{sourcesData:y}),$=T.node.computed_values??{},F=T.errors??[];return m({cardId:R,ok:F.length===0,computed_values:$,errors:F})}catch(n){return g(n)}}async function de(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("simulateCardCycle requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=await ce(R,u),A=p.status==="success"?{isValid:p.data.isValid,issues:p.data.issues}:{isValid:!1,issues:[p.status==="fail"?p.error:"internal error"]},T=u.source_defs??[],$=u.card_data??{},F=[],X=[],J=[];if(T.length>0){F=a$2.enrichSourcesSync(T,{card_data:$,requires:C}),X=F.filter(I=>I._skip!==!0);for(let I of X){let D=I.projections,L=I._projections;if(D&&L){for(let W of Object.keys(D))if(L[W]===void 0){let me=typeof I.bindTo=="string"?I.bindTo:"(unknown)";J.push({bindTo:me,key:W,error:`Projection "${W}" resolved to undefined`});}}}}let z=[],he=new Set(X.map(I=>typeof I.bindTo=="string"?I.bindTo:"")),le=Object.fromEntries(Object.entries(y).filter(([I])=>he.has(I))),fe=n["task-executor-ref"],Se=(fe?.howToRun&&fe?.whatToRun?fe:void 0)??G();for(let I=0;I<F.length;I++){let D=F[I],L=typeof D.bindTo=="string"?D.bindTo:`source_${I}`;if(D._skip===!0){z.push({bindTo:L,skipped:!0});continue}if(!Se){z.push({bindTo:L,skipped:!0,error:"No task executor configured"});continue}try{let W={...D},me=await r.invokeExecutor(Se,"run-source-preflight",{timeout:D.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(W)}),U=JSON.parse(me.trim());U.ok&&!Object.prototype.hasOwnProperty.call(y,L)&&Object.prototype.hasOwnProperty.call(U,"resultValue")&&(le[L]=U.resultValue),z.push({bindTo:L,reachable:U.reachable,latencyMs:U.latencyMs,error:U.ok?void 0:U.error});}catch{z.push({bindTo:L,skipped:!0,error:"Executor does not support run-source-preflight"});}}let se=u.compute,be={},Y=[];if(se&&Array.isArray(se)&&se.length>0){let I={id:R,card_data:$,requires:C,source_defs:u.source_defs,compute:se},D=a$2.runSync(I,{sourcesData:le});be=D.node.computed_values??{},Y=D.errors??[];}let ye=A.isValid&&J.length===0&&Y.length===0&&z.every(I=>I.reachable!==!1);return m({cardId:R,ok:ye,validation:A,source_probes:z,projection_errors:J,fetched_sources:le,computed_values:be,compute_errors:Y})}catch(n){return g(n)}}return {validateCardPreflight:Ce,probeSourcePreflight:ne,runSourcePreflight:Ne,evalCardCompute:oe,simulateCardCycle:de,describeTaskExecutorCapabilities:qe,updatesInCardStore:je,readFromCardStore:q}}
|
|
2
|
-
export{St as a,Yt as b,Ut as c,Xt as d,sr as e,ar as f};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1,p,q,t as t$1}from'./chunk-FULAMLUU.js';import {D,l,z,B,i,H,G,n,h,A,q as q$1,p as p$1,E,t,m as m$1,u,F,s,o,C}from'./chunk-QJQ53PLM.js';import {a,b,c}from'./chunk-44L64VQ2.js';import {a as a$2}from'./chunk-QE3QXEHI.js';import {e,f}from'./chunk-UGB7PC4P.js';function Ct(o){return typeof o=="string"&&o.trim().length>0}function ht(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.selfRef is required`);if(!Ct(o.howToRun))throw new Error(`${r}: adapter.selfRef.howToRun is required`);if(!Ct(o.whatToRun))throw new Error(`${r}: adapter.selfRef.whatToRun is required`)}function St(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.callbackTransport is required`);if(typeof o.createCallback!="function")throw new Error(`${r}: adapter.callbackTransport.createCallback is required`)}function $t(o,r="callbackTransport"){return {createCallback(S){let _=o();return ht(_,r),{token:S,via:_}}}}function Ye(o){return $t(()=>o,"createStaticExecutionRefCallbackTransport")}function Yt(o){return Ye({meta:"board-live-cards",howToRun:"http:post",whatToRun:a({kind:"http-url",value:String(o||"").trim()})})}function Ut(o){return Ye({meta:"board-live-cards",howToRun:"in-process-loop",whatToRun:a({kind:"in-process-loop",value:String(o||"").trim()})})}function Xt(o){let r=typeof o=="string"?{notifyChannel:o}:o??{},S={};return r.notifyChannel&&(S.notifyChannel=r.notifyChannel),r.boardRuntimeStoreRef&&(S.boardRuntimeStoreRef=r.boardRuntimeStoreRef),r.queueStoreRef&&(S.queueStoreRef=r.queueStoreRef),Ye({meta:"board-live-cards",howToRun:"built-in",whatToRun:a({kind:"built-in",value:"board-live-cards"}),...Object.keys(S).length>0?{extra:S}:{}})}function m(o){return o!==void 0?{status:"success",data:o}:{status:"success"}}function d(o){return {status:"fail",error:o}}function g(o){return {status:"error",error:o instanceof Error?o.message:String(o)}}function Dt(o){let r=new TextEncoder().encode(o),S=Array.from(r,_=>String.fromCharCode(_)).join("");return btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(o){let r=o.replace(/-/g,"+").replace(/_/g,"/"),S=r+"=".repeat((4-r.length%4)%4),_=atob(S),E=Uint8Array.from(_,K=>K.charCodeAt(0));return new TextDecoder().decode(E)}function Pe(o){try{let r=JSON.parse(vt(o));return typeof r?.t=="string"?{taskName:r.t}:null}catch{return null}}function bt(o){return Dt(JSON.stringify(o))}function yt(o){try{let r=JSON.parse(vt(o));return typeof r?.cbk=="string"&&typeof r?.cid=="string"&&typeof r?.b=="string"&&typeof r?.d=="string"?r:null}catch{return null}}function N(){return new Date().toISOString()}function Vt(o){let r=new Map;return {appendEntries(S,_){if(!S||_.length===0)return;let E=r.get(S)??[];r.set(S,[...E,..._]);},dispatchEntriesForJournalId(S,_){if(!S)return;let E=r.get(S);if(!(!E||E.length===0)){for(let K of E)try{_(K);}catch(j){try{o(K,j instanceof Error?j.message:String(j));}catch{}}r.delete(S);}}}}function sr(o$1,r,S={}){St(r.callbackTransport,"createBoardLiveCardsPublic");let _=r.callbackTransport,E$1=r.onWarn??(()=>{}),K=a(o$1),j=S.boardRuntimeStoreRef,G$1=S.scratchStoreRef,ce=S.taskExecutorRef,ke=S.chatHandlerFlow,Ce=S.emitNotification??(t=>{if(!r.publishBoardChangeNotifications)return;let e=t.kind==="notification-batch"?t.notifications:[t];return r.publishBoardChangeNotifications(e)});function ne(){if(!j)throw new Error(`Board at ${o$1.value} has no board runtime store configured. Pass boardRuntimeStoreRef at construction or init.`);return j}function Ne(t){if(t.length!==0)try{let e$1=e(t),s=f({kind:"notification-batch",notifications:e$1}),i=Ce(s);i&&typeof i.catch=="function"&&i.catch(f=>E$1(`[board-live-cards-public] emitNotification failed: ${f instanceof Error?f.message:String(f)}`));}catch(e){E$1(`[board-live-cards-public] emitNotification failed: ${e instanceof Error?e.message:String(e)}`);}}function qe(){let t=q$2().readCardStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let e=r.kvStorageForRef(t);return {readIndex(){return e.read("_index")},writeIndex(s){e.write("_index",s);},readCard(s){return e.read(s)},writeCard(s,i){return e.write(s,i),r.hashFn(i)},removeCard(s){e.delete(s);},cardExists(s){return e.read(s)!==null},defaultCardKey(s){return s}}}let je={readValues(t){let e=r.kvStorageForRef(ne()),s=e.listKeys().sort();if(s.length===0)return {version:null,values:{}};let i={};for(let f of s)i[f]=e.read(f);return {version:r.hashFn(i),values:i}},writeValues(t,e,s){let i=r.kvStorageForRef(ne());for(let f of s)i.delete(f);for(let[f,v]of Object.entries(e))i.write(f,v);return r.hashFn(e)}},q$2=()=>t(r.kvStorageForRef(ne())),oe=()=>s(je),de=()=>o(r.journalAdapterForRef(ne())),l$1=()=>m$1(qe(),E$1),n$1=()=>{let t=q$2().readOutputsStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return u(r.kvStorageForRef(t))};function u$1(){return ce??q$2().readTaskExecutorRef()}function R(){return !!oe().readSnapshot(o$1.value).values[q$1]}function y(){let t=oe().readSnapshot(o$1.value);if(!t.values[q$1])throw new Error(`Board not initialized at ${o$1.value}`);return F(t.values)}function C$1(t,e){let s=oe().commitSnapshot(o$1.value,{schemaVersion:p$1,expectedVersion:e,commitId:r.genId(),committedAt:N(),deleteKeys:[],shallowMerge:E(t)});if(!s.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${e??"null"} current=${s.currentVersion??"null"}`)}function p$2(t){de().appendEvent(t);}async function A$1(){let e=Vt((a,c)=>{let h=a.payload,w=(h?.enrichedCard??{}).id??h?.cardId??"unknown";p$2({type:"task-failed",taskName:w,error:c,timestamp:N()});}),s=y(),i$1=q(s.graph),{events:f,newCursor:v}=de().readEntriesAfterCursor(s.lastDrainedJournalId),k=Y(),b=n(k,a=>r.resolveBlob(a)),x={...s.runtimeByCardId},P=new Map,Z={readRuntime(a){return P.get(a)??x[a]??{_sources:{}}},writeRuntime(a,c){P.set(a,c),x[a]=c;}},ee=[],V=new Map,ae={readSourceData(a,c){let h=`${a}/${c}`;return V.has(h)?V.get(h):b.readSourceData(a,c)},ingestSourceDataStaged(a,c,h,H){b.ingestSourceDataStaged(a,c,h,H);},commitSourceData(a,c,h){let H=`${a}/.staged/${h}/${c}`,w=k.read(H);if(w==null){let B=k.keyRef?.(H);B&&(w=r.resolveBlob(B));}if(w==null)return false;let M=`${a}/${c}`,Q=w.trim();try{V.set(M,JSON.parse(Q));}catch{V.set(M,Q);}return ee.push({cardId:a,outputFile:c,deliveryToken:h}),true},hasSource(a,c){let h=`${a}/${c}`;return V.has(h)?true:b.hasSource(a,c)},listSources(a){let c=b.listSources(a),h=new Set;for(let w of V.keys())w.startsWith(`${a}/`)&&h.add(w.slice(`${a}/`.length));let H=new Set([...c,...h]);return Array.from(H)}},pe=()=>i$1.config.tasks,te={cardStore:l$1(),cardRuntimeStore:Z,fetchedSourcesStore:ae,outputStore:n$1(),executionRequestStore:e,activeTaskConfigs:()=>pe()},ge=[],$e=[],De=[],Ve=new Map,We=new Set,Nt=(a,c)=>{ge.push({type:"task-completed",taskName:a,data:c,timestamp:N()});},Je=(a,c)=>{p$2({type:"task-failed",taskName:a,error:c,timestamp:N()});},Re=t$1(i$1,{handlers:{"card-handler":C(o$1,v,te,Nt,Je,(a,c)=>{$e.push({cardId:a,values:c});},a=>{De.push(a);})},onNodeRemoved:a=>{Ve.delete(a),P.delete(a),delete x[a],We.add(a);}});for(pe=()=>Re.getState().config.tasks,ge=f;ge.length>0;){let a=ge;ge=[];for(let c of a)if(c.type==="task-restart"){let h=te.cardStore.readCard(c.taskName);h&&Ve.set(c.taskName,h);}Re.pushAll(a),await Re.waitForHandlers();}let Ze=Re.getState();await Re.dispose({wait:true});let qt=oe().readSnapshot(o$1.value).version;C$1({lastDrainedJournalId:v,graph:p(Ze),runtimeByCardId:x},qt);for(let{cardId:a,values:c}of $e)te.outputStore.writeComputedValues(a,c);for(let a of De)te.outputStore.writeDataObjects(a);for(let{cardId:a,outputFile:c,deliveryToken:h}of ee)b.commitSourceData(a,c,h);let ve;try{ve=z(B(K,Ze)),te.outputStore.writeStatusSnapshot(ve);}catch(a){E$1(`[board-live-cards-public] status publish failed: ${a instanceof Error?a.message:String(a)}`);}let ie=[];for(let{cardId:a,values:c}of $e)ie.push({kind:"computed_values",cardId:a,values:c});for(let a of De)for(let[c,h]of Object.entries(a))c&&ie.push({kind:"data_object",key:c,payload:h});for(let[a,c]of Ve)a!==i&&ie.push({kind:"card_refreshed",cardId:a,card:c});for(let a of We)ie.push({kind:"card_removed",cardId:a});ve!==void 0&&ie.push({kind:"status",status:ve}),Ne(ie);let ue=u$1()??{howToRun:"built-in",whatToRun:a({kind:"built-in",value:"source-cli-task-executor"})},et=r.supportsDirectSourceOutput?.(ue)===true;e.dispatchEntriesForJournalId(v,a$1=>{if(a$1.taskKind!=="source-fetch"){E$1(`[process-accumulated-events] unknown taskKind "${a$1.taskKind}" \u2014 skipping`);return}let c=a$1.payload,h=c.enrichedCard?.id??"unknown",H=c.enrichedCard?.source_defs??[];if(ue.howToRun==="queue-storage"&&et){try{let w=r.queueStorageForRef(T(),"task-executor"),M=typeof ue.extra?.boardId=="string"?ue.extra.boardId:void 0,Q=[];for(let B of H){if(!B.outputFile){E$1(`[dispatch] source "${B.bindTo}" has no outputFile \u2014 skipping`);continue}let we=r.genId(),Te=`${h}/.staged/${we}/${B.outputFile}`,tt=k.keyRef?.(Te);if(!tt)continue;let rt={ref:a(tt),deliveryToken:we,outputFile:B.outputFile,cardId:h},jt=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:B.bindTo,d:B.outputFile,cs:void 0,rqt:c.rqt,dt:rt.deliveryToken});Q.push({...M?{boardId:M}:{},ref:ue,args:{source_def:B,base_ref:a(o$1),callback:_.createCallback(jt),output:rt}});}Q.length>0&&w.enqueueMany(Q);}catch(w){Je(h,w instanceof Error?w.message:String(w));}return}for(let w of H){if(!w.outputFile){E$1(`[dispatch] source "${w.bindTo}" has no outputFile \u2014 skipping`);continue}let M;if(et){let B=r.genId(),we=`${h}/.staged/${B}/${w.outputFile}`,Te=k.keyRef?.(we);Te&&(M={ref:a(Te),deliveryToken:B,outputFile:w.outputFile,cardId:h});}let Q=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:w.bindTo,d:w.outputFile,cs:void 0,rqt:c.rqt,...M?{dt:M.deliveryToken}:{}});r.dispatchExecution(ue,{source_def:w,base_ref:a(o$1),callback:_.createCallback(Q),...M?{output:M}:{}}).catch(B=>Je(h,B instanceof Error?B.message:String(B)));}});}function T(){let t=q$2().readQueueStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);return t}function $(){r.queueStorageForRef(T(),"process-accumulated").enqueue({boardRef:a(o$1)}),r.requestProcessAccumulated?.();}function F$1(){let t=r.queueStorageForRef(T(),"process-accumulated");for(;;){let e=t.lease({max:64,visibilityMs:1e3});if(e.length<=0)return;for(let s of e)t.ack(s.id,s.leaseToken);if(e.length<64)return}}async function X(){try{let t=()=>{let s=y(),{events:i}=de().readEntriesAfterCursor(s.lastDrainedJournalId);i.length<=0||$();},e=await c(r.lock,A$1,t);return m({ran:e!==!1})}catch(t){return g(t)}}function J(){$();}function z$1(t){try{let e=t.params?.cardStoreRef;if(!e)return d("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(j=t.params?.boardRuntimeStoreRef,!j)return d("init requires params.boardRuntimeStoreRef \u2014 pass the board runtime store ref here");if(!R()){let P=a$1(D);C$1({lastDrainedJournalId:"",graph:p(P),runtimeByCardId:{}},null);}let s=t.params?.outputsStoreRef;if(!s)return d("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let i=t.params?.queueStoreRef;if(!i)return d("init requires params.queueStoreRef \u2014 pass the queue store ref here");let f=t.params?.fetchedSourcesStoreRef;if(!f)return d("init requires params.fetchedSourcesStoreRef \u2014 pass the fetched sources store ref here");G$1=t.params?.scratchStoreRef;let v=t.params?.chatStoreRef;if(!v)return d("init requires params.chatStoreRef \u2014 pass the chat store ref here");let k=t.params?.artifactsStoreRef;if(!k)return d("init requires params.artifactsStoreRef \u2014 pass the artifacts store ref here");let b=q$2();b.writeBoardRuntimeStoreRef(j),b.writeCardStoreRef(e),b.writeOutputsStoreRef(s),b.writeQueueStoreRef(i),b.writeFetchedSourcesStoreRef(f),b.writeChatStoreRef(v),b.writeArtifactsStoreRef(k),l$1().writeCard(l().id,l());let x=ye({params:{cardId:l().id,restart:!0}});if(x.status!=="success")return x;try{n$1().writeStatusSnapshot(z(B(K,q(y().graph))));}catch{}return m()}catch(e){return g(e)}}function he(t){try{let e=n$1().readStatusSnapshot();if(!e){e=z(B(K,q(y().graph)));try{n$1().writeStatusSnapshot(e);}catch{}}return m(e)}catch(e){return g(e)}}function le(t){try{let e=t.params?.id;if(!e)return d("removeCard requires params.id");try{r.kvStorage("card-upsert").delete(e);}catch{}return p$2({type:"task-removal",taskName:e,timestamp:N()}),e!==i&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function fe(t){try{let e=t.params?.cardId;if(!e)return d("addCardFiles requires params.cardId");let s=H(l$1(),{emitNotification:Ce}).appendFiles({params:{id:e},body:t.body});return s.status!=="success"?s:m({cardId:e,files_added:s.data.files_added,notified:!0})}catch(e){return g(e)}}function Se(t){try{let e=t.params?.id;return e?(p$2({type:"task-restart",taskName:e,timestamp:N()}),J(),m()):d("retrigger requires params.id")}catch(e){return g(e)}}async function se(t){return F$1(),X()}function be(){let t=q$2().readFetchedSourcesStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no fetched sources store configured. Run: init --fetched-sources-store-ref <b64-ref>`);return t}function Y(){return r.blobStorageForRef(be())}function ye(t){try{let e=t.params?.cardId,s=t.params?.all,i$1=!!t.params?.restart;if(!e&&!s)return d("upsertCard requires --card-id <id> or --all");let f=s?l$1().readAllCards().map(k=>k.id):[e];for(let k of f)if(!l$1().readCard(k))return d(`Card "${k}" not found in board at ${o$1.value}`);let v=!1;for(let k of f){let b=l$1().readCard(k),x=G(b),P=r.hashFn(x),Z=r.kvStorage("card-upsert"),ee=Z.read(k),V=ee?.taskConfigHash!==P;if(!(!V&&!i$1)){if(V){let ae=ee?.blobRef??l$1().readCardKey(k)??k;p$2({type:"task-upsert",taskName:k,taskConfig:x,timestamp:N()}),Z.write(k,{blobRef:ae,taskConfigHash:P,updatedAt:N()}),v=v||k!==i;}i$1&&p$2({type:"task-restart",taskName:k,timestamp:N()});}}return v&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function I(t){try{let e=t.params?.token;if(!e)return d("taskFailed requires params.token");let s=t.params?.error??"unknown error",i=Pe(e);return i?(p$2({type:"task-failed",taskName:i.taskName,error:s,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function D$1(t){try{let e=t.params?.token;if(!e)return d("taskProgress requires params.token");let i=(t.body??{}).update??{},f=Pe(e);return f?(p$2({type:"task-progress",taskName:f.taskName,update:i,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function L(t){try{let e=t.params?.token,s=t.params?.ref;if(!e)return d("sourceDataFetched requires params.token");if(!s)return d("sourceDataFetched requires params.ref");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,cid:v,b:k,d:b$1,cs:x,rqt:P,dt:Z}=i,ee=n(Y(),te=>r.resolveBlob(te)),V=Z||r.genId();Z||ee.ingestSourceDataStaged(v,b$1,b(s),V);let ae=Pe(f);if(!ae)return d("Invalid callback token embedded in source token");let pe=N();return p$2({type:"task-progress",taskName:ae.taskName,update:{bindTo:k,outputFile:b$1,fetchedAt:pe,deliveryToken:V,sourceChecksum:x,rqt:P},timestamp:pe}),J(),m()}catch(e){return g(e)}}function W(t){try{let e=t.params?.token,s=t.params?.reason??"unknown";if(!e)return d("sourceDataFetchFailure requires params.token");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,b:v,d:k,cs:b,rqt:x}=i,P=Pe(f);return P?(p$2({type:"task-progress",taskName:P.taskName,update:{bindTo:v,outputFile:k,failure:!0,reason:s,sourceChecksum:b,rqt:x},timestamp:N()}),J(),m()):d("Invalid callback token embedded in source token")}catch(e){return g(e)}}function me(t){try{let e=q$2().readCardStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no card store configured`)}catch(e){return g(e)}}function U(t){try{return m({storeRef:j??null})}catch(e){return g(e)}}function wt(t){try{let e=q$2().readOutputsStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no outputs store configured`)}catch(e){return g(e)}}function Tt(t){try{return m({storeRef:G$1??null})}catch(e){return g(e)}}function It(t){try{let e=q$2().readChatStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function xt(t){try{let e=q$2().readArtifactsStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function Et(t){try{let e=q$2().readFetchedSourcesStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function At(t){try{let e=t.params?.key;if(!e)return d("getConfig requires params.key");let s=q$2(),i;switch(e){case "task-executor":i=ce??null;break;case "chat-handler-flow":i=ke??null;break;case "board-runtime-store-ref":i=s.readBoardRuntimeStoreRef();break;case "card-store-ref":i=s.readCardStoreRef();break;case "outputs-store-ref":i=s.readOutputsStoreRef();break;case "scratch-store-ref":i=G$1??null;break;case "chat-store-ref":i=s.readChatStoreRef();break;case "artifacts-store-ref":i=s.readArtifactsStoreRef();break;case "fetched-sources-store-ref":i=s.readFetchedSourcesStoreRef();break;default:return d(`getConfig: unknown key "${e}"`)}return m({value:i})}catch(e){return g(e)}}function Bt(t){try{let e=t.params?.key;if(!e)return d("getOutputsDataObject requires params.key");if(e===h)return m(null);let s=n$1().readDataObject(e);return m(s)}catch(e){return g(e)}}function Ue(t){try{return m(A(n$1().readAllDataObjects()))}catch(e){return g(e)}}function _t(t){try{let e=t.params?.key;if(!e)return d("getOutputsComputedValues requires params.key");let s=n$1().readComputedValues(e);return m(s)}catch(e){return g(e)}}function Xe(t){try{return m(n$1().readAllComputedValues())}catch(e){return g(e)}}function ze(){return n(Y(),t=>r.resolveBlob(t))}function Qe(t){let e=Y().keyRef?.(t);if(!e)throw new Error("configured fetched-sources store does not support keyRef");return a(e)}function Ft(t){try{let e=t.params?.key;if(!e)return d("getOutputsFetchedSources requires params.key");let s=ze().listSources(e),i={};for(let f of s)i[f]=Qe(`${e}/${f}`);return m(i)}catch(e){return g(e)}}function Ot(t){try{let e=ze(),s=new Set;for(let f of Y().listKeys()){let v=f.indexOf("/");v>0&&!f.includes("/.staged/")&&s.add(f.slice(0,v));}let i={};for(let f of s){let v=e.listSources(f);if(v.length>0){i[f]={};for(let k of v)i[f][k]=Qe(`${f}/${k}`);}}return m(i)}catch(e){return g(e)}}function Pt(t){try{let e=l$1().readAllCards().filter(b=>b.id!==i),s=he({});if(s.status!=="success")return s;let i$1=Ue({});if(i$1.status!=="success")return i$1;let f=Xe({});if(f.status!=="success")return f;let v=f.data,k={};for(let b of e){let x=typeof b?.id=="string"?b.id:null;if(!x)continue;let P=b.card_data&&typeof b.card_data=="object"&&!Array.isArray(b.card_data)?b.card_data:{};k[x]={schema_version:"v1",card_id:x,card_data:{...P},computed_values:v[x]&&typeof v[x]=="object"?v[x]:{}};}return m({cardDefinitions:e,statusSnapshot:s.data,dataObjectsByToken:i$1.data,cardRuntimeById:k})}catch(e){return g(e)}}return {init:z$1,status:he,getBoardRuntimeStoreRef:U,getCardStoreRef:me,getOutputsStoreRef:wt,getScratchStoreRef:Tt,getChatStoreRef:It,getArtifactsStoreRef:xt,getFetchedSourcesStoreRef:Et,getConfig:At,getOutputsDataObject:Bt,getAllOutputsDataObjects:Ue,getOutputsComputedValues:_t,getAllOutputsComputedValues:Xe,getOutputsFetchedSources:Ft,getAllOutputsFetchedSources:Ot,buildSseOneShotPayload:Pt,removeCard:le,addCardFiles:fe,retrigger:Se,processAccumulatedEvents:se,upsertCard:ye,taskFailed:I,taskProgress:D$1,sourceDataFetched:L,sourceDataFetchFailure:W}}function ar(o,r,S){let _=S?.taskExecutorRef,E=()=>{if(S){if(!S.boardRuntimeStoreRef)throw new Error(`Board at ${o.value} requires boardRuntimeStoreRef for non-core runtime operations.`);return t(r.kvStorageForRef(S.boardRuntimeStoreRef))}return t(r.kvStorage("config"))};function K(){let l=E().readCardStoreRef();if(!l)throw new Error(`Board at ${o.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let n=r.kvStorageForRef(l);return {readIndex(){return n.read("_index")},writeIndex(u){n.write("_index",u);},readCard(u){return n.read(u)},writeCard(u,R){return n.write(u,R),r.hashFn(R)},removeCard(u){n.delete(u);},cardExists(u){return n.read(u)!==null},defaultCardKey(u){return u}}}let j=()=>m$1(K(),r.onWarn??(()=>{}));function G(){return _??E().readTaskExecutorRef()}async function ce(l,n){let u=r.validateSchema(n),R=[],y=G();if(y&&Array.isArray(n.source_defs))for(let p of n.source_defs){let A=typeof p.bindTo=="string"?p.bindTo:"(unknown)";try{let T;try{T=await r.invokeExecutor(y,"validate-source-def",{timeout:r.executorTimeouts?.validationMs??1e4,input:JSON.stringify(p)});}catch(F){let X=F;if(T=typeof X?.stdout=="string"?X.stdout:"",!T.trim()){R.push(`source "${A}": executor validate-source-def failed \u2014 ${F instanceof Error?F.message:String(F)}`);continue}}let $=JSON.parse(T.trim());if(!$.ok&&Array.isArray($.errors))for(let F of $.errors)R.push(`source "${A}": ${F}`);}catch(T){R.push(`source "${A}": executor validate-source-def failed \u2014 ${T instanceof Error?T.message:String(T)}`);}}let C=[...u.errors,...R];return m({cardId:l,isValid:C.length===0,issues:C})}function ke(l,n){let u=l.params?.sourceIdx,R=l.params?.outRef;if(u===void 0)return d(`${n} requires params.sourceIdx`);if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d(`${n} requires card JSON object in body`);let y=l.body,C=y["card-content"]??y,p=y["mock-projections"]??{},A=C.source_defs??[];if(u<0||u>=A.length)return d(`sourceIdx ${u} out of range (card has ${A.length} source(s))`);let T=A[u],$=typeof T.bindTo=="string"?T.bindTo:"source";return {src:T,bindTo:$,outRef:R,mockProjections:p}}async function Ce(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("validateCardPreflight requires card JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)";return await ce(R,u)}catch(n){return g(n)}}async function ne(l){try{let n=ke(l,"probeSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"probe-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());return C.ok?m({bindTo:n.bindTo,reachable:C.reachable,latencyMs:C.latencyMs,note:C.note}):d(C.error??"Preflight probe failed")}catch{return d("Executor does not support probe-source-preflight")}}catch(n){return g(n)}}async function Ne(l){try{let n=ke(l,"runSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"run-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.probeMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());if(!C.ok)return m({bindTo:n.bindTo,ok:!1,result:null,issues:[C.error??"Preflight run failed"]});if(n.outRef){let p=b(n.outRef);r.absoluteBlob.write(p.value,JSON.stringify(C.resultValue,null,2));}return m({bindTo:typeof C.bindTo=="string"?C.bindTo:n.bindTo,ok:!0,result:C.resultValue??null,issues:[]})}catch(R){let y=R instanceof Error?R.message:String(R);return m({bindTo:n.bindTo,ok:!1,result:null,issues:[y]})}}catch(n){return g(n)}}async function qe(l){try{let n=G();if(!n)return d("No task-executor registered for this board");let u=await r.invokeExecutor(n,"describe-capabilities",{timeout:r.executorTimeouts?.describeMs??1e4});return m(JSON.parse(u.trim()))}catch(n){return g(n)}}function je(l){try{let n=l.body;if(!n||!Array.isArray(n.ops))return d("updatesInCardStore requires body.ops array");let u=n.ops,R=j();for(let y of u){let C=y.op,p=y.id;if(!p)return d('op is missing "id"');if(C==="update"){let A=y["card-content"];if(!A)return d(`update op for "${p}" is missing "card-content"`);R.writeCard(p,A);}else return d(`Unknown op type: "${C??"(none)"}"`)}return m()}catch(n){return g(n)}}function q(l){try{let n=l.body;if(!n||!Array.isArray(n.ids))return d("readFromCardStore requires body.ids array");let u=n.ids,R=j(),y=u.map(C=>({id:C,"card-content":R.readCard(C)}));return m({cards:y})}catch(n){return g(n)}}function oe(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("evalCardCompute requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=u.compute;if(!p||!Array.isArray(p)||p.length===0)return m({cardId:R,ok:!0,computed_values:{},errors:[]});let A={id:R,card_data:u.card_data??{},requires:C,source_defs:u.source_defs,compute:p},T=a$2.runSync(A,{sourcesData:y}),$=T.node.computed_values??{},F=T.errors??[];return m({cardId:R,ok:F.length===0,computed_values:$,errors:F})}catch(n){return g(n)}}async function de(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("simulateCardCycle requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=await ce(R,u),A=p.status==="success"?{isValid:p.data.isValid,issues:p.data.issues}:{isValid:!1,issues:[p.status==="fail"?p.error:"internal error"]},T=u.source_defs??[],$=u.card_data??{},F=[],X=[],J=[];if(T.length>0){F=a$2.enrichSourcesSync(T,{card_data:$,requires:C}),X=F.filter(I=>I._skip!==!0);for(let I of X){let D=I.projections,L=I._projections;if(D&&L){for(let W of Object.keys(D))if(L[W]===void 0){let me=typeof I.bindTo=="string"?I.bindTo:"(unknown)";J.push({bindTo:me,key:W,error:`Projection "${W}" resolved to undefined`});}}}}let z=[],he=new Set(X.map(I=>typeof I.bindTo=="string"?I.bindTo:"")),le=Object.fromEntries(Object.entries(y).filter(([I])=>he.has(I))),fe=n["task-executor-ref"],Se=(fe?.howToRun&&fe?.whatToRun?fe:void 0)??G();for(let I=0;I<F.length;I++){let D=F[I],L=typeof D.bindTo=="string"?D.bindTo:`source_${I}`;if(D._skip===!0){z.push({bindTo:L,skipped:!0});continue}if(!Se){z.push({bindTo:L,skipped:!0,error:"No task executor configured"});continue}try{let W={...D},me=await r.invokeExecutor(Se,"run-source-preflight",{timeout:D.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(W)}),U=JSON.parse(me.trim());U.ok&&!Object.prototype.hasOwnProperty.call(y,L)&&Object.prototype.hasOwnProperty.call(U,"resultValue")&&(le[L]=U.resultValue),z.push({bindTo:L,reachable:U.reachable,latencyMs:U.latencyMs,error:U.ok?void 0:U.error});}catch{z.push({bindTo:L,skipped:!0,error:"Executor does not support run-source-preflight"});}}let se=u.compute,be={},Y=[];if(se&&Array.isArray(se)&&se.length>0){let I={id:R,card_data:$,requires:C,source_defs:u.source_defs,compute:se},D=a$2.runSync(I,{sourcesData:le});be=D.node.computed_values??{},Y=D.errors??[];}let ye=A.isValid&&J.length===0&&Y.length===0&&z.every(I=>I.reachable!==!1);return m({cardId:R,ok:ye,validation:A,source_probes:z,projection_errors:J,fetched_sources:le,computed_values:be,compute_errors:Y})}catch(n){return g(n)}}return {validateCardPreflight:Ce,probeSourcePreflight:ne,runSourcePreflight:Ne,evalCardCompute:oe,simulateCardCycle:de,describeTaskExecutorCapabilities:qe,updatesInCardStore:je,readFromCardStore:q}}
|
|
2
|
+
export{St as a,Yt as b,Ut as c,Xt as d,sr as e,ar as f};//# sourceMappingURL=chunk-C7OY3PYL.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-C7OY3PYL.js.map
|