yaml-flow 8.6.1 → 8.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/browser/asset-integrity.json +3 -3
  2. package/examples/board/demo-shell-with-server.html +2 -2
  3. package/examples/board/doc.html +2 -2
  4. package/examples/board/server/board-server.js +544 -45
  5. package/examples/board/server-config.json +2 -1
  6. package/examples/board/test/server-http-test.js +12 -4
  7. package/examples/board-local/demo-shell-localstorage.html +3 -3
  8. package/lib/{artifacts-store-lib-CLOtsiav.d.cts → artifacts-store-lib-BR-Samty.d.cts} +1 -1
  9. package/lib/{artifacts-store-lib-C1rtrkxm.d.ts → artifacts-store-lib-DT7XlWUL.d.ts} +1 -1
  10. package/lib/artifacts-store-public.d.cts +3 -3
  11. package/lib/artifacts-store-public.d.ts +3 -3
  12. package/lib/board-live-cards-mcp.cjs +1 -1
  13. package/lib/board-live-cards-mcp.d.cts +56 -23
  14. package/lib/board-live-cards-mcp.d.ts +56 -23
  15. package/lib/board-live-cards-mcp.js +1 -1
  16. package/lib/board-live-cards-node.cjs +8 -8
  17. package/lib/board-live-cards-node.d.cts +39 -21
  18. package/lib/board-live-cards-node.d.ts +39 -21
  19. package/lib/board-live-cards-node.js +8 -8
  20. package/lib/{board-live-cards-public-CBVjm327.d.ts → board-live-cards-public-BMUIPOrc.d.ts} +67 -42
  21. package/lib/board-live-cards-public-async-DKZqbJVU.d.ts +256 -0
  22. package/lib/board-live-cards-public-async-dMWNbWq6.d.cts +256 -0
  23. package/lib/{board-live-cards-public-CPJy-aGW.d.cts → board-live-cards-public-wkNmBIRC.d.cts} +67 -42
  24. package/lib/board-live-cards-public.cjs +1 -1
  25. package/lib/board-live-cards-public.d.cts +2 -2
  26. package/lib/board-live-cards-public.d.ts +2 -2
  27. package/lib/board-live-cards-public.js +1 -1
  28. package/lib/board-live-cards-server-runtime.cjs +1 -1
  29. package/lib/board-live-cards-server-runtime.d.cts +7 -6
  30. package/lib/board-live-cards-server-runtime.d.ts +7 -6
  31. package/lib/board-live-cards-server-runtime.js +1 -1
  32. package/lib/board-worker-adapter.cjs +4 -3
  33. package/lib/board-worker-adapter.d.cts +24 -14
  34. package/lib/board-worker-adapter.d.ts +24 -14
  35. package/lib/board-worker-adapter.js +4 -3
  36. package/lib/card-store-public.d.cts +2 -2
  37. package/lib/card-store-public.d.ts +2 -2
  38. package/lib/{chat-storage-lib-CKylihjm.d.cts → chat-storage-lib-BIUbE-fM.d.cts} +1 -1
  39. package/lib/{chat-storage-lib-Bce-xx6l.d.ts → chat-storage-lib-BlG-sobS.d.ts} +1 -1
  40. package/lib/chat-store-public.d.cts +3 -3
  41. package/lib/chat-store-public.d.ts +3 -3
  42. package/lib/{chunk-CWREBRXS.js → chunk-BQS3EIEK.js} +3 -3
  43. package/lib/{chunk-LDAP75GN.js → chunk-CIAJNUR4.js} +2 -2
  44. package/lib/chunk-GJJMEAVN.cjs +2 -0
  45. package/lib/chunk-H5HBXPOI.cjs +3 -0
  46. package/lib/chunk-HEEDJEKM.js +2 -0
  47. package/lib/chunk-KQX6R4PV.cjs +8 -0
  48. package/lib/chunk-MLVTJASJ.js +2 -0
  49. package/lib/chunk-N6P2JW4W.js +3 -0
  50. package/lib/chunk-OEFTOO47.cjs +3 -0
  51. package/lib/chunk-OSWJKJLB.js +8 -0
  52. package/lib/chunk-PBCDDO4V.cjs +2 -0
  53. package/lib/{chunk-I4WH5U5D.cjs → chunk-PMUSJQSR.cjs} +2 -2
  54. package/lib/chunk-SCWHDI3I.js +2 -0
  55. package/lib/{chunk-UVE65IPR.cjs → chunk-SFVO2LB2.cjs} +3 -3
  56. package/lib/{chunk-5DB54ZX2.cjs → chunk-U2N6MCD5.cjs} +2 -2
  57. package/lib/chunk-VMW4Z6EF.js +3 -0
  58. package/lib/chunk-WOALA3V5.cjs +2 -0
  59. package/lib/{chunk-LBMEVV4U.js → chunk-XQRNDX4Q.js} +2 -2
  60. package/lib/cloud-storage.cjs +2 -0
  61. package/lib/cloud-storage.d.cts +177 -0
  62. package/lib/cloud-storage.d.ts +177 -0
  63. package/lib/cloud-storage.js +2 -0
  64. package/lib/execution-refs.cjs +1 -1
  65. package/lib/execution-refs.js +1 -1
  66. package/lib/index.cjs +2 -2
  67. package/lib/index.d.cts +1 -1
  68. package/lib/index.d.ts +1 -1
  69. package/lib/index.js +1 -1
  70. package/lib/{types-DRl0Hy_p.d.cts → queue-lane-registry-BPKWWgd4.d.cts} +66 -14
  71. package/lib/{types-BuK2UMxk.d.ts → queue-lane-registry-Be6c0ftj.d.ts} +66 -14
  72. package/lib/server-runtime/index.cjs +1 -1
  73. package/lib/server-runtime/index.d.cts +18 -7
  74. package/lib/server-runtime/index.d.ts +18 -7
  75. package/lib/server-runtime/index.js +1 -1
  76. package/lib/step-machine-public/index.cjs +1 -1
  77. package/lib/step-machine-public/index.d.cts +1 -1
  78. package/lib/step-machine-public/index.d.ts +1 -1
  79. package/lib/step-machine-public/index.js +1 -1
  80. package/lib/{storage-interface-Ct-C4tlz.d.cts → storage-interface-BFiD3kyB.d.cts} +11 -1
  81. package/lib/{storage-interface-Ct-C4tlz.d.ts → storage-interface-BFiD3kyB.d.ts} +11 -1
  82. package/lib/stores/index.cjs +1 -1
  83. package/lib/stores/index.d.cts +1 -1
  84. package/lib/stores/index.d.ts +1 -1
  85. package/lib/stores/index.js +1 -1
  86. package/lib/stores/kv.d.cts +1 -1
  87. package/lib/stores/kv.d.ts +1 -1
  88. package/package.json +6 -1
  89. package/lib/chunk-6APH25VI.js +0 -2
  90. package/lib/chunk-KNFFDVLD.cjs +0 -2
  91. package/lib/chunk-LVNQCE5X.cjs +0 -3
  92. package/lib/chunk-M7EQRS6W.js +0 -3
  93. package/lib/chunk-NJJ7WEDT.cjs +0 -2
  94. package/lib/chunk-P64UKI3L.cjs +0 -8
  95. package/lib/chunk-Q6VSL327.js +0 -8
  96. package/lib/chunk-VCCTAUIG.js +0 -2
@@ -1,8 +0,0 @@
1
- 'use strict';var chunkNJJ7WEDT_cjs=require('./chunk-NJJ7WEDT.cjs'),chunkLVNQCE5X_cjs=require('./chunk-LVNQCE5X.cjs'),chunkUVE65IPR_cjs=require('./chunk-UVE65IPR.cjs'),chunkKNFFDVLD_cjs=require('./chunk-KNFFDVLD.cjs'),chunkYMEIPKLW_cjs=require('./chunk-YMEIPKLW.cjs'),chunkGYQXDNNI_cjs=require('./chunk-GYQXDNNI.cjs');var be={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ye=32;function tr(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function we(m){if(!m||typeof m!="object")return false;let y=m.summary;return !y||typeof y!="object"?false:Number(y.card_count||0)>0}function Ce(m,y){if(!y||typeof y!="object")return;let w=y;if(w.kind==="notification-batch"&&Array.isArray(w.notifications)){for(let _ of w.notifications)Ce(m,_);return}w.kind==="status"&&we(w.status)&&(m.status=w.status),w.kind==="computed_values"&&w.cardId&&(m.computedValues[w.cardId]=w.values),w.kind==="data_object"&&w.key&&(m.dataObjects[w.key]=w.payload),w.kind==="card_refreshed"&&w.cardId&&(m.cards[w.cardId]=w.card),w.kind==="card_removed"&&w.cardId&&(delete m.cards[w.cardId],delete m.computedValues[w.cardId]);}function lr(m){let y=String(m.apiBasePath||"/api/board").replace(/\/$/,""),w={...be,...m.corsHeaders||{}},_=m.boardId||"",j=m.logger||{info:console.log,warn:console.warn,error:console.error},z=m.invocationAdapter,st=m.chatFlowRunner||null,B=m.chatStorage??chunkNJJ7WEDT_cjs.b(),at=chunkGYQXDNNI_cjs.a(B),it=m.notificationTransport||null,Y=m.serverUrl||null,J=m.executionExtra||{},Ct=m.onSseClientConnected,Rt=m.onSseClientDisconnected,kt=m.onChannelSubscribed,St=m.onChannelUnsubscribed,p=new Map,k=new Map,I=new Map,$=null;function M(t){let e=chunkLVNQCE5X_cjs.e(t.baseRef,t.boardAdapter),r=t.nonCoreAdapter??(K(t.boardAdapter)?t.boardAdapter:null),n=r?chunkLVNQCE5X_cjs.f(t.baseRef,r):null,o=t.boardAdapter.kvStorageForRef(t.cardStoreRef),a=chunkYMEIPKLW_cjs.a(chunkLVNQCE5X_cjs.a({readIndex:()=>o.read("_index"),writeIndex:b=>o.write("_index",b),readCard:b=>o.read(b),writeCard:(b,O)=>(o.write(b,O),b),removeCard:b=>{o.delete(b);},cardExists:b=>o.read(b)!==null,defaultCardKey:b=>b},j.warn)),i=t.artifactsAdapter||t.boardAdapter,u=t.filesArtifactsStore??null,C=t.artifactsAdapter?i.blobStorage(""):i.blobStorage("files"),h=null;return {label:t.label,board:e,nonCore:n,cardStore:a,get filesArtifacts(){return h??=u??chunkNJJ7WEDT_cjs.c(C)},boardAdapter:t.boardAdapter,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,scratchStoreRef:t.scratchStoreRef,archiveStoreRef:t.archiveStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:tr(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let S=m.boards.map(M),G=new Map;function N(t){return G.get(t)??0}function K(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function tt(t){let e=S[N(t)];return {files:e?e.filesArtifacts:null}}function At(t){let e=tt(t);return e.files?chunkNJJ7WEDT_cjs.d(e.files):null}function D(){return chunkNJJ7WEDT_cjs.e()}function L(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ct(t){if(!t||t.notificationTeardown||!it||!t.notifyRef)return;let e=await it.subscribe(t.notifyRef,r=>{Ce(t.notification,r);let n=r.kind==="notification-batch"?r.notifications:[r];oe(n);});t.notificationTeardown=e;}async function Re(t){if(!t||t.initialized)return;let e={cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef};t.artifactsStoreRef&&(e.artifactsStoreRef=t.artifactsStoreRef),t.scratchStoreRef&&(e.scratchStoreRef=t.scratchStoreRef),t.archiveStoreRef&&(e.archiveStoreRef=t.archiveStoreRef);let r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow),t.inferenceAdapterRef&&(r["inference-adapter-ref"]=t.inferenceAdapterRef);let n=t.board.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 ct(t),!t.chatHandlerFlow&&t.chatHandlerRef&&z.describe)try{let o=await z.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?j.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&j.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){j.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}function Ft(t){if(!t.boardAdapter.publishBoardChangeNotifications)return;let e=[],r=t.board.status({});r.status==="success"&&r.data!=null&&we(r.data)&&e.push({kind:"status",status:r.data});let n=t.board.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,a]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:a});let o=t.board.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,a]of Object.entries(o.data))s&&e.push({kind:"computed_values",cardId:s,values:a});e.length>0&&t.boardAdapter.publishBoardChangeNotifications(e);}function Mt(t,e){if(!t||t.cardsBootstrapped)return;let r=t.cardStore.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(G.set(o.id,e),t.board.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function ft(){for(let t of S)await Re(t);}async function E(){await ft();for(let t=0;t<S.length;t++)Ft(S[t]),Mt(S[t],t);}function T(t){return S[N(t)]??null}function rt(t){let e=T(t);if(!e)return null;let r=e.cardStore.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}function Nt(){let t=r=>{if(!r||!r.cardStore)return [];let n=r.cardStore.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of S)e.push(...t(r));return e}function H(){return S[0]??null}function ke(){return {status(){let t=Ht();return t==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:t}},getOutputsDataObject(t){let e=t?.params?.key;return e?{status:"success",data:zt()[e]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},getOutputsComputedValues(t){let e=t?.params?.key;return e?{status:"success",data:Vt()[e]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},getOutputsFetchedSources(t){let e=t?.params?.key;if(!e)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let r=T(e)??H();return r?r.board.getOutputsFetchedSources({params:{key:e}}):{status:"fail",error:"Board context is unavailable"}},removeCard(t){let e=t?.params?.id;if(!e)return {status:"fail",error:"removeCard requires params.id"};let r=T(e)??H();return r?r.board.removeCard({params:{id:e}}):{status:"fail",error:"Board context is unavailable"}},cardRefreshedNotify(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let r=T(e)??H();return r?r.board.cardRefreshedNotify({params:{cardId:e}}):{status:"fail",error:"Board context is unavailable"}},upsertCard(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"upsertCard requires params.cardId"};let r=T(e)??H();return r?r.board.upsertCard({params:{cardId:e,restart:t.params.restart===true}}):{status:"fail",error:"Board context is unavailable"}}}}function Se(){let t=()=>{let e=H();if(!e?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return e.nonCore};return {describeTaskExecutorCapabilities(e){return t().describeTaskExecutorCapabilities(e)},validateCardPreflight(e){return t().validateCardPreflight(e)},evalCardCompute(e){return t().evalCardCompute(e)},probeSourcePreflight(e){return t().probeSourcePreflight(e)},runSourcePreflight(e){return t().runSourcePreflight(e)},simulateCardCycle(e){return t().simulateCardCycle(e)}}}function gt(){return {get(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(e){let r=rt(e);return r?{status:"success",data:{cards:[r]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:Nt()}}},set(t){let e=t.body;if(e==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let r=Array.isArray(e)?e:[e];for(let n of r){let o=n,s=typeof o.id=="string"?o.id:"";if(!s)return {status:"fail",error:"each card must have a string `id` field"};let a=G.get(s)??0,i=S[a]??H();if(!i)return {status:"fail",error:"Board context is unavailable"};let u=i.cardStore.set({body:o});if(u.status!=="success")return u;G.set(s,a);}return {status:"success",data:{count:r.length}}},del(t){let e=[t.params?.id,...t.body?.ids??[]].filter(r=>typeof r=="string"&&!!r);if(e.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let r of e){let n=T(r)??H();if(!n)return {status:"fail",error:"Board context is unavailable"};let o=n.cardStore.del({params:{id:r}});if(o.status!=="success")return o;G.delete(r);}return {status:"success",data:{count:e.length}}},patch(t){let e=typeof t.params?.id=="string"?t.params.id:void 0,r=typeof t.params?.path=="string"?t.params.path:void 0;if(!e||!r)return {status:"fail",error:"patch requires params.id and params.path"};let n=T(e)??H();return n?n.cardStore.patch(t):{status:"fail",error:"Board context is unavailable"}},appendFiles(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(!e)return {status:"fail",error:"appendFiles requires params.id"};let r=T(e)??H();return r?r.cardStore.appendFiles(t):{status:"fail",error:"Board context is unavailable"}}}}function V(){return chunkKNFFDVLD_cjs.a({board:ke(),nonCore:Se(),cardStore:gt(),chatStore:at,uploadCardFile({cardId:t,fileName:e,contentType:r,bytes:n}){return xt(t,e,r,n,{inChat:false})},buildFileDownloadUrl({cardId:t,fileIdx:e,storedName:r}){let n=`${Y||""}${y}/cards/${encodeURIComponent(t)}/files/${e}`;return r?`${n}?sn=${encodeURIComponent(r)}`:n},readFetchedSourceJsonByRef({cardId:t,ref:e}){let r=T(t)??H();if(!r)return null;let o=r.boardAdapter.resolveBlob(chunkUVE65IPR_cjs.b(e)).trim();return o?JSON.parse(o):null}})}function A(t,...e){for(let r of e)if(typeof t[r]=="string")return String(t[r]);return ""}function W(t,...e){for(let r of e)if(t[r]!==void 0)return Number(t[r])}function dt(t,...e){for(let r of e){let n=t[r];if(n&&typeof n=="object"&&!Array.isArray(n))return n}return {}}function Z(t,e,...r){for(let n of r){let o=t[n];if(o&&typeof o=="object"&&!Array.isArray(o))return o}throw Object.assign(new Error(`MCP tool requires ${e}`),{statusCode:400})}function vt(t,e,...r){for(let n of r){let o=t[n];if(o!==void 0){let s=Number(o);if(Number.isFinite(s))return s}}throw Object.assign(new Error(`MCP tool requires ${e}`),{statusCode:400})}function Ae(t){if(Array.isArray(t.bytes))return new Uint8Array(t.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof t.text=="string")return new TextEncoder().encode(t.text);if(typeof t.base64=="string"){let e=String(t.base64).replace(/-/g,"+").replace(/_/g,"/"),r=e+"=".repeat((4-e.length%4)%4),n=atob(r);return Uint8Array.from(n,o=>o.charCodeAt(0))}return null}function Ut(t,e){let r=A(t,"board_id"),n=A(t,"card_id");if(!r)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!n)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(r!==_)throw Object.assign(new Error(`Unknown board_id: ${r}`),{statusCode:400});return V().setChatProcessing({cardId:n,active:e}),{status:"success",data:{boardId:_,cardId:n,active:e}}}function pt(t){let e=A(t,"board_id"),r=A(t,"card_id");if(!e)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return {cardId:r}}function _t(t,e){if(t?.status==="success")return Object.prototype.hasOwnProperty.call(t,"data")?t.data:void 0;throw t?.status==="fail"||t?.status==="error"?Object.assign(new Error(t.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}function qt(t){let e=A(t,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let r=e.split(".");if(!(r.length>=2&&r[0]==="chat"&&r.every(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function Dt(t,e){let r=t.meta;for(let n of e.split(".")){if(!r||typeof r!="object"||Array.isArray(r)||!Object.prototype.hasOwnProperty.call(r,n))return {exists:false,value:null};r=r[n];}return {exists:true,value:r}}function ve(t){let{cardId:e}=pt(t),r=V().getChatProcessing({cardId:e});return {status:"success",data:{boardId:_,cardId:e,active:r.active}}}function _e(t){let{cardId:e}=pt(t),r=qt(t);if(!Object.prototype.hasOwnProperty.call(t,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(r.split(".").includes("__visible_controlplane_only")){let n=_t(gt().get({params:{id:e}}),"cardStore.get"),o=Array.isArray(n.cards)&&n.cards.length>0&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null,s=o?Dt(o,"__visible_controlplane_only").value:void 0;if(t.value!==s)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:_,cardId:e,key:r}}}return _t(gt().patch({params:{id:e,path:`meta.${r}`},body:{value:t.value}}),"cardStore.patch"),{status:"success",data:{boardId:_,cardId:e,key:r}}}function Be(t){let{cardId:e}=pt(t),r=qt(t),n=_t(gt().get({params:{id:e}}),"cardStore.get"),o=Array.isArray(n.cards)&&n.cards.length>0&&n.cards[0]&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null;if(!o)throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});let s=Dt(o,r);return {status:"success",data:{boardId:_,cardId:e,key:r,exists:s.exists,value:s.value}}}function Ie(t){return {"discover.source-kinds":()=>t.discoverSourceKinds(),"inspect.board-runtime-status":()=>t.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>t.inspectCardDefinitionAndRuntime({cardId:A(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let r=W(e,"tail_turns"),n=W(e,"tail"),o=A(e,"turn_id"),s=e.all_turns===true,a=A(e,"tail_turns_before_id");return t.inspectChatMessagesOnCards({cardId:A(e,"card_id"),...r!==void 0?{lastUserTurns:r}:{},...n!==void 0?{tail:n}:{},...o?{turnId:o}:{},...s?{allTurns:true}:{},...a?{tailTurnsBeforeId:a}:{}})},"inspect.file-contents":e=>t.inspectFileContents({cardId:A(e,"card_id"),fileIdx:Number(W(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>t.preflightValidateCandidateCardDefinition({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>t.preflightMaterializeCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockRequires:Z(e,"mock_requires","mock_requires"),mockFetchedSources:Z(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>t.preflightProbeSingleSourceInCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockProjections:dt(e,"mock_projections"),sourceIdx:vt(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>t.preflightRunSingleSourceInCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockProjections:dt(e,"mock_projections"),sourceIdx:vt(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>t.preflightRunSingleSourceInLiveCard({cardId:A(e,"card_id"),sourceIdx:vt(e,"source_idx","source_idx"),mockRequires:Z(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>t.preflightRunOneCycleWithCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockRequires:dt(e,"mock_requires")}),"manage.read-card":e=>t.manageReadCard({cardId:A(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let r=A(e,"turn_id");if(!r)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return t.manageAddChatEntryAndAnyAttachments({cardId:A(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...r?{turn:r}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>t.manageUpsertCard({cardId:A(e,"card_id"),candidateCardContent:dt(e,"candidate_card_content")}),"manage.remove-card":e=>t.manageRemoveCard({cardId:A(e,"card_id")})}}function xe(){return {"getstate.is-chat-processing":t=>ve(t),"setstate.chat-processing-started":t=>Ut(t,true),"setstate.chat-processing-done":t=>Ut(t,false),"getstate.card-meta":t=>Be(t),"setstate.card-meta":t=>_e(t),"manage.upload-card-file":t=>{let e=A(t,"board_id"),r=A(t,"card_id"),n=A(t,"file_name"),o=A(t,"content_type")||"application/octet-stream",s=Ae(t);if(!e)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});if(!r)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!n)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!s)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return xt(r,n,o,s,{inChat:false})},"manage.admin-read-card":t=>{let{cardId:e}=pt(t);return {status:"success",data:{cards:V().adminReadCard({cardId:e})}}},"manage.admin-upsert-card":t=>{let e=A(t,"board_id"),r=A(t,"card_id");if(!e)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return V().adminUpsertCard({cardId:r,candidateCardContent:dt(t,"candidate_card_content")})}}}async function Lt(t,e,r){let n=r[t];if(!n)throw Object.assign(new Error(`Unknown MCP tool: ${t}`),{statusCode:400});let o=await n(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.status;if(a==="success")return Object.prototype.hasOwnProperty.call(s,"data")?o:{status:"success",data:{}};if(a==="fail"||a==="error")return o}return {status:"success",data:o}}function mt(t,e){if(!t||typeof t!="object"||Array.isArray(t))return e;let r=t;if(typeof r.error=="string"&&r.error.trim())return r.error;if(r.step==="validate"){let n=r.validation;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n.data;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s.issues;if(Array.isArray(a)){let u=a.find(C=>typeof C=="string"&&C.trim());if(typeof u=="string")return `Validation failed: ${u}`}let i=s.errors;if(Array.isArray(i)&&i.length>0)return "Validation failed"}}return "Validation failed"}return e}function Ht(){let t=S.map(s=>{try{let i=s.boardAdapter.kvStorageForRef(s.outputsStoreRef).read("status");if(i!=null)return i}catch{}return s.notification.status}).filter(Boolean);if(t.length===0)return null;if(t.length===1)return t[0];let e=[],r=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],n={};for(let s of r)n[s]=0;for(let s of t){let a=s,i=Array.isArray(a.cards)?a.cards:[];e.push(...i);for(let u of r)n[u]+=Number(a?.summary?.[u]||0);}let o=t[0];return {...o,cards:e,summary:{...o.summary||{},card_count:e.length,...n}}}function Vt(){let t={},e=r=>{for(let[n,o]of Object.entries(r.notification.computedValues)){let s=r.notification.cards[n];t[n]={schema_version:"v1",card_id:n,card_data:s?.card_data??{},computed_values:o??{}};}};for(let r of S)e(r);return t}function zt(){let t={};for(let e of S)Object.assign(t,e.notification.dataObjects||{});return t}function yt(){let t=Nt(),e=Vt(),r=zt(),n={};for(let s of t){if(!s?.id)continue;let a=s.id,i=e[a]||{},u={...i.card_data&&typeof i.card_data=="object"?i.card_data:s.card_data&&typeof s.card_data=="object"?s.card_data:{}};n[a]={schema_version:i.schema_version||"v1",card_id:i.card_id||a,card_data:u,computed_values:i.computed_values&&typeof i.computed_values=="object"?i.computed_values:{}};}let o={};for(let s of t){if(!s?.id)continue;let a=s.id;try{let i=It(a),u=V().getChatProcessing({cardId:a}).active;(i.length>0||u)&&(o[a]={messages:i.map(C=>({role:String(C.role||"system"),text:String(C.text||""),files:Array.isArray(C.files)?C.files:[]})),receiving:!1,processing:u});}catch{}}return {boardId:_,cardDefinitions:t,statusSnapshot:Ht(),dataObjectsByToken:r,cardRuntimeById:n,cardChatsByCardId:o}}function Bt(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=T(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let a=rt(t);if(!a)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=o?JSON.stringify(a):null,u=e(a)||a;if(o&&JSON.stringify(u)===i)return;let C=s.cardStore.set({body:u});if(C.status!=="success")throw Object.assign(new Error(C.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let h=s.board.upsertCard({params:{cardId:t,restart:true}});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to upsert card: ${t}`),{statusCode:500})}}function je(t,e){Bt(t,e,{syncBoard:true});}function Jt(t,e){Bt(t,e,{syncBoard:false});}function Oe(t){let e=T(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!rt(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=e.board.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}function $e(t,e){Bt(t,r=>{if(!e||typeof e!="object"||Object.keys(e).length===0)return r;function n(o,s,a){let i=String(s||"").split(".").filter(Boolean);if(!i.length)return;let u=o;for(let C=0;C<i.length-1;C++){let h=i[C];(!u[h]||typeof u[h]!="object")&&(u[h]={}),u=u[h];}u[i[i.length-1]]=a;}if(e.fieldValues!==void 0&&e.fieldValues!==null){let o=null,s=r.view;if(s&&Array.isArray(s.elements)){for(let a of s.elements)if(a?.data&&a.data.writeTo){o=a.data.writeTo;break}}o?n(r,o,e.fieldValues):typeof e.fieldValues=="object"&&!Array.isArray(e.fieldValues)&&(r.card_data={...r.card_data||{},...e.fieldValues});}else {if(Array.isArray(e._stagedFiles)&&e._stagedFiles.length>0)return r;for(let[o,s]of Object.entries(e))o!=="_stagedFiles"&&(s!==null&&typeof s=="object"&&!Array.isArray(s)&&r[o]!==null&&typeof r[o]=="object"&&!Array.isArray(r[o])?r[o]={...r[o],...s}:r[o]=s);}return r},{syncBoard:true,restartOnlyIfChanged:true});}function Ee(t){let e=String(t||"").trim();if(!e)return "upload.bin";let r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (r>=0?e.slice(r+1):e)||"upload.bin"}function Pe(t){B.clear(t);try{V().setChatProcessing({cardId:t,active:!1});}catch{}}function Te(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"";return B.append(t,e,s,n,o)}function It(t){return B.readAll(t)}function Fe(t){let e=[];try{let r=rt(t);if(!r)return e;let n=D().read(r.card_data&&typeof r.card_data=="object"?r.card_data:null);for(let o of n)e.push(o.stored_name);}catch{}return e}function Me(t,e,r,n){let o=L(t),s=tt(t),a=Ee(e),i=At(t),u=i?i.allocateStoredName(o,a,{seedNames:Fe(t),maxLen:Ye}):`${String(Date.now())}-${a}`;return s.files&&s.files.putBytes(`${o}/${u}`,new Uint8Array(n),r||"application/octet-stream"),{name:a,stored_name:u,size:n.length,mime_type:r||"application/octet-stream",uploaded_at:new Date().toISOString()}}function xt(t,e,r,n,o){if(!n.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let s=o?.inChat===true,a=Me(t,e,r,n),i=null;if(Jt(t,u=>{let C=new Date().toISOString(),h=u.card_data&&typeof u.card_data=="object"?u.card_data:{};u.card_data=h;let b=D().normalizeIncoming([{name:a.name,stored_name:a.stored_name,size:a.size,mime_type:a.mime_type,uploaded_at:a.uploaded_at||C,chat:s}],C);return i=D().merge(h,b).findIndex(nt=>nt.stored_name===a.stored_name),u}),s){let u=typeof i=="number"&&i>=0?` #${i}`:"";Te(t,"system",`file uploaded: ${a.name} as ${a.stored_name}${u}`,[],o?.turnId??"");}return {ok:true,file:a}}function Gt(t){let e=T(t);if(!e)return null;let r=e.board.getConfig({params:{key:"chat-handler-flow"}}),n=r.status==="success"?r.data?.value:null,o=e.chatHandlerRef;return n==null&&(!o||typeof o!="object")?null:{ctx:e,handlerFlow:n,handlerRef:o}}function Ne(t,e,r=false,n=""){let o=Gt(t);if(!o)return;let{ctx:s,handlerFlow:a,handlerRef:i}=o;if(!r)try{V().setChatProcessing({cardId:t,active:!0});}catch{}let u={boardId:_,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...J,...Y?{serverUrl:Y}:{}};if(!st&&a!=null){try{V().setChatProcessing({cardId:t,active:!1});}catch{}j.warn(`[chat-handler-flow] configured for card "${t}" but no chatFlowRunner was provided`);return}if(a!=null){let h=st;if(!h)return;h.run(a,u,{boardId:_,cardId:String(t),label:s.label,logger:j,serverUrl:Y,executionExtra:J}).then(b=>{if(b.dispatched)j.info(`[chat-handler-flow] invoked for card "${t}" (boardId: "${_}")`);else {try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler-flow] dispatch failed for card "${t}": ${b.error||"unknown"}`);}},b=>{try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler-flow] invoke failed for card "${t}": ${b?.message||String(b)}`);});return}let C=i;C&&z.invoke(C,u).then(h=>{if(h.dispatched)j.info(`[chat-handler] invoked for card "${t}" (boardId: "${_}")`);else {try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler] dispatch failed for card "${t}": ${h.error||"unknown"}`);}},h=>{try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler] invoke failed for card "${t}": ${h?.message||String(h)}`);});}function Ue(t,e,r){let n=e==="chat-send"?Jt:je,o;n(t,s=>{let a=new Date().toISOString(),i=s.card_data&&typeof s.card_data=="object"?s.card_data:{};if(s.card_data=i,e==="chat-send"){let u=r&&typeof r.text=="string"?r.text.trim():"",C=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"",h=[];if(Array.isArray(r?.files)){for(let b of r.files)if(b){if(typeof b=="string"){h.push({name:b});continue}if(typeof b=="object"){let O=b;typeof O.name=="string"&&h.push({name:O.name,size:O.size,mime_type:O.mime_type,uploaded_at:O.uploaded_at,stored_name:O.stored_name,chat:O.chat===true});}}}if(u||h.length>0){let b=at.runBatch({cardId:t,commands:[{command:"append",role:"user",text:u,files:h,turn:C},{command:"set-processing",active:true}]});if(b.status!=="success")throw new Error(b.error);let O=b.data.results[0]?.data?.id;if(typeof O!="string"||!O)throw new Error(`chat-send did not return an append id for card ${t}`);o={cardId:t,lastEntryId:O,processingAlreadySet:true,turnId:C};try{let bt=It(t);oe([{kind:"card_chats",cardId:t,messages:bt.map(X=>({role:String(X.role||"system"),text:String(X.text||""),files:Array.isArray(X.files)?X.files:[]})),receiving:!0,processing:B.isProcessing(t)}]);}catch{}}return s}if(e==="file-upload"){let u=D().normalizeIncoming(r?.files,a);return u.length>0&&D().merge(i,u),s}if(e==="action"){let u=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!u)return s;i.lastAction={buttonId:u,at:a},i.lastActionText=`${u} @ ${a}`;}return s}),o&&Ne(o.cardId,o.lastEntryId,o.processingAlreadySet,o.turnId??"");}function f(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...w,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}function Kt(t,e,r){let n=rt(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=D().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,a=L(t),i=tt(t),u=String(s.stored_name||""),C=`${a}/${u}`,h=i.files?i.files.getBytes(C):null;if(!h)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:h}}function qe(t,e,r,n){let{fileRecord:o,bytes:s}=Kt(e,r,n),a=String(o.name||o.stored_name||"download.bin"),i=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":i,"Content-Disposition":`attachment; filename="${a}"`,"Content-Length":s.length}),t.end(s);}function De(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 Wt(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
- `)}async function U(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(Zt(e)).trim();return r?JSON.parse(r):{}}async function Le(t){let e=[];for await(let r of t)e.push(r);return typeof Buffer<"u"?Buffer.concat(e):Zt(e)}function Zt(t){let e=t.reduce((o,s)=>o+s.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Xt(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=S[0];return n?n.board.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}function Qt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=S[0];return n?n.board.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}function He(t,e,r){let n=String(t||"").trim();if(!n)return {statusCode:400,body:{error:"callback token is required"}};let o=e==="success"?Xt(n,r):Qt(n,r);return o.status==="success"?{statusCode:200,body:o}:o.status==="fail"?{statusCode:400,body:{error:o.error}}:{statusCode:500,body:{error:o.error}}}let Yt=0;function te(t){let e=JSON.stringify(t);return Yt++,`id: ${Yt}
3
- data: ${e}
4
-
5
- `}function ee(t){let e=t;try{e.flushHeaders?.();}catch{}try{e.flush?.();}catch{}try{e.socket?.setNoDelay?.(!0);}catch{}try{e.socket?.uncork?.();}catch{}}function jt(t,e){let r=p.get(t);if(r&&!(e&&r.res!==e)){p.delete(t),Et();try{Rt?.(t);}catch{}try{r.res.end();}catch{}}}function ht(t,e){let r=p.get(t);if(!r)return;let n=te(e);try{r.res.write(n),ee(r.res);}catch{jt(t,r.res);}}function re(t,e,r,n,o){if(!p.has(e)){f(t,404,{error:`SSE client not connected: ${e}`});return}o?kt?.(e,r,n):St?.(e,r,n),f(t,200,{ok:true,clientId:e,channelName:r,...n.cardId?{cardId:n.cardId}:{},subscribed:o});}function Ot(){let t=new Set;for(let e of p.values())for(let r of e.subscribedChatCardIds)t.add(r);return Array.from(t)}function Ve(t){let e=k.has(t)?k.get(t):null,{cursor:r}=B.readAfter(t,e),n=B.isProcessing(t),o=n!==(I.get(t)??false),s=r!==e;return s&&k.set(t,r),I.set(t,n),s||o}function ne(t,e=true){let r=It(t),n=Date.now();return {kind:"card_chats",cardId:t,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:r.map(o=>({role:String(o.role||"system"),text:String(o.text||""),files:Array.isArray(o.files)?o.files:[]})),receiving:e,processing:B.isProcessing(t)}}function $t(t,e=true){let r={kind:"notification-batch",notifications:[ne(t,e)]};for(let[n,o]of p.entries())o.subscribedChatCardIds.has(t)&&ht(n,r);}function Et(){Ot().length>0||($&&(clearInterval($),$=null),k.clear(),I.clear());}function ze(){if($)return;let t=()=>{let e=Ot();if(e.length===0){Et();return}let r=new Set(e);for(let n of Array.from(k.keys()))r.has(n)||k.delete(n);for(let n of Array.from(I.keys()))r.has(n)||I.delete(n);for(let n of e)Ve(n)&&$t(n,true);};t(),$=setInterval(t,1e3);}function Je(t,e){let r=p.get(t);if(!r)return false;r.subscribedChatCardIds.add(e);let{cursor:n}=B.readAfter(e,null);return k.set(e,n),I.set(e,B.isProcessing(e)),ze(),ht(t,{kind:"notification-batch",notifications:[ne(e,true)]}),true}function Ge(t,e){let r=p.get(t);return r?(r.subscribedChatCardIds.delete(e),Ot().includes(e)||(k.delete(e),I.delete(e)),Et(),true):false}function Ke(t){if(!t||typeof t!="object")return false;let e=t.kind;return e==="card_chats"||e==="chat_messages"}function oe(t){if(!t||t.length===0)return;let e=[],r=new Set;for(let n of t)Ke(n)&&typeof n.cardId=="string"?r.add(String(n.cardId)):e.push(n);if(e.length>0){let n={kind:"notification-batch",notifications:e};for(let o of p.keys())ht(o,n);}for(let n of r)$t(n,true);}function We(t,e,r){let n=p.get(r),o=n?new Set(n.subscribedChatCardIds):new Set;n&&jt(r,n.res),e.writeHead(200,{...w,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),ee(e),p.set(r,{res:e,subscribedChatCardIds:o});let s=yt(),a=te(s);e.write(a);try{Ct?.(r,u=>{ht(r,u);});}catch{}let i=setInterval(()=>{try{e.write(`: keepalive
6
-
7
- `);}catch{}},15e3);t.on("close",()=>{clearInterval(i),jt(r,e);});}async function Ze(t,e,r){let n=t.method||"GET",o=r,s=o.pathname;try{if(n==="GET"&&s===`${y}/init-board`)return await ft(),f(e,200,yt()),!0;if(n==="GET"&&s===`${y}/sse`){await ft();let d=String(o.searchParams.get("clientId")||"").trim();if(!d)return f(e,400,{error:"clientId query param is required for SSE"}),!0;We(t,e,d);for(let c=0;c<S.length;c++)Ft(S[c]),Mt(S[c],c);return !0}if(n==="GET"&&s===`${y}/board-status`)return f(e,200,yt()),!0;let a=s.match(new RegExp(`^${F(y)}/callback/board-worker/([^/]+)/(success|failure)$`));if(n==="POST"&&a){await ft();let d=decodeURIComponent(a[1]),c=a[2],g=await U(t),l=He(d,c,g);return f(e,l.statusCode,l.body),!0}if(n==="POST"&&s===`${y}/mcp`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f(e,400,{error:"tool is required"}),!0;if(c==="inspect.file-contents")return f(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let l=await Lt(c,g,Ie(V()));if(l&&typeof l=="object"&&!Array.isArray(l)){let R=l;if(R.status==="fail")return f(e,400,{error:mt(l,"Request failed")}),!0;if(R.status==="error")return f(e,500,{error:mt(l,"Internal error")}),!0}f(e,200,l);}catch(l){let R=typeof l?.statusCode=="number"?Number(l.statusCode):500,x=l instanceof Error?l.message:String(l);f(e,R,{error:x});}return !0}if(n==="POST"&&s===`${y}/mcp-controlplane`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f(e,400,{error:"tool is required"}),!0;try{let l=await Lt(c,g,xe());if(l&&typeof l=="object"&&!Array.isArray(l)){let R=l;if(R.status==="fail")return f(e,400,{error:mt(l,"Request failed")}),!0;if(R.status==="error")return f(e,500,{error:mt(l,"Internal error")}),!0}f(e,200,l);}catch(l){let R=typeof l?.statusCode=="number"?Number(l.statusCode):500,x=l instanceof Error?l.message:String(l);f(e,R,{error:x});}return !0}if(n==="POST"&&s===`${y}/mcp-raw`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f(e,400,{error:"tool is required"}),!0;if(c!=="inspect.file-contents")return f(e,400,{error:`Tool does not support raw response: ${c}`}),!0;let l=A(g,"card_id","cardId"),R=W(g,"file_idx","fileIdx"),x=W(g,"head-lines","headLines"),v=W(g,"tail-lines","tailLines"),P=W(g,"head-bytes","headBytes"),et=W(g,"tail-bytes","tailBytes");if(!l)return f(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(R===void 0||!Number.isInteger(R)||R<0)return f(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([x,v,P,et].filter(q=>q!==void 0).length>1)return f(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[q,ot]of [["head-lines",x],["tail-lines",v],["head-bytes",P],["tail-bytes",et]])if(ot!==void 0&&(!Number.isInteger(ot)||ot<0))return f(e,400,{error:`inspect.file-contents requires ${q} to be a non-negative integer`}),!0;let se=V().inspectFileContents({cardId:l,fileIdx:R}),Xe=typeof se?.stored_name=="string"?se.stored_name:null,{fileRecord:Pt,bytes:lt}=Kt(l,R,Xe),ae=String(Pt.name||Pt.stored_name||"download.bin"),Tt=String(Pt.mime_type||"application/octet-stream"),wt=(o.searchParams.get("resp")||"").trim().toLowerCase();if(wt&&wt!=="json-b64")return f(e,400,{error:`unsupported resp mode: ${wt}`}),!0;let Qe=wt==="json-b64",Q;if(x!==void 0||v!==void 0){if(!De(Tt))return f(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let q=new TextDecoder().decode(lt),ot=x!==void 0?Wt(q,"head",x):Wt(q,"tail",v);Q=typeof Buffer<"u"?Buffer.from(ot,"utf8"):new TextEncoder().encode(ot);}else if(P!==void 0||et!==void 0){let q=P??et;Q=P!==void 0?lt.slice(0,q):lt.slice(Math.max(0,lt.length-q));}else Q=lt;if(Qe){let q=typeof Buffer<"u"?Buffer.from(Q).toString("base64"):btoa(String.fromCharCode(...Q));return f(e,200,{bodyBase64:q,mimeType:Tt,filename:ae,byteLength:Q.length}),!0}return e.writeHead(200,{"Content-Type":Tt,"Content-Disposition":`attachment; filename="${ae}"`,"Content-Length":Q.length}),e.end(Q),!0}let i=s.match(new RegExp(`^${F(y)}/cards/([^/]+)$`));if(n==="GET"&&i){await E();let d=decodeURIComponent(i[1]),c=rt(d);return c?(f(e,200,c),!0):(f(e,404,{error:`card not found: ${d}`}),!0)}if(n==="PATCH"&&i){await E();let d=decodeURIComponent(i[1]),c=await U(t);return $e(d,c),f(e,200,{ok:!0}),!0}let u=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/retrigger$`));if(n==="POST"&&u){await E();let d=decodeURIComponent(u[1]);return Oe(d),f(e,200,{ok:!0}),!0}let C=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/actions$`));if(n==="POST"&&C){await E();let d=decodeURIComponent(C[1]),c=Date.now(),g=new Date(c).toISOString(),l=await U(t),R=l?.actionType;if(R==="chat-send"&&!Gt(d)){let v=Date.now();return f(e,409,{error:`chat handler is not configured for card: ${d}`,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:409}),!0}if(R==="chat-send"){let v=l?.payload??{},P=typeof v["turn-id"]=="string"?v["turn-id"]:typeof v.turnId=="string"?v.turnId:typeof v.turn=="string"?v.turn:"";if(!P||!String(P).trim()){let et=Date.now();return f(e,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${d}`,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(et).toISOString(),responseSentAtMs:et,responseStatus:400}),!0}}Ue(d,R,l?.payload);let x=Date.now();return f(e,200,{ok:!0,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(x).toISOString(),responseSentAtMs:x,responseStatus:200}),!0}let h=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats$`));if(n==="GET"&&h){await E();let d=decodeURIComponent(h[1]),c=String(o.searchParams.get("turn-id")||""),g=String(o.searchParams.get("all-turns")||"").toLowerCase()==="true",l=String(o.searchParams.get("tail-turns-before-id")||""),R=o.searchParams.get("tail-turns"),x=R==null||R===""?g||c?void 0:1:Number.parseInt(R,10),v=at.readAll({params:{cardId:d},body:{...x===void 0?{}:{tailTurns:x},...c?{turnId:c}:{},...g?{allTurns:!0}:{},...l?{tailTurnsBeforeId:l}:{}}});if(v.status!=="success")return f(e,400,{error:v.error||"Failed to read chats"}),!0;let P=v.data.records;return f(e,200,{ok:!0,messages:P}),!0}if(n==="POST"&&h){await E();let d=decodeURIComponent(h[1]),c=await U(t),g=typeof c?.role=="string"?c.role:"assistant",l=typeof c?.text=="string"?c.text:"",R=Array.isArray(c?.files)?c.files:[],x=typeof c?.turn=="string"?c.turn:typeof c?.["turn-id"]=="string"?c["turn-id"]:typeof c?.turnId=="string"?c.turnId:"",v=c?.done===!0,P=B.append(d,g,l,R,x);return v&&B.setProcessing(d,!1),$t(d,!v),f(e,200,{ok:!0,id:P}),!0}let b=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats/subscribe-sse$`));if(n==="POST"&&b){await E();let d=decodeURIComponent(b[1]),c=await U(t),g=typeof c?.clientId=="string"?c.clientId.trim():"";return g?Je(g,d)?(f(e,200,{ok:!0,clientId:g,cardId:d,subscribed:!0}),!0):(f(e,404,{error:`SSE client not connected: ${g}`}),!0):(f(e,400,{error:"clientId is required"}),!0)}let O=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(n==="POST"&&O){await E();let d=decodeURIComponent(O[1]),c=await U(t),g=typeof c?.clientId=="string"?c.clientId.trim():"";return g?Ge(g,d)?(f(e,200,{ok:!0,clientId:g,cardId:d,subscribed:!1}),!0):(f(e,404,{error:`SSE client not connected: ${g}`}),!0):(f(e,400,{error:"clientId is required"}),!0)}let nt=s.match(new RegExp(`^${F(y)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&nt){await E();let d=decodeURIComponent(nt[1]),c=nt[2]==="subscribe",g=await U(t),l=typeof g?.clientId=="string"?g.clientId.trim():"";return l?(re(e,l,d,{},c),!0):(f(e,400,{error:"clientId is required"}),!0)}let ut=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&ut){await E();let d=decodeURIComponent(ut[1]),c=decodeURIComponent(ut[2]),g=ut[3]==="subscribe",l=await U(t),R=typeof l?.clientId=="string"?l.clientId.trim():"";return R?(re(e,R,c,{cardId:d},g),!0):(f(e,400,{error:"clientId is required"}),!0)}let bt=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/files$`));if(n==="POST"&&bt){await E();let d=decodeURIComponent(bt[1]),c=String(o.searchParams.get("inChat")||"").toLowerCase()==="true",g=String(o.searchParams.get("turn-id")||"").trim();if(c&&!g)return f(e,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${d}`}),!0;let l=t.headers["x-file-name"],R=String(t.headers["content-type"]||"application/octet-stream"),x=Array.isArray(l)?l[0]:l,v=x?decodeURIComponent(String(x)):"upload.bin",P=await Le(t);return f(e,200,xt(d,v,R,P,{inChat:c,turnId:g})),!0}let X=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/files/(\\d+)$`));if(n==="GET"&&X){let d=decodeURIComponent(X[1]),c=parseInt(X[2],10),g=o.searchParams.get("sn");return qe(e,d,c,g),!0}return !1}catch(a){let i=a?.statusCode||500;return f(e,i,{error:String(a?.message||a)}),true}}return {get apiBasePath(){return y},get corsHeaders(){return w},handleRuntimeApi:Ze,buildPublishedRuntimePayload:yt,clearChatRecords:Pe,reportSourceFetched(t,e){return Xt(t,{ref:e})},reportSourceFetchFailure(t,e){return Qt(t,{reason:e})},get cardStore(){return S[0]?.cardStore??{set(){return {status:"fail",error:"no board context"}}}}}}function fr(m){let y=String(m.apiBasePath||"/api/boards").replace(/\/$/,""),w={...be,...m.corsHeaders||{}},_=m.serverMetaStore,j=m.boardRuntimeFactory,z=new Map,st="boards-config.json";function B(){let p=_.getText(st);if(!p)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(p)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function at(p){_.putText(st,JSON.stringify(p,null,2));}function it(p){let k=String(p||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return k.length>0&&k.length<=64?k:null}function Y(p){if(z.has(p))return z.get(p);let I=B().boards.find(M=>M.id===p)||{},$=j(p,I);return z.set(p,$),$}function J(p,k,I){let $=JSON.stringify(I),M=typeof Buffer<"u"?Buffer.byteLength($):new TextEncoder().encode($).length;p.writeHead(k,{...w,"Content-Type":"application/json; charset=utf-8","Content-Length":M}),p.end($);}async function Ct(p,k,I){let $=p.method||"GET",M=I.pathname;if($==="GET"&&M===y)return J(k,200,{ok:true,boards:B().boards}),true;if($==="POST"&&M===y){let S=[];for await(let L of p)S.push(L);let G=typeof Buffer<"u"?Buffer.concat(S).toString("utf-8").trim():new TextDecoder().decode(er(S)).trim(),N={};try{N=G?JSON.parse(G):{};}catch{N={};}let K=it(N.id);if(!K)return J(k,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let tt=B();if(tt.boards.some(L=>L.id===K))return J(k,409,{error:`Board "${K}" is already registered`}),true;let At=typeof N.label=="string"&&N.label.trim()?N.label.trim():K,D={id:K,label:At};for(let[L,ct]of Object.entries(N))L==="id"||L==="label"||ct!=null&&(D[L]=ct);return tt.boards.push(D),at(tt),J(k,200,{ok:true,board:D}),true}return false}async function Rt(p,k,I){let M=I.pathname.match(new RegExp(`^${F(y)}/([^/]+)(/|$)`));if(!M)return false;let S=it(decodeURIComponent(M[1]));return S?B().boards.some(K=>K.id===S)?!!await Y(S).handleRuntimeApi(p,k,I):(J(k,404,{error:`Board "${S}" not registered. POST ${y} with {id} to register it first.`}),true):(J(k,400,{error:"Invalid board id"}),true)}async function kt(p,k,I){return !!(await Ct(p,k,I)||await Rt(p,k,I))}function St(p){if(!B().boards.some(I=>I.id===p))throw Object.assign(new Error(`Board "${p}" not registered`),{statusCode:404});return {service:Y(p)}}return {get apiBasePath(){return y},get corsHeaders(){return w},handleApi:kt,requireBoardService:St}}function F(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function er(m){let y=m.reduce((j,z)=>j+z.length,0),w=new Uint8Array(y),_=0;for(let j of m)w.set(j,_),_+=j.length;return w}exports.a=lr;exports.b=fr;//# sourceMappingURL=chunk-P64UKI3L.cjs.map
8
- //# sourceMappingURL=chunk-P64UKI3L.cjs.map
@@ -1,8 +0,0 @@
1
- import {b,c,e as e$1,d}from'./chunk-6APH25VI.js';import {e,f,a as a$2}from'./chunk-M7EQRS6W.js';import {b as b$1}from'./chunk-CWREBRXS.js';import {a as a$3}from'./chunk-VCCTAUIG.js';import {a as a$1}from'./chunk-KBELAKIY.js';import {a}from'./chunk-76ON3V7R.js';var be={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ye=32;function tr(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function we(m){if(!m||typeof m!="object")return false;let y=m.summary;return !y||typeof y!="object"?false:Number(y.card_count||0)>0}function Ce(m,y){if(!y||typeof y!="object")return;let w=y;if(w.kind==="notification-batch"&&Array.isArray(w.notifications)){for(let _ of w.notifications)Ce(m,_);return}w.kind==="status"&&we(w.status)&&(m.status=w.status),w.kind==="computed_values"&&w.cardId&&(m.computedValues[w.cardId]=w.values),w.kind==="data_object"&&w.key&&(m.dataObjects[w.key]=w.payload),w.kind==="card_refreshed"&&w.cardId&&(m.cards[w.cardId]=w.card),w.kind==="card_removed"&&w.cardId&&(delete m.cards[w.cardId],delete m.computedValues[w.cardId]);}function lr(m){let y=String(m.apiBasePath||"/api/board").replace(/\/$/,""),w={...be,...m.corsHeaders||{}},_=m.boardId||"",j=m.logger||{info:console.log,warn:console.warn,error:console.error},z=m.invocationAdapter,st=m.chatFlowRunner||null,B=m.chatStorage??b(),at=a(B),it=m.notificationTransport||null,Y=m.serverUrl||null,J=m.executionExtra||{},Ct=m.onSseClientConnected,Rt=m.onSseClientDisconnected,kt=m.onChannelSubscribed,St=m.onChannelUnsubscribed,p=new Map,k=new Map,I=new Map,$=null;function M(t){let e$1=e(t.baseRef,t.boardAdapter),r=t.nonCoreAdapter??(K(t.boardAdapter)?t.boardAdapter:null),n=r?f(t.baseRef,r):null,o=t.boardAdapter.kvStorageForRef(t.cardStoreRef),a=a$1(a$2({readIndex:()=>o.read("_index"),writeIndex:b=>o.write("_index",b),readCard:b=>o.read(b),writeCard:(b,O)=>(o.write(b,O),b),removeCard:b=>{o.delete(b);},cardExists:b=>o.read(b)!==null,defaultCardKey:b=>b},j.warn)),i=t.artifactsAdapter||t.boardAdapter,u=t.filesArtifactsStore??null,C=t.artifactsAdapter?i.blobStorage(""):i.blobStorage("files"),h=null;return {label:t.label,board:e$1,nonCore:n,cardStore:a,get filesArtifacts(){return h??=u??c(C)},boardAdapter:t.boardAdapter,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,scratchStoreRef:t.scratchStoreRef,archiveStoreRef:t.archiveStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:tr(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let S=m.boards.map(M),G=new Map;function N(t){return G.get(t)??0}function K(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function tt(t){let e=S[N(t)];return {files:e?e.filesArtifacts:null}}function At(t){let e=tt(t);return e.files?d(e.files):null}function D(){return e$1()}function L(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ct(t){if(!t||t.notificationTeardown||!it||!t.notifyRef)return;let e=await it.subscribe(t.notifyRef,r=>{Ce(t.notification,r);let n=r.kind==="notification-batch"?r.notifications:[r];oe(n);});t.notificationTeardown=e;}async function Re(t){if(!t||t.initialized)return;let e={cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef};t.artifactsStoreRef&&(e.artifactsStoreRef=t.artifactsStoreRef),t.scratchStoreRef&&(e.scratchStoreRef=t.scratchStoreRef),t.archiveStoreRef&&(e.archiveStoreRef=t.archiveStoreRef);let r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow),t.inferenceAdapterRef&&(r["inference-adapter-ref"]=t.inferenceAdapterRef);let n=t.board.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 ct(t),!t.chatHandlerFlow&&t.chatHandlerRef&&z.describe)try{let o=await z.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?j.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&j.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){j.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}function Ft(t){if(!t.boardAdapter.publishBoardChangeNotifications)return;let e=[],r=t.board.status({});r.status==="success"&&r.data!=null&&we(r.data)&&e.push({kind:"status",status:r.data});let n=t.board.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,a]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:a});let o=t.board.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,a]of Object.entries(o.data))s&&e.push({kind:"computed_values",cardId:s,values:a});e.length>0&&t.boardAdapter.publishBoardChangeNotifications(e);}function Mt(t,e){if(!t||t.cardsBootstrapped)return;let r=t.cardStore.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(G.set(o.id,e),t.board.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function ft(){for(let t of S)await Re(t);}async function E(){await ft();for(let t=0;t<S.length;t++)Ft(S[t]),Mt(S[t],t);}function T(t){return S[N(t)]??null}function rt(t){let e=T(t);if(!e)return null;let r=e.cardStore.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}function Nt(){let t=r=>{if(!r||!r.cardStore)return [];let n=r.cardStore.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of S)e.push(...t(r));return e}function H(){return S[0]??null}function ke(){return {status(){let t=Ht();return t==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:t}},getOutputsDataObject(t){let e=t?.params?.key;return e?{status:"success",data:zt()[e]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},getOutputsComputedValues(t){let e=t?.params?.key;return e?{status:"success",data:Vt()[e]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},getOutputsFetchedSources(t){let e=t?.params?.key;if(!e)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let r=T(e)??H();return r?r.board.getOutputsFetchedSources({params:{key:e}}):{status:"fail",error:"Board context is unavailable"}},removeCard(t){let e=t?.params?.id;if(!e)return {status:"fail",error:"removeCard requires params.id"};let r=T(e)??H();return r?r.board.removeCard({params:{id:e}}):{status:"fail",error:"Board context is unavailable"}},cardRefreshedNotify(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let r=T(e)??H();return r?r.board.cardRefreshedNotify({params:{cardId:e}}):{status:"fail",error:"Board context is unavailable"}},upsertCard(t){let e=t?.params?.cardId;if(!e)return {status:"fail",error:"upsertCard requires params.cardId"};let r=T(e)??H();return r?r.board.upsertCard({params:{cardId:e,restart:t.params.restart===true}}):{status:"fail",error:"Board context is unavailable"}}}}function Se(){let t=()=>{let e=H();if(!e?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return e.nonCore};return {describeTaskExecutorCapabilities(e){return t().describeTaskExecutorCapabilities(e)},validateCardPreflight(e){return t().validateCardPreflight(e)},evalCardCompute(e){return t().evalCardCompute(e)},probeSourcePreflight(e){return t().probeSourcePreflight(e)},runSourcePreflight(e){return t().runSourcePreflight(e)},simulateCardCycle(e){return t().simulateCardCycle(e)}}}function gt(){return {get(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(e){let r=rt(e);return r?{status:"success",data:{cards:[r]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:Nt()}}},set(t){let e=t.body;if(e==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let r=Array.isArray(e)?e:[e];for(let n of r){let o=n,s=typeof o.id=="string"?o.id:"";if(!s)return {status:"fail",error:"each card must have a string `id` field"};let a=G.get(s)??0,i=S[a]??H();if(!i)return {status:"fail",error:"Board context is unavailable"};let u=i.cardStore.set({body:o});if(u.status!=="success")return u;G.set(s,a);}return {status:"success",data:{count:r.length}}},del(t){let e=[t.params?.id,...t.body?.ids??[]].filter(r=>typeof r=="string"&&!!r);if(e.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let r of e){let n=T(r)??H();if(!n)return {status:"fail",error:"Board context is unavailable"};let o=n.cardStore.del({params:{id:r}});if(o.status!=="success")return o;G.delete(r);}return {status:"success",data:{count:e.length}}},patch(t){let e=typeof t.params?.id=="string"?t.params.id:void 0,r=typeof t.params?.path=="string"?t.params.path:void 0;if(!e||!r)return {status:"fail",error:"patch requires params.id and params.path"};let n=T(e)??H();return n?n.cardStore.patch(t):{status:"fail",error:"Board context is unavailable"}},appendFiles(t){let e=typeof t.params?.id=="string"?t.params.id:void 0;if(!e)return {status:"fail",error:"appendFiles requires params.id"};let r=T(e)??H();return r?r.cardStore.appendFiles(t):{status:"fail",error:"Board context is unavailable"}}}}function V(){return a$3({board:ke(),nonCore:Se(),cardStore:gt(),chatStore:at,uploadCardFile({cardId:t,fileName:e,contentType:r,bytes:n}){return xt(t,e,r,n,{inChat:false})},buildFileDownloadUrl({cardId:t,fileIdx:e,storedName:r}){let n=`${Y||""}${y}/cards/${encodeURIComponent(t)}/files/${e}`;return r?`${n}?sn=${encodeURIComponent(r)}`:n},readFetchedSourceJsonByRef({cardId:t,ref:e}){let r=T(t)??H();if(!r)return null;let o=r.boardAdapter.resolveBlob(b$1(e)).trim();return o?JSON.parse(o):null}})}function A(t,...e){for(let r of e)if(typeof t[r]=="string")return String(t[r]);return ""}function W(t,...e){for(let r of e)if(t[r]!==void 0)return Number(t[r])}function dt(t,...e){for(let r of e){let n=t[r];if(n&&typeof n=="object"&&!Array.isArray(n))return n}return {}}function Z(t,e,...r){for(let n of r){let o=t[n];if(o&&typeof o=="object"&&!Array.isArray(o))return o}throw Object.assign(new Error(`MCP tool requires ${e}`),{statusCode:400})}function vt(t,e,...r){for(let n of r){let o=t[n];if(o!==void 0){let s=Number(o);if(Number.isFinite(s))return s}}throw Object.assign(new Error(`MCP tool requires ${e}`),{statusCode:400})}function Ae(t){if(Array.isArray(t.bytes))return new Uint8Array(t.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof t.text=="string")return new TextEncoder().encode(t.text);if(typeof t.base64=="string"){let e=String(t.base64).replace(/-/g,"+").replace(/_/g,"/"),r=e+"=".repeat((4-e.length%4)%4),n=atob(r);return Uint8Array.from(n,o=>o.charCodeAt(0))}return null}function Ut(t,e){let r=A(t,"board_id"),n=A(t,"card_id");if(!r)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!n)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(r!==_)throw Object.assign(new Error(`Unknown board_id: ${r}`),{statusCode:400});return V().setChatProcessing({cardId:n,active:e}),{status:"success",data:{boardId:_,cardId:n,active:e}}}function pt(t){let e=A(t,"board_id"),r=A(t,"card_id");if(!e)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return {cardId:r}}function _t(t,e){if(t?.status==="success")return Object.prototype.hasOwnProperty.call(t,"data")?t.data:void 0;throw t?.status==="fail"||t?.status==="error"?Object.assign(new Error(t.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}function qt(t){let e=A(t,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let r=e.split(".");if(!(r.length>=2&&r[0]==="chat"&&r.every(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function Dt(t,e){let r=t.meta;for(let n of e.split(".")){if(!r||typeof r!="object"||Array.isArray(r)||!Object.prototype.hasOwnProperty.call(r,n))return {exists:false,value:null};r=r[n];}return {exists:true,value:r}}function ve(t){let{cardId:e}=pt(t),r=V().getChatProcessing({cardId:e});return {status:"success",data:{boardId:_,cardId:e,active:r.active}}}function _e(t){let{cardId:e}=pt(t),r=qt(t);if(!Object.prototype.hasOwnProperty.call(t,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(r.split(".").includes("__visible_controlplane_only")){let n=_t(gt().get({params:{id:e}}),"cardStore.get"),o=Array.isArray(n.cards)&&n.cards.length>0&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null,s=o?Dt(o,"__visible_controlplane_only").value:void 0;if(t.value!==s)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:_,cardId:e,key:r}}}return _t(gt().patch({params:{id:e,path:`meta.${r}`},body:{value:t.value}}),"cardStore.patch"),{status:"success",data:{boardId:_,cardId:e,key:r}}}function Be(t){let{cardId:e}=pt(t),r=qt(t),n=_t(gt().get({params:{id:e}}),"cardStore.get"),o=Array.isArray(n.cards)&&n.cards.length>0&&n.cards[0]&&typeof n.cards[0]=="object"&&!Array.isArray(n.cards[0])?n.cards[0]:null;if(!o)throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});let s=Dt(o,r);return {status:"success",data:{boardId:_,cardId:e,key:r,exists:s.exists,value:s.value}}}function Ie(t){return {"discover.source-kinds":()=>t.discoverSourceKinds(),"inspect.board-runtime-status":()=>t.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>t.inspectCardDefinitionAndRuntime({cardId:A(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let r=W(e,"tail_turns"),n=W(e,"tail"),o=A(e,"turn_id"),s=e.all_turns===true,a=A(e,"tail_turns_before_id");return t.inspectChatMessagesOnCards({cardId:A(e,"card_id"),...r!==void 0?{lastUserTurns:r}:{},...n!==void 0?{tail:n}:{},...o?{turnId:o}:{},...s?{allTurns:true}:{},...a?{tailTurnsBeforeId:a}:{}})},"inspect.file-contents":e=>t.inspectFileContents({cardId:A(e,"card_id"),fileIdx:Number(W(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>t.preflightValidateCandidateCardDefinition({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>t.preflightMaterializeCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockRequires:Z(e,"mock_requires","mock_requires"),mockFetchedSources:Z(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>t.preflightProbeSingleSourceInCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockProjections:dt(e,"mock_projections"),sourceIdx:vt(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>t.preflightRunSingleSourceInCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockProjections:dt(e,"mock_projections"),sourceIdx:vt(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>t.preflightRunSingleSourceInLiveCard({cardId:A(e,"card_id"),sourceIdx:vt(e,"source_idx","source_idx"),mockRequires:Z(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>t.preflightRunOneCycleWithCandidateCard({candidateCardContent:Z(e,"candidate_card_content","candidate_card_content"),mockRequires:dt(e,"mock_requires")}),"manage.read-card":e=>t.manageReadCard({cardId:A(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let r=A(e,"turn_id");if(!r)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return t.manageAddChatEntryAndAnyAttachments({cardId:A(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...r?{turn:r}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>t.manageUpsertCard({cardId:A(e,"card_id"),candidateCardContent:dt(e,"candidate_card_content")}),"manage.remove-card":e=>t.manageRemoveCard({cardId:A(e,"card_id")})}}function xe(){return {"getstate.is-chat-processing":t=>ve(t),"setstate.chat-processing-started":t=>Ut(t,true),"setstate.chat-processing-done":t=>Ut(t,false),"getstate.card-meta":t=>Be(t),"setstate.card-meta":t=>_e(t),"manage.upload-card-file":t=>{let e=A(t,"board_id"),r=A(t,"card_id"),n=A(t,"file_name"),o=A(t,"content_type")||"application/octet-stream",s=Ae(t);if(!e)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});if(!r)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!n)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!s)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return xt(r,n,o,s,{inChat:false})},"manage.admin-read-card":t=>{let{cardId:e}=pt(t);return {status:"success",data:{cards:V().adminReadCard({cardId:e})}}},"manage.admin-upsert-card":t=>{let e=A(t,"board_id"),r=A(t,"card_id");if(!e)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!r)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(e!==_)throw Object.assign(new Error(`Unknown board_id: ${e}`),{statusCode:400});return V().adminUpsertCard({cardId:r,candidateCardContent:dt(t,"candidate_card_content")})}}}async function Lt(t,e,r){let n=r[t];if(!n)throw Object.assign(new Error(`Unknown MCP tool: ${t}`),{statusCode:400});let o=await n(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.status;if(a==="success")return Object.prototype.hasOwnProperty.call(s,"data")?o:{status:"success",data:{}};if(a==="fail"||a==="error")return o}return {status:"success",data:o}}function mt(t,e){if(!t||typeof t!="object"||Array.isArray(t))return e;let r=t;if(typeof r.error=="string"&&r.error.trim())return r.error;if(r.step==="validate"){let n=r.validation;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n.data;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s.issues;if(Array.isArray(a)){let u=a.find(C=>typeof C=="string"&&C.trim());if(typeof u=="string")return `Validation failed: ${u}`}let i=s.errors;if(Array.isArray(i)&&i.length>0)return "Validation failed"}}return "Validation failed"}return e}function Ht(){let t=S.map(s=>{try{let i=s.boardAdapter.kvStorageForRef(s.outputsStoreRef).read("status");if(i!=null)return i}catch{}return s.notification.status}).filter(Boolean);if(t.length===0)return null;if(t.length===1)return t[0];let e=[],r=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],n={};for(let s of r)n[s]=0;for(let s of t){let a=s,i=Array.isArray(a.cards)?a.cards:[];e.push(...i);for(let u of r)n[u]+=Number(a?.summary?.[u]||0);}let o=t[0];return {...o,cards:e,summary:{...o.summary||{},card_count:e.length,...n}}}function Vt(){let t={},e=r=>{for(let[n,o]of Object.entries(r.notification.computedValues)){let s=r.notification.cards[n];t[n]={schema_version:"v1",card_id:n,card_data:s?.card_data??{},computed_values:o??{}};}};for(let r of S)e(r);return t}function zt(){let t={};for(let e of S)Object.assign(t,e.notification.dataObjects||{});return t}function yt(){let t=Nt(),e=Vt(),r=zt(),n={};for(let s of t){if(!s?.id)continue;let a=s.id,i=e[a]||{},u={...i.card_data&&typeof i.card_data=="object"?i.card_data:s.card_data&&typeof s.card_data=="object"?s.card_data:{}};n[a]={schema_version:i.schema_version||"v1",card_id:i.card_id||a,card_data:u,computed_values:i.computed_values&&typeof i.computed_values=="object"?i.computed_values:{}};}let o={};for(let s of t){if(!s?.id)continue;let a=s.id;try{let i=It(a),u=V().getChatProcessing({cardId:a}).active;(i.length>0||u)&&(o[a]={messages:i.map(C=>({role:String(C.role||"system"),text:String(C.text||""),files:Array.isArray(C.files)?C.files:[]})),receiving:!1,processing:u});}catch{}}return {boardId:_,cardDefinitions:t,statusSnapshot:Ht(),dataObjectsByToken:r,cardRuntimeById:n,cardChatsByCardId:o}}function Bt(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=T(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let a=rt(t);if(!a)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=o?JSON.stringify(a):null,u=e(a)||a;if(o&&JSON.stringify(u)===i)return;let C=s.cardStore.set({body:u});if(C.status!=="success")throw Object.assign(new Error(C.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let h=s.board.upsertCard({params:{cardId:t,restart:true}});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to upsert card: ${t}`),{statusCode:500})}}function je(t,e){Bt(t,e,{syncBoard:true});}function Jt(t,e){Bt(t,e,{syncBoard:false});}function Oe(t){let e=T(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!rt(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=e.board.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}function $e(t,e){Bt(t,r=>{if(!e||typeof e!="object"||Object.keys(e).length===0)return r;function n(o,s,a){let i=String(s||"").split(".").filter(Boolean);if(!i.length)return;let u=o;for(let C=0;C<i.length-1;C++){let h=i[C];(!u[h]||typeof u[h]!="object")&&(u[h]={}),u=u[h];}u[i[i.length-1]]=a;}if(e.fieldValues!==void 0&&e.fieldValues!==null){let o=null,s=r.view;if(s&&Array.isArray(s.elements)){for(let a of s.elements)if(a?.data&&a.data.writeTo){o=a.data.writeTo;break}}o?n(r,o,e.fieldValues):typeof e.fieldValues=="object"&&!Array.isArray(e.fieldValues)&&(r.card_data={...r.card_data||{},...e.fieldValues});}else {if(Array.isArray(e._stagedFiles)&&e._stagedFiles.length>0)return r;for(let[o,s]of Object.entries(e))o!=="_stagedFiles"&&(s!==null&&typeof s=="object"&&!Array.isArray(s)&&r[o]!==null&&typeof r[o]=="object"&&!Array.isArray(r[o])?r[o]={...r[o],...s}:r[o]=s);}return r},{syncBoard:true,restartOnlyIfChanged:true});}function Ee(t){let e=String(t||"").trim();if(!e)return "upload.bin";let r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (r>=0?e.slice(r+1):e)||"upload.bin"}function Pe(t){B.clear(t);try{V().setChatProcessing({cardId:t,active:!1});}catch{}}function Te(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"";return B.append(t,e,s,n,o)}function It(t){return B.readAll(t)}function Fe(t){let e=[];try{let r=rt(t);if(!r)return e;let n=D().read(r.card_data&&typeof r.card_data=="object"?r.card_data:null);for(let o of n)e.push(o.stored_name);}catch{}return e}function Me(t,e,r,n){let o=L(t),s=tt(t),a=Ee(e),i=At(t),u=i?i.allocateStoredName(o,a,{seedNames:Fe(t),maxLen:Ye}):`${String(Date.now())}-${a}`;return s.files&&s.files.putBytes(`${o}/${u}`,new Uint8Array(n),r||"application/octet-stream"),{name:a,stored_name:u,size:n.length,mime_type:r||"application/octet-stream",uploaded_at:new Date().toISOString()}}function xt(t,e,r,n,o){if(!n.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let s=o?.inChat===true,a=Me(t,e,r,n),i=null;if(Jt(t,u=>{let C=new Date().toISOString(),h=u.card_data&&typeof u.card_data=="object"?u.card_data:{};u.card_data=h;let b=D().normalizeIncoming([{name:a.name,stored_name:a.stored_name,size:a.size,mime_type:a.mime_type,uploaded_at:a.uploaded_at||C,chat:s}],C);return i=D().merge(h,b).findIndex(nt=>nt.stored_name===a.stored_name),u}),s){let u=typeof i=="number"&&i>=0?` #${i}`:"";Te(t,"system",`file uploaded: ${a.name} as ${a.stored_name}${u}`,[],o?.turnId??"");}return {ok:true,file:a}}function Gt(t){let e=T(t);if(!e)return null;let r=e.board.getConfig({params:{key:"chat-handler-flow"}}),n=r.status==="success"?r.data?.value:null,o=e.chatHandlerRef;return n==null&&(!o||typeof o!="object")?null:{ctx:e,handlerFlow:n,handlerRef:o}}function Ne(t,e,r=false,n=""){let o=Gt(t);if(!o)return;let{ctx:s,handlerFlow:a,handlerRef:i}=o;if(!r)try{V().setChatProcessing({cardId:t,active:!0});}catch{}let u={boardId:_,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...J,...Y?{serverUrl:Y}:{}};if(!st&&a!=null){try{V().setChatProcessing({cardId:t,active:!1});}catch{}j.warn(`[chat-handler-flow] configured for card "${t}" but no chatFlowRunner was provided`);return}if(a!=null){let h=st;if(!h)return;h.run(a,u,{boardId:_,cardId:String(t),label:s.label,logger:j,serverUrl:Y,executionExtra:J}).then(b=>{if(b.dispatched)j.info(`[chat-handler-flow] invoked for card "${t}" (boardId: "${_}")`);else {try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler-flow] dispatch failed for card "${t}": ${b.error||"unknown"}`);}},b=>{try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler-flow] invoke failed for card "${t}": ${b?.message||String(b)}`);});return}let C=i;C&&z.invoke(C,u).then(h=>{if(h.dispatched)j.info(`[chat-handler] invoked for card "${t}" (boardId: "${_}")`);else {try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler] dispatch failed for card "${t}": ${h.error||"unknown"}`);}},h=>{try{B.setProcessing(t,!1);}catch{}j.warn(`[chat-handler] invoke failed for card "${t}": ${h?.message||String(h)}`);});}function Ue(t,e,r){let n=e==="chat-send"?Jt:je,o;n(t,s=>{let a=new Date().toISOString(),i=s.card_data&&typeof s.card_data=="object"?s.card_data:{};if(s.card_data=i,e==="chat-send"){let u=r&&typeof r.text=="string"?r.text.trim():"",C=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"",h=[];if(Array.isArray(r?.files)){for(let b of r.files)if(b){if(typeof b=="string"){h.push({name:b});continue}if(typeof b=="object"){let O=b;typeof O.name=="string"&&h.push({name:O.name,size:O.size,mime_type:O.mime_type,uploaded_at:O.uploaded_at,stored_name:O.stored_name,chat:O.chat===true});}}}if(u||h.length>0){let b=at.runBatch({cardId:t,commands:[{command:"append",role:"user",text:u,files:h,turn:C},{command:"set-processing",active:true}]});if(b.status!=="success")throw new Error(b.error);let O=b.data.results[0]?.data?.id;if(typeof O!="string"||!O)throw new Error(`chat-send did not return an append id for card ${t}`);o={cardId:t,lastEntryId:O,processingAlreadySet:true,turnId:C};try{let bt=It(t);oe([{kind:"card_chats",cardId:t,messages:bt.map(X=>({role:String(X.role||"system"),text:String(X.text||""),files:Array.isArray(X.files)?X.files:[]})),receiving:!0,processing:B.isProcessing(t)}]);}catch{}}return s}if(e==="file-upload"){let u=D().normalizeIncoming(r?.files,a);return u.length>0&&D().merge(i,u),s}if(e==="action"){let u=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!u)return s;i.lastAction={buttonId:u,at:a},i.lastActionText=`${u} @ ${a}`;}return s}),o&&Ne(o.cardId,o.lastEntryId,o.processingAlreadySet,o.turnId??"");}function f$1(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...w,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}function Kt(t,e,r){let n=rt(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=D().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,a=L(t),i=tt(t),u=String(s.stored_name||""),C=`${a}/${u}`,h=i.files?i.files.getBytes(C):null;if(!h)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:h}}function qe(t,e,r,n){let{fileRecord:o,bytes:s}=Kt(e,r,n),a=String(o.name||o.stored_name||"download.bin"),i=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":i,"Content-Disposition":`attachment; filename="${a}"`,"Content-Length":s.length}),t.end(s);}function De(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 Wt(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
- `)}async function U(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(Zt(e)).trim();return r?JSON.parse(r):{}}async function Le(t){let e=[];for await(let r of t)e.push(r);return typeof Buffer<"u"?Buffer.concat(e):Zt(e)}function Zt(t){let e=t.reduce((o,s)=>o+s.length,0),r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Xt(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=S[0];return n?n.board.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}function Qt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=S[0];return n?n.board.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}function He(t,e,r){let n=String(t||"").trim();if(!n)return {statusCode:400,body:{error:"callback token is required"}};let o=e==="success"?Xt(n,r):Qt(n,r);return o.status==="success"?{statusCode:200,body:o}:o.status==="fail"?{statusCode:400,body:{error:o.error}}:{statusCode:500,body:{error:o.error}}}let Yt=0;function te(t){let e=JSON.stringify(t);return Yt++,`id: ${Yt}
3
- data: ${e}
4
-
5
- `}function ee(t){let e=t;try{e.flushHeaders?.();}catch{}try{e.flush?.();}catch{}try{e.socket?.setNoDelay?.(!0);}catch{}try{e.socket?.uncork?.();}catch{}}function jt(t,e){let r=p.get(t);if(r&&!(e&&r.res!==e)){p.delete(t),Et();try{Rt?.(t);}catch{}try{r.res.end();}catch{}}}function ht(t,e){let r=p.get(t);if(!r)return;let n=te(e);try{r.res.write(n),ee(r.res);}catch{jt(t,r.res);}}function re(t,e,r,n,o){if(!p.has(e)){f$1(t,404,{error:`SSE client not connected: ${e}`});return}o?kt?.(e,r,n):St?.(e,r,n),f$1(t,200,{ok:true,clientId:e,channelName:r,...n.cardId?{cardId:n.cardId}:{},subscribed:o});}function Ot(){let t=new Set;for(let e of p.values())for(let r of e.subscribedChatCardIds)t.add(r);return Array.from(t)}function Ve(t){let e=k.has(t)?k.get(t):null,{cursor:r}=B.readAfter(t,e),n=B.isProcessing(t),o=n!==(I.get(t)??false),s=r!==e;return s&&k.set(t,r),I.set(t,n),s||o}function ne(t,e=true){let r=It(t),n=Date.now();return {kind:"card_chats",cardId:t,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:r.map(o=>({role:String(o.role||"system"),text:String(o.text||""),files:Array.isArray(o.files)?o.files:[]})),receiving:e,processing:B.isProcessing(t)}}function $t(t,e=true){let r={kind:"notification-batch",notifications:[ne(t,e)]};for(let[n,o]of p.entries())o.subscribedChatCardIds.has(t)&&ht(n,r);}function Et(){Ot().length>0||($&&(clearInterval($),$=null),k.clear(),I.clear());}function ze(){if($)return;let t=()=>{let e=Ot();if(e.length===0){Et();return}let r=new Set(e);for(let n of Array.from(k.keys()))r.has(n)||k.delete(n);for(let n of Array.from(I.keys()))r.has(n)||I.delete(n);for(let n of e)Ve(n)&&$t(n,true);};t(),$=setInterval(t,1e3);}function Je(t,e){let r=p.get(t);if(!r)return false;r.subscribedChatCardIds.add(e);let{cursor:n}=B.readAfter(e,null);return k.set(e,n),I.set(e,B.isProcessing(e)),ze(),ht(t,{kind:"notification-batch",notifications:[ne(e,true)]}),true}function Ge(t,e){let r=p.get(t);return r?(r.subscribedChatCardIds.delete(e),Ot().includes(e)||(k.delete(e),I.delete(e)),Et(),true):false}function Ke(t){if(!t||typeof t!="object")return false;let e=t.kind;return e==="card_chats"||e==="chat_messages"}function oe(t){if(!t||t.length===0)return;let e=[],r=new Set;for(let n of t)Ke(n)&&typeof n.cardId=="string"?r.add(String(n.cardId)):e.push(n);if(e.length>0){let n={kind:"notification-batch",notifications:e};for(let o of p.keys())ht(o,n);}for(let n of r)$t(n,true);}function We(t,e,r){let n=p.get(r),o=n?new Set(n.subscribedChatCardIds):new Set;n&&jt(r,n.res),e.writeHead(200,{...w,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),ee(e),p.set(r,{res:e,subscribedChatCardIds:o});let s=yt(),a=te(s);e.write(a);try{Ct?.(r,u=>{ht(r,u);});}catch{}let i=setInterval(()=>{try{e.write(`: keepalive
6
-
7
- `);}catch{}},15e3);t.on("close",()=>{clearInterval(i),jt(r,e);});}async function Ze(t,e,r){let n=t.method||"GET",o=r,s=o.pathname;try{if(n==="GET"&&s===`${y}/init-board`)return await ft(),f$1(e,200,yt()),!0;if(n==="GET"&&s===`${y}/sse`){await ft();let d=String(o.searchParams.get("clientId")||"").trim();if(!d)return f$1(e,400,{error:"clientId query param is required for SSE"}),!0;We(t,e,d);for(let c=0;c<S.length;c++)Ft(S[c]),Mt(S[c],c);return !0}if(n==="GET"&&s===`${y}/board-status`)return f$1(e,200,yt()),!0;let a=s.match(new RegExp(`^${F(y)}/callback/board-worker/([^/]+)/(success|failure)$`));if(n==="POST"&&a){await ft();let d=decodeURIComponent(a[1]),c=a[2],g=await U(t),l=He(d,c,g);return f$1(e,l.statusCode,l.body),!0}if(n==="POST"&&s===`${y}/mcp`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f$1(e,400,{error:"tool is required"}),!0;if(c==="inspect.file-contents")return f$1(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let l=await Lt(c,g,Ie(V()));if(l&&typeof l=="object"&&!Array.isArray(l)){let R=l;if(R.status==="fail")return f$1(e,400,{error:mt(l,"Request failed")}),!0;if(R.status==="error")return f$1(e,500,{error:mt(l,"Internal error")}),!0}f$1(e,200,l);}catch(l){let R=typeof l?.statusCode=="number"?Number(l.statusCode):500,x=l instanceof Error?l.message:String(l);f$1(e,R,{error:x});}return !0}if(n==="POST"&&s===`${y}/mcp-controlplane`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f$1(e,400,{error:"tool is required"}),!0;try{let l=await Lt(c,g,xe());if(l&&typeof l=="object"&&!Array.isArray(l)){let R=l;if(R.status==="fail")return f$1(e,400,{error:mt(l,"Request failed")}),!0;if(R.status==="error")return f$1(e,500,{error:mt(l,"Internal error")}),!0}f$1(e,200,l);}catch(l){let R=typeof l?.statusCode=="number"?Number(l.statusCode):500,x=l instanceof Error?l.message:String(l);f$1(e,R,{error:x});}return !0}if(n==="POST"&&s===`${y}/mcp-raw`){await E();let d=await U(t),c=typeof d.tool=="string"?d.tool.trim():"",g=d.args&&typeof d.args=="object"&&!Array.isArray(d.args)?d.args:{};if(!c)return f$1(e,400,{error:"tool is required"}),!0;if(c!=="inspect.file-contents")return f$1(e,400,{error:`Tool does not support raw response: ${c}`}),!0;let l=A(g,"card_id","cardId"),R=W(g,"file_idx","fileIdx"),x=W(g,"head-lines","headLines"),v=W(g,"tail-lines","tailLines"),P=W(g,"head-bytes","headBytes"),et=W(g,"tail-bytes","tailBytes");if(!l)return f$1(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(R===void 0||!Number.isInteger(R)||R<0)return f$1(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([x,v,P,et].filter(q=>q!==void 0).length>1)return f$1(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[q,ot]of [["head-lines",x],["tail-lines",v],["head-bytes",P],["tail-bytes",et]])if(ot!==void 0&&(!Number.isInteger(ot)||ot<0))return f$1(e,400,{error:`inspect.file-contents requires ${q} to be a non-negative integer`}),!0;let se=V().inspectFileContents({cardId:l,fileIdx:R}),Xe=typeof se?.stored_name=="string"?se.stored_name:null,{fileRecord:Pt,bytes:lt}=Kt(l,R,Xe),ae=String(Pt.name||Pt.stored_name||"download.bin"),Tt=String(Pt.mime_type||"application/octet-stream"),wt=(o.searchParams.get("resp")||"").trim().toLowerCase();if(wt&&wt!=="json-b64")return f$1(e,400,{error:`unsupported resp mode: ${wt}`}),!0;let Qe=wt==="json-b64",Q;if(x!==void 0||v!==void 0){if(!De(Tt))return f$1(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let q=new TextDecoder().decode(lt),ot=x!==void 0?Wt(q,"head",x):Wt(q,"tail",v);Q=typeof Buffer<"u"?Buffer.from(ot,"utf8"):new TextEncoder().encode(ot);}else if(P!==void 0||et!==void 0){let q=P??et;Q=P!==void 0?lt.slice(0,q):lt.slice(Math.max(0,lt.length-q));}else Q=lt;if(Qe){let q=typeof Buffer<"u"?Buffer.from(Q).toString("base64"):btoa(String.fromCharCode(...Q));return f$1(e,200,{bodyBase64:q,mimeType:Tt,filename:ae,byteLength:Q.length}),!0}return e.writeHead(200,{"Content-Type":Tt,"Content-Disposition":`attachment; filename="${ae}"`,"Content-Length":Q.length}),e.end(Q),!0}let i=s.match(new RegExp(`^${F(y)}/cards/([^/]+)$`));if(n==="GET"&&i){await E();let d=decodeURIComponent(i[1]),c=rt(d);return c?(f$1(e,200,c),!0):(f$1(e,404,{error:`card not found: ${d}`}),!0)}if(n==="PATCH"&&i){await E();let d=decodeURIComponent(i[1]),c=await U(t);return $e(d,c),f$1(e,200,{ok:!0}),!0}let u=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/retrigger$`));if(n==="POST"&&u){await E();let d=decodeURIComponent(u[1]);return Oe(d),f$1(e,200,{ok:!0}),!0}let C=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/actions$`));if(n==="POST"&&C){await E();let d=decodeURIComponent(C[1]),c=Date.now(),g=new Date(c).toISOString(),l=await U(t),R=l?.actionType;if(R==="chat-send"&&!Gt(d)){let v=Date.now();return f$1(e,409,{error:`chat handler is not configured for card: ${d}`,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:409}),!0}if(R==="chat-send"){let v=l?.payload??{},P=typeof v["turn-id"]=="string"?v["turn-id"]:typeof v.turnId=="string"?v.turnId:typeof v.turn=="string"?v.turn:"";if(!P||!String(P).trim()){let et=Date.now();return f$1(e,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${d}`,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(et).toISOString(),responseSentAtMs:et,responseStatus:400}),!0}}Ue(d,R,l?.payload);let x=Date.now();return f$1(e,200,{ok:!0,requestReceivedAt:g,requestReceivedAtMs:c,responseSentAt:new Date(x).toISOString(),responseSentAtMs:x,responseStatus:200}),!0}let h=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats$`));if(n==="GET"&&h){await E();let d=decodeURIComponent(h[1]),c=String(o.searchParams.get("turn-id")||""),g=String(o.searchParams.get("all-turns")||"").toLowerCase()==="true",l=String(o.searchParams.get("tail-turns-before-id")||""),R=o.searchParams.get("tail-turns"),x=R==null||R===""?g||c?void 0:1:Number.parseInt(R,10),v=at.readAll({params:{cardId:d},body:{...x===void 0?{}:{tailTurns:x},...c?{turnId:c}:{},...g?{allTurns:!0}:{},...l?{tailTurnsBeforeId:l}:{}}});if(v.status!=="success")return f$1(e,400,{error:v.error||"Failed to read chats"}),!0;let P=v.data.records;return f$1(e,200,{ok:!0,messages:P}),!0}if(n==="POST"&&h){await E();let d=decodeURIComponent(h[1]),c=await U(t),g=typeof c?.role=="string"?c.role:"assistant",l=typeof c?.text=="string"?c.text:"",R=Array.isArray(c?.files)?c.files:[],x=typeof c?.turn=="string"?c.turn:typeof c?.["turn-id"]=="string"?c["turn-id"]:typeof c?.turnId=="string"?c.turnId:"",v=c?.done===!0,P=B.append(d,g,l,R,x);return v&&B.setProcessing(d,!1),$t(d,!v),f$1(e,200,{ok:!0,id:P}),!0}let b=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats/subscribe-sse$`));if(n==="POST"&&b){await E();let d=decodeURIComponent(b[1]),c=await U(t),g=typeof c?.clientId=="string"?c.clientId.trim():"";return g?Je(g,d)?(f$1(e,200,{ok:!0,clientId:g,cardId:d,subscribed:!0}),!0):(f$1(e,404,{error:`SSE client not connected: ${g}`}),!0):(f$1(e,400,{error:"clientId is required"}),!0)}let O=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(n==="POST"&&O){await E();let d=decodeURIComponent(O[1]),c=await U(t),g=typeof c?.clientId=="string"?c.clientId.trim():"";return g?Ge(g,d)?(f$1(e,200,{ok:!0,clientId:g,cardId:d,subscribed:!1}),!0):(f$1(e,404,{error:`SSE client not connected: ${g}`}),!0):(f$1(e,400,{error:"clientId is required"}),!0)}let nt=s.match(new RegExp(`^${F(y)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&nt){await E();let d=decodeURIComponent(nt[1]),c=nt[2]==="subscribe",g=await U(t),l=typeof g?.clientId=="string"?g.clientId.trim():"";return l?(re(e,l,d,{},c),!0):(f$1(e,400,{error:"clientId is required"}),!0)}let ut=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(n==="POST"&&ut){await E();let d=decodeURIComponent(ut[1]),c=decodeURIComponent(ut[2]),g=ut[3]==="subscribe",l=await U(t),R=typeof l?.clientId=="string"?l.clientId.trim():"";return R?(re(e,R,c,{cardId:d},g),!0):(f$1(e,400,{error:"clientId is required"}),!0)}let bt=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/files$`));if(n==="POST"&&bt){await E();let d=decodeURIComponent(bt[1]),c=String(o.searchParams.get("inChat")||"").toLowerCase()==="true",g=String(o.searchParams.get("turn-id")||"").trim();if(c&&!g)return f$1(e,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${d}`}),!0;let l=t.headers["x-file-name"],R=String(t.headers["content-type"]||"application/octet-stream"),x=Array.isArray(l)?l[0]:l,v=x?decodeURIComponent(String(x)):"upload.bin",P=await Le(t);return f$1(e,200,xt(d,v,R,P,{inChat:c,turnId:g})),!0}let X=s.match(new RegExp(`^${F(y)}/cards/([^/]+)/files/(\\d+)$`));if(n==="GET"&&X){let d=decodeURIComponent(X[1]),c=parseInt(X[2],10),g=o.searchParams.get("sn");return qe(e,d,c,g),!0}return !1}catch(a){let i=a?.statusCode||500;return f$1(e,i,{error:String(a?.message||a)}),true}}return {get apiBasePath(){return y},get corsHeaders(){return w},handleRuntimeApi:Ze,buildPublishedRuntimePayload:yt,clearChatRecords:Pe,reportSourceFetched(t,e){return Xt(t,{ref:e})},reportSourceFetchFailure(t,e){return Qt(t,{reason:e})},get cardStore(){return S[0]?.cardStore??{set(){return {status:"fail",error:"no board context"}}}}}}function fr(m){let y=String(m.apiBasePath||"/api/boards").replace(/\/$/,""),w={...be,...m.corsHeaders||{}},_=m.serverMetaStore,j=m.boardRuntimeFactory,z=new Map,st="boards-config.json";function B(){let p=_.getText(st);if(!p)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(p)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function at(p){_.putText(st,JSON.stringify(p,null,2));}function it(p){let k=String(p||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return k.length>0&&k.length<=64?k:null}function Y(p){if(z.has(p))return z.get(p);let I=B().boards.find(M=>M.id===p)||{},$=j(p,I);return z.set(p,$),$}function J(p,k,I){let $=JSON.stringify(I),M=typeof Buffer<"u"?Buffer.byteLength($):new TextEncoder().encode($).length;p.writeHead(k,{...w,"Content-Type":"application/json; charset=utf-8","Content-Length":M}),p.end($);}async function Ct(p,k,I){let $=p.method||"GET",M=I.pathname;if($==="GET"&&M===y)return J(k,200,{ok:true,boards:B().boards}),true;if($==="POST"&&M===y){let S=[];for await(let L of p)S.push(L);let G=typeof Buffer<"u"?Buffer.concat(S).toString("utf-8").trim():new TextDecoder().decode(er(S)).trim(),N={};try{N=G?JSON.parse(G):{};}catch{N={};}let K=it(N.id);if(!K)return J(k,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let tt=B();if(tt.boards.some(L=>L.id===K))return J(k,409,{error:`Board "${K}" is already registered`}),true;let At=typeof N.label=="string"&&N.label.trim()?N.label.trim():K,D={id:K,label:At};for(let[L,ct]of Object.entries(N))L==="id"||L==="label"||ct!=null&&(D[L]=ct);return tt.boards.push(D),at(tt),J(k,200,{ok:true,board:D}),true}return false}async function Rt(p,k,I){let M=I.pathname.match(new RegExp(`^${F(y)}/([^/]+)(/|$)`));if(!M)return false;let S=it(decodeURIComponent(M[1]));return S?B().boards.some(K=>K.id===S)?!!await Y(S).handleRuntimeApi(p,k,I):(J(k,404,{error:`Board "${S}" not registered. POST ${y} with {id} to register it first.`}),true):(J(k,400,{error:"Invalid board id"}),true)}async function kt(p,k,I){return !!(await Ct(p,k,I)||await Rt(p,k,I))}function St(p){if(!B().boards.some(I=>I.id===p))throw Object.assign(new Error(`Board "${p}" not registered`),{statusCode:404});return {service:Y(p)}}return {get apiBasePath(){return y},get corsHeaders(){return w},handleApi:kt,requireBoardService:St}}function F(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function er(m){let y=m.reduce((j,z)=>j+z.length,0),w=new Uint8Array(y),_=0;for(let j of m)w.set(j,_),_+=j.length;return w}export{lr as a,fr as b};//# sourceMappingURL=chunk-Q6VSL327.js.map
8
- //# sourceMappingURL=chunk-Q6VSL327.js.map
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-JMDHDY6M.js';function w(o,i){if(o?.status==="success")return Object.prototype.hasOwnProperty.call(o,"data")?o.data:void 0;throw o?.status==="fail"||o?.status==="error"?new Error(o.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function z(o,i){if(o?.status==="success"&&Object.prototype.hasOwnProperty.call(o,"data"))return o.data;throw o?.status==="success"?new Error(`${i} returned success without data`):o?.status==="fail"||o?.status==="error"?new Error(o.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function t(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}function b(o){return Array.isArray(o)?o:[]}function N(o,i){if(typeof i!="string"||i.length===0)return;let u=o,m=i;m.startsWith("fetched_sources.")&&(u=t(o).fetched_sources,m=m.slice(16));for(let k of m.split(".")){if(u==null||typeof u!="object")return;u=u[k];}return u}function $(o,i){let u=t(o.view),m=b(u.elements);return {layout:u.layout,features:u.features,elements:m.map((k,x)=>{let v=t(k),I=t(v.data),B=typeof v.visible=="string"?!!N(i,v.visible):true,U=typeof I.bind=="string"?I.bind:void 0,M=typeof I.maxRows=="number"?I.maxRows:void 0,P=U?N(i,U):void 0,q={id:typeof v.id=="string"&&v.id?v.id:`element-${x}`,kind:v.kind,label:v.label,visible:B};return P!==void 0&&(q.resolved=Array.isArray(P)&&typeof M=="number"?P.slice(0,M):P),q})}}function K(o,i){let u=typeof o.id=="string"&&o.id?o.id:"card",m=b(o.provides),k=m.length>0?m:[{bindTo:u,ref:"card_data"}],x={};for(let v of k){let I=t(v),B=typeof I.bindTo=="string"?I.bindTo:"",U=typeof I.ref=="string"?I.ref:"";if(!B||!U)continue;let M=N(i,U);M!==void 0&&(x[B]=M);}return x}function ie(o){if(typeof o!="string"||!o.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(o.trim());if(!i)return null;let u=Number.parseInt(i[2],10);return !Number.isInteger(u)||u<0?null:u}function ce(o){return {"card-content":o}}function O(o){let{meta:i,...u}=o;return u}function ue(o,i){return Object.prototype.hasOwnProperty.call(o,i)}function W(o){return t(o.meta).__visible_controlplane_only===true}function L(o,i){let u=w(o.get({params:{id:i}}),"cardStore.get"),m=Array.isArray(u?.cards)?u.cards:[];if(m.length===0)throw new Error(`Card "${i}" not found`);return m[0]}function me(o){let{board:i,nonCore:u,cardStore:m,chatStore:k,uploadCardFile:x,buildFileDownloadUrl:v,readFetchedSourceJsonByRef:I}=o;function B(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let e=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=atob(n);return Uint8Array.from(s,a=>a.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function U(){let r=t(await J(u.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:r.version,commonSourceFields:t(r.commonSourceDefFields),sourceKinds:t(r.sourceKinds)}}function M(){let r=t(w(i.status({}),"status")),e=t(r.summary),n=b(r.cards);return {meta:t(r.meta),summary:{card_count:typeof e.card_count=="number"?e.card_count:0,completed:typeof e.completed=="number"?e.completed:0,eligible:typeof e.eligible=="number"?e.eligible:0,pending:typeof e.pending=="number"?e.pending:0,blocked:typeof e.blocked=="number"?e.blocked:0,in_progress:typeof e.in_progress=="number"?e.in_progress:0,failed:typeof e.failed=="number"?e.failed:0,unresolved:typeof e.unresolved=="number"?e.unresolved:0},cards:n.map(s=>{let a=t(s);return {"card-id":typeof a.name=="string"?a.name:null,status:a.status??null,error:a.error??null,requires:b(a.requires),requires_satisfied:b(a.requires_satisfied),requires_missing:b(a.requires_missing),provides_declared:b(a.provides_declared),provides_runtime:b(a.provides_runtime)}})}}function P(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let n=t(w(i.status({}),"status")),a=b(n.cards).map(t).find(p=>p.name===e);if(!a)throw new Error(`card "${e}" not found in board status`);let d=t(L(m,e));if(W(d))throw Object.assign(new Error(`card "${e}" not found`),{statusCode:404});let f=O(d),c=b(a.requires_satisfied).filter(p=>typeof p=="string"&&!!p),g=b(a.provides_runtime).filter(p=>typeof p=="string"&&!!p),R=Object.fromEntries(c.map(p=>[p,w(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)])),h=Object.fromEntries(g.map(p=>[p,w(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)])),C=t(w(i.getOutputsComputedValues({params:{key:e}}),"getOutputsComputedValues")),l=w(i.getOutputsFetchedSources({params:{key:e}}),"getOutputsFetchedSources"),_=b(d.source_defs).map(t),y={};for(let p of _)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(y[p.outputFile]=p.bindTo);let S={};for(let[p,j]of Object.entries(l)){let T=y[p]??p;if(!I||typeof j!="string"){S[T]=null;continue}try{S[T]=I({cardId:e,ref:j});}catch{S[T]=null;}}let A={card_data:t(d.card_data),requires:R,fetched_sources:S,computed_values:C};return {cardId:e,card_status_in_board:a,card_definition_and_static_data:f,refs_for_fetched_source_files:l,runtime_data:{requires:R,provides:h,computed_values:C,rendered_view:$(d,A)}}}function q(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectChatMessagesOnCards requires cardId");let n=typeof r.turnId=="string"?r.turnId:"",s=r.allTurns===true,a=typeof r.tailTurnsBeforeId=="string"?r.tailTurnsBeforeId:"",d=s?void 0:r.lastUserTurns??(n?void 0:1),f=r.tail,c={...d===void 0?{}:{tailTurns:d},...n?{turnId:n}:{},...s?{allTurns:true}:{},...a?{tailTurnsBeforeId:a}:{}},g=Object.keys(c).length>0?{params:{cardId:e},body:c}:{params:{cardId:e}},R=w(k.readAll(g),"chatStore.readAll"),h=t(L(m,e)),C=b(t(h.card_data).files).map((y,S)=>({idx:S,stored_name:t(y).stored_name})).filter(y=>typeof y.stored_name=="string"&&y.stored_name.length>0),_=(Array.isArray(R.records)?R.records:[]).map(y=>{let A=t(y.payload),p={...y},j=typeof y?.role=="string"?y.role:typeof A.role=="string"?String(A.role):"",T=typeof y?.text=="string"?y.text:typeof A.text=="string"?String(A.text):"";if(j==="system"){let D=ie(T);if(D!==null&&C.some(E=>E.idx===D)){let E=`Retrieve using inspect-file-contents --card-id ${e} --file-idx ${D}`;p.retrieval_hint=E,Object.keys(A).length>0&&typeof y.role!="string"&&(p.payload={...A,retrieval_hint:E});}}return p});return {cardId:e,messages:typeof f=="number"&&f>=0?_.slice(-f):_}}function H(r){let e=String(r.cardId||"").trim(),n=Number(r.fileIdx);if(!e)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(n)||n<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let s=t(L(m,e)),a=b(t(s.card_data).files).map(t);if(n>=a.length)throw new Error(`attachment index ${n} is out of range for card "${e}"`);let d=a[n],f=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:e,fileIdx:n,downloadUrl:v({cardId:e,fileIdx:n,storedName:f}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function F(r){return await u.validateCardPreflight({body:ce(r.candidateCardContent)})}function G(r){if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!r.mockFetchedSources||typeof r.mockFetchedSources!="object"||Array.isArray(r.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let e=u.evalCardCompute({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires,"mock-fetched-sources":r.mockFetchedSources}});if(e.status!=="success")return e;let n=t(z(e,"evalCardCompute")),s=t(r.candidateCardContent),a={card_data:t(s.card_data),requires:t(r.mockRequires),fetched_sources:t(r.mockFetchedSources),computed_values:t(n.computed_values)};return {status:"success",data:{cardId:typeof n.cardId=="string"?n.cardId:typeof s.id=="string"?s.id:"(unknown)",ok:n.ok===true,computed_values:t(n.computed_values),errors:b(n.errors).map(d=>{let f=t(d);return {bindTo:typeof f.bindTo=="string"?f.bindTo:"",error:typeof f.error=="string"?f.error:""}}),provides_outputs:K(s,a),rendered_view:$(s,a)}}}async function Q(r){return await u.probeSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function X(r){return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function Y(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let n=t(L(m,e)),s=b(n.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),a$1={};if(r.sourceIdx>=0&&r.sourceIdx<s.length){let d=s[r.sourceIdx],f=a.enrichSourcesSync([d],{card_data:t(n.card_data),requires:r.mockRequires});Array.isArray(f)&&f.length>0&&(a$1=t(f[0]._projections));}return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":n,"mock-requires":r.mockRequires,"mock-projections":a$1}})}async function Z(r){let e=t(await J(u.simulateCardCycle({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires}}),"simulateCardCycle")),n=t(r.candidateCardContent),s=t(e.validation),a=b(e.source_probes),d=b(e.projection_errors),f=t(e.fetched_sources),c=b(e.compute_errors),g=t(e.computed_values),R={card_data:t(n.card_data),requires:r.mockRequires,fetched_sources:f,computed_values:g},h=[];for(let C of b(s.issues))typeof C=="string"&&C&&h.push(C);for(let C of a){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",y=typeof l.error=="string"?l.error:"";y&&h.push(`${_}: ${y}`);}for(let C of d){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",y=typeof l.key=="string"?l.key:"projection",S=typeof l.error=="string"?l.error:"projection failed";h.push(`${_}.${y}: ${S}`);}for(let C of c){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"compute",y=typeof l.error=="string"?l.error:"compute failed";h.push(`${_}: ${y}`);}return {status:"success",data:{cardId:typeof e.cardId=="string"?e.cardId:"(unknown)",ok:e.ok===true,issues:h,provides_outputs:K(n,R),rendered_view:$(n,R)}}}function ee(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageReadCard requires cardId");let n=w(m.get({params:{id:e}}),"cardStore.get"),s=Array.isArray(n.cards)?n.cards.map(t):[];if(s.some(W))throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});return s.map(a=>O(a))}function re(r){let e=String(r.cardId||"").trim(),n=String(r.role||"").trim(),s=typeof r.text=="string"?r.text:"",a=typeof r.turn=="string"?r.turn:"";if(!e)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!n)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(n==="assistant"&&a){let c=w(k.readAll({params:{cardId:e},body:{turnId:a}}),"chatStore.readAll(existing turn messages)"),g=Array.isArray(c.records)?c.records.find(R=>R.role==="assistant"&&String(R.turn||"")===a):void 0;if(g)return {status:"success",data:{cardId:e,id:String(g.id),role:n,turn:a,files:Array.isArray(g.files)?g.files:[]}}}let d=b(r.files).map(c=>{let g=t(c),R=String(g.file_name??g.fileName??g.name??"").trim(),h=String(g.content_type??g.contentType??"application/octet-stream");if(!R)throw new Error("file entry requires file_name");return x({cardId:e,fileName:R,contentType:h,bytes:B(g)}).file});d.forEach((c,g)=>{let R=n==="assistant"?`AI generated: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`:`file uploaded: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`;w(k.append({params:{cardId:e},body:{role:"system",text:R,files:[],turn:a}}),"chatStore.append(system attachment message)");});let f=w(k.append({params:{cardId:e},body:{role:n,text:s,files:d,turn:a}}),"chatStore.append");return {status:"success",data:{cardId:e,id:String(f.id),role:n,turn:a,files:d}}}async function te(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=O(n);if(!e)throw new Error("manageUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let a=await F({candidateCardContent:s}),d=t(a),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:a};let c=null;try{c=L(m,e);}catch{c=null;}let g=c&&ue(t(c),"meta")?{...s,meta:t(c).meta}:s,R=m.set({body:g});w(R,"cardStore.set");let h;try{h=i.upsertCard({params:{cardId:e,restart:!0}}),w(h,"upsertCard");}catch(l){try{c&&m.set({body:c});}catch{}throw l}let C=null;try{C=i.cardRefreshedNotify({params:{cardId:e}}),w(C,"cardRefreshedNotify");}catch{C=null;}return {status:"success",data:{validation:a,card_saved:null,board_result:h,refresh_notify:C}}}function ne(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageRemoveCard requires cardId");let n=i.removeCard({params:{id:e}});w(n,"removeCard");let s=m.del({params:{id:e}});return w(s,"cardStore.del"),{status:"success",data:{board_result:n,store_result:s}}}function oe(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("adminReadCard requires cardId");let n=w(m.get({params:{id:e}}),"cardStore.get");return Array.isArray(n.cards)?n.cards.map(s=>t(s)):[]}async function ae(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=O(n);if(!e)throw new Error("adminUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let a=await F({candidateCardContent:s}),d=t(a),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:a};let c=null;try{c=L(m,e);}catch{c=null;}let g=c?t(t(c).meta):{},R={...s,meta:{...g,__visible_controlplane_only:true}},h=m.set({body:R});w(h,"cardStore.set");let C;try{C=i.upsertCard({params:{cardId:e,restart:!0}}),w(C,"upsertCard");}catch(_){try{c&&m.set({body:c});}catch{}throw _}let l=null;try{l=i.cardRefreshedNotify({params:{cardId:e}}),w(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:a,card_saved:null,board_result:C,refresh_notify:l}}}function se(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("getChatProcessing requires cardId");let n=z(k.isProcessing({params:{cardId:e}}),"chatStore.isProcessing");return {cardId:e,active:!!n.active}}function de(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("setChatProcessing requires cardId");if(typeof r.active!="boolean")throw new Error("setChatProcessing requires boolean active");return w(k.setProcessing({params:{cardId:e},body:{active:r.active}}),"chatStore.setProcessing"),{cardId:e,active:r.active}}return {discoverSourceKinds:U,inspectBoardRuntimeStatus:M,inspectCardDefinitionAndRuntime:P,inspectChatMessagesOnCards:q,inspectFileContents:H,preflightValidateCandidateCardDefinition:F,preflightMaterializeCandidateCard:G,preflightProbeSingleSourceInCandidateCard:Q,preflightRunSingleSourceInCandidateCard:X,preflightRunSingleSourceInLiveCard:Y,preflightRunOneCycleWithCandidateCard:Z,manageReadCard:ee,manageAddChatEntryAndAnyAttachments:re,manageUpsertCard:te,manageRemoveCard:ne,adminReadCard:oe,adminUpsertCard:ae,getChatProcessing:se,setChatProcessing:de}}async function J(o,i){return w(await o,i)}export{me as a};//# sourceMappingURL=chunk-VCCTAUIG.js.map
2
- //# sourceMappingURL=chunk-VCCTAUIG.js.map