yaml-flow 8.6.2 → 8.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser/asset-integrity.json +3 -3
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/chat-flow/flow-steps.json +10 -5
- package/examples/board/test/server-http-test.js +93 -0
- package/examples/board-local/demo-shell-localstorage.html +3 -3
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.d.cts +1 -0
- package/lib/board-live-cards-mcp.d.ts +1 -0
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +2 -2
- package/lib/board-live-cards-node.js +1 -1
- package/lib/board-live-cards-server-runtime.cjs +1 -1
- package/lib/board-live-cards-server-runtime.js +1 -1
- package/lib/chunk-KXWT3CY6.cjs +8 -0
- package/lib/chunk-OJLA6NLU.js +8 -0
- package/lib/chunk-R5L5WUKN.js +2 -0
- package/lib/chunk-YEB5QHGE.cjs +2 -0
- package/lib/server-runtime/index.cjs +1 -1
- package/lib/server-runtime/index.js +1 -1
- package/package.json +1 -1
- package/lib/chunk-GJJMEAVN.cjs +0 -2
- package/lib/chunk-KQX6R4PV.cjs +0 -8
- package/lib/chunk-OSWJKJLB.js +0 -8
- package/lib/chunk-SCWHDI3I.js +0 -2
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';var chunkWOALA3V5_cjs=require('./chunk-WOALA3V5.cjs'),chunkH5HBXPOI_cjs=require('./chunk-H5HBXPOI.cjs'),chunkOEFTOO47_cjs=require('./chunk-OEFTOO47.cjs'),chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),chunkYEB5QHGE_cjs=require('./chunk-YEB5QHGE.cjs'),chunkYMEIPKLW_cjs=require('./chunk-YMEIPKLW.cjs'),chunkGYQXDNNI_cjs=require('./chunk-GYQXDNNI.cjs');function wt(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Qe(r){if(!r||typeof r!="object")return false;let t=r.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function ze(r,t){if(!t||typeof t!="object")return;let s=t;if(s.kind==="notification-batch"&&Array.isArray(s.notifications)){for(let o of s.notifications)ze(r,o);return}s.kind==="status"&&Qe(s.status)&&(r.status=s.status),s.kind==="computed_values"&&s.cardId&&(r.computedValues[s.cardId]=s.values),s.kind==="data_object"&&s.key&&(r.dataObjects[s.key]=s.payload),s.kind==="card_refreshed"&&s.cardId&&(r.cards[s.cardId]=s.card),s.kind==="card_removed"&&s.cardId&&(delete r.cards[s.cardId],delete r.computedValues[s.cardId]);}function ge(r){return typeof r.journalStorage=="function"}function Ct(r){return typeof r.whatToRun=="string"?r.whatToRun.startsWith("b64:")?chunkSFVO2LB2_cjs.b(r.whatToRun).value:r.whatToRun:r.whatToRun.value}function se(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(r){let t=r.reduce((u,p)=>u+p.length,0),s=new Uint8Array(t),o=0;for(let u of r)s.set(u,o),o+=u.length;return s}function ht(r){let t=new Map,s=new Map,o=new Map,u=0,p=null;function R(i){let m=JSON.stringify(i);return u++,`id: ${u}
|
|
2
|
+
data: ${m}
|
|
3
|
+
|
|
4
|
+
`}function C(i){let m=i;try{m.flushHeaders?.();}catch{}try{m.flush?.();}catch{}try{m.socket?.setNoDelay?.(!0);}catch{}try{m.socket?.uncork?.();}catch{}}function F(i,m){let v=t.get(i);if(v&&!(m&&v.res!==m)){t.delete(i),j();try{r.onSseClientDisconnected?.(i);}catch{}try{v.res.end();}catch{}}}function T(i,m,v){let P=t.get(i);P&&F(i,P.res),t.set(i,{res:m,subscribedChatCardIds:v??new Set});}function g(i,m){let v=t.get(i);if(!v)return;let P=R(m);try{v.res.write(P),C(v.res);}catch{F(i,v.res);}}function b(){let i=new Set;for(let m of t.values())for(let v of m.subscribedChatCardIds)i.add(v);return Array.from(i)}function A(i){let m=s.has(i)?s.get(i):null,{cursor:v}=r.chatStorage.readAfter(i,m),P=r.chatStorage.isProcessing(i),G=P!==(o.get(i)??false),ue=v!==m;return ue&&s.set(i,v),o.set(i,P),ue||G}function O(i,m){let v=r.readChatRecords(i),P=Date.now();return {kind:"card_chats",cardId:i,sentAt:new Date(P).toISOString(),sentAtMs:P,messages:v.map(G=>({role:String(G.role||"system"),text:String(G.text||""),files:Array.isArray(G.files)?G.files:[]})),receiving:m,processing:r.chatStorage.isProcessing(i)}}function I(i,m=true){let v={kind:"notification-batch",notifications:[O(i,m)]};for(let[P,G]of t.entries())G.subscribedChatCardIds.has(i)&&g(P,v);}function j(){b().length>0||(p&&(clearInterval(p),p=null),s.clear(),o.clear());}function w(){if(p)return;let i=()=>{let m=b();if(m.length===0){j();return}let v=new Set(m);for(let P of Array.from(s.keys()))v.has(P)||s.delete(P);for(let P of Array.from(o.keys()))v.has(P)||o.delete(P);for(let P of m)A(P)&&I(P,true);};i(),p=setInterval(i,1e3);}function k(i,m){let v=t.get(i);if(!v)return false;v.subscribedChatCardIds.add(m);let{cursor:P}=r.chatStorage.readAfter(m,null);return s.set(m,P),o.set(m,r.chatStorage.isProcessing(m)),w(),g(i,{kind:"notification-batch",notifications:[O(m,true)]}),true}function L(i,m){let v=t.get(i);return v?(v.subscribedChatCardIds.delete(m),b().includes(m)||(s.delete(m),o.delete(m)),j(),true):false}function d(i){if(!i||typeof i!="object")return false;let m=i.kind;return m==="card_chats"||m==="chat_messages"}function l(i){if(!i||i.length===0)return;let m=[],v=new Set;for(let P of i)d(P)&&typeof P.cardId=="string"?v.add(String(P.cardId)):m.push(P);if(m.length>0){let P={kind:"notification-batch",notifications:m};for(let G of t.keys())g(G,P);}for(let P of v)I(P,true);}return {size:()=>t.size,has:i=>t.has(i),get:i=>t.get(i),buildFrame:R,flushTransport:C,register:T,disconnect:F,writeFrame:g,subscribeChat:k,unsubscribeChat:L,broadcastNotificationBatch:l,broadcastCardChats:I}}function z(r,...t){for(let s of t)if(typeof r[s]=="string")return String(r[s]);return ""}function ye(r,...t){for(let s of t)if(r[s]!==void 0)return Number(r[s])}function _e(r,...t){for(let s of t){let o=r[s];if(o&&typeof o=="object"&&!Array.isArray(o))return o}return {}}function he(r,t,...s){for(let o of s){let u=r[o];if(u&&typeof u=="object"&&!Array.isArray(u))return u}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function We(r,t,...s){for(let o of s){let u=r[o];if(u!==void 0){let p=Number(u);if(Number.isFinite(p))return p}}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function Rt(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(t=>Math.max(0,Math.min(255,Number(t)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let t=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),s=t+"=".repeat((4-t.length%4)%4),o=atob(s);return Uint8Array.from(o,u=>u.charCodeAt(0))}return null}function Je(r,t){if(r?.status==="success")return Object.prototype.hasOwnProperty.call(r,"data")?r.data:void 0;throw r?.status==="fail"||r?.status==="error"?Object.assign(new Error(r.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function Ke(r,t){return Je(await r,t)}function Ge(r){let t=z(r,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let s=t.split(".");if(!(s.length>=2&&s[0]==="chat"&&s.every(u=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return t}function Ze(r,t){let s=r.meta;for(let o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,o))return {exists:false,value:null};s=s[o];}return {exists:true,value:s}}function kt(r){let{boardId:t,getMcpFacade:s,getMcpCardStoreFacade:o}=r;function u(T){let g=z(T,"board_id"),b=z(T,"card_id");if(!g)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!b)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(g!==t)throw Object.assign(new Error(`Unknown board_id: ${g}`),{statusCode:400});return {cardId:b}}function p(T,g){let{cardId:b}=u(T);return s().setChatProcessing({cardId:b,active:g}),{status:"success",data:{boardId:t,cardId:b,active:g}}}function R(T){let{cardId:g}=u(T),b=s().getChatProcessing({cardId:g});return {status:"success",data:{boardId:t,cardId:g,active:b.active}}}async function C(T){let{cardId:g}=u(T),b=Ge(T);if(!Object.prototype.hasOwnProperty.call(T,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(b.split(".").includes("__visible_controlplane_only")){let A=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(A.cards)&&A.cards.length>0&&typeof A.cards[0]=="object"&&!Array.isArray(A.cards[0])?A.cards[0]:null,I=O?Ze(O,"__visible_controlplane_only").value:void 0;if(T.value!==I)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:g,key:b}}}return Je(await o().patch({params:{id:g,path:`meta.${b}`},body:{value:T.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:g,key:b}}}async function F(T){let{cardId:g}=u(T),b=Ge(T),A=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(A.cards)&&A.cards.length>0&&A.cards[0]&&typeof A.cards[0]=="object"&&!Array.isArray(A.cards[0])?A.cards[0]:null;if(!O)throw Object.assign(new Error(`Card "${g}" not found`),{statusCode:404});let I=Ze(O,b);return {status:"success",data:{boardId:t,cardId:g,key:b,exists:I.exists,value:I.value}}}return {requireCardArgs:u,setChatProcessing:p,getChatProcessing:R,setCardMeta:C,getCardMeta:F}}function St(r){let{boardId:t,boardContexts:s,readCardDefinitions:o,readChatRecords:u,getChatProcessing:p}=r;async function R(){let g=(await Promise.all(s.map(async j=>{try{let w=j.boardAdapter.kvStorageForRef(j.outputsStoreRef),k=await Promise.resolve(w.read("status"));if(k!=null)return k}catch{}return j.notification.status}))).filter(Boolean);if(g.length===0)return null;if(g.length===1)return g[0];let b=[],A=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],O={};for(let j of A)O[j]=0;for(let j of g){let w=j,k=Array.isArray(w.cards)?w.cards:[];b.push(...k);for(let L of A)O[L]+=Number(w?.summary?.[L]||0);}let I=g[0];return {...I,cards:b,summary:{...I.summary||{},card_count:b.length,...O}}}async function C(){let g={},b=async A=>{try{let O=await A.boardOps.getAllOutputsComputedValues({});if(O.status==="success"&&O.data&&typeof O.data=="object"){for(let[I,j]of Object.entries(O.data)){let w=A.notification.cards[I];g[I]={schema_version:"v1",card_id:I,card_data:w?.card_data??{},computed_values:j??{}};}return}}catch{}for(let[O,I]of Object.entries(A.notification.computedValues)){let j=A.notification.cards[O];g[O]={schema_version:"v1",card_id:O,card_data:j?.card_data??{},computed_values:I??{}};}};for(let A of s)await b(A);return g}async function F(){let g={};for(let b of s){try{let A=await b.boardOps.getAllOutputsDataObjects({});if(A.status==="success"&&A.data&&typeof A.data=="object"){Object.assign(g,A.data);continue}}catch{}Object.assign(g,b.notification.dataObjects||{});}return g}async function T(){let g=await o(),b=await C(),A=await F(),O={};for(let j of g){if(!j?.id)continue;let w=j.id,k=b[w]||{},L={...k.card_data&&typeof k.card_data=="object"?k.card_data:j.card_data&&typeof j.card_data=="object"?j.card_data:{}};O[w]={schema_version:k.schema_version||"v1",card_id:k.card_id||w,card_data:L,computed_values:k.computed_values&&typeof k.computed_values=="object"?k.computed_values:{}};}let I={};for(let j of g){if(!j?.id)continue;let w=j.id;try{let k=u(w),L=p(w);(k.length>0||L)&&(I[w]={messages:k.map(d=>({role:String(d.role||"system"),text:String(d.text||""),files:Array.isArray(d.files)?d.files:[]})),receiving:!1,processing:L});}catch{}}return {boardId:t,cardDefinitions:g,statusSnapshot:await R(),dataObjectsByToken:A,cardRuntimeById:O,cardChatsByCardId:I}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:C,readDataObjectsByToken:F,buildPublishedRuntimePayload:T}}function Ht(r){let t=String(r||"").trim();if(!t)return "upload.bin";let s=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (s>=0?t.slice(s+1):t)||"upload.bin"}function At(r){let{safeCardId:t,artifactsStores:s,cardFileMetadataStore:o,readCardFromStore:u,updateCardLocalOnly:p,writeChatRecord:R}=r;async function C(g){let b=[];try{let A=await u(g);if(!A)return b;let O=o().read(A.card_data&&typeof A.card_data=="object"?A.card_data:null);for(let I of O)b.push(String(I.stored_name??""));}catch{}return b}async function F(g,b,A,O){let I=t(g),j=s(g),w=Ht(b),k=await C(g),d=`${String(k.length+1).padStart(3,"0")}-${w}`.slice(-36);return j.files&&await j.files.putBytes(`${I}/${d}`,new Uint8Array(O),A||"application/octet-stream"),{name:w,stored_name:d,size:O.length,mime_type:A||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function T(g,b,A,O,I){if(!O.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let j=I?.inChat===true,w=await F(g,b,A,O),k=null;if(await p(g,L=>{let d=new Date().toISOString(),l=L.card_data&&typeof L.card_data=="object"?L.card_data:{};L.card_data=l;let i=o().normalizeIncoming([{name:w.name,stored_name:w.stored_name,size:w.size,mime_type:w.mime_type,uploaded_at:w.uploaded_at||d,chat:j}],d);return k=o().merge(l,i).findIndex(v=>v.stored_name===w.stored_name),L}),j){let L=typeof k=="number"&&k>=0?` #${k}`:"";R(g,"system",`file uploaded: ${w.name} as ${w.stored_name}${L}`,[],I?.turnId??"");}return {ok:true,file:{...w,...typeof k=="number"&&k>=0?{file_idx:k}:{},chat:j},...typeof k=="number"&&k>=0?{file_idx:k}:{}}}return {uploadCardFile:T,readCardStoredFileNames:C}}function vt(r){return {"discover.source-kinds":()=>r.discoverSourceKinds(),"inspect.board-runtime-status":()=>r.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>r.inspectCardDefinitionAndRuntime({cardId:z(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let s=ye(t,"tail_turns"),o=ye(t,"tail"),u=z(t,"turn_id"),p=t.all_turns===true,R=z(t,"tail_turns_before_id");return r.inspectChatMessagesOnCards({cardId:z(t,"card_id"),...s!==void 0?{lastUserTurns:s}:{},...o!==void 0?{tail:o}:{},...u?{turnId:u}:{},...p?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":t=>r.inspectFileContents({cardId:z(t,"card_id"),fileIdx:Number(ye(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>r.preflightValidateCandidateCardDefinition({candidateCardContent:he(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>r.preflightMaterializeCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:he(t,"mock_requires","mock_requires"),mockFetchedSources:he(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>r.preflightProbeSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>r.preflightRunSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>r.preflightRunSingleSourceInLiveCard({cardId:z(t,"card_id"),sourceIdx:We(t,"source_idx","source_idx"),mockRequires:he(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>r.preflightRunOneCycleWithCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:_e(t,"mock_requires")}),"manage.read-card":t=>r.manageReadCard({cardId:z(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let s=z(t,"turn_id");if(!s)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return r.manageAddChatEntryAndAnyAttachments({cardId:z(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...s?{turn:s}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.upsert-card":t=>r.manageUpsertCard({cardId:z(t,"card_id"),candidateCardContent:_e(t,"candidate_card_content")}),"manage.remove-card":t=>r.manageRemoveCard({cardId:z(t,"card_id")})}}function Pt(r){let{boardId:t,uploadCardFile:s,getMcpFacade:o,controlplane:u}=r;return {"getstate.is-chat-processing":p=>u.getChatProcessing(p),"setstate.chat-processing-started":p=>u.setChatProcessing(p,true),"setstate.chat-processing-done":p=>u.setChatProcessing(p,false),"getstate.card-meta":p=>u.getCardMeta(p),"setstate.card-meta":p=>u.setCardMeta(p),"manage.upload-card-file":p=>{let R=z(p,"board_id"),C=z(p,"card_id"),F=z(p,"file_name"),T=z(p,"content_type")||"application/octet-stream",g=Rt(p);if(!R)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});if(!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!F)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!g)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return s(C,F,T,g,{inChat:false})},"manage.admin-read-card":async p=>{let{cardId:R}=u.requireCardArgs(p);return {status:"success",data:{cards:await o().adminReadCard({cardId:R})}}},"manage.admin-upsert-card":p=>{let R=z(p,"board_id"),C=z(p,"card_id");if(!R)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});return o().adminUpsertCard({cardId:C,candidateCardContent:_e(p,"candidate_card_content")})}}}function Bt(r){let{boardContexts:t,cardOwnerIndex:s,cardContextForCard:o,readStatusSnapshot:u,readDataObjectsByToken:p,readCardRuntimeArtifacts:R,readCardFromStore:C,readCardDefinitions:F,processAccumulatedLaneInternal:T,uploadCardFile:g,chatStorePublic:b,serverUrl:A,apiBasePath:O}=r;function I(){return t[0]??null}function j(){return {async status(){let d=await u();return d==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:d}},async getOutputsDataObject(d){let l=d?.params?.key;return l?{status:"success",data:(await p())[l]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(d){let l=d?.params?.key;return l?{status:"success",data:(await R())[l]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(d){let l=d?.params?.key;if(!l)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let i=o(l)??I();return i?i.boardOps.getOutputsFetchedSources({params:{key:l}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(d){let l=d?.params?.id;if(!l)return {status:"fail",error:"removeCard requires params.id"};let i=o(l)??I();return i?i.boardOps.removeCard({params:{id:l}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let i=o(l)??I();return i?i.boardOps.cardRefreshedNotify({params:{cardId:l}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"upsertCard requires params.cardId"};let i=o(l)??I();if(!i)return {status:"fail",error:"Board context is unavailable"};let m=await i.boardOps.upsertCard({params:{cardId:l,restart:d.params.restart===true}});if(m.status!=="success")return m;if(ge(i.boardAdapter)){let v=await T(true);if(v.status!=="success")return v}return m}}}function w(){let d=()=>{let l=I();if(!l?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return l.nonCore};return {describeTaskExecutorCapabilities(l){return d().describeTaskExecutorCapabilities(l)},validateCardPreflight(l){return d().validateCardPreflight(l)},evalCardCompute(l){return d().evalCardCompute(l)},probeSourcePreflight(l){return d().probeSourcePreflight(l)},runSourcePreflight(l){return d().runSourcePreflight(l)},simulateCardCycle(l){return d().simulateCardCycle(l)}}}function k(){return {async get(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(l){let i=await C(l);return i?{status:"success",data:{cards:[i]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await F()}}},async set(d){let l=d.body;if(l==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let i=Array.isArray(l)?l:[l];for(let m of i){let v=m,P=typeof v.id=="string"?v.id:"";if(!P)return {status:"fail",error:"each card must have a string `id` field"};let G=s.get(P)??0,ue=t[G]??I();if(!ue)return {status:"fail",error:"Board context is unavailable"};let fe=await ue.cardStoreOps.set({body:v});if(fe.status!=="success")return fe;s.set(P,G);}return {status:"success",data:{count:i.length}}},async del(d){let l=[d.params?.id,...d.body?.ids??[]].filter(i=>typeof i=="string"&&!!i);if(l.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let i of l){let m=o(i)??I();if(!m)return {status:"fail",error:"Board context is unavailable"};let v=await m.cardStoreOps.del({params:{id:i}});if(v.status!=="success")return v;s.delete(i);}return {status:"success",data:{count:l.length}}},async patch(d){let l=typeof d.params?.id=="string"?d.params.id:void 0,i=typeof d.params?.path=="string"?d.params.path:void 0;if(!l||!i)return {status:"fail",error:"patch requires params.id and params.path"};let m=o(l)??I();return m?m.cardStoreOps.patch(d):{status:"fail",error:"Board context is unavailable"}},async appendFiles(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(!l)return {status:"fail",error:"appendFiles requires params.id"};let i=o(l)??I();return i?i.cardStoreOps.appendFiles(d):{status:"fail",error:"Board context is unavailable"}}}}function L(){return chunkYEB5QHGE_cjs.a({board:j(),nonCore:w(),cardStore:k(),chatStore:b,uploadCardFile({cardId:d,fileName:l,contentType:i,bytes:m}){return g(d,l,i,m,{inChat:true})},buildFileDownloadUrl({cardId:d,fileIdx:l,storedName:i}){let m=`${A||""}${O}/cards/${encodeURIComponent(d)}/files/${l}`;return i?`${m}?sn=${encodeURIComponent(i)}`:m},readFetchedSourceJsonByRef({cardId:d,ref:l}){let i=o(d)??I();if(!i||ge(i.boardAdapter))return null;let P=i.boardAdapter.resolveBlob(chunkSFVO2LB2_cjs.b(l)).trim();return P?JSON.parse(P):null}})}return {mcpBoardFacade:j,mcpNonCoreFacade:w,mcpCardStoreFacade:k,createMcpFacade:L}}function xt(r){let{sseHub:t,corsHeaders:s,json:o,buildPublishedRuntimePayload:u,onSseClientConnected:p,onChannelSubscribed:R,onChannelUnsubscribed:C}=r;function F(g,b,A,O,I){if(!t.has(b)){o(g,404,{error:`SSE client not connected: ${b}`});return}I?R?.(b,A,O):C?.(b,A,O),o(g,200,{ok:true,clientId:b,channelName:A,...O.cardId?{cardId:O.cardId}:{},subscribed:I});}async function T(g,b,A){let O=t.get(A),I=O?new Set(O.subscribedChatCardIds):new Set;b.writeHead(200,{...s,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),t.flushTransport(b),t.register(A,b,I);let j=await u(),w=t.buildFrame(j);b.write(w);try{p?.(A,L=>{t.writeFrame(A,L);});}catch{}let k=setInterval(()=>{try{b.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);g.on("close",()=>{clearInterval(k),t.disconnect(A,b);});}return {handleChannelSubscription:F,handleSse:T}}async function Xe(r,t,s){let o=s[r];if(!o)throw Object.assign(new Error(`Unknown MCP tool: ${r}`),{statusCode:400});let u=await o(t);if(u&&typeof u=="object"&&!Array.isArray(u)){let p=u,R=p.status;if(R==="success")return Object.prototype.hasOwnProperty.call(p,"data")?u:{status:"success",data:{}};if(R==="fail"||R==="error")return u}return {status:"success",data:u}}function Me(r,t){if(!r||typeof r!="object"||Array.isArray(r))return t;let s=r;if(typeof s.error=="string"&&s.error.trim())return s.error;if(s.step==="validate"){let o=s.validation;if(o&&typeof o=="object"&&!Array.isArray(o)){let p=o.data;if(p&&typeof p=="object"&&!Array.isArray(p)){let R=p.issues;if(Array.isArray(R)){let F=R.find(T=>typeof T=="string"&&T.trim());if(typeof F=="string")return `Validation failed: ${F}`}let C=p.errors;if(Array.isArray(C)&&C.length>0)return "Validation failed"}}return "Validation failed"}return t}function It(r){let{apiBasePath:t,boardContexts:s,json:o,readJsonBody:u,readRawBody:p,initBoardAndSetup:R,bootstrapBoard:C,buildPublishedRuntimePayload:F,publishPersistedStateSnapshot:T,upsertCardsFromSource:g,applyBoardWorkerCallback:b,handleSse:A,handleChannelSubscription:O,createMcpFacade:I,createMcpToolRegistry:j,createMcpControlplaneToolRegistry:w,readCardFromStore:k,patchCard:L,retriggerCard:d,applyCardAction:l,resolveChatHandlerTarget:i,chatStorePublic:m,chatStorage:v,sseHub:P,uploadCardFile:G,sendCardFileDownloadResponse:ue,resolveCardFileDownloadPayload:fe,isLikelyTextMimeType:ie,sliceTextByLines:be}=r;async function Se(ee,x,Ve){let W=ee.method||"GET",te=Ve,Y=te.pathname;try{if(W==="GET"&&Y===`${t}/init-board`)return await R(),o(x,200,await F()),!0;if(W==="GET"&&Y===`${t}/sse`){await R();let S=String(te.searchParams.get("clientId")||"").trim();if(!S)return o(x,400,{error:"clientId query param is required for SSE"}),!0;await A(ee,x,S);for(let h=0;h<s.length;h++)await T(s[h]),await g(s[h],h),await T(s[h]);return !0}if(W==="GET"&&Y===`${t}/board-status`)return o(x,200,await F()),!0;let we=Y.match(new RegExp(`^${se(t)}/callback/board-worker/([^/]+)/(success|failure)$`));if(W==="POST"&&we){await R();let S=decodeURIComponent(we[1]),h=we[2],M=await u(ee),B=await b(S,h,M);return o(x,B.statusCode,B.body),!0}if(W==="POST"&&Y===`${t}/mcp`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;if(h==="inspect.file-contents")return o(x,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let B=await Xe(h,M,j(I()));if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(x,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(x,500,{error:Me(B,"Internal error")}),!0}o(x,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(x,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-controlplane`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;try{let B=await Xe(h,M,w());if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(x,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(x,500,{error:Me(B,"Internal error")}),!0}o(x,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(x,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-raw`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;if(h!=="inspect.file-contents")return o(x,400,{error:`Tool does not support raw response: ${h}`}),!0;let B=z(M,"card_id","cardId"),q=ye(M,"file_idx","fileIdx"),Z=ye(M,"head-lines","headLines"),Q=ye(M,"tail-lines","tailLines"),ne=ye(M,"head-bytes","headBytes"),le=ye(M,"tail-bytes","tailBytes");if(!B)return o(x,400,{error:"inspect.file-contents requires card_id"}),!0;if(q===void 0||!Number.isInteger(q)||q<0)return o(x,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([Z,Q,ne,le].filter(ce=>ce!==void 0).length>1)return o(x,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[ce,ke]of [["head-lines",Z],["tail-lines",Q],["head-bytes",ne],["tail-bytes",le]])if(ke!==void 0&&(!Number.isInteger(ke)||ke<0))return o(x,400,{error:`inspect.file-contents requires ${ce} to be a non-negative integer`}),!0;let xe=await I().inspectFileContents({cardId:B,fileIdx:q}),$e=typeof xe?.stored_name=="string"?xe.stored_name:null,{fileRecord:Fe,bytes:Ae}=await fe(B,q,$e),qe=String(Fe.name||Fe.stored_name||"download.bin"),Te=String(Fe.mime_type||"application/octet-stream"),ve=(te.searchParams.get("resp")||"").trim().toLowerCase();if(ve&&ve!=="json-b64")return o(x,400,{error:`unsupported resp mode: ${ve}`}),!0;let Ne=ve==="json-b64",me;if(Z!==void 0||Q!==void 0){if(!ie(Te))return o(x,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let ce=new TextDecoder().decode(Ae),ke=Z!==void 0?be(ce,"head",Z):be(ce,"tail",Q);me=typeof Buffer<"u"?Buffer.from(ke,"utf8"):new TextEncoder().encode(ke);}else if(ne!==void 0||le!==void 0){let ce=ne??le;me=ne!==void 0?Ae.slice(0,ce):Ae.slice(Math.max(0,Ae.length-ce));}else me=Ae;if(Ne){let ce=typeof Buffer<"u"?Buffer.from(me).toString("base64"):btoa(String.fromCharCode(...me));return o(x,200,{bodyBase64:ce,mimeType:Te,filename:qe,byteLength:me.length}),!0}return x.writeHead(200,{"Content-Type":Te,"Content-Disposition":`attachment; filename="${qe}"`,"Content-Length":me.length}),x.end(me),!0}let Ce=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)$`));if(W==="GET"&&Ce){await C();let S=decodeURIComponent(Ce[1]),h=await k(S);return h?(o(x,200,h),!0):(o(x,404,{error:`card not found: ${S}`}),!0)}if(W==="PATCH"&&Ce){await C();let S=decodeURIComponent(Ce[1]),h=await u(ee);return await L(S,h),o(x,200,{ok:!0}),!0}let je=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/retrigger$`));if(W==="POST"&&je){await C();let S=decodeURIComponent(je[1]);return await d(S),o(x,200,{ok:!0}),!0}let pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/actions$`));if(W==="POST"&&pe){await C();let S=decodeURIComponent(pe[1]),h=Date.now(),M=new Date(h).toISOString(),B=await u(ee),q=B?.actionType;if(q==="chat-send"&&!await i(S)){let Q=Date.now();return o(x,409,{error:`chat handler is not configured for card: ${S}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Q).toISOString(),responseSentAtMs:Q,responseStatus:409}),!0}if(q==="chat-send"){let Q=B?.payload??{},ne=typeof Q["turn-id"]=="string"?Q["turn-id"]:typeof Q.turnId=="string"?Q.turnId:typeof Q.turn=="string"?Q.turn:"";if(!ne||!String(ne).trim()){let le=Date.now();return o(x,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${S}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(le).toISOString(),responseSentAtMs:le,responseStatus:400}),!0}}await l(S,q,B?.payload);let Z=Date.now();return o(x,200,{ok:!0,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Z).toISOString(),responseSentAtMs:Z,responseStatus:200}),!0}let Pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats$`));if(W==="GET"&&Pe){await C();let S=decodeURIComponent(Pe[1]),h=String(te.searchParams.get("turn-id")||""),M=String(te.searchParams.get("all-turns")||"").toLowerCase()==="true",B=String(te.searchParams.get("tail-turns-before-id")||""),q=te.searchParams.get("tail-turns"),Z=q==null||q===""?M||h?void 0:1:Number.parseInt(q,10),Q=m.readAll({params:{cardId:S},body:{...Z===void 0?{}:{tailTurns:Z},...h?{turnId:h}:{},...M?{allTurns:!0}:{},...B?{tailTurnsBeforeId:B}:{}}});if(Q.status!=="success")return o(x,400,{error:Q.error||"Failed to read chats"}),!0;let ne=Q.data.records;return o(x,200,{ok:!0,messages:ne}),!0}if(W==="POST"&&Pe){await C();let S=decodeURIComponent(Pe[1]),h=await u(ee),M=typeof h?.role=="string"?h.role:"assistant",B=typeof h?.text=="string"?h.text:"",q=Array.isArray(h?.files)?h.files:[],Z=typeof h?.turn=="string"?h.turn:typeof h?.["turn-id"]=="string"?h["turn-id"]:typeof h?.turnId=="string"?h.turnId:"",Q=h?.done===!0,ne=v.append(S,M,B,q,Z);return Q&&v.setProcessing(S,!1),P.broadcastCardChats(S,!Q),o(x,200,{ok:!0,id:ne}),!0}let Ee=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(W==="POST"&&Ee){await C();let S=decodeURIComponent(Ee[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.subscribeChat(M,S)?(o(x,200,{ok:!0,clientId:M,cardId:S,subscribed:!0}),!0):(o(x,404,{error:`SSE client not connected: ${M}`}),!0):(o(x,400,{error:"clientId is required"}),!0)}let Le=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(W==="POST"&&Le){await C();let S=decodeURIComponent(Le[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.unsubscribeChat(M,S)?(o(x,200,{ok:!0,clientId:M,cardId:S,subscribed:!1}),!0):(o(x,404,{error:`SSE client not connected: ${M}`}),!0):(o(x,400,{error:"clientId is required"}),!0)}let Re=Y.match(new RegExp(`^${se(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Re){await C();let S=decodeURIComponent(Re[1]),h=Re[2]==="subscribe",M=await u(ee),B=typeof M?.clientId=="string"?M.clientId.trim():"";return B?(O(x,B,S,{},h),!0):(o(x,400,{error:"clientId is required"}),!0)}let Be=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Be){await C();let S=decodeURIComponent(Be[1]),h=decodeURIComponent(Be[2]),M=Be[3]==="subscribe",B=await u(ee),q=typeof B?.clientId=="string"?B.clientId.trim():"";return q?(O(x,q,h,{cardId:S},M),!0):(o(x,400,{error:"clientId is required"}),!0)}let De=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files$`));if(W==="POST"&&De){await C();let S=decodeURIComponent(De[1]),h=String(te.searchParams.get("inChat")||"").toLowerCase()==="true",M=String(te.searchParams.get("turn-id")||"").trim();if(h&&!M)return o(x,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${S}`}),!0;let B=ee.headers["x-file-name"],q=String(ee.headers["content-type"]||"application/octet-stream"),Z=Array.isArray(B)?B[0]:B,Q=Z?decodeURIComponent(String(Z)):"upload.bin",ne=await p(ee);return o(x,200,await G(S,Q,q,ne,{inChat:h,turnId:M})),!0}let Oe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files/(\\d+)$`));if(W==="GET"&&Oe){let S=decodeURIComponent(Oe[1]),h=parseInt(Oe[2],10),M=te.searchParams.get("sn");return await ue(x,S,h,M),!0}return !1}catch(we){let Ce=we?.statusCode||500;return o(x,Ce,{error:String(we?.message||we)}),true}}return {handleRuntimeApi:Se}}function Ye(r,t){return t?{...r,...t.pollIntervalMs!=null?{pollIntervalMs:t.pollIntervalMs}:{},...t.visibilityMs!=null?{visibilityMs:t.visibilityMs}:{},...t.concurrency!=null?{concurrency:t.concurrency}:{},...t.maxAttempts!=null?{maxAttempts:t.maxAttempts}:{}}:r}function _t(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.leaseRequests(u))).map(R=>({id:R.messageId,attempt:R.attempt,message:R.request,ack:()=>Promise.resolve(t.ackRequest(R.messageId,R.leaseToken)),nack:C=>Promise.resolve(t.nackRequest(R.messageId,R.leaseToken,C))}))},async handle(u){await s(u.args,u);},onError:o?(u,p)=>o(u,p.attempt,p.message):void 0}}function Wt(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.lease(u))).map(R=>({id:R.id,attempt:R.attempt,message:R.body,ack:()=>Promise.resolve(t.ack(R.id,R.leaseToken)),nack:C=>Promise.resolve(t.nack(R.id,R.leaseToken,C))}))},async handle(){await s();},onError:o?(u,p)=>o(u,p.attempt):void 0}}function br(r){let t=r.logger??{info(){},warn(){},error(){}},s=r.boardAdapter,o=r.runtime.queueLaneTuning??{},u=s.processAccumulatedStore(),p=s.chatAgentStore(),R=[];if(R.push(Ye(Wt("process-accumulated",u,async()=>{let C=await r.runtime.processAccumulatedLane();if(C.status!=="success")throw new Error(C.error||`processAccumulatedLane returned ${C.status}`)},(C,F)=>{t.error(`[board-server] queued process-accumulated failed for ${r.boardId} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.processAccumulated)),R.push(Ye(_t("chat-agent",p,async(C,F)=>{await r.runtime.handleChatAgentRequest(F);},(C,F,T)=>{let g=typeof T.args?.cardId=="string"?T.args.cardId:"";t.error(`[board-server] queued chat-agent failed for ${r.boardId}${g?`/${g}`:""} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.chatAgent)),r.executeTaskExecutorRequest){let C=s.boardWorkerStore();R.push(Ye(_t("task-executor",C,r.executeTaskExecutorRequest,(F,T)=>{t.error(`[board-server] queued board-worker failed for ${r.boardId} (attempt ${T}): ${String(F&&F.message||F)}`);}),o.taskExecutor));}return chunkWOALA3V5_cjs.f(R)}var Ft={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ot="chat-handler-flow-queue";function Lr(r){let t=String(r.apiBasePath||"/api/board").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.queueLaneTuning??{},u=r.boardId||"",p=r.logger||{info:console.log,warn:console.warn,error:console.error},R=r.invocationAdapter,C=r.chatFlowRunner||null,F=r.chatStorage??chunkWOALA3V5_cjs.b(),T=chunkGYQXDNNI_cjs.a(F),g=r.notificationTransport||null,b=r.serverUrl||null,A=r.executionExtra||{},O=r.onSseClientConnected,I=r.onSseClientDisconnected,j=r.onChannelSubscribed,w=r.onChannelUnsubscribed,k=ht({chatStorage:F,readChatRecords:e=>le(e),onSseClientDisconnected:I});function L(e){function n(y){if(Array.isArray(y))return y;if(y&&typeof y=="object"){let E=y;return Array.isArray(E.files)?E.files:[y]}return null}function a(y){return {async get(E){return y.get(E)},async set(E){return y.set(E)},async del(E){return y.del(E)},async patch(E){return y.patch(E)},async appendFiles(E){return y.appendFiles(E)}}}function f(y){function E(V){return {status:"success",data:V}}function $(V){return {status:"fail",error:V}}function D(V){return {status:"error",error:V instanceof Error?V.message:String(V)}}return {async get(V){try{let U=V.params?.id;if(U){let re=await y.readCard(U);return re?E({cards:[re]}):$(`card "${U}" not found`)}return E({cards:await y.readAllCards()})}catch(U){return D(U)}},async set(V){try{let U=V.body;if(U==null)return $("set requires a body (card object or array of cards)");let re=Array.isArray(U)?U:[U];for(let ae of re){if(typeof ae.id!="string")return $("each card must have a string `id` field");await y.writeCard(ae.id,ae);}return E({count:re.length})}catch(U){return D(U)}},async del(V){try{let U=V.body?.ids??[],re=V.params?.id,ae=re?[...U,re]:U;if(ae.length===0)return $("del requires body.ids (string[]) or params.id");for(let Ie of ae)await y.removeCard(Ie);return E({count:ae.length})}catch(U){return D(U)}},async patch(V){try{let U=V.params?.id,re=V.params?.path;if(!U)return $("patch requires params.id");if(!re)return $("patch requires params.path");let ae=V.body,Ie=ae&&Object.prototype.hasOwnProperty.call(ae,"value")?ae.value:V.body;return await y.patchCard(U,re,Ie),E({count:1})}catch(U){return D(U)}},async appendFiles(V){try{let U=V.params?.id;if(!U)return $("appendFiles requires params.id");let re=await y.readCard(U);if(!re)return $(`card "${U}" not found`);let ae=n(V.body);if(!ae||ae.length===0)return $("appendFiles requires a file metadata object, array, or body.files array");let Ie=re.card_data&&typeof re.card_data=="object"&&!Array.isArray(re.card_data)?re.card_data:{},nt=Array.isArray(Ie.files)?Ie.files:[],qt=[...nt,...ae];return await y.patchCard(U,"card_data.files",qt),E({files_added:ae.map((Nt,Ut)=>({idx:nt.length+Ut,entry:Nt}))})}catch(U){return D(U)}}}}let c=ge(e.boardAdapter)?chunkH5HBXPOI_cjs.j(e.baseRef,e.boardAdapter):chunkOEFTOO47_cjs.y(e.baseRef,e.boardAdapter),_=e.nonCoreAdapter??(!ge(e.boardAdapter)&&m(e.boardAdapter)?e.boardAdapter:null),N=_?chunkOEFTOO47_cjs.z(e.baseRef,_):null,K,H=ge(e.boardAdapter)?(()=>{let y=chunkH5HBXPOI_cjs.d(chunkH5HBXPOI_cjs.c(chunkH5HBXPOI_cjs.b(e.boardAdapter.kvStorageForRef(e.cardStoreRef)),e.boardAdapter.hashFn),p.warn),E=f(y);return K={get($){return E.get($)},set($){return E.set($)}},E})():(()=>{let y=e.boardAdapter.kvStorageForRef(e.cardStoreRef),$=chunkYMEIPKLW_cjs.a(chunkOEFTOO47_cjs.l({readIndex:()=>y.read("_index"),writeIndex:D=>y.write("_index",D),readCard:D=>y.read(D),writeCard:(D,V)=>(y.write(D,V),D),removeCard:D=>{y.delete(D);},cardExists:D=>y.read(D)!==null,defaultCardKey:D=>D},p.warn));return K=$,a($)})(),X=e.artifactsAdapter||e.boardAdapter,J=e.filesArtifactsStore??null,oe=J?{putBytes(y,E,$){J.putBytes(y,E,$);},getBytes(y){return J.getBytes(y)},listKeys(y){return J.list(y).map(E=>E.key)}}:null;if(!oe&&!ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files"),E=chunkWOALA3V5_cjs.c(y);oe={putBytes($,D,V){E.putBytes($,D,V);},getBytes($){return E.getBytes($)},listKeys($){return E.list($).map(D=>D.key)}};}else if(!oe&&ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files");oe={async putBytes(E,$){if(y.writeBytes){await y.writeBytes(E,$);return}let D=JSON.stringify({__kind:"bytes-array",data:[...$]});await y.write(E,D);},async getBytes(E){if(y.readBytes){let D=await y.readBytes(E);if(D!==null)return D}let $=await y.read(E);if($===null)return null;try{let D=JSON.parse($);if(D&&D.__kind==="bytes-array"&&Array.isArray(D.data))return new Uint8Array(D.data)}catch{}return new TextEncoder().encode($)},async listKeys(E){return await y.listKeys(E)}};}let de={async init(y){return c.init(y)},async status(y){return c.status(y)},async getConfig(y){return c.getConfig(y)},async getAllOutputsDataObjects(y){return c.getAllOutputsDataObjects(y)},async getAllOutputsComputedValues(y){return c.getAllOutputsComputedValues(y)},async getOutputsFetchedSources(y){return c.getOutputsFetchedSources(y)},async upsertCard(y){return c.upsertCard(y)},async removeCard(y){return c.removeCard(y)},async cardRefreshedNotify(y){return c.cardRefreshedNotify(y)},async sourceDataFetched(y){return c.sourceDataFetched(y)},async sourceDataFetchFailure(y){return c.sourceDataFetchFailure(y)}};return {label:e.label,board:c,nonCore:N,publicCardStore:K,boardOps:de,cardStoreOps:H,get filesArtifacts(){return oe},boardAdapter:e.boardAdapter,cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef,artifactsStoreRef:e.artifactsStoreRef,scratchStoreRef:e.scratchStoreRef,archiveStoreRef:e.archiveStoreRef,notifyRef:e.notifyRef,taskExecutorRef:e.taskExecutorRef,chatHandlerRef:e.chatHandlerRef,chatHandlerFlow:e.chatHandlerFlow,inferenceAdapterRef:e.inferenceAdapterRef,notification:wt(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d=r.boards.map(L),l=new Map;function i(e){return l.get(e)??0}function m(e){let n=e;return typeof n.invokeExecutor=="function"&&typeof n.validateSchema=="function"}function v(e){let n=d[i(e)];return {files:n?n.filesArtifacts:null}}function P(){return chunkWOALA3V5_cjs.e()}function G(e){return String(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ue(e){if(!e||e.notificationTeardown||!g||!e.notifyRef)return;let n=await g.subscribe(e.notifyRef,a=>{ze(e.notification,a);let f=a.kind==="notification-batch"?a.notifications:[a];k.broadcastNotificationBatch(f);});e.notificationTeardown=n;}async function fe(e){if(!e||e.initialized)return;let n={cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef};e.artifactsStoreRef&&(n.artifactsStoreRef=e.artifactsStoreRef),e.scratchStoreRef&&(n.scratchStoreRef=e.scratchStoreRef),e.archiveStoreRef&&(n.archiveStoreRef=e.archiveStoreRef);let a={};e.taskExecutorRef&&(a["task-executor-ref"]=e.taskExecutorRef),e.chatHandlerFlow!==void 0&&(a["chat-handler-flow"]=e.chatHandlerFlow),e.inferenceAdapterRef&&(a["inference-adapter-ref"]=e.inferenceAdapterRef);let f=await e.boardOps.init({params:n,body:a});if(f.status!=="success")throw Object.assign(new Error(f.error||`init failed for ${e.label}`),{statusCode:500});if(await ue(e),!e.chatHandlerFlow&&e.chatHandlerRef&&R.describe)try{let c=await R.describe(e.chatHandlerRef);c&&c.kind!=="chat-handler"?p.warn(`[init] chat-handler describe returned kind="${c.kind}", expected "chat-handler" for ${e.label}`):c&&p.info(`[init] chat-handler validated: ${c.name} (protocol ${c.protocolVersion}) for ${e.label}`);}catch(c){p.warn(`[init] chat-handler describe failed for ${e.label}: ${c?.message||String(c)}`);}e.initialized=true;}async function ie(e){if(!e.boardAdapter.publishBoardChangeNotifications)return;let n=[],a=await e.boardOps.status({});a.status==="success"&&a.data!=null&&Qe(a.data)&&n.push({kind:"status",status:a.data});let f=await e.boardOps.getAllOutputsDataObjects({});if(f.status==="success"&&f.data!=null)for(let[_,N]of Object.entries(f.data))_&&n.push({kind:"data_object",key:_,payload:N});let c=await e.boardOps.getAllOutputsComputedValues({});if(c.status==="success"&&c.data!=null)for(let[_,N]of Object.entries(c.data))_&&n.push({kind:"computed_values",cardId:_,values:N});n.length>0&&e.boardAdapter.publishBoardChangeNotifications(n);}async function be(e,n){if(!e||e.cardsBootstrapped)return;let a=await e.cardStoreOps.get({}),f=a.status==="success"&&Array.isArray(a.data?.cards)?a.data.cards:[];for(let c of f)typeof c.id=="string"&&(l.set(c.id,n),await e.boardOps.upsertCard({params:{cardId:c.id}}));e.cardsBootstrapped=true;}async function Se(){for(let e of d)await fe(e);}async function ee(){await Se();for(let e=0;e<d.length;e++)await ie(d[e]),await be(d[e],e),await ie(d[e]);}async function x(e=false){e||await Se();for(let n of d){let a=await n.board.processAccumulatedEvents({});if(a.status!=="success")return a}return {status:"success"}}async function Ve(){return await Se(),x(true)}function W(e){return d[i(e)]??null}async function te(e){let n=W(e);if(!n)return null;let a=await n.cardStoreOps.get({params:{id:e}});if(a.status!=="success")return null;let f=Array.isArray(a.data?.cards)?a.data.cards:[];return f.length>0?f[0]:null}async function Y(){let e=async a=>{if(!a)return [];let f=await a.cardStoreOps.get({});return f.status!=="success"||!Array.isArray(f.data?.cards)?[]:f.data.cards},n=[];for(let a of d)n.push(...await e(a));return n}function we(){return d[0]??null}let Ce=Bt({boardContexts:d,cardOwnerIndex:l,cardContextForCard:e=>W(e),readStatusSnapshot:()=>Be(),readDataObjectsByToken:()=>Oe(),readCardRuntimeArtifacts:()=>De(),readCardFromStore:e=>te(e),readCardDefinitions:()=>Y(),processAccumulatedLaneInternal:e=>x(e),uploadCardFile:(e,n,a,f,c)=>xe(e,n,a,f,c),chatStorePublic:T,serverUrl:b,apiBasePath:t}),je=Ce.mcpCardStoreFacade,pe=Ce.createMcpFacade,Pe=kt({boardId:u,getMcpFacade:()=>pe(),getMcpCardStoreFacade:()=>je()});function Ee(e){return vt(e)}function Le(){return Pt({boardId:u,uploadCardFile:xe,getMcpFacade:()=>pe(),controlplane:Pe})}let Re=St({boardId:u,boardContexts:d,readCardDefinitions:()=>Y(),readChatRecords:e=>le(e),getChatProcessing:e=>pe().getChatProcessing({cardId:e}).active}),Be=Re.readStatusSnapshot,De=Re.readCardRuntimeArtifacts,Oe=Re.readDataObjectsByToken,S=Re.buildPublishedRuntimePayload;async function h(e,n,a){let f=a?.syncBoard!==false,c=a?.restartOnlyIfChanged===true,_=W(e);if(!_)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let N=await te(e);if(!N)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let K=c?JSON.stringify(N):null,H=n(N)||N;if(c&&JSON.stringify(H)===K)return;let X=await _.cardStoreOps.set({body:H});if(X.status!=="success")throw Object.assign(new Error(X.error||`Failed to persist card: ${e}`),{statusCode:500});if(f){let J=await _.boardOps.upsertCard({params:{cardId:e,restart:true}});if(J.status!=="success")throw Object.assign(new Error(J.error||`Failed to upsert card: ${e}`),{statusCode:500})}}async function M(e,n){await h(e,n,{syncBoard:true});}async function B(e,n){await h(e,n,{syncBoard:false});}async function q(e){let n=W(e);if(!n)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});if(!await te(e))throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let f=await n.boardOps.upsertCard({params:{cardId:e,restart:true}});if(f.status!=="success")throw Object.assign(new Error(f.error||`Failed to retrigger card: ${e}`),{statusCode:500})}async function Z(e,n){await h(e,a=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return a;function f(c,_,N){let K=String(_||"").split(".").filter(Boolean);if(!K.length)return;let H=c;for(let X=0;X<K.length-1;X++){let J=K[X];(!H[J]||typeof H[J]!="object")&&(H[J]={}),H=H[J];}H[K[K.length-1]]=N;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let c=null,_=a.view;if(_&&Array.isArray(_.elements)){for(let N of _.elements)if(N?.data&&N.data.writeTo){c=N.data.writeTo;break}}c?f(a,c,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(a.card_data={...a.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return a;for(let[c,_]of Object.entries(n))c!=="_stagedFiles"&&(_!==null&&typeof _=="object"&&!Array.isArray(_)&&a[c]!==null&&typeof a[c]=="object"&&!Array.isArray(a[c])?a[c]={...a[c],..._}:a[c]=_);}return a},{syncBoard:true,restartOnlyIfChanged:true});}function Q(e){F.clear(e);try{pe().setChatProcessing({cardId:e,active:!1});}catch{}}function ne(e,n,a,f,c=""){let _=typeof a=="string"?a.trim():"";return F.append(e,n||"system",_,f,c)}function le(e){return F.readAll(e)}let xe=At({safeCardId:e=>G(e),artifactsStores:e=>v(e),cardFileMetadataStore:()=>P(),readCardFromStore:e=>te(e),updateCardLocalOnly:(e,n)=>B(e,n),writeChatRecord:(e,n,a,f,c)=>ne(e,n,a,f,c)}).uploadCardFile;async function $e(e){let n=W(e);if(!n)return null;let a=await n.boardOps.getConfig({params:{key:"chat-handler-flow"}}),f=a.status==="success"?a.data?.value:null,c=n.chatHandlerRef;return f==null&&(!c||typeof c!="object")?null:{ctx:n,handlerFlow:f,handlerRef:c}}async function Fe(e,n,a=false,f=""){let c=await $e(e);if(!c)return;let{ctx:_,handlerFlow:N,handlerRef:K}=c;if(!a)try{pe().setChatProcessing({cardId:e,active:!0});}catch{}let H={boardId:u,cardId:String(e),lastChatEntryId:n,...f?{turnId:f}:{},...A,...b?{serverUrl:b}:{}},X=N!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:Ot}}:K;try{ge(_.boardAdapter)?await _.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}):_.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}),await Promise.resolve(_.boardAdapter.requestProcessAccumulated?.());}catch(J){try{pe().setChatProcessing({cardId:e,active:!1});}catch{}p.warn(`[chat-handler] queue failed for card "${e}": ${J instanceof Error?J.message:String(J)}`);}}async function Ae(e,n,a){if(n.howToRun==="built-in"&&Ct(n)===Ot){let f=C,c=a.__chatHandlerFlow,_={...a};return delete _.__chatHandlerFlow,f?f.run(c,_,{boardId:u,cardId:String(_.cardId||""),label:e.label,logger:p,serverUrl:b,executionExtra:A}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return R.invoke(n,a)}async function qe(e,n=false){n||await Se();let a=typeof e.args?.cardId=="string"?e.args.cardId:"",f=a?W(a):we();if(!f)throw new Error(a?`Board context is unavailable for chat-agent request: ${a}`:"Board context is unavailable for chat-agent request");let c=await Ae(f,e.ref,e.args);if(!c.dispatched){if(a)try{F.setProcessing(a,!1);}catch{}throw new Error(c.error||`chat-agent dispatch failed for card "${a||"unknown"}"`)}}async function Te(e,n,a){let f=n==="chat-send"?B:M,c;await f(e,_=>{let N=new Date().toISOString(),K=_.card_data&&typeof _.card_data=="object"?_.card_data:{};if(_.card_data=K,n==="chat-send"){let H=a&&typeof a.text=="string"?a.text.trim():"",X=a&&typeof a["turn-id"]=="string"?a["turn-id"]:a&&typeof a.turnId=="string"?a.turnId:a&&typeof a.turn=="string"?a.turn:"",J=[];if(Array.isArray(a?.files)){for(let oe of a.files)if(oe){if(typeof oe=="string"){J.push({name:oe});continue}if(typeof oe=="object"){let de=oe;typeof de.name=="string"&&J.push({name:de.name,size:de.size,mime_type:de.mime_type,uploaded_at:de.uploaded_at,stored_name:de.stored_name,chat:de.chat===true});}}}if(H||J.length>0){let oe=T.runBatch({cardId:e,commands:[{command:"append",role:"user",text:H,files:J,turn:X},{command:"set-processing",active:true}]});if(oe.status!=="success")throw new Error(oe.error);let de=oe.data.results[0]?.data?.id;if(typeof de!="string"||!de)throw new Error(`chat-send did not return an append id for card ${e}`);c={cardId:e,lastEntryId:de,processingAlreadySet:true,turnId:X};try{let $=le(e);k.broadcastNotificationBatch([{kind:"card_chats",cardId:e,messages:$.map(D=>({role:String(D.role||"system"),text:String(D.text||""),files:Array.isArray(D.files)?D.files:[]})),receiving:!0,processing:F.isProcessing(e)}]);}catch{}}return _}if(n==="file-upload"){let H=P().normalizeIncoming(a?.files,N);return H.length>0&&P().merge(K,H),_}if(n==="action"){let H=a&&typeof a.buttonId=="string"?a.buttonId:"";if(!H)return _;K.lastAction={buttonId:H,at:N},K.lastActionText=`${H} @ ${N}`;}return _}),c&&Fe(c.cardId,c.lastEntryId,c.processingAlreadySet,c.turnId??"");}function ve(e,n,a){let f=JSON.stringify(a),c=typeof Buffer<"u"?Buffer.byteLength(f):new TextEncoder().encode(f).length;e.writeHead(n,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":c}),e.end(f);}async function Ne(e,n,a){let f=await te(e);if(!f)throw Object.assign(new Error("Card not found"),{statusCode:404});let c=P().resolve(f.card_data,n,a);if(!c.ok&&c.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!c.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let _=c.file,N=G(e),K=v(e),H=String(_.stored_name||""),X=`${N}/${H}`,J=K.files?await K.files.getBytes(X):null;if(!J)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:_,bytes:J}}async function me(e,n,a,f){let{fileRecord:c,bytes:_}=await Ne(n,a,f),N=String(c.name||c.stored_name||"download.bin"),K=String(c.mime_type||"application/octet-stream");e.writeHead(200,{"Content-Type":K,"Content-Disposition":`attachment; filename="${N}"`,"Content-Length":_.length}),e.end(_);}function ce(e){let n=String(e||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function ke(e,n,a){let f=e.split(/\r?\n/);return (n==="head"?f.slice(0,a):f.slice(-a)).join(`
|
|
7
|
+
`)}async function Mt(e){let n=[];for await(let f of e)n.push(f);let a=typeof Buffer<"u"?Buffer.concat(n).toString("utf-8").trim():new TextDecoder().decode(He(n)).trim();return a?JSON.parse(a):{}}async function jt(e){let n=[];for await(let a of e)n.push(a);return typeof Buffer<"u"?Buffer.concat(n):He(n)}async function et(e,n){let a=typeof n.ref=="string"?n.ref.trim():"";if(!a)return {status:"fail",error:"board-worker success callback requires body.ref"};let f=d[0];return f?f.boardOps.sourceDataFetched({params:{token:e,ref:a}}):{status:"fail",error:"no board context"}}async function tt(e,n){let a=typeof n.reason=="string"&&n.reason.trim()?n.reason:"unknown",f=d[0];return f?f.boardOps.sourceDataFetchFailure({params:{token:e,reason:a}}):{status:"fail",error:"no board context"}}async function Et(e,n,a){let f=String(e||"").trim();if(!f)return {statusCode:400,body:{error:"callback token is required"}};let c=n==="success"?await et(f,a):await tt(f,a);return c.status==="success"?{statusCode:200,body:c}:c.status==="fail"?{statusCode:400,body:{error:c.error}}:{statusCode:500,body:{error:c.error}}}let rt=xt({sseHub:k,corsHeaders:s,json:ve,buildPublishedRuntimePayload:()=>S(),onSseClientConnected:O,onChannelSubscribed:j,onChannelUnsubscribed:w}),Lt=rt.handleChannelSubscription,Dt=rt.handleSse,$t=It({apiBasePath:t,boardContexts:d,json:ve,readJsonBody:e=>Mt(e),readRawBody:e=>jt(e),initBoardAndSetup:()=>Se(),bootstrapBoard:()=>ee(),buildPublishedRuntimePayload:()=>S(),publishPersistedStateSnapshot:e=>ie(e),upsertCardsFromSource:(e,n)=>be(e,n),applyBoardWorkerCallback:(e,n,a)=>Et(e,n,a),handleSse:(e,n,a)=>Dt(e,n,a),handleChannelSubscription:(e,n,a,f,c)=>Lt(e,n,a,f,c),createMcpFacade:()=>pe(),createMcpToolRegistry:e=>Ee(e),createMcpControlplaneToolRegistry:()=>Le(),readCardFromStore:e=>te(e),patchCard:(e,n)=>Z(e,n),retriggerCard:e=>q(e),applyCardAction:(e,n,a)=>Te(e,n,a),resolveChatHandlerTarget:e=>$e(e),chatStorePublic:T,chatStorage:{append:(e,n,a,f,c)=>F.append(e,n,a,f,c),setProcessing:(e,n)=>F.setProcessing(e,n)},sseHub:k,uploadCardFile:(e,n,a,f,c)=>xe(e,n,a,f,c),sendCardFileDownloadResponse:(e,n,a,f)=>me(e,n,a,f),resolveCardFileDownloadPayload:(e,n,a)=>Ne(e,n,a),isLikelyTextMimeType:e=>ce(e),sliceTextByLines:(e,n,a)=>ke(e,n,a)}).handleRuntimeApi;return {get apiBasePath(){return t},get corsHeaders(){return s},get queueLaneTuning(){return o},handleRuntimeApi:$t,buildPublishedRuntimePayload:S,processAccumulatedEvents:Ve,processAccumulatedLane:x,handleChatAgentRequest:qe,clearChatRecords:Q,reportSourceFetched(e,n){return et(e,{ref:n})},reportSourceFetchFailure(e,n){return tt(e,{reason:n})},get cardStore(){return d[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Dr(r){let t=String(r.apiBasePath||"/api/boards").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.serverMetaStore,u=r.boardRuntimeFactory,p=new Map,R="boards-config.json";function C(){let w=o.getText(R);if(!w)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(w)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function F(w){o.putText(R,JSON.stringify(w,null,2));}function T(w){let k=String(w||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return k.length>0&&k.length<=64?k:null}function g(w){if(p.has(w))return p.get(w);let L=C().boards.find(l=>l.id===w)||{},d=u(w,L);return p.set(w,d),d}function b(w,k,L){let d=JSON.stringify(L),l=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;w.writeHead(k,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":l}),w.end(d);}async function A(w,k,L){let d=w.method||"GET",l=L.pathname;if(d==="GET"&&l===t)return b(k,200,{ok:true,boards:C().boards}),true;if(d==="POST"&&l===t){let i=[];for await(let ie of w)i.push(ie);let m=typeof Buffer<"u"?Buffer.concat(i).toString("utf-8").trim():new TextDecoder().decode(He(i)).trim(),v={};try{v=m?JSON.parse(m):{};}catch{v={};}let P=T(v.id);if(!P)return b(k,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let G=C();if(G.boards.some(ie=>ie.id===P))return b(k,409,{error:`Board "${P}" is already registered`}),true;let ue=typeof v.label=="string"&&v.label.trim()?v.label.trim():P,fe={id:P,label:ue};for(let[ie,be]of Object.entries(v))ie==="id"||ie==="label"||be!=null&&(fe[ie]=be);return G.boards.push(fe),F(G),b(k,200,{ok:true,board:fe}),true}return false}async function O(w,k,L){let l=L.pathname.match(new RegExp(`^${se(t)}/([^/]+)(/|$)`));if(!l)return false;let i=T(decodeURIComponent(l[1]));return i?C().boards.some(P=>P.id===i)?!!await g(i).handleRuntimeApi(w,k,L):(b(k,404,{error:`Board "${i}" not registered. POST ${t} with {id} to register it first.`}),true):(b(k,400,{error:"Invalid board id"}),true)}async function I(w,k,L){return !!(await A(w,k,L)||await O(w,k,L))}function j(w){if(!C().boards.some(L=>L.id===w))throw Object.assign(new Error(`Board "${w}" not registered`),{statusCode:404});return {service:g(w)}}return {get apiBasePath(){return t},get corsHeaders(){return s},handleApi:I,requireBoardService:j}}exports.a=br;exports.b=Lr;exports.c=Dr;//# sourceMappingURL=chunk-KXWT3CY6.cjs.map
|
|
8
|
+
//# sourceMappingURL=chunk-KXWT3CY6.cjs.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {f,b,c as c$1,e}from'./chunk-MLVTJASJ.js';import {j,d,c,b as b$1}from'./chunk-VMW4Z6EF.js';import {y,z as z$1,l}from'./chunk-N6P2JW4W.js';import {b as b$2}from'./chunk-BQS3EIEK.js';import {a as a$2}from'./chunk-R5L5WUKN.js';import {a as a$1}from'./chunk-KBELAKIY.js';import {a}from'./chunk-76ON3V7R.js';function wt(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function Qe(r){if(!r||typeof r!="object")return false;let t=r.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function ze(r,t){if(!t||typeof t!="object")return;let s=t;if(s.kind==="notification-batch"&&Array.isArray(s.notifications)){for(let o of s.notifications)ze(r,o);return}s.kind==="status"&&Qe(s.status)&&(r.status=s.status),s.kind==="computed_values"&&s.cardId&&(r.computedValues[s.cardId]=s.values),s.kind==="data_object"&&s.key&&(r.dataObjects[s.key]=s.payload),s.kind==="card_refreshed"&&s.cardId&&(r.cards[s.cardId]=s.card),s.kind==="card_removed"&&s.cardId&&(delete r.cards[s.cardId],delete r.computedValues[s.cardId]);}function ge(r){return typeof r.journalStorage=="function"}function Ct(r){return typeof r.whatToRun=="string"?r.whatToRun.startsWith("b64:")?b$2(r.whatToRun).value:r.whatToRun:r.whatToRun.value}function se(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(r){let t=r.reduce((u,p)=>u+p.length,0),s=new Uint8Array(t),o=0;for(let u of r)s.set(u,o),o+=u.length;return s}function ht(r){let t=new Map,s=new Map,o=new Map,u=0,p=null;function R(i){let m=JSON.stringify(i);return u++,`id: ${u}
|
|
2
|
+
data: ${m}
|
|
3
|
+
|
|
4
|
+
`}function C(i){let m=i;try{m.flushHeaders?.();}catch{}try{m.flush?.();}catch{}try{m.socket?.setNoDelay?.(!0);}catch{}try{m.socket?.uncork?.();}catch{}}function F(i,m){let v=t.get(i);if(v&&!(m&&v.res!==m)){t.delete(i),j();try{r.onSseClientDisconnected?.(i);}catch{}try{v.res.end();}catch{}}}function T(i,m,v){let P=t.get(i);P&&F(i,P.res),t.set(i,{res:m,subscribedChatCardIds:v??new Set});}function g(i,m){let v=t.get(i);if(!v)return;let P=R(m);try{v.res.write(P),C(v.res);}catch{F(i,v.res);}}function b(){let i=new Set;for(let m of t.values())for(let v of m.subscribedChatCardIds)i.add(v);return Array.from(i)}function A(i){let m=s.has(i)?s.get(i):null,{cursor:v}=r.chatStorage.readAfter(i,m),P=r.chatStorage.isProcessing(i),G=P!==(o.get(i)??false),ue=v!==m;return ue&&s.set(i,v),o.set(i,P),ue||G}function O(i,m){let v=r.readChatRecords(i),P=Date.now();return {kind:"card_chats",cardId:i,sentAt:new Date(P).toISOString(),sentAtMs:P,messages:v.map(G=>({role:String(G.role||"system"),text:String(G.text||""),files:Array.isArray(G.files)?G.files:[]})),receiving:m,processing:r.chatStorage.isProcessing(i)}}function I(i,m=true){let v={kind:"notification-batch",notifications:[O(i,m)]};for(let[P,G]of t.entries())G.subscribedChatCardIds.has(i)&&g(P,v);}function j(){b().length>0||(p&&(clearInterval(p),p=null),s.clear(),o.clear());}function w(){if(p)return;let i=()=>{let m=b();if(m.length===0){j();return}let v=new Set(m);for(let P of Array.from(s.keys()))v.has(P)||s.delete(P);for(let P of Array.from(o.keys()))v.has(P)||o.delete(P);for(let P of m)A(P)&&I(P,true);};i(),p=setInterval(i,1e3);}function k(i,m){let v=t.get(i);if(!v)return false;v.subscribedChatCardIds.add(m);let{cursor:P}=r.chatStorage.readAfter(m,null);return s.set(m,P),o.set(m,r.chatStorage.isProcessing(m)),w(),g(i,{kind:"notification-batch",notifications:[O(m,true)]}),true}function L(i,m){let v=t.get(i);return v?(v.subscribedChatCardIds.delete(m),b().includes(m)||(s.delete(m),o.delete(m)),j(),true):false}function d(i){if(!i||typeof i!="object")return false;let m=i.kind;return m==="card_chats"||m==="chat_messages"}function l(i){if(!i||i.length===0)return;let m=[],v=new Set;for(let P of i)d(P)&&typeof P.cardId=="string"?v.add(String(P.cardId)):m.push(P);if(m.length>0){let P={kind:"notification-batch",notifications:m};for(let G of t.keys())g(G,P);}for(let P of v)I(P,true);}return {size:()=>t.size,has:i=>t.has(i),get:i=>t.get(i),buildFrame:R,flushTransport:C,register:T,disconnect:F,writeFrame:g,subscribeChat:k,unsubscribeChat:L,broadcastNotificationBatch:l,broadcastCardChats:I}}function z(r,...t){for(let s of t)if(typeof r[s]=="string")return String(r[s]);return ""}function ye(r,...t){for(let s of t)if(r[s]!==void 0)return Number(r[s])}function _e(r,...t){for(let s of t){let o=r[s];if(o&&typeof o=="object"&&!Array.isArray(o))return o}return {}}function he(r,t,...s){for(let o of s){let u=r[o];if(u&&typeof u=="object"&&!Array.isArray(u))return u}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function We(r,t,...s){for(let o of s){let u=r[o];if(u!==void 0){let p=Number(u);if(Number.isFinite(p))return p}}throw Object.assign(new Error(`MCP tool requires ${t}`),{statusCode:400})}function Rt(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(t=>Math.max(0,Math.min(255,Number(t)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let t=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),s=t+"=".repeat((4-t.length%4)%4),o=atob(s);return Uint8Array.from(o,u=>u.charCodeAt(0))}return null}function Je(r,t){if(r?.status==="success")return Object.prototype.hasOwnProperty.call(r,"data")?r.data:void 0;throw r?.status==="fail"||r?.status==="error"?Object.assign(new Error(r.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function Ke(r,t){return Je(await r,t)}function Ge(r){let t=z(r,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let s=t.split(".");if(!(s.length>=2&&s[0]==="chat"&&s.every(u=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return t}function Ze(r,t){let s=r.meta;for(let o of t.split(".")){if(!s||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,o))return {exists:false,value:null};s=s[o];}return {exists:true,value:s}}function kt(r){let{boardId:t,getMcpFacade:s,getMcpCardStoreFacade:o}=r;function u(T){let g=z(T,"board_id"),b=z(T,"card_id");if(!g)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!b)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(g!==t)throw Object.assign(new Error(`Unknown board_id: ${g}`),{statusCode:400});return {cardId:b}}function p(T,g){let{cardId:b}=u(T);return s().setChatProcessing({cardId:b,active:g}),{status:"success",data:{boardId:t,cardId:b,active:g}}}function R(T){let{cardId:g}=u(T),b=s().getChatProcessing({cardId:g});return {status:"success",data:{boardId:t,cardId:g,active:b.active}}}async function C(T){let{cardId:g}=u(T),b=Ge(T);if(!Object.prototype.hasOwnProperty.call(T,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(b.split(".").includes("__visible_controlplane_only")){let A=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(A.cards)&&A.cards.length>0&&typeof A.cards[0]=="object"&&!Array.isArray(A.cards[0])?A.cards[0]:null,I=O?Ze(O,"__visible_controlplane_only").value:void 0;if(T.value!==I)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:g,key:b}}}return Je(await o().patch({params:{id:g,path:`meta.${b}`},body:{value:T.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:g,key:b}}}async function F(T){let{cardId:g}=u(T),b=Ge(T),A=await Ke(o().get({params:{id:g}}),"cardStore.get"),O=Array.isArray(A.cards)&&A.cards.length>0&&A.cards[0]&&typeof A.cards[0]=="object"&&!Array.isArray(A.cards[0])?A.cards[0]:null;if(!O)throw Object.assign(new Error(`Card "${g}" not found`),{statusCode:404});let I=Ze(O,b);return {status:"success",data:{boardId:t,cardId:g,key:b,exists:I.exists,value:I.value}}}return {requireCardArgs:u,setChatProcessing:p,getChatProcessing:R,setCardMeta:C,getCardMeta:F}}function St(r){let{boardId:t,boardContexts:s,readCardDefinitions:o,readChatRecords:u,getChatProcessing:p}=r;async function R(){let g=(await Promise.all(s.map(async j=>{try{let w=j.boardAdapter.kvStorageForRef(j.outputsStoreRef),k=await Promise.resolve(w.read("status"));if(k!=null)return k}catch{}return j.notification.status}))).filter(Boolean);if(g.length===0)return null;if(g.length===1)return g[0];let b=[],A=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],O={};for(let j of A)O[j]=0;for(let j of g){let w=j,k=Array.isArray(w.cards)?w.cards:[];b.push(...k);for(let L of A)O[L]+=Number(w?.summary?.[L]||0);}let I=g[0];return {...I,cards:b,summary:{...I.summary||{},card_count:b.length,...O}}}async function C(){let g={},b=async A=>{try{let O=await A.boardOps.getAllOutputsComputedValues({});if(O.status==="success"&&O.data&&typeof O.data=="object"){for(let[I,j]of Object.entries(O.data)){let w=A.notification.cards[I];g[I]={schema_version:"v1",card_id:I,card_data:w?.card_data??{},computed_values:j??{}};}return}}catch{}for(let[O,I]of Object.entries(A.notification.computedValues)){let j=A.notification.cards[O];g[O]={schema_version:"v1",card_id:O,card_data:j?.card_data??{},computed_values:I??{}};}};for(let A of s)await b(A);return g}async function F(){let g={};for(let b of s){try{let A=await b.boardOps.getAllOutputsDataObjects({});if(A.status==="success"&&A.data&&typeof A.data=="object"){Object.assign(g,A.data);continue}}catch{}Object.assign(g,b.notification.dataObjects||{});}return g}async function T(){let g=await o(),b=await C(),A=await F(),O={};for(let j of g){if(!j?.id)continue;let w=j.id,k=b[w]||{},L={...k.card_data&&typeof k.card_data=="object"?k.card_data:j.card_data&&typeof j.card_data=="object"?j.card_data:{}};O[w]={schema_version:k.schema_version||"v1",card_id:k.card_id||w,card_data:L,computed_values:k.computed_values&&typeof k.computed_values=="object"?k.computed_values:{}};}let I={};for(let j of g){if(!j?.id)continue;let w=j.id;try{let k=u(w),L=p(w);(k.length>0||L)&&(I[w]={messages:k.map(d=>({role:String(d.role||"system"),text:String(d.text||""),files:Array.isArray(d.files)?d.files:[]})),receiving:!1,processing:L});}catch{}}return {boardId:t,cardDefinitions:g,statusSnapshot:await R(),dataObjectsByToken:A,cardRuntimeById:O,cardChatsByCardId:I}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:C,readDataObjectsByToken:F,buildPublishedRuntimePayload:T}}function Ht(r){let t=String(r||"").trim();if(!t)return "upload.bin";let s=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (s>=0?t.slice(s+1):t)||"upload.bin"}function At(r){let{safeCardId:t,artifactsStores:s,cardFileMetadataStore:o,readCardFromStore:u,updateCardLocalOnly:p,writeChatRecord:R}=r;async function C(g){let b=[];try{let A=await u(g);if(!A)return b;let O=o().read(A.card_data&&typeof A.card_data=="object"?A.card_data:null);for(let I of O)b.push(String(I.stored_name??""));}catch{}return b}async function F(g,b,A,O){let I=t(g),j=s(g),w=Ht(b),k=await C(g),d=`${String(k.length+1).padStart(3,"0")}-${w}`.slice(-36);return j.files&&await j.files.putBytes(`${I}/${d}`,new Uint8Array(O),A||"application/octet-stream"),{name:w,stored_name:d,size:O.length,mime_type:A||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function T(g,b,A,O,I){if(!O.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let j=I?.inChat===true,w=await F(g,b,A,O),k=null;if(await p(g,L=>{let d=new Date().toISOString(),l=L.card_data&&typeof L.card_data=="object"?L.card_data:{};L.card_data=l;let i=o().normalizeIncoming([{name:w.name,stored_name:w.stored_name,size:w.size,mime_type:w.mime_type,uploaded_at:w.uploaded_at||d,chat:j}],d);return k=o().merge(l,i).findIndex(v=>v.stored_name===w.stored_name),L}),j){let L=typeof k=="number"&&k>=0?` #${k}`:"";R(g,"system",`file uploaded: ${w.name} as ${w.stored_name}${L}`,[],I?.turnId??"");}return {ok:true,file:{...w,...typeof k=="number"&&k>=0?{file_idx:k}:{},chat:j},...typeof k=="number"&&k>=0?{file_idx:k}:{}}}return {uploadCardFile:T,readCardStoredFileNames:C}}function vt(r){return {"discover.source-kinds":()=>r.discoverSourceKinds(),"inspect.board-runtime-status":()=>r.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>r.inspectCardDefinitionAndRuntime({cardId:z(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let s=ye(t,"tail_turns"),o=ye(t,"tail"),u=z(t,"turn_id"),p=t.all_turns===true,R=z(t,"tail_turns_before_id");return r.inspectChatMessagesOnCards({cardId:z(t,"card_id"),...s!==void 0?{lastUserTurns:s}:{},...o!==void 0?{tail:o}:{},...u?{turnId:u}:{},...p?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":t=>r.inspectFileContents({cardId:z(t,"card_id"),fileIdx:Number(ye(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>r.preflightValidateCandidateCardDefinition({candidateCardContent:he(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>r.preflightMaterializeCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:he(t,"mock_requires","mock_requires"),mockFetchedSources:he(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>r.preflightProbeSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>r.preflightRunSingleSourceInCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockProjections:_e(t,"mock_projections"),sourceIdx:We(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>r.preflightRunSingleSourceInLiveCard({cardId:z(t,"card_id"),sourceIdx:We(t,"source_idx","source_idx"),mockRequires:he(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>r.preflightRunOneCycleWithCandidateCard({candidateCardContent:he(t,"candidate_card_content","candidate_card_content"),mockRequires:_e(t,"mock_requires")}),"manage.read-card":t=>r.manageReadCard({cardId:z(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let s=z(t,"turn_id");if(!s)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return r.manageAddChatEntryAndAnyAttachments({cardId:z(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...s?{turn:s}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.upsert-card":t=>r.manageUpsertCard({cardId:z(t,"card_id"),candidateCardContent:_e(t,"candidate_card_content")}),"manage.remove-card":t=>r.manageRemoveCard({cardId:z(t,"card_id")})}}function Pt(r){let{boardId:t,uploadCardFile:s,getMcpFacade:o,controlplane:u}=r;return {"getstate.is-chat-processing":p=>u.getChatProcessing(p),"setstate.chat-processing-started":p=>u.setChatProcessing(p,true),"setstate.chat-processing-done":p=>u.setChatProcessing(p,false),"getstate.card-meta":p=>u.getCardMeta(p),"setstate.card-meta":p=>u.setCardMeta(p),"manage.upload-card-file":p=>{let R=z(p,"board_id"),C=z(p,"card_id"),F=z(p,"file_name"),T=z(p,"content_type")||"application/octet-stream",g=Rt(p);if(!R)throw Object.assign(new Error("manage.upload-card-file requires board_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});if(!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!F)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!g)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return s(C,F,T,g,{inChat:false})},"manage.admin-read-card":async p=>{let{cardId:R}=u.requireCardArgs(p);return {status:"success",data:{cards:await o().adminReadCard({cardId:R})}}},"manage.admin-upsert-card":p=>{let R=z(p,"board_id"),C=z(p,"card_id");if(!R)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(R!==t)throw Object.assign(new Error(`Unknown board_id: ${R}`),{statusCode:400});return o().adminUpsertCard({cardId:C,candidateCardContent:_e(p,"candidate_card_content")})}}}function Bt(r){let{boardContexts:t,cardOwnerIndex:s,cardContextForCard:o,readStatusSnapshot:u,readDataObjectsByToken:p,readCardRuntimeArtifacts:R,readCardFromStore:C,readCardDefinitions:F,processAccumulatedLaneInternal:T,uploadCardFile:g,chatStorePublic:b,serverUrl:A,apiBasePath:O}=r;function I(){return t[0]??null}function j(){return {async status(){let d=await u();return d==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:d}},async getOutputsDataObject(d){let l=d?.params?.key;return l?{status:"success",data:(await p())[l]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(d){let l=d?.params?.key;return l?{status:"success",data:(await R())[l]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(d){let l=d?.params?.key;if(!l)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let i=o(l)??I();return i?i.boardOps.getOutputsFetchedSources({params:{key:l}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(d){let l=d?.params?.id;if(!l)return {status:"fail",error:"removeCard requires params.id"};let i=o(l)??I();return i?i.boardOps.removeCard({params:{id:l}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let i=o(l)??I();return i?i.boardOps.cardRefreshedNotify({params:{cardId:l}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(d){let l=d?.params?.cardId;if(!l)return {status:"fail",error:"upsertCard requires params.cardId"};let i=o(l)??I();if(!i)return {status:"fail",error:"Board context is unavailable"};let m=await i.boardOps.upsertCard({params:{cardId:l,restart:d.params.restart===true}});if(m.status!=="success")return m;if(ge(i.boardAdapter)){let v=await T(true);if(v.status!=="success")return v}return m}}}function w(){let d=()=>{let l=I();if(!l?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return l.nonCore};return {describeTaskExecutorCapabilities(l){return d().describeTaskExecutorCapabilities(l)},validateCardPreflight(l){return d().validateCardPreflight(l)},evalCardCompute(l){return d().evalCardCompute(l)},probeSourcePreflight(l){return d().probeSourcePreflight(l)},runSourcePreflight(l){return d().runSourcePreflight(l)},simulateCardCycle(l){return d().simulateCardCycle(l)}}}function k(){return {async get(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(l){let i=await C(l);return i?{status:"success",data:{cards:[i]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await F()}}},async set(d){let l=d.body;if(l==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let i=Array.isArray(l)?l:[l];for(let m of i){let v=m,P=typeof v.id=="string"?v.id:"";if(!P)return {status:"fail",error:"each card must have a string `id` field"};let G=s.get(P)??0,ue=t[G]??I();if(!ue)return {status:"fail",error:"Board context is unavailable"};let fe=await ue.cardStoreOps.set({body:v});if(fe.status!=="success")return fe;s.set(P,G);}return {status:"success",data:{count:i.length}}},async del(d){let l=[d.params?.id,...d.body?.ids??[]].filter(i=>typeof i=="string"&&!!i);if(l.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let i of l){let m=o(i)??I();if(!m)return {status:"fail",error:"Board context is unavailable"};let v=await m.cardStoreOps.del({params:{id:i}});if(v.status!=="success")return v;s.delete(i);}return {status:"success",data:{count:l.length}}},async patch(d){let l=typeof d.params?.id=="string"?d.params.id:void 0,i=typeof d.params?.path=="string"?d.params.path:void 0;if(!l||!i)return {status:"fail",error:"patch requires params.id and params.path"};let m=o(l)??I();return m?m.cardStoreOps.patch(d):{status:"fail",error:"Board context is unavailable"}},async appendFiles(d){let l=typeof d.params?.id=="string"?d.params.id:void 0;if(!l)return {status:"fail",error:"appendFiles requires params.id"};let i=o(l)??I();return i?i.cardStoreOps.appendFiles(d):{status:"fail",error:"Board context is unavailable"}}}}function L(){return a$2({board:j(),nonCore:w(),cardStore:k(),chatStore:b,uploadCardFile({cardId:d,fileName:l,contentType:i,bytes:m}){return g(d,l,i,m,{inChat:true})},buildFileDownloadUrl({cardId:d,fileIdx:l,storedName:i}){let m=`${A||""}${O}/cards/${encodeURIComponent(d)}/files/${l}`;return i?`${m}?sn=${encodeURIComponent(i)}`:m},readFetchedSourceJsonByRef({cardId:d,ref:l}){let i=o(d)??I();if(!i||ge(i.boardAdapter))return null;let P=i.boardAdapter.resolveBlob(b$2(l)).trim();return P?JSON.parse(P):null}})}return {mcpBoardFacade:j,mcpNonCoreFacade:w,mcpCardStoreFacade:k,createMcpFacade:L}}function xt(r){let{sseHub:t,corsHeaders:s,json:o,buildPublishedRuntimePayload:u,onSseClientConnected:p,onChannelSubscribed:R,onChannelUnsubscribed:C}=r;function F(g,b,A,O,I){if(!t.has(b)){o(g,404,{error:`SSE client not connected: ${b}`});return}I?R?.(b,A,O):C?.(b,A,O),o(g,200,{ok:true,clientId:b,channelName:A,...O.cardId?{cardId:O.cardId}:{},subscribed:I});}async function T(g,b,A){let O=t.get(A),I=O?new Set(O.subscribedChatCardIds):new Set;b.writeHead(200,{...s,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),t.flushTransport(b),t.register(A,b,I);let j=await u(),w=t.buildFrame(j);b.write(w);try{p?.(A,L=>{t.writeFrame(A,L);});}catch{}let k=setInterval(()=>{try{b.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);g.on("close",()=>{clearInterval(k),t.disconnect(A,b);});}return {handleChannelSubscription:F,handleSse:T}}async function Xe(r,t,s){let o=s[r];if(!o)throw Object.assign(new Error(`Unknown MCP tool: ${r}`),{statusCode:400});let u=await o(t);if(u&&typeof u=="object"&&!Array.isArray(u)){let p=u,R=p.status;if(R==="success")return Object.prototype.hasOwnProperty.call(p,"data")?u:{status:"success",data:{}};if(R==="fail"||R==="error")return u}return {status:"success",data:u}}function Me(r,t){if(!r||typeof r!="object"||Array.isArray(r))return t;let s=r;if(typeof s.error=="string"&&s.error.trim())return s.error;if(s.step==="validate"){let o=s.validation;if(o&&typeof o=="object"&&!Array.isArray(o)){let p=o.data;if(p&&typeof p=="object"&&!Array.isArray(p)){let R=p.issues;if(Array.isArray(R)){let F=R.find(T=>typeof T=="string"&&T.trim());if(typeof F=="string")return `Validation failed: ${F}`}let C=p.errors;if(Array.isArray(C)&&C.length>0)return "Validation failed"}}return "Validation failed"}return t}function It(r){let{apiBasePath:t,boardContexts:s,json:o,readJsonBody:u,readRawBody:p,initBoardAndSetup:R,bootstrapBoard:C,buildPublishedRuntimePayload:F,publishPersistedStateSnapshot:T,upsertCardsFromSource:g,applyBoardWorkerCallback:b,handleSse:A,handleChannelSubscription:O,createMcpFacade:I,createMcpToolRegistry:j,createMcpControlplaneToolRegistry:w,readCardFromStore:k,patchCard:L,retriggerCard:d,applyCardAction:l,resolveChatHandlerTarget:i,chatStorePublic:m,chatStorage:v,sseHub:P,uploadCardFile:G,sendCardFileDownloadResponse:ue,resolveCardFileDownloadPayload:fe,isLikelyTextMimeType:ie,sliceTextByLines:be}=r;async function Se(ee,x,Ve){let W=ee.method||"GET",te=Ve,Y=te.pathname;try{if(W==="GET"&&Y===`${t}/init-board`)return await R(),o(x,200,await F()),!0;if(W==="GET"&&Y===`${t}/sse`){await R();let S=String(te.searchParams.get("clientId")||"").trim();if(!S)return o(x,400,{error:"clientId query param is required for SSE"}),!0;await A(ee,x,S);for(let h=0;h<s.length;h++)await T(s[h]),await g(s[h],h),await T(s[h]);return !0}if(W==="GET"&&Y===`${t}/board-status`)return o(x,200,await F()),!0;let we=Y.match(new RegExp(`^${se(t)}/callback/board-worker/([^/]+)/(success|failure)$`));if(W==="POST"&&we){await R();let S=decodeURIComponent(we[1]),h=we[2],M=await u(ee),B=await b(S,h,M);return o(x,B.statusCode,B.body),!0}if(W==="POST"&&Y===`${t}/mcp`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;if(h==="inspect.file-contents")return o(x,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let B=await Xe(h,M,j(I()));if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(x,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(x,500,{error:Me(B,"Internal error")}),!0}o(x,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(x,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-controlplane`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;try{let B=await Xe(h,M,w());if(B&&typeof B=="object"&&!Array.isArray(B)){let q=B;if(q.status==="fail")return o(x,400,{error:Me(B,"Request failed")}),!0;if(q.status==="error")return o(x,500,{error:Me(B,"Internal error")}),!0}o(x,200,B);}catch(B){let q=typeof B?.statusCode=="number"?Number(B.statusCode):500,Z=B instanceof Error?B.message:String(B);o(x,q,{error:Z});}return !0}if(W==="POST"&&Y===`${t}/mcp-raw`){await C();let S=await u(ee),h=typeof S.tool=="string"?S.tool.trim():"",M=S.args&&typeof S.args=="object"&&!Array.isArray(S.args)?S.args:{};if(!h)return o(x,400,{error:"tool is required"}),!0;if(h!=="inspect.file-contents")return o(x,400,{error:`Tool does not support raw response: ${h}`}),!0;let B=z(M,"card_id","cardId"),q=ye(M,"file_idx","fileIdx"),Z=ye(M,"head-lines","headLines"),Q=ye(M,"tail-lines","tailLines"),ne=ye(M,"head-bytes","headBytes"),le=ye(M,"tail-bytes","tailBytes");if(!B)return o(x,400,{error:"inspect.file-contents requires card_id"}),!0;if(q===void 0||!Number.isInteger(q)||q<0)return o(x,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([Z,Q,ne,le].filter(ce=>ce!==void 0).length>1)return o(x,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[ce,ke]of [["head-lines",Z],["tail-lines",Q],["head-bytes",ne],["tail-bytes",le]])if(ke!==void 0&&(!Number.isInteger(ke)||ke<0))return o(x,400,{error:`inspect.file-contents requires ${ce} to be a non-negative integer`}),!0;let xe=await I().inspectFileContents({cardId:B,fileIdx:q}),$e=typeof xe?.stored_name=="string"?xe.stored_name:null,{fileRecord:Fe,bytes:Ae}=await fe(B,q,$e),qe=String(Fe.name||Fe.stored_name||"download.bin"),Te=String(Fe.mime_type||"application/octet-stream"),ve=(te.searchParams.get("resp")||"").trim().toLowerCase();if(ve&&ve!=="json-b64")return o(x,400,{error:`unsupported resp mode: ${ve}`}),!0;let Ne=ve==="json-b64",me;if(Z!==void 0||Q!==void 0){if(!ie(Te))return o(x,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let ce=new TextDecoder().decode(Ae),ke=Z!==void 0?be(ce,"head",Z):be(ce,"tail",Q);me=typeof Buffer<"u"?Buffer.from(ke,"utf8"):new TextEncoder().encode(ke);}else if(ne!==void 0||le!==void 0){let ce=ne??le;me=ne!==void 0?Ae.slice(0,ce):Ae.slice(Math.max(0,Ae.length-ce));}else me=Ae;if(Ne){let ce=typeof Buffer<"u"?Buffer.from(me).toString("base64"):btoa(String.fromCharCode(...me));return o(x,200,{bodyBase64:ce,mimeType:Te,filename:qe,byteLength:me.length}),!0}return x.writeHead(200,{"Content-Type":Te,"Content-Disposition":`attachment; filename="${qe}"`,"Content-Length":me.length}),x.end(me),!0}let Ce=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)$`));if(W==="GET"&&Ce){await C();let S=decodeURIComponent(Ce[1]),h=await k(S);return h?(o(x,200,h),!0):(o(x,404,{error:`card not found: ${S}`}),!0)}if(W==="PATCH"&&Ce){await C();let S=decodeURIComponent(Ce[1]),h=await u(ee);return await L(S,h),o(x,200,{ok:!0}),!0}let je=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/retrigger$`));if(W==="POST"&&je){await C();let S=decodeURIComponent(je[1]);return await d(S),o(x,200,{ok:!0}),!0}let pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/actions$`));if(W==="POST"&&pe){await C();let S=decodeURIComponent(pe[1]),h=Date.now(),M=new Date(h).toISOString(),B=await u(ee),q=B?.actionType;if(q==="chat-send"&&!await i(S)){let Q=Date.now();return o(x,409,{error:`chat handler is not configured for card: ${S}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Q).toISOString(),responseSentAtMs:Q,responseStatus:409}),!0}if(q==="chat-send"){let Q=B?.payload??{},ne=typeof Q["turn-id"]=="string"?Q["turn-id"]:typeof Q.turnId=="string"?Q.turnId:typeof Q.turn=="string"?Q.turn:"";if(!ne||!String(ne).trim()){let le=Date.now();return o(x,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${S}`,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(le).toISOString(),responseSentAtMs:le,responseStatus:400}),!0}}await l(S,q,B?.payload);let Z=Date.now();return o(x,200,{ok:!0,requestReceivedAt:M,requestReceivedAtMs:h,responseSentAt:new Date(Z).toISOString(),responseSentAtMs:Z,responseStatus:200}),!0}let Pe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats$`));if(W==="GET"&&Pe){await C();let S=decodeURIComponent(Pe[1]),h=String(te.searchParams.get("turn-id")||""),M=String(te.searchParams.get("all-turns")||"").toLowerCase()==="true",B=String(te.searchParams.get("tail-turns-before-id")||""),q=te.searchParams.get("tail-turns"),Z=q==null||q===""?M||h?void 0:1:Number.parseInt(q,10),Q=m.readAll({params:{cardId:S},body:{...Z===void 0?{}:{tailTurns:Z},...h?{turnId:h}:{},...M?{allTurns:!0}:{},...B?{tailTurnsBeforeId:B}:{}}});if(Q.status!=="success")return o(x,400,{error:Q.error||"Failed to read chats"}),!0;let ne=Q.data.records;return o(x,200,{ok:!0,messages:ne}),!0}if(W==="POST"&&Pe){await C();let S=decodeURIComponent(Pe[1]),h=await u(ee),M=typeof h?.role=="string"?h.role:"assistant",B=typeof h?.text=="string"?h.text:"",q=Array.isArray(h?.files)?h.files:[],Z=typeof h?.turn=="string"?h.turn:typeof h?.["turn-id"]=="string"?h["turn-id"]:typeof h?.turnId=="string"?h.turnId:"",Q=h?.done===!0,ne=v.append(S,M,B,q,Z);return Q&&v.setProcessing(S,!1),P.broadcastCardChats(S,!Q),o(x,200,{ok:!0,id:ne}),!0}let Ee=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/subscribe-sse$`));if(W==="POST"&&Ee){await C();let S=decodeURIComponent(Ee[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.subscribeChat(M,S)?(o(x,200,{ok:!0,clientId:M,cardId:S,subscribed:!0}),!0):(o(x,404,{error:`SSE client not connected: ${M}`}),!0):(o(x,400,{error:"clientId is required"}),!0)}let Le=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(W==="POST"&&Le){await C();let S=decodeURIComponent(Le[1]),h=await u(ee),M=typeof h?.clientId=="string"?h.clientId.trim():"";return M?P.unsubscribeChat(M,S)?(o(x,200,{ok:!0,clientId:M,cardId:S,subscribed:!1}),!0):(o(x,404,{error:`SSE client not connected: ${M}`}),!0):(o(x,400,{error:"clientId is required"}),!0)}let Re=Y.match(new RegExp(`^${se(t)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Re){await C();let S=decodeURIComponent(Re[1]),h=Re[2]==="subscribe",M=await u(ee),B=typeof M?.clientId=="string"?M.clientId.trim():"";return B?(O(x,B,S,{},h),!0):(o(x,400,{error:"clientId is required"}),!0)}let Be=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(W==="POST"&&Be){await C();let S=decodeURIComponent(Be[1]),h=decodeURIComponent(Be[2]),M=Be[3]==="subscribe",B=await u(ee),q=typeof B?.clientId=="string"?B.clientId.trim():"";return q?(O(x,q,h,{cardId:S},M),!0):(o(x,400,{error:"clientId is required"}),!0)}let De=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files$`));if(W==="POST"&&De){await C();let S=decodeURIComponent(De[1]),h=String(te.searchParams.get("inChat")||"").toLowerCase()==="true",M=String(te.searchParams.get("turn-id")||"").trim();if(h&&!M)return o(x,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${S}`}),!0;let B=ee.headers["x-file-name"],q=String(ee.headers["content-type"]||"application/octet-stream"),Z=Array.isArray(B)?B[0]:B,Q=Z?decodeURIComponent(String(Z)):"upload.bin",ne=await p(ee);return o(x,200,await G(S,Q,q,ne,{inChat:h,turnId:M})),!0}let Oe=Y.match(new RegExp(`^${se(t)}/cards/([^/]+)/files/(\\d+)$`));if(W==="GET"&&Oe){let S=decodeURIComponent(Oe[1]),h=parseInt(Oe[2],10),M=te.searchParams.get("sn");return await ue(x,S,h,M),!0}return !1}catch(we){let Ce=we?.statusCode||500;return o(x,Ce,{error:String(we?.message||we)}),true}}return {handleRuntimeApi:Se}}function Ye(r,t){return t?{...r,...t.pollIntervalMs!=null?{pollIntervalMs:t.pollIntervalMs}:{},...t.visibilityMs!=null?{visibilityMs:t.visibilityMs}:{},...t.concurrency!=null?{concurrency:t.concurrency}:{},...t.maxAttempts!=null?{maxAttempts:t.maxAttempts}:{}}:r}function _t(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.leaseRequests(u))).map(R=>({id:R.messageId,attempt:R.attempt,message:R.request,ack:()=>Promise.resolve(t.ackRequest(R.messageId,R.leaseToken)),nack:C=>Promise.resolve(t.nackRequest(R.messageId,R.leaseToken,C))}))},async handle(u){await s(u.args,u);},onError:o?(u,p)=>o(u,p.attempt,p.message):void 0}}function Wt(r,t,s,o){return {id:r,async lease(u){return (await Promise.resolve(t.lease(u))).map(R=>({id:R.id,attempt:R.attempt,message:R.body,ack:()=>Promise.resolve(t.ack(R.id,R.leaseToken)),nack:C=>Promise.resolve(t.nack(R.id,R.leaseToken,C))}))},async handle(){await s();},onError:o?(u,p)=>o(u,p.attempt):void 0}}function br(r){let t=r.logger??{info(){},warn(){},error(){}},s=r.boardAdapter,o=r.runtime.queueLaneTuning??{},u=s.processAccumulatedStore(),p=s.chatAgentStore(),R=[];if(R.push(Ye(Wt("process-accumulated",u,async()=>{let C=await r.runtime.processAccumulatedLane();if(C.status!=="success")throw new Error(C.error||`processAccumulatedLane returned ${C.status}`)},(C,F)=>{t.error(`[board-server] queued process-accumulated failed for ${r.boardId} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.processAccumulated)),R.push(Ye(_t("chat-agent",p,async(C,F)=>{await r.runtime.handleChatAgentRequest(F);},(C,F,T)=>{let g=typeof T.args?.cardId=="string"?T.args.cardId:"";t.error(`[board-server] queued chat-agent failed for ${r.boardId}${g?`/${g}`:""} (attempt ${F}): ${String(C&&C.message||C)}`);}),o.chatAgent)),r.executeTaskExecutorRequest){let C=s.boardWorkerStore();R.push(Ye(_t("task-executor",C,r.executeTaskExecutorRequest,(F,T)=>{t.error(`[board-server] queued board-worker failed for ${r.boardId} (attempt ${T}): ${String(F&&F.message||F)}`);}),o.taskExecutor));}return f(R)}var Ft={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},Ot="chat-handler-flow-queue";function Lr(r){let t=String(r.apiBasePath||"/api/board").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.queueLaneTuning??{},u=r.boardId||"",p=r.logger||{info:console.log,warn:console.warn,error:console.error},R=r.invocationAdapter,C=r.chatFlowRunner||null,F=r.chatStorage??b(),T=a(F),g=r.notificationTransport||null,b$2=r.serverUrl||null,A=r.executionExtra||{},O=r.onSseClientConnected,I=r.onSseClientDisconnected,j$1=r.onChannelSubscribed,w=r.onChannelUnsubscribed,k=ht({chatStorage:F,readChatRecords:e=>le(e),onSseClientDisconnected:I});function L(e){function n(y){if(Array.isArray(y))return y;if(y&&typeof y=="object"){let E=y;return Array.isArray(E.files)?E.files:[y]}return null}function a(y){return {async get(E){return y.get(E)},async set(E){return y.set(E)},async del(E){return y.del(E)},async patch(E){return y.patch(E)},async appendFiles(E){return y.appendFiles(E)}}}function f(y){function E(V){return {status:"success",data:V}}function $(V){return {status:"fail",error:V}}function D(V){return {status:"error",error:V instanceof Error?V.message:String(V)}}return {async get(V){try{let U=V.params?.id;if(U){let re=await y.readCard(U);return re?E({cards:[re]}):$(`card "${U}" not found`)}return E({cards:await y.readAllCards()})}catch(U){return D(U)}},async set(V){try{let U=V.body;if(U==null)return $("set requires a body (card object or array of cards)");let re=Array.isArray(U)?U:[U];for(let ae of re){if(typeof ae.id!="string")return $("each card must have a string `id` field");await y.writeCard(ae.id,ae);}return E({count:re.length})}catch(U){return D(U)}},async del(V){try{let U=V.body?.ids??[],re=V.params?.id,ae=re?[...U,re]:U;if(ae.length===0)return $("del requires body.ids (string[]) or params.id");for(let Ie of ae)await y.removeCard(Ie);return E({count:ae.length})}catch(U){return D(U)}},async patch(V){try{let U=V.params?.id,re=V.params?.path;if(!U)return $("patch requires params.id");if(!re)return $("patch requires params.path");let ae=V.body,Ie=ae&&Object.prototype.hasOwnProperty.call(ae,"value")?ae.value:V.body;return await y.patchCard(U,re,Ie),E({count:1})}catch(U){return D(U)}},async appendFiles(V){try{let U=V.params?.id;if(!U)return $("appendFiles requires params.id");let re=await y.readCard(U);if(!re)return $(`card "${U}" not found`);let ae=n(V.body);if(!ae||ae.length===0)return $("appendFiles requires a file metadata object, array, or body.files array");let Ie=re.card_data&&typeof re.card_data=="object"&&!Array.isArray(re.card_data)?re.card_data:{},nt=Array.isArray(Ie.files)?Ie.files:[],qt=[...nt,...ae];return await y.patchCard(U,"card_data.files",qt),E({files_added:ae.map((Nt,Ut)=>({idx:nt.length+Ut,entry:Nt}))})}catch(U){return D(U)}}}}let c$2=ge(e.boardAdapter)?j(e.baseRef,e.boardAdapter):y(e.baseRef,e.boardAdapter),_=e.nonCoreAdapter??(!ge(e.boardAdapter)&&m(e.boardAdapter)?e.boardAdapter:null),N=_?z$1(e.baseRef,_):null,K,H=ge(e.boardAdapter)?(()=>{let y=d(c(b$1(e.boardAdapter.kvStorageForRef(e.cardStoreRef)),e.boardAdapter.hashFn),p.warn),E=f(y);return K={get($){return E.get($)},set($){return E.set($)}},E})():(()=>{let y=e.boardAdapter.kvStorageForRef(e.cardStoreRef),$=a$1(l({readIndex:()=>y.read("_index"),writeIndex:D=>y.write("_index",D),readCard:D=>y.read(D),writeCard:(D,V)=>(y.write(D,V),D),removeCard:D=>{y.delete(D);},cardExists:D=>y.read(D)!==null,defaultCardKey:D=>D},p.warn));return K=$,a($)})(),X=e.artifactsAdapter||e.boardAdapter,J=e.filesArtifactsStore??null,oe=J?{putBytes(y,E,$){J.putBytes(y,E,$);},getBytes(y){return J.getBytes(y)},listKeys(y){return J.list(y).map(E=>E.key)}}:null;if(!oe&&!ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files"),E=c$1(y);oe={putBytes($,D,V){E.putBytes($,D,V);},getBytes($){return E.getBytes($)},listKeys($){return E.list($).map(D=>D.key)}};}else if(!oe&&ge(X)){let y=e.artifactsAdapter?X.blobStorage(""):X.blobStorage("files");oe={async putBytes(E,$){if(y.writeBytes){await y.writeBytes(E,$);return}let D=JSON.stringify({__kind:"bytes-array",data:[...$]});await y.write(E,D);},async getBytes(E){if(y.readBytes){let D=await y.readBytes(E);if(D!==null)return D}let $=await y.read(E);if($===null)return null;try{let D=JSON.parse($);if(D&&D.__kind==="bytes-array"&&Array.isArray(D.data))return new Uint8Array(D.data)}catch{}return new TextEncoder().encode($)},async listKeys(E){return await y.listKeys(E)}};}let de={async init(y){return c$2.init(y)},async status(y){return c$2.status(y)},async getConfig(y){return c$2.getConfig(y)},async getAllOutputsDataObjects(y){return c$2.getAllOutputsDataObjects(y)},async getAllOutputsComputedValues(y){return c$2.getAllOutputsComputedValues(y)},async getOutputsFetchedSources(y){return c$2.getOutputsFetchedSources(y)},async upsertCard(y){return c$2.upsertCard(y)},async removeCard(y){return c$2.removeCard(y)},async cardRefreshedNotify(y){return c$2.cardRefreshedNotify(y)},async sourceDataFetched(y){return c$2.sourceDataFetched(y)},async sourceDataFetchFailure(y){return c$2.sourceDataFetchFailure(y)}};return {label:e.label,board:c$2,nonCore:N,publicCardStore:K,boardOps:de,cardStoreOps:H,get filesArtifacts(){return oe},boardAdapter:e.boardAdapter,cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef,artifactsStoreRef:e.artifactsStoreRef,scratchStoreRef:e.scratchStoreRef,archiveStoreRef:e.archiveStoreRef,notifyRef:e.notifyRef,taskExecutorRef:e.taskExecutorRef,chatHandlerRef:e.chatHandlerRef,chatHandlerFlow:e.chatHandlerFlow,inferenceAdapterRef:e.inferenceAdapterRef,notification:wt(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d$1=r.boards.map(L),l$1=new Map;function i(e){return l$1.get(e)??0}function m(e){let n=e;return typeof n.invokeExecutor=="function"&&typeof n.validateSchema=="function"}function v(e){let n=d$1[i(e)];return {files:n?n.filesArtifacts:null}}function P(){return e()}function G(e){return String(e||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function ue(e){if(!e||e.notificationTeardown||!g||!e.notifyRef)return;let n=await g.subscribe(e.notifyRef,a=>{ze(e.notification,a);let f=a.kind==="notification-batch"?a.notifications:[a];k.broadcastNotificationBatch(f);});e.notificationTeardown=n;}async function fe(e){if(!e||e.initialized)return;let n={cardStoreRef:e.cardStoreRef,outputsStoreRef:e.outputsStoreRef};e.artifactsStoreRef&&(n.artifactsStoreRef=e.artifactsStoreRef),e.scratchStoreRef&&(n.scratchStoreRef=e.scratchStoreRef),e.archiveStoreRef&&(n.archiveStoreRef=e.archiveStoreRef);let a={};e.taskExecutorRef&&(a["task-executor-ref"]=e.taskExecutorRef),e.chatHandlerFlow!==void 0&&(a["chat-handler-flow"]=e.chatHandlerFlow),e.inferenceAdapterRef&&(a["inference-adapter-ref"]=e.inferenceAdapterRef);let f=await e.boardOps.init({params:n,body:a});if(f.status!=="success")throw Object.assign(new Error(f.error||`init failed for ${e.label}`),{statusCode:500});if(await ue(e),!e.chatHandlerFlow&&e.chatHandlerRef&&R.describe)try{let c=await R.describe(e.chatHandlerRef);c&&c.kind!=="chat-handler"?p.warn(`[init] chat-handler describe returned kind="${c.kind}", expected "chat-handler" for ${e.label}`):c&&p.info(`[init] chat-handler validated: ${c.name} (protocol ${c.protocolVersion}) for ${e.label}`);}catch(c){p.warn(`[init] chat-handler describe failed for ${e.label}: ${c?.message||String(c)}`);}e.initialized=true;}async function ie(e){if(!e.boardAdapter.publishBoardChangeNotifications)return;let n=[],a=await e.boardOps.status({});a.status==="success"&&a.data!=null&&Qe(a.data)&&n.push({kind:"status",status:a.data});let f=await e.boardOps.getAllOutputsDataObjects({});if(f.status==="success"&&f.data!=null)for(let[_,N]of Object.entries(f.data))_&&n.push({kind:"data_object",key:_,payload:N});let c=await e.boardOps.getAllOutputsComputedValues({});if(c.status==="success"&&c.data!=null)for(let[_,N]of Object.entries(c.data))_&&n.push({kind:"computed_values",cardId:_,values:N});n.length>0&&e.boardAdapter.publishBoardChangeNotifications(n);}async function be(e,n){if(!e||e.cardsBootstrapped)return;let a=await e.cardStoreOps.get({}),f=a.status==="success"&&Array.isArray(a.data?.cards)?a.data.cards:[];for(let c of f)typeof c.id=="string"&&(l$1.set(c.id,n),await e.boardOps.upsertCard({params:{cardId:c.id}}));e.cardsBootstrapped=true;}async function Se(){for(let e of d$1)await fe(e);}async function ee(){await Se();for(let e=0;e<d$1.length;e++)await ie(d$1[e]),await be(d$1[e],e),await ie(d$1[e]);}async function x(e=false){e||await Se();for(let n of d$1){let a=await n.board.processAccumulatedEvents({});if(a.status!=="success")return a}return {status:"success"}}async function Ve(){return await Se(),x(true)}function W(e){return d$1[i(e)]??null}async function te(e){let n=W(e);if(!n)return null;let a=await n.cardStoreOps.get({params:{id:e}});if(a.status!=="success")return null;let f=Array.isArray(a.data?.cards)?a.data.cards:[];return f.length>0?f[0]:null}async function Y(){let e=async a=>{if(!a)return [];let f=await a.cardStoreOps.get({});return f.status!=="success"||!Array.isArray(f.data?.cards)?[]:f.data.cards},n=[];for(let a of d$1)n.push(...await e(a));return n}function we(){return d$1[0]??null}let Ce=Bt({boardContexts:d$1,cardOwnerIndex:l$1,cardContextForCard:e=>W(e),readStatusSnapshot:()=>Be(),readDataObjectsByToken:()=>Oe(),readCardRuntimeArtifacts:()=>De(),readCardFromStore:e=>te(e),readCardDefinitions:()=>Y(),processAccumulatedLaneInternal:e=>x(e),uploadCardFile:(e,n,a,f,c)=>xe(e,n,a,f,c),chatStorePublic:T,serverUrl:b$2,apiBasePath:t}),je=Ce.mcpCardStoreFacade,pe=Ce.createMcpFacade,Pe=kt({boardId:u,getMcpFacade:()=>pe(),getMcpCardStoreFacade:()=>je()});function Ee(e){return vt(e)}function Le(){return Pt({boardId:u,uploadCardFile:xe,getMcpFacade:()=>pe(),controlplane:Pe})}let Re=St({boardId:u,boardContexts:d$1,readCardDefinitions:()=>Y(),readChatRecords:e=>le(e),getChatProcessing:e=>pe().getChatProcessing({cardId:e}).active}),Be=Re.readStatusSnapshot,De=Re.readCardRuntimeArtifacts,Oe=Re.readDataObjectsByToken,S=Re.buildPublishedRuntimePayload;async function h(e,n,a){let f=a?.syncBoard!==false,c=a?.restartOnlyIfChanged===true,_=W(e);if(!_)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let N=await te(e);if(!N)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let K=c?JSON.stringify(N):null,H=n(N)||N;if(c&&JSON.stringify(H)===K)return;let X=await _.cardStoreOps.set({body:H});if(X.status!=="success")throw Object.assign(new Error(X.error||`Failed to persist card: ${e}`),{statusCode:500});if(f){let J=await _.boardOps.upsertCard({params:{cardId:e,restart:true}});if(J.status!=="success")throw Object.assign(new Error(J.error||`Failed to upsert card: ${e}`),{statusCode:500})}}async function M(e,n){await h(e,n,{syncBoard:true});}async function B(e,n){await h(e,n,{syncBoard:false});}async function q(e){let n=W(e);if(!n)throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});if(!await te(e))throw Object.assign(new Error(`Card not found: ${e}`),{statusCode:404});let f=await n.boardOps.upsertCard({params:{cardId:e,restart:true}});if(f.status!=="success")throw Object.assign(new Error(f.error||`Failed to retrigger card: ${e}`),{statusCode:500})}async function Z(e,n){await h(e,a=>{if(!n||typeof n!="object"||Object.keys(n).length===0)return a;function f(c,_,N){let K=String(_||"").split(".").filter(Boolean);if(!K.length)return;let H=c;for(let X=0;X<K.length-1;X++){let J=K[X];(!H[J]||typeof H[J]!="object")&&(H[J]={}),H=H[J];}H[K[K.length-1]]=N;}if(n.fieldValues!==void 0&&n.fieldValues!==null){let c=null,_=a.view;if(_&&Array.isArray(_.elements)){for(let N of _.elements)if(N?.data&&N.data.writeTo){c=N.data.writeTo;break}}c?f(a,c,n.fieldValues):typeof n.fieldValues=="object"&&!Array.isArray(n.fieldValues)&&(a.card_data={...a.card_data||{},...n.fieldValues});}else {if(Array.isArray(n._stagedFiles)&&n._stagedFiles.length>0)return a;for(let[c,_]of Object.entries(n))c!=="_stagedFiles"&&(_!==null&&typeof _=="object"&&!Array.isArray(_)&&a[c]!==null&&typeof a[c]=="object"&&!Array.isArray(a[c])?a[c]={...a[c],..._}:a[c]=_);}return a},{syncBoard:true,restartOnlyIfChanged:true});}function Q(e){F.clear(e);try{pe().setChatProcessing({cardId:e,active:!1});}catch{}}function ne(e,n,a,f,c=""){let _=typeof a=="string"?a.trim():"";return F.append(e,n||"system",_,f,c)}function le(e){return F.readAll(e)}let xe=At({safeCardId:e=>G(e),artifactsStores:e=>v(e),cardFileMetadataStore:()=>P(),readCardFromStore:e=>te(e),updateCardLocalOnly:(e,n)=>B(e,n),writeChatRecord:(e,n,a,f,c)=>ne(e,n,a,f,c)}).uploadCardFile;async function $e(e){let n=W(e);if(!n)return null;let a=await n.boardOps.getConfig({params:{key:"chat-handler-flow"}}),f=a.status==="success"?a.data?.value:null,c=n.chatHandlerRef;return f==null&&(!c||typeof c!="object")?null:{ctx:n,handlerFlow:f,handlerRef:c}}async function Fe(e,n,a=false,f=""){let c=await $e(e);if(!c)return;let{ctx:_,handlerFlow:N,handlerRef:K}=c;if(!a)try{pe().setChatProcessing({cardId:e,active:!0});}catch{}let H={boardId:u,cardId:String(e),lastChatEntryId:n,...f?{turnId:f}:{},...A,...b$2?{serverUrl:b$2}:{}},X=N!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:Ot}}:K;try{ge(_.boardAdapter)?await _.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}):_.boardAdapter.chatAgentStore().enqueueRequest({boardId:u,ref:X,args:N!=null?{...H,__chatHandlerFlow:N}:H}),await Promise.resolve(_.boardAdapter.requestProcessAccumulated?.());}catch(J){try{pe().setChatProcessing({cardId:e,active:!1});}catch{}p.warn(`[chat-handler] queue failed for card "${e}": ${J instanceof Error?J.message:String(J)}`);}}async function Ae(e,n,a){if(n.howToRun==="built-in"&&Ct(n)===Ot){let f=C,c=a.__chatHandlerFlow,_={...a};return delete _.__chatHandlerFlow,f?f.run(c,_,{boardId:u,cardId:String(_.cardId||""),label:e.label,logger:p,serverUrl:b$2,executionExtra:A}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return R.invoke(n,a)}async function qe(e,n=false){n||await Se();let a=typeof e.args?.cardId=="string"?e.args.cardId:"",f=a?W(a):we();if(!f)throw new Error(a?`Board context is unavailable for chat-agent request: ${a}`:"Board context is unavailable for chat-agent request");let c=await Ae(f,e.ref,e.args);if(!c.dispatched){if(a)try{F.setProcessing(a,!1);}catch{}throw new Error(c.error||`chat-agent dispatch failed for card "${a||"unknown"}"`)}}async function Te(e,n,a){let f=n==="chat-send"?B:M,c;await f(e,_=>{let N=new Date().toISOString(),K=_.card_data&&typeof _.card_data=="object"?_.card_data:{};if(_.card_data=K,n==="chat-send"){let H=a&&typeof a.text=="string"?a.text.trim():"",X=a&&typeof a["turn-id"]=="string"?a["turn-id"]:a&&typeof a.turnId=="string"?a.turnId:a&&typeof a.turn=="string"?a.turn:"",J=[];if(Array.isArray(a?.files)){for(let oe of a.files)if(oe){if(typeof oe=="string"){J.push({name:oe});continue}if(typeof oe=="object"){let de=oe;typeof de.name=="string"&&J.push({name:de.name,size:de.size,mime_type:de.mime_type,uploaded_at:de.uploaded_at,stored_name:de.stored_name,chat:de.chat===true});}}}if(H||J.length>0){let oe=T.runBatch({cardId:e,commands:[{command:"append",role:"user",text:H,files:J,turn:X},{command:"set-processing",active:true}]});if(oe.status!=="success")throw new Error(oe.error);let de=oe.data.results[0]?.data?.id;if(typeof de!="string"||!de)throw new Error(`chat-send did not return an append id for card ${e}`);c={cardId:e,lastEntryId:de,processingAlreadySet:true,turnId:X};try{let $=le(e);k.broadcastNotificationBatch([{kind:"card_chats",cardId:e,messages:$.map(D=>({role:String(D.role||"system"),text:String(D.text||""),files:Array.isArray(D.files)?D.files:[]})),receiving:!0,processing:F.isProcessing(e)}]);}catch{}}return _}if(n==="file-upload"){let H=P().normalizeIncoming(a?.files,N);return H.length>0&&P().merge(K,H),_}if(n==="action"){let H=a&&typeof a.buttonId=="string"?a.buttonId:"";if(!H)return _;K.lastAction={buttonId:H,at:N},K.lastActionText=`${H} @ ${N}`;}return _}),c&&Fe(c.cardId,c.lastEntryId,c.processingAlreadySet,c.turnId??"");}function ve(e,n,a){let f=JSON.stringify(a),c=typeof Buffer<"u"?Buffer.byteLength(f):new TextEncoder().encode(f).length;e.writeHead(n,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":c}),e.end(f);}async function Ne(e,n,a){let f=await te(e);if(!f)throw Object.assign(new Error("Card not found"),{statusCode:404});let c=P().resolve(f.card_data,n,a);if(!c.ok&&c.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!c.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let _=c.file,N=G(e),K=v(e),H=String(_.stored_name||""),X=`${N}/${H}`,J=K.files?await K.files.getBytes(X):null;if(!J)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:_,bytes:J}}async function me(e,n,a,f){let{fileRecord:c,bytes:_}=await Ne(n,a,f),N=String(c.name||c.stored_name||"download.bin"),K=String(c.mime_type||"application/octet-stream");e.writeHead(200,{"Content-Type":K,"Content-Disposition":`attachment; filename="${N}"`,"Content-Length":_.length}),e.end(_);}function ce(e){let n=String(e||"").toLowerCase();return n.startsWith("text/")||n.includes("json")||n.includes("xml")||n.includes("javascript")||n.includes("typescript")||n.includes("yaml")||n.includes("csv")}function ke(e,n,a){let f=e.split(/\r?\n/);return (n==="head"?f.slice(0,a):f.slice(-a)).join(`
|
|
7
|
+
`)}async function Mt(e){let n=[];for await(let f of e)n.push(f);let a=typeof Buffer<"u"?Buffer.concat(n).toString("utf-8").trim():new TextDecoder().decode(He(n)).trim();return a?JSON.parse(a):{}}async function jt(e){let n=[];for await(let a of e)n.push(a);return typeof Buffer<"u"?Buffer.concat(n):He(n)}async function et(e,n){let a=typeof n.ref=="string"?n.ref.trim():"";if(!a)return {status:"fail",error:"board-worker success callback requires body.ref"};let f=d$1[0];return f?f.boardOps.sourceDataFetched({params:{token:e,ref:a}}):{status:"fail",error:"no board context"}}async function tt(e,n){let a=typeof n.reason=="string"&&n.reason.trim()?n.reason:"unknown",f=d$1[0];return f?f.boardOps.sourceDataFetchFailure({params:{token:e,reason:a}}):{status:"fail",error:"no board context"}}async function Et(e,n,a){let f=String(e||"").trim();if(!f)return {statusCode:400,body:{error:"callback token is required"}};let c=n==="success"?await et(f,a):await tt(f,a);return c.status==="success"?{statusCode:200,body:c}:c.status==="fail"?{statusCode:400,body:{error:c.error}}:{statusCode:500,body:{error:c.error}}}let rt=xt({sseHub:k,corsHeaders:s,json:ve,buildPublishedRuntimePayload:()=>S(),onSseClientConnected:O,onChannelSubscribed:j$1,onChannelUnsubscribed:w}),Lt=rt.handleChannelSubscription,Dt=rt.handleSse,$t=It({apiBasePath:t,boardContexts:d$1,json:ve,readJsonBody:e=>Mt(e),readRawBody:e=>jt(e),initBoardAndSetup:()=>Se(),bootstrapBoard:()=>ee(),buildPublishedRuntimePayload:()=>S(),publishPersistedStateSnapshot:e=>ie(e),upsertCardsFromSource:(e,n)=>be(e,n),applyBoardWorkerCallback:(e,n,a)=>Et(e,n,a),handleSse:(e,n,a)=>Dt(e,n,a),handleChannelSubscription:(e,n,a,f,c)=>Lt(e,n,a,f,c),createMcpFacade:()=>pe(),createMcpToolRegistry:e=>Ee(e),createMcpControlplaneToolRegistry:()=>Le(),readCardFromStore:e=>te(e),patchCard:(e,n)=>Z(e,n),retriggerCard:e=>q(e),applyCardAction:(e,n,a)=>Te(e,n,a),resolveChatHandlerTarget:e=>$e(e),chatStorePublic:T,chatStorage:{append:(e,n,a,f,c)=>F.append(e,n,a,f,c),setProcessing:(e,n)=>F.setProcessing(e,n)},sseHub:k,uploadCardFile:(e,n,a,f,c)=>xe(e,n,a,f,c),sendCardFileDownloadResponse:(e,n,a,f)=>me(e,n,a,f),resolveCardFileDownloadPayload:(e,n,a)=>Ne(e,n,a),isLikelyTextMimeType:e=>ce(e),sliceTextByLines:(e,n,a)=>ke(e,n,a)}).handleRuntimeApi;return {get apiBasePath(){return t},get corsHeaders(){return s},get queueLaneTuning(){return o},handleRuntimeApi:$t,buildPublishedRuntimePayload:S,processAccumulatedEvents:Ve,processAccumulatedLane:x,handleChatAgentRequest:qe,clearChatRecords:Q,reportSourceFetched(e,n){return et(e,{ref:n})},reportSourceFetchFailure(e,n){return tt(e,{reason:n})},get cardStore(){return d$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function Dr(r){let t=String(r.apiBasePath||"/api/boards").replace(/\/$/,""),s={...Ft,...r.corsHeaders||{}},o=r.serverMetaStore,u=r.boardRuntimeFactory,p=new Map,R="boards-config.json";function C(){let w=o.getText(R);if(!w)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(w)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function F(w){o.putText(R,JSON.stringify(w,null,2));}function T(w){let k=String(w||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return k.length>0&&k.length<=64?k:null}function g(w){if(p.has(w))return p.get(w);let L=C().boards.find(l=>l.id===w)||{},d=u(w,L);return p.set(w,d),d}function b(w,k,L){let d=JSON.stringify(L),l=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;w.writeHead(k,{...s,"Content-Type":"application/json; charset=utf-8","Content-Length":l}),w.end(d);}async function A(w,k,L){let d=w.method||"GET",l=L.pathname;if(d==="GET"&&l===t)return b(k,200,{ok:true,boards:C().boards}),true;if(d==="POST"&&l===t){let i=[];for await(let ie of w)i.push(ie);let m=typeof Buffer<"u"?Buffer.concat(i).toString("utf-8").trim():new TextDecoder().decode(He(i)).trim(),v={};try{v=m?JSON.parse(m):{};}catch{v={};}let P=T(v.id);if(!P)return b(k,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let G=C();if(G.boards.some(ie=>ie.id===P))return b(k,409,{error:`Board "${P}" is already registered`}),true;let ue=typeof v.label=="string"&&v.label.trim()?v.label.trim():P,fe={id:P,label:ue};for(let[ie,be]of Object.entries(v))ie==="id"||ie==="label"||be!=null&&(fe[ie]=be);return G.boards.push(fe),F(G),b(k,200,{ok:true,board:fe}),true}return false}async function O(w,k,L){let l=L.pathname.match(new RegExp(`^${se(t)}/([^/]+)(/|$)`));if(!l)return false;let i=T(decodeURIComponent(l[1]));return i?C().boards.some(P=>P.id===i)?!!await g(i).handleRuntimeApi(w,k,L):(b(k,404,{error:`Board "${i}" not registered. POST ${t} with {id} to register it first.`}),true):(b(k,400,{error:"Invalid board id"}),true)}async function I(w,k,L){return !!(await A(w,k,L)||await O(w,k,L))}function j(w){if(!C().boards.some(L=>L.id===w))throw Object.assign(new Error(`Board "${w}" not registered`),{statusCode:404});return {service:g(w)}}return {get apiBasePath(){return t},get corsHeaders(){return s},handleApi:I,requireBoardService:j}}export{br as a,Lr as b,Dr as c};//# sourceMappingURL=chunk-OJLA6NLU.js.map
|
|
8
|
+
//# sourceMappingURL=chunk-OJLA6NLU.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-JMDHDY6M.js';function h(a,d){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?new Error(a.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function K(a,d){if(a?.status==="success"&&Object.prototype.hasOwnProperty.call(a,"data"))return a.data;throw a?.status==="success"?new Error(`${d} returned success without data`):a?.status==="fail"||a?.status==="error"?new Error(a.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function t(a){return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}function R(a){return Array.isArray(a)?a:[]}function V(a,d){if(typeof d!="string"||d.length===0)return;let c=a,m=d;m.startsWith("fetched_sources.")&&(c=t(a).fetched_sources,m=m.slice(16));for(let k of m.split(".")){if(c==null||typeof c!="object")return;c=c[k];}return c}function N(a,d){let c=t(a.view),m=R(c.elements);return {layout:c.layout,features:c.features,elements:m.map((k,M)=>{let v=t(k),I=t(v.data),B=typeof v.visible=="string"?!!V(d,v.visible):true,P=typeof I.bind=="string"?I.bind:void 0,U=typeof I.maxRows=="number"?I.maxRows:void 0,L=P?V(d,P):void 0,E={id:typeof v.id=="string"&&v.id?v.id:`element-${M}`,kind:v.kind,label:v.label,visible:B};return L!==void 0&&(E.resolved=Array.isArray(L)&&typeof U=="number"?L.slice(0,U):L),E})}}function W(a,d){let c=typeof a.id=="string"&&a.id?a.id:"card",m=R(a.provides),k=m.length>0?m:[{bindTo:c,ref:"card_data"}],M={};for(let v of k){let I=t(v),B=typeof I.bindTo=="string"?I.bindTo:"",P=typeof I.ref=="string"?I.ref:"";if(!B||!P)continue;let U=V(d,P);U!==void 0&&(M[B]=U);}return M}function de(a){if(typeof a!="string"||!a.trim())return null;let d=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(a.trim());if(!d)return null;let c=Number.parseInt(d[2],10);return !Number.isInteger(c)||c<0?null:c}function ce(a){return {"card-content":a}}function F(a){let{meta:d,...c}=a;return c}function ue(a,d){return Object.prototype.hasOwnProperty.call(a,d)}function J(a){return t(a.meta).__visible_controlplane_only===true}async function T(a,d){let c=await S(a.get({params:{id:d}}),"cardStore.get"),m=Array.isArray(c?.cards)?c.cards:[];if(m.length===0)throw new Error(`Card "${d}" not found`);return m[0]}function me(a$1){let{board:d,nonCore:c,cardStore:m,chatStore:k,uploadCardFile:M,buildFileDownloadUrl:v,readFetchedSourceJsonByRef:I}=a$1;function B(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let e=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function P(){let r=t(await S(c.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:r.version,commonSourceFields:t(r.commonSourceDefFields),sourceKinds:t(r.sourceKinds)}}async function U(){let r=t(await S(d.status({}),"status")),e=t(r.summary),n=R(r.cards);return {meta:t(r.meta),summary:{card_count:typeof e.card_count=="number"?e.card_count:0,completed:typeof e.completed=="number"?e.completed:0,eligible:typeof e.eligible=="number"?e.eligible:0,pending:typeof e.pending=="number"?e.pending:0,blocked:typeof e.blocked=="number"?e.blocked:0,in_progress:typeof e.in_progress=="number"?e.in_progress:0,failed:typeof e.failed=="number"?e.failed:0,unresolved:typeof e.unresolved=="number"?e.unresolved:0},cards:n.map(s=>{let o=t(s);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:R(o.requires),requires_satisfied:R(o.requires_satisfied),requires_missing:R(o.requires_missing),provides_declared:R(o.provides_declared),provides_runtime:R(o.provides_runtime)}})}}async function L(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let n=t(await S(d.status({}),"status")),o=R(n.cards).map(t).find(p=>p.name===e);if(!o)throw new Error(`card "${e}" not found in board status`);let i=t(await T(m,e));if(J(i))throw Object.assign(new Error(`card "${e}" not found`),{statusCode:404});let C=F(i),w=R(o.requires_satisfied).filter(p=>typeof p=="string"&&!!p),y=R(o.provides_runtime).filter(p=>typeof p=="string"&&!!p),f=Object.fromEntries(await Promise.all(w.map(async p=>[p,await S(d.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),g=Object.fromEntries(await Promise.all(y.map(async p=>[p,await S(d.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),l=t(await S(d.getOutputsComputedValues({params:{key:e}}),"getOutputsComputedValues")),u=await S(d.getOutputsFetchedSources({params:{key:e}}),"getOutputsFetchedSources"),_=R(i.source_defs).map(t),b={};for(let p of _)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(b[p.outputFile]=p.bindTo);let A={};for(let[p,j]of Object.entries(u)){let q=b[p]??p;if(!I||typeof j!="string"){A[q]=null;continue}try{A[q]=I({cardId:e,ref:j});}catch{A[q]=null;}}let x={card_data:t(i.card_data),requires:f,fetched_sources:A,computed_values:l};return {cardId:e,card_status_in_board:o,card_definition_and_static_data:C,refs_for_fetched_source_files:u,runtime_data:{requires:f,provides:g,computed_values:l,rendered_view:N(i,x)}}}async function E(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectChatMessagesOnCards requires cardId");let n=typeof r.turnId=="string"?r.turnId:"",s=r.allTurns===true,o=typeof r.tailTurnsBeforeId=="string"?r.tailTurnsBeforeId:"",i=s?void 0:r.lastUserTurns??(n?void 0:1),C=r.tail,w={...i===void 0?{}:{tailTurns:i},...n?{turnId:n}:{},...s?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},y=Object.keys(w).length>0?{params:{cardId:e},body:w}:{params:{cardId:e}},f=h(k.readAll(y),"chatStore.readAll"),g=t(await T(m,e)),l=R(t(g.card_data).files).map((b,A)=>({idx:A,stored_name:t(b).stored_name})).filter(b=>typeof b.stored_name=="string"&&b.stored_name.length>0),_=(Array.isArray(f.records)?f.records:[]).map(b=>{let x=t(b.payload),p={...b},j=typeof b?.role=="string"?b.role:typeof x.role=="string"?String(x.role):"",q=typeof b?.text=="string"?b.text:typeof x.text=="string"?String(x.text):"";if(j==="system"){let $=de(q);if($!==null&&l.some(O=>O.idx===$)){let O=`Retrieve using inspect-file-contents --card-id ${e} --file-idx ${$}`;p.retrieval_hint=O,Object.keys(x).length>0&&typeof b.role!="string"&&(p.payload={...x,retrieval_hint:O});}}return p});return {cardId:e,messages:typeof C=="number"&&C>=0?_.slice(-C):_}}async function H(r){let e=String(r.cardId||"").trim(),n=Number(r.fileIdx);if(!e)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(n)||n<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let s=t(await T(m,e)),o=R(t(s.card_data).files).map(t);if(n>=o.length)throw new Error(`attachment index ${n} is out of range for card "${e}"`);let i=o[n],C=typeof i.stored_name=="string"?i.stored_name:null;return {cardId:e,fileIdx:n,downloadUrl:v({cardId:e,fileIdx:n,storedName:C}),...typeof i.name=="string"?{name:i.name}:{},...typeof i.stored_name=="string"?{stored_name:i.stored_name}:{},...typeof i.mime_type=="string"?{mime_type:i.mime_type}:{},...typeof i.size=="number"?{size:i.size}:{},...typeof i.uploaded_at=="string"?{uploaded_at:i.uploaded_at}:{}}}async function D(r){return await c.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=c.evalCardCompute({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires,"mock-fetched-sources":r.mockFetchedSources}});if(e.status!=="success")return e;let n=t(K(e,"evalCardCompute")),s=t(r.candidateCardContent),o={card_data:t(s.card_data),requires:t(r.mockRequires),fetched_sources:t(r.mockFetchedSources),computed_values:t(n.computed_values)};return {status:"success",data:{cardId:typeof n.cardId=="string"?n.cardId:typeof s.id=="string"?s.id:"(unknown)",ok:n.ok===true,computed_values:t(n.computed_values),errors:R(n.errors).map(i=>{let C=t(i);return {bindTo:typeof C.bindTo=="string"?C.bindTo:"",error:typeof C.error=="string"?C.error:""}}),provides_outputs:W(s,o),rendered_view:N(s,o)}}}async function Q(r){return await c.probeSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function X(r){return await c.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function Y(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let n=t(await T(m,e)),s=R(n.source_defs).filter(i=>!!i&&typeof i=="object"&&!Array.isArray(i)),o={};if(r.sourceIdx>=0&&r.sourceIdx<s.length){let i=s[r.sourceIdx],C=a.enrichSourcesSync([i],{card_data:t(n.card_data),requires:r.mockRequires});Array.isArray(C)&&C.length>0&&(o=t(C[0]._projections));}return await c.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":n,"mock-requires":r.mockRequires,"mock-projections":o}})}async function Z(r){let e=t(await S(c.simulateCardCycle({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires}}),"simulateCardCycle")),n=t(r.candidateCardContent),s=t(e.validation),o=R(e.source_probes),i=R(e.projection_errors),C=t(e.fetched_sources),w=R(e.compute_errors),y=t(e.computed_values),f={card_data:t(n.card_data),requires:r.mockRequires,fetched_sources:C,computed_values:y},g=[];for(let l of R(s.issues))typeof l=="string"&&l&&g.push(l);for(let l of o){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"source",b=typeof u.error=="string"?u.error:"";b&&g.push(`${_}: ${b}`);}for(let l of i){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"source",b=typeof u.key=="string"?u.key:"projection",A=typeof u.error=="string"?u.error:"projection failed";g.push(`${_}.${b}: ${A}`);}for(let l of w){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"compute",b=typeof u.error=="string"?u.error:"compute failed";g.push(`${_}: ${b}`);}return {status:"success",data:{cardId:typeof e.cardId=="string"?e.cardId:"(unknown)",ok:e.ok===true,issues:g,provides_outputs:W(n,f),rendered_view:N(n,f)}}}async function ee(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get"),s=Array.isArray(n.cards)?n.cards.map(t):[];if(s.some(J))throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});return s.map(o=>F(o))}async function re(r){let e=String(r.cardId||"").trim(),n=String(r.role||"").trim(),s=typeof r.text=="string"?r.text:"",o=typeof r.turn=="string"?r.turn:"";if(!e)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!n)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(n==="assistant"&&o){let y=h(k.readAll({params:{cardId:e},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),f=Array.isArray(y.records)?y.records.find(g=>g.role==="assistant"&&String(g.turn||"")===o):void 0;if(f)return {status:"success",data:{cardId:e,id:String(f.id),role:n,turn:o,files:Array.isArray(f.files)?f.files:[]}}}let i=await Promise.all(R(r.files).map(async y=>{let f=t(y),g=String(f.file_name??f.fileName??f.name??"").trim(),l=String(f.content_type??f.contentType??"application/octet-stream");if(!g)throw new Error("file entry requires file_name");return await M({cardId:e,fileName:g,contentType:l,bytes:B(f)})})),C=i.map(y=>y.file);i.forEach((y,f)=>{let g=t(y.file),l=typeof y.file_idx=="number"&&Number.isInteger(y.file_idx)&&y.file_idx>=0?y.file_idx:f,u=n==="assistant"?`AI generated: ${String(g.name||"")} as ${String(g.stored_name||"")} #${l}`:`file uploaded: ${String(g.name||"")} as ${String(g.stored_name||"")} #${l}`;h(k.append({params:{cardId:e},body:{role:"system",text:u,files:[],turn:o}}),"chatStore.append(system attachment message)");});let w=h(k.append({params:{cardId:e},body:{role:n,text:s,files:C,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:e,id:String(w.id),role:n,turn:o,files:C}}}async function te(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("manageUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),i=t(o),C=t(i.data);if(i.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:o};let w=null;try{w=await T(m,e);}catch{w=null;}let y=w&&ue(t(w),"meta")?{...s,meta:t(w).meta}:s,f=await m.set({body:y});h(f,"cardStore.set");let g;try{g=await d.upsertCard({params:{cardId:e,restart:!0}}),h(g,"upsertCard");}catch(u){try{w&&await m.set({body:w});}catch{}throw u}let l=null;try{l=await d.cardRefreshedNotify({params:{cardId:e}}),h(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:g,refresh_notify:l}}}async function ne(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageRemoveCard requires cardId");let n=await d.removeCard({params:{id:e}});h(n,"removeCard");let s=await m.del({params:{id:e}});return h(s,"cardStore.del"),{status:"success",data:{board_result:n,store_result:s}}}async function ae(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("adminReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get");return Array.isArray(n.cards)?n.cards.map(s=>t(s)):[]}async function oe(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("adminUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),i=t(o),C=t(i.data);if(i.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:o};let w=null;try{w=await T(m,e);}catch{w=null;}let y=w?t(t(w).meta):{},f={...s,meta:{...y,__visible_controlplane_only:true}},g=await m.set({body:f});h(g,"cardStore.set");let l;try{l=await d.upsertCard({params:{cardId:e,restart:!0}}),h(l,"upsertCard");}catch(_){try{w&&await m.set({body:w});}catch{}throw _}let u=null;try{u=await d.cardRefreshedNotify({params:{cardId:e}}),h(u,"cardRefreshedNotify");}catch{u=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:l,refresh_notify:u}}}function se(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("getChatProcessing requires cardId");let n=K(k.isProcessing({params:{cardId:e}}),"chatStore.isProcessing");return {cardId:e,active:!!n.active}}function ie(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("setChatProcessing requires cardId");if(typeof r.active!="boolean")throw new Error("setChatProcessing requires boolean active");return h(k.setProcessing({params:{cardId:e},body:{active:r.active}}),"chatStore.setProcessing"),{cardId:e,active:r.active}}return {discoverSourceKinds:P,inspectBoardRuntimeStatus:U,inspectCardDefinitionAndRuntime:L,inspectChatMessagesOnCards:E,inspectFileContents:H,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:G,preflightProbeSingleSourceInCandidateCard:Q,preflightRunSingleSourceInCandidateCard:X,preflightRunSingleSourceInLiveCard:Y,preflightRunOneCycleWithCandidateCard:Z,manageReadCard:ee,manageAddChatEntryAndAnyAttachments:re,manageUpsertCard:te,manageRemoveCard:ne,adminReadCard:ae,adminUpsertCard:oe,getChatProcessing:se,setChatProcessing:ie}}async function S(a,d){return h(await a,d)}export{me as a};//# sourceMappingURL=chunk-R5L5WUKN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-R5L5WUKN.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');function h(a,d){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?new Error(a.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function K(a,d){if(a?.status==="success"&&Object.prototype.hasOwnProperty.call(a,"data"))return a.data;throw a?.status==="success"?new Error(`${d} returned success without data`):a?.status==="fail"||a?.status==="error"?new Error(a.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function t(a){return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}function R(a){return Array.isArray(a)?a:[]}function V(a,d){if(typeof d!="string"||d.length===0)return;let c=a,m=d;m.startsWith("fetched_sources.")&&(c=t(a).fetched_sources,m=m.slice(16));for(let k of m.split(".")){if(c==null||typeof c!="object")return;c=c[k];}return c}function N(a,d){let c=t(a.view),m=R(c.elements);return {layout:c.layout,features:c.features,elements:m.map((k,M)=>{let v=t(k),I=t(v.data),B=typeof v.visible=="string"?!!V(d,v.visible):true,P=typeof I.bind=="string"?I.bind:void 0,U=typeof I.maxRows=="number"?I.maxRows:void 0,L=P?V(d,P):void 0,E={id:typeof v.id=="string"&&v.id?v.id:`element-${M}`,kind:v.kind,label:v.label,visible:B};return L!==void 0&&(E.resolved=Array.isArray(L)&&typeof U=="number"?L.slice(0,U):L),E})}}function W(a,d){let c=typeof a.id=="string"&&a.id?a.id:"card",m=R(a.provides),k=m.length>0?m:[{bindTo:c,ref:"card_data"}],M={};for(let v of k){let I=t(v),B=typeof I.bindTo=="string"?I.bindTo:"",P=typeof I.ref=="string"?I.ref:"";if(!B||!P)continue;let U=V(d,P);U!==void 0&&(M[B]=U);}return M}function de(a){if(typeof a!="string"||!a.trim())return null;let d=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(a.trim());if(!d)return null;let c=Number.parseInt(d[2],10);return !Number.isInteger(c)||c<0?null:c}function ce(a){return {"card-content":a}}function F(a){let{meta:d,...c}=a;return c}function ue(a,d){return Object.prototype.hasOwnProperty.call(a,d)}function J(a){return t(a.meta).__visible_controlplane_only===true}async function T(a,d){let c=await S(a.get({params:{id:d}}),"cardStore.get"),m=Array.isArray(c?.cards)?c.cards:[];if(m.length===0)throw new Error(`Card "${d}" not found`);return m[0]}function me(a){let{board:d,nonCore:c,cardStore:m,chatStore:k,uploadCardFile:M,buildFileDownloadUrl:v,readFetchedSourceJsonByRef:I}=a;function B(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let e=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function P(){let r=t(await S(c.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:r.version,commonSourceFields:t(r.commonSourceDefFields),sourceKinds:t(r.sourceKinds)}}async function U(){let r=t(await S(d.status({}),"status")),e=t(r.summary),n=R(r.cards);return {meta:t(r.meta),summary:{card_count:typeof e.card_count=="number"?e.card_count:0,completed:typeof e.completed=="number"?e.completed:0,eligible:typeof e.eligible=="number"?e.eligible:0,pending:typeof e.pending=="number"?e.pending:0,blocked:typeof e.blocked=="number"?e.blocked:0,in_progress:typeof e.in_progress=="number"?e.in_progress:0,failed:typeof e.failed=="number"?e.failed:0,unresolved:typeof e.unresolved=="number"?e.unresolved:0},cards:n.map(s=>{let o=t(s);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:R(o.requires),requires_satisfied:R(o.requires_satisfied),requires_missing:R(o.requires_missing),provides_declared:R(o.provides_declared),provides_runtime:R(o.provides_runtime)}})}}async function L(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let n=t(await S(d.status({}),"status")),o=R(n.cards).map(t).find(p=>p.name===e);if(!o)throw new Error(`card "${e}" not found in board status`);let i=t(await T(m,e));if(J(i))throw Object.assign(new Error(`card "${e}" not found`),{statusCode:404});let C=F(i),w=R(o.requires_satisfied).filter(p=>typeof p=="string"&&!!p),y=R(o.provides_runtime).filter(p=>typeof p=="string"&&!!p),f=Object.fromEntries(await Promise.all(w.map(async p=>[p,await S(d.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),g=Object.fromEntries(await Promise.all(y.map(async p=>[p,await S(d.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),l=t(await S(d.getOutputsComputedValues({params:{key:e}}),"getOutputsComputedValues")),u=await S(d.getOutputsFetchedSources({params:{key:e}}),"getOutputsFetchedSources"),_=R(i.source_defs).map(t),b={};for(let p of _)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(b[p.outputFile]=p.bindTo);let A={};for(let[p,j]of Object.entries(u)){let q=b[p]??p;if(!I||typeof j!="string"){A[q]=null;continue}try{A[q]=I({cardId:e,ref:j});}catch{A[q]=null;}}let x={card_data:t(i.card_data),requires:f,fetched_sources:A,computed_values:l};return {cardId:e,card_status_in_board:o,card_definition_and_static_data:C,refs_for_fetched_source_files:u,runtime_data:{requires:f,provides:g,computed_values:l,rendered_view:N(i,x)}}}async function E(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectChatMessagesOnCards requires cardId");let n=typeof r.turnId=="string"?r.turnId:"",s=r.allTurns===true,o=typeof r.tailTurnsBeforeId=="string"?r.tailTurnsBeforeId:"",i=s?void 0:r.lastUserTurns??(n?void 0:1),C=r.tail,w={...i===void 0?{}:{tailTurns:i},...n?{turnId:n}:{},...s?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},y=Object.keys(w).length>0?{params:{cardId:e},body:w}:{params:{cardId:e}},f=h(k.readAll(y),"chatStore.readAll"),g=t(await T(m,e)),l=R(t(g.card_data).files).map((b,A)=>({idx:A,stored_name:t(b).stored_name})).filter(b=>typeof b.stored_name=="string"&&b.stored_name.length>0),_=(Array.isArray(f.records)?f.records:[]).map(b=>{let x=t(b.payload),p={...b},j=typeof b?.role=="string"?b.role:typeof x.role=="string"?String(x.role):"",q=typeof b?.text=="string"?b.text:typeof x.text=="string"?String(x.text):"";if(j==="system"){let $=de(q);if($!==null&&l.some(O=>O.idx===$)){let O=`Retrieve using inspect-file-contents --card-id ${e} --file-idx ${$}`;p.retrieval_hint=O,Object.keys(x).length>0&&typeof b.role!="string"&&(p.payload={...x,retrieval_hint:O});}}return p});return {cardId:e,messages:typeof C=="number"&&C>=0?_.slice(-C):_}}async function H(r){let e=String(r.cardId||"").trim(),n=Number(r.fileIdx);if(!e)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(n)||n<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let s=t(await T(m,e)),o=R(t(s.card_data).files).map(t);if(n>=o.length)throw new Error(`attachment index ${n} is out of range for card "${e}"`);let i=o[n],C=typeof i.stored_name=="string"?i.stored_name:null;return {cardId:e,fileIdx:n,downloadUrl:v({cardId:e,fileIdx:n,storedName:C}),...typeof i.name=="string"?{name:i.name}:{},...typeof i.stored_name=="string"?{stored_name:i.stored_name}:{},...typeof i.mime_type=="string"?{mime_type:i.mime_type}:{},...typeof i.size=="number"?{size:i.size}:{},...typeof i.uploaded_at=="string"?{uploaded_at:i.uploaded_at}:{}}}async function D(r){return await c.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=c.evalCardCompute({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires,"mock-fetched-sources":r.mockFetchedSources}});if(e.status!=="success")return e;let n=t(K(e,"evalCardCompute")),s=t(r.candidateCardContent),o={card_data:t(s.card_data),requires:t(r.mockRequires),fetched_sources:t(r.mockFetchedSources),computed_values:t(n.computed_values)};return {status:"success",data:{cardId:typeof n.cardId=="string"?n.cardId:typeof s.id=="string"?s.id:"(unknown)",ok:n.ok===true,computed_values:t(n.computed_values),errors:R(n.errors).map(i=>{let C=t(i);return {bindTo:typeof C.bindTo=="string"?C.bindTo:"",error:typeof C.error=="string"?C.error:""}}),provides_outputs:W(s,o),rendered_view:N(s,o)}}}async function Q(r){return await c.probeSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function X(r){return await c.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function Y(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let n=t(await T(m,e)),s=R(n.source_defs).filter(i=>!!i&&typeof i=="object"&&!Array.isArray(i)),o={};if(r.sourceIdx>=0&&r.sourceIdx<s.length){let i=s[r.sourceIdx],C=chunkIXZG74EW_cjs.a.enrichSourcesSync([i],{card_data:t(n.card_data),requires:r.mockRequires});Array.isArray(C)&&C.length>0&&(o=t(C[0]._projections));}return await c.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":n,"mock-requires":r.mockRequires,"mock-projections":o}})}async function Z(r){let e=t(await S(c.simulateCardCycle({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires}}),"simulateCardCycle")),n=t(r.candidateCardContent),s=t(e.validation),o=R(e.source_probes),i=R(e.projection_errors),C=t(e.fetched_sources),w=R(e.compute_errors),y=t(e.computed_values),f={card_data:t(n.card_data),requires:r.mockRequires,fetched_sources:C,computed_values:y},g=[];for(let l of R(s.issues))typeof l=="string"&&l&&g.push(l);for(let l of o){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"source",b=typeof u.error=="string"?u.error:"";b&&g.push(`${_}: ${b}`);}for(let l of i){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"source",b=typeof u.key=="string"?u.key:"projection",A=typeof u.error=="string"?u.error:"projection failed";g.push(`${_}.${b}: ${A}`);}for(let l of w){let u=t(l),_=typeof u.bindTo=="string"?u.bindTo:"compute",b=typeof u.error=="string"?u.error:"compute failed";g.push(`${_}: ${b}`);}return {status:"success",data:{cardId:typeof e.cardId=="string"?e.cardId:"(unknown)",ok:e.ok===true,issues:g,provides_outputs:W(n,f),rendered_view:N(n,f)}}}async function ee(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get"),s=Array.isArray(n.cards)?n.cards.map(t):[];if(s.some(J))throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});return s.map(o=>F(o))}async function re(r){let e=String(r.cardId||"").trim(),n=String(r.role||"").trim(),s=typeof r.text=="string"?r.text:"",o=typeof r.turn=="string"?r.turn:"";if(!e)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!n)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(n==="assistant"&&o){let y=h(k.readAll({params:{cardId:e},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),f=Array.isArray(y.records)?y.records.find(g=>g.role==="assistant"&&String(g.turn||"")===o):void 0;if(f)return {status:"success",data:{cardId:e,id:String(f.id),role:n,turn:o,files:Array.isArray(f.files)?f.files:[]}}}let i=await Promise.all(R(r.files).map(async y=>{let f=t(y),g=String(f.file_name??f.fileName??f.name??"").trim(),l=String(f.content_type??f.contentType??"application/octet-stream");if(!g)throw new Error("file entry requires file_name");return await M({cardId:e,fileName:g,contentType:l,bytes:B(f)})})),C=i.map(y=>y.file);i.forEach((y,f)=>{let g=t(y.file),l=typeof y.file_idx=="number"&&Number.isInteger(y.file_idx)&&y.file_idx>=0?y.file_idx:f,u=n==="assistant"?`AI generated: ${String(g.name||"")} as ${String(g.stored_name||"")} #${l}`:`file uploaded: ${String(g.name||"")} as ${String(g.stored_name||"")} #${l}`;h(k.append({params:{cardId:e},body:{role:"system",text:u,files:[],turn:o}}),"chatStore.append(system attachment message)");});let w=h(k.append({params:{cardId:e},body:{role:n,text:s,files:C,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:e,id:String(w.id),role:n,turn:o,files:C}}}async function te(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("manageUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),i=t(o),C=t(i.data);if(i.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:o};let w=null;try{w=await T(m,e);}catch{w=null;}let y=w&&ue(t(w),"meta")?{...s,meta:t(w).meta}:s,f=await m.set({body:y});h(f,"cardStore.set");let g;try{g=await d.upsertCard({params:{cardId:e,restart:!0}}),h(g,"upsertCard");}catch(u){try{w&&await m.set({body:w});}catch{}throw u}let l=null;try{l=await d.cardRefreshedNotify({params:{cardId:e}}),h(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:g,refresh_notify:l}}}async function ne(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageRemoveCard requires cardId");let n=await d.removeCard({params:{id:e}});h(n,"removeCard");let s=await m.del({params:{id:e}});return h(s,"cardStore.del"),{status:"success",data:{board_result:n,store_result:s}}}async function ae(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("adminReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get");return Array.isArray(n.cards)?n.cards.map(s=>t(s)):[]}async function oe(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("adminUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),i=t(o),C=t(i.data);if(i.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:o};let w=null;try{w=await T(m,e);}catch{w=null;}let y=w?t(t(w).meta):{},f={...s,meta:{...y,__visible_controlplane_only:true}},g=await m.set({body:f});h(g,"cardStore.set");let l;try{l=await d.upsertCard({params:{cardId:e,restart:!0}}),h(l,"upsertCard");}catch(_){try{w&&await m.set({body:w});}catch{}throw _}let u=null;try{u=await d.cardRefreshedNotify({params:{cardId:e}}),h(u,"cardRefreshedNotify");}catch{u=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:l,refresh_notify:u}}}function se(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("getChatProcessing requires cardId");let n=K(k.isProcessing({params:{cardId:e}}),"chatStore.isProcessing");return {cardId:e,active:!!n.active}}function ie(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("setChatProcessing requires cardId");if(typeof r.active!="boolean")throw new Error("setChatProcessing requires boolean active");return h(k.setProcessing({params:{cardId:e},body:{active:r.active}}),"chatStore.setProcessing"),{cardId:e,active:r.active}}return {discoverSourceKinds:P,inspectBoardRuntimeStatus:U,inspectCardDefinitionAndRuntime:L,inspectChatMessagesOnCards:E,inspectFileContents:H,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:G,preflightProbeSingleSourceInCandidateCard:Q,preflightRunSingleSourceInCandidateCard:X,preflightRunSingleSourceInLiveCard:Y,preflightRunOneCycleWithCandidateCard:Z,manageReadCard:ee,manageAddChatEntryAndAnyAttachments:re,manageUpsertCard:te,manageRemoveCard:ne,adminReadCard:ae,adminUpsertCard:oe,getChatProcessing:se,setChatProcessing:ie}}async function S(a,d){return h(await a,d)}exports.a=me;//# sourceMappingURL=chunk-YEB5QHGE.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-YEB5QHGE.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkKXWT3CY6_cjs=require('../chunk-KXWT3CY6.cjs');require('../chunk-WOALA3V5.cjs'),require('../chunk-H5HBXPOI.cjs'),require('../chunk-PBCDDO4V.cjs'),require('../chunk-OEFTOO47.cjs'),require('../chunk-U2N6MCD5.cjs'),require('../chunk-SFVO2LB2.cjs'),require('../chunk-G4XXRHL2.cjs'),require('../chunk-LODXIALE.cjs'),require('../chunk-YEB5QHGE.cjs'),require('../chunk-IXZG74EW.cjs'),require('../chunk-NMZ6XNLB.cjs'),require('../chunk-UJ7ZTV4J.cjs'),require('../chunk-YMEIPKLW.cjs'),require('../chunk-GYQXDNNI.cjs'),require('../chunk-GNFE24S7.cjs');Object.defineProperty(exports,"createHostedBoardQueueLaneRegistry",{enumerable:true,get:function(){return chunkKXWT3CY6_cjs.a}});Object.defineProperty(exports,"createMultiBoardServerRuntime",{enumerable:true,get:function(){return chunkKXWT3CY6_cjs.c}});Object.defineProperty(exports,"createSingleBoardServerRuntime",{enumerable:true,get:function(){return chunkKXWT3CY6_cjs.b}});//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as createHostedBoardQueueLaneRegistry,c as createMultiBoardServerRuntime,b as createSingleBoardServerRuntime}from'../chunk-
|
|
1
|
+
export{a as createHostedBoardQueueLaneRegistry,c as createMultiBoardServerRuntime,b as createSingleBoardServerRuntime}from'../chunk-OJLA6NLU.js';import'../chunk-MLVTJASJ.js';import'../chunk-VMW4Z6EF.js';import'../chunk-HEEDJEKM.js';import'../chunk-N6P2JW4W.js';import'../chunk-XQRNDX4Q.js';import'../chunk-BQS3EIEK.js';import'../chunk-VGT3TRQG.js';import'../chunk-WDPOGXTY.js';import'../chunk-R5L5WUKN.js';import'../chunk-JMDHDY6M.js';import'../chunk-VLBB3D6B.js';import'../chunk-MNEOJWPS.js';import'../chunk-KBELAKIY.js';import'../chunk-76ON3V7R.js';import'../chunk-FW4363Y4.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
package/lib/chunk-GJJMEAVN.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');function h(a,i){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?new Error(a.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function K(a,i){if(a?.status==="success"&&Object.prototype.hasOwnProperty.call(a,"data"))return a.data;throw a?.status==="success"?new Error(`${i} returned success without data`):a?.status==="fail"||a?.status==="error"?new Error(a.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function t(a){return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}function y(a){return Array.isArray(a)?a:[]}function V(a,i){if(typeof i!="string"||i.length===0)return;let u=a,m=i;m.startsWith("fetched_sources.")&&(u=t(a).fetched_sources,m=m.slice(16));for(let k of m.split(".")){if(u==null||typeof u!="object")return;u=u[k];}return u}function N(a,i){let u=t(a.view),m=y(u.elements);return {layout:u.layout,features:u.features,elements:m.map((k,x)=>{let v=t(k),I=t(v.data),B=typeof v.visible=="string"?!!V(i,v.visible):true,U=typeof I.bind=="string"?I.bind:void 0,M=typeof I.maxRows=="number"?I.maxRows:void 0,L=U?V(i,U):void 0,E={id:typeof v.id=="string"&&v.id?v.id:`element-${x}`,kind:v.kind,label:v.label,visible:B};return L!==void 0&&(E.resolved=Array.isArray(L)&&typeof M=="number"?L.slice(0,M):L),E})}}function W(a,i){let u=typeof a.id=="string"&&a.id?a.id:"card",m=y(a.provides),k=m.length>0?m:[{bindTo:u,ref:"card_data"}],x={};for(let v of k){let I=t(v),B=typeof I.bindTo=="string"?I.bindTo:"",U=typeof I.ref=="string"?I.ref:"";if(!B||!U)continue;let M=V(i,U);M!==void 0&&(x[B]=M);}return x}function ie(a){if(typeof a!="string"||!a.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(a.trim());if(!i)return null;let u=Number.parseInt(i[2],10);return !Number.isInteger(u)||u<0?null:u}function ce(a){return {"card-content":a}}function F(a){let{meta:i,...u}=a;return u}function ue(a,i){return Object.prototype.hasOwnProperty.call(a,i)}function J(a){return t(a.meta).__visible_controlplane_only===true}async function T(a,i){let u=await S(a.get({params:{id:i}}),"cardStore.get"),m=Array.isArray(u?.cards)?u.cards:[];if(m.length===0)throw new Error(`Card "${i}" not found`);return m[0]}function me(a){let{board:i,nonCore:u,cardStore:m,chatStore:k,uploadCardFile:x,buildFileDownloadUrl:v,readFetchedSourceJsonByRef:I}=a;function B(r){if(Array.isArray(r.bytes))return new Uint8Array(r.bytes.map(e=>Math.max(0,Math.min(255,Number(e)||0))));if(typeof r.text=="string")return new TextEncoder().encode(r.text);if(typeof r.base64=="string"){let e=String(r.base64).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function U(){let r=t(await S(u.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:r.version,commonSourceFields:t(r.commonSourceDefFields),sourceKinds:t(r.sourceKinds)}}async function M(){let r=t(await S(i.status({}),"status")),e=t(r.summary),n=y(r.cards);return {meta:t(r.meta),summary:{card_count:typeof e.card_count=="number"?e.card_count:0,completed:typeof e.completed=="number"?e.completed:0,eligible:typeof e.eligible=="number"?e.eligible:0,pending:typeof e.pending=="number"?e.pending:0,blocked:typeof e.blocked=="number"?e.blocked:0,in_progress:typeof e.in_progress=="number"?e.in_progress:0,failed:typeof e.failed=="number"?e.failed:0,unresolved:typeof e.unresolved=="number"?e.unresolved:0},cards:n.map(s=>{let o=t(s);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:y(o.requires),requires_satisfied:y(o.requires_satisfied),requires_missing:y(o.requires_missing),provides_declared:y(o.provides_declared),provides_runtime:y(o.provides_runtime)}})}}async function L(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let n=t(await S(i.status({}),"status")),o=y(n.cards).map(t).find(p=>p.name===e);if(!o)throw new Error(`card "${e}" not found in board status`);let d=t(await T(m,e));if(J(d))throw Object.assign(new Error(`card "${e}" not found`),{statusCode:404});let f=F(d),c=y(o.requires_satisfied).filter(p=>typeof p=="string"&&!!p),g=y(o.provides_runtime).filter(p=>typeof p=="string"&&!!p),b=Object.fromEntries(await Promise.all(c.map(async p=>[p,await S(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),R=Object.fromEntries(await Promise.all(g.map(async p=>[p,await S(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),C=t(await S(i.getOutputsComputedValues({params:{key:e}}),"getOutputsComputedValues")),l=await S(i.getOutputsFetchedSources({params:{key:e}}),"getOutputsFetchedSources"),_=y(d.source_defs).map(t),w={};for(let p of _)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(w[p.outputFile]=p.bindTo);let A={};for(let[p,j]of Object.entries(l)){let q=w[p]??p;if(!I||typeof j!="string"){A[q]=null;continue}try{A[q]=I({cardId:e,ref:j});}catch{A[q]=null;}}let P={card_data:t(d.card_data),requires:b,fetched_sources:A,computed_values:C};return {cardId:e,card_status_in_board:o,card_definition_and_static_data:f,refs_for_fetched_source_files:l,runtime_data:{requires:b,provides:R,computed_values:C,rendered_view:N(d,P)}}}async function E(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("inspectChatMessagesOnCards requires cardId");let n=typeof r.turnId=="string"?r.turnId:"",s=r.allTurns===true,o=typeof r.tailTurnsBeforeId=="string"?r.tailTurnsBeforeId:"",d=s?void 0:r.lastUserTurns??(n?void 0:1),f=r.tail,c={...d===void 0?{}:{tailTurns:d},...n?{turnId:n}:{},...s?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},g=Object.keys(c).length>0?{params:{cardId:e},body:c}:{params:{cardId:e}},b=h(k.readAll(g),"chatStore.readAll"),R=t(await T(m,e)),C=y(t(R.card_data).files).map((w,A)=>({idx:A,stored_name:t(w).stored_name})).filter(w=>typeof w.stored_name=="string"&&w.stored_name.length>0),_=(Array.isArray(b.records)?b.records:[]).map(w=>{let P=t(w.payload),p={...w},j=typeof w?.role=="string"?w.role:typeof P.role=="string"?String(P.role):"",q=typeof w?.text=="string"?w.text:typeof P.text=="string"?String(P.text):"";if(j==="system"){let $=ie(q);if($!==null&&C.some(O=>O.idx===$)){let O=`Retrieve using inspect-file-contents --card-id ${e} --file-idx ${$}`;p.retrieval_hint=O,Object.keys(P).length>0&&typeof w.role!="string"&&(p.payload={...P,retrieval_hint:O});}}return p});return {cardId:e,messages:typeof f=="number"&&f>=0?_.slice(-f):_}}async function H(r){let e=String(r.cardId||"").trim(),n=Number(r.fileIdx);if(!e)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(n)||n<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let s=t(await T(m,e)),o=y(t(s.card_data).files).map(t);if(n>=o.length)throw new Error(`attachment index ${n} is out of range for card "${e}"`);let d=o[n],f=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:e,fileIdx:n,downloadUrl:v({cardId:e,fileIdx:n,storedName:f}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function D(r){return await u.validateCardPreflight({body:ce(r.candidateCardContent)})}function G(r){if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!r.mockFetchedSources||typeof r.mockFetchedSources!="object"||Array.isArray(r.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let e=u.evalCardCompute({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires,"mock-fetched-sources":r.mockFetchedSources}});if(e.status!=="success")return e;let n=t(K(e,"evalCardCompute")),s=t(r.candidateCardContent),o={card_data:t(s.card_data),requires:t(r.mockRequires),fetched_sources:t(r.mockFetchedSources),computed_values:t(n.computed_values)};return {status:"success",data:{cardId:typeof n.cardId=="string"?n.cardId:typeof s.id=="string"?s.id:"(unknown)",ok:n.ok===true,computed_values:t(n.computed_values),errors:y(n.errors).map(d=>{let f=t(d);return {bindTo:typeof f.bindTo=="string"?f.bindTo:"",error:typeof f.error=="string"?f.error:""}}),provides_outputs:W(s,o),rendered_view:N(s,o)}}}async function Q(r){return await u.probeSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function X(r){return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":r.candidateCardContent,"mock-projections":r.mockProjections}})}async function Y(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!r.mockRequires||typeof r.mockRequires!="object"||Array.isArray(r.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let n=t(await T(m,e)),s=y(n.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),o={};if(r.sourceIdx>=0&&r.sourceIdx<s.length){let d=s[r.sourceIdx],f=chunkIXZG74EW_cjs.a.enrichSourcesSync([d],{card_data:t(n.card_data),requires:r.mockRequires});Array.isArray(f)&&f.length>0&&(o=t(f[0]._projections));}return await u.runSourcePreflight({params:{sourceIdx:r.sourceIdx},body:{"card-content":n,"mock-requires":r.mockRequires,"mock-projections":o}})}async function Z(r){let e=t(await S(u.simulateCardCycle({body:{"card-content":r.candidateCardContent,"mock-requires":r.mockRequires}}),"simulateCardCycle")),n=t(r.candidateCardContent),s=t(e.validation),o=y(e.source_probes),d=y(e.projection_errors),f=t(e.fetched_sources),c=y(e.compute_errors),g=t(e.computed_values),b={card_data:t(n.card_data),requires:r.mockRequires,fetched_sources:f,computed_values:g},R=[];for(let C of y(s.issues))typeof C=="string"&&C&&R.push(C);for(let C of o){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",w=typeof l.error=="string"?l.error:"";w&&R.push(`${_}: ${w}`);}for(let C of d){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"source",w=typeof l.key=="string"?l.key:"projection",A=typeof l.error=="string"?l.error:"projection failed";R.push(`${_}.${w}: ${A}`);}for(let C of c){let l=t(C),_=typeof l.bindTo=="string"?l.bindTo:"compute",w=typeof l.error=="string"?l.error:"compute failed";R.push(`${_}: ${w}`);}return {status:"success",data:{cardId:typeof e.cardId=="string"?e.cardId:"(unknown)",ok:e.ok===true,issues:R,provides_outputs:W(n,b),rendered_view:N(n,b)}}}async function ee(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get"),s=Array.isArray(n.cards)?n.cards.map(t):[];if(s.some(J))throw Object.assign(new Error(`Card "${e}" not found`),{statusCode:404});return s.map(o=>F(o))}async function re(r){let e=String(r.cardId||"").trim(),n=String(r.role||"").trim(),s=typeof r.text=="string"?r.text:"",o=typeof r.turn=="string"?r.turn:"";if(!e)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!n)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(n==="assistant"&&o){let c=h(k.readAll({params:{cardId:e},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),g=Array.isArray(c.records)?c.records.find(b=>b.role==="assistant"&&String(b.turn||"")===o):void 0;if(g)return {status:"success",data:{cardId:e,id:String(g.id),role:n,turn:o,files:Array.isArray(g.files)?g.files:[]}}}let d=await Promise.all(y(r.files).map(async c=>{let g=t(c),b=String(g.file_name??g.fileName??g.name??"").trim(),R=String(g.content_type??g.contentType??"application/octet-stream");if(!b)throw new Error("file entry requires file_name");return (await x({cardId:e,fileName:b,contentType:R,bytes:B(g)})).file}));d.forEach((c,g)=>{let b=n==="assistant"?`AI generated: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`:`file uploaded: ${String(c.name||"")} as ${String(c.stored_name||"")} #${g}`;h(k.append({params:{cardId:e},body:{role:"system",text:b,files:[],turn:o}}),"chatStore.append(system attachment message)");});let f=h(k.append({params:{cardId:e},body:{role:n,text:s,files:d,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:e,id:String(f.id),role:n,turn:o,files:d}}}async function te(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("manageUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),d=t(o),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let c=null;try{c=await T(m,e);}catch{c=null;}let g=c&&ue(t(c),"meta")?{...s,meta:t(c).meta}:s,b=await m.set({body:g});h(b,"cardStore.set");let R;try{R=await i.upsertCard({params:{cardId:e,restart:!0}}),h(R,"upsertCard");}catch(l){try{c&&await m.set({body:c});}catch{}throw l}let C=null;try{C=await i.cardRefreshedNotify({params:{cardId:e}}),h(C,"cardRefreshedNotify");}catch{C=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:R,refresh_notify:C}}}async function ne(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("manageRemoveCard requires cardId");let n=await i.removeCard({params:{id:e}});h(n,"removeCard");let s=await m.del({params:{id:e}});return h(s,"cardStore.del"),{status:"success",data:{board_result:n,store_result:s}}}async function ae(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("adminReadCard requires cardId");let n=await S(m.get({params:{id:e}}),"cardStore.get");return Array.isArray(n.cards)?n.cards.map(s=>t(s)):[]}async function oe(r){let e=String(r.cardId||"").trim(),n=t(r.candidateCardContent),s=F(n);if(!e)throw new Error("adminUpsertCard requires cardId");if(typeof s.id!="string"||!s.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(s.id!==e)throw new Error(`candidateCardContent.id must match cardId (${e})`);let o=await D({candidateCardContent:s}),d=t(o),f=t(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let c=null;try{c=await T(m,e);}catch{c=null;}let g=c?t(t(c).meta):{},b={...s,meta:{...g,__visible_controlplane_only:true}},R=await m.set({body:b});h(R,"cardStore.set");let C;try{C=await i.upsertCard({params:{cardId:e,restart:!0}}),h(C,"upsertCard");}catch(_){try{c&&await m.set({body:c});}catch{}throw _}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:e}}),h(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:C,refresh_notify:l}}}function se(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("getChatProcessing requires cardId");let n=K(k.isProcessing({params:{cardId:e}}),"chatStore.isProcessing");return {cardId:e,active:!!n.active}}function de(r){let e=String(r.cardId||"").trim();if(!e)throw new Error("setChatProcessing requires cardId");if(typeof r.active!="boolean")throw new Error("setChatProcessing requires boolean active");return h(k.setProcessing({params:{cardId:e},body:{active:r.active}}),"chatStore.setProcessing"),{cardId:e,active:r.active}}return {discoverSourceKinds:U,inspectBoardRuntimeStatus:M,inspectCardDefinitionAndRuntime:L,inspectChatMessagesOnCards:E,inspectFileContents:H,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:G,preflightProbeSingleSourceInCandidateCard:Q,preflightRunSingleSourceInCandidateCard:X,preflightRunSingleSourceInLiveCard:Y,preflightRunOneCycleWithCandidateCard:Z,manageReadCard:ee,manageAddChatEntryAndAnyAttachments:re,manageUpsertCard:te,manageRemoveCard:ne,adminReadCard:ae,adminUpsertCard:oe,getChatProcessing:se,setChatProcessing:de}}async function S(a,i){return h(await a,i)}exports.a=me;//# sourceMappingURL=chunk-GJJMEAVN.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-GJJMEAVN.cjs.map
|