yaml-flow 8.11.3 → 8.11.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.
Files changed (51) hide show
  1. package/browser/asset-integrity.json +3 -3
  2. package/browser/server-runtime-controlface.js +4 -4
  3. package/examples/board/test/server-http-test-browser.ts +1 -1
  4. package/examples/board/test/server-http-test.js +1 -1
  5. package/lib/board-live-cards-node.d.cts +2 -2
  6. package/lib/board-live-cards-node.d.ts +2 -2
  7. package/lib/board-live-cards-server-runtime.cjs +1 -1
  8. package/lib/board-live-cards-server-runtime.d.cts +1 -1
  9. package/lib/board-live-cards-server-runtime.d.ts +1 -1
  10. package/lib/board-live-cards-server-runtime.js +1 -1
  11. package/lib/board-livegraph-runtime/index.cjs +1 -1
  12. package/lib/board-livegraph-runtime/index.d.cts +1 -0
  13. package/lib/board-livegraph-runtime/index.d.ts +1 -0
  14. package/lib/board-livegraph-runtime/index.js +1 -1
  15. package/lib/chunk-37JSBRZO.js +2 -0
  16. package/lib/{chunk-ZCU5O2LR.js → chunk-4BEQXKRF.js} +2 -2
  17. package/lib/chunk-LRO5AL75.cjs +2 -0
  18. package/lib/chunk-MQAVZUXB.cjs +3 -0
  19. package/lib/chunk-WHKT5HN4.js +3 -0
  20. package/lib/{chunk-FFHG3CFU.cjs → chunk-Z26U6RSG.cjs} +2 -2
  21. package/lib/index.cjs +2 -2
  22. package/lib/index.js +1 -1
  23. package/lib/server-jobs-queue-runner/index.d.cts +1 -1
  24. package/lib/server-jobs-queue-runner/index.d.ts +1 -1
  25. package/lib/server-runtime/index.cjs +1 -1
  26. package/lib/server-runtime/index.d.cts +2 -2
  27. package/lib/server-runtime/index.d.ts +2 -2
  28. package/lib/server-runtime/index.js +1 -1
  29. package/lib/server-runtime-agentface/index.d.cts +1 -1
  30. package/lib/server-runtime-agentface/index.d.ts +1 -1
  31. package/lib/server-runtime-controlface/index.cjs +1 -1
  32. package/lib/server-runtime-controlface/index.d.cts +1 -1
  33. package/lib/server-runtime-controlface/index.d.ts +1 -1
  34. package/lib/server-runtime-controlface/index.js +1 -1
  35. package/lib/server-runtime-core/index.cjs +1 -1
  36. package/lib/server-runtime-core/index.d.cts +7 -4
  37. package/lib/server-runtime-core/index.d.ts +7 -4
  38. package/lib/server-runtime-core/index.js +1 -1
  39. package/lib/server-runtime-watchers/index.d.cts +3 -3
  40. package/lib/server-runtime-watchers/index.d.ts +3 -3
  41. package/lib/server-runtime-webhooks/index.d.cts +1 -1
  42. package/lib/server-runtime-webhooks/index.d.ts +1 -1
  43. package/lib/{sse-hub-D_94fV87.d.ts → sse-hub-D_QHswxL.d.ts} +1 -1
  44. package/lib/{sse-hub-BRBvymHR.d.cts → sse-hub-XO6crN9o.d.cts} +1 -1
  45. package/lib/{types-BsqzUZNl.d.ts → types-B8Yieskx.d.ts} +2 -0
  46. package/lib/{types-DxhB6Toz.d.cts → types-gTf9pAyC.d.cts} +2 -0
  47. package/package.json +1 -1
  48. package/lib/chunk-CZ6ZFWFT.js +0 -2
  49. package/lib/chunk-NMOUBZXX.cjs +0 -2
  50. package/lib/chunk-SEUSFOMM.js +0 -3
  51. package/lib/chunk-YQ4MW72D.cjs +0 -3
@@ -1582,7 +1582,7 @@ try {
1582
1582
  console.log('[T3c] ok: fresh /sse first payload hydrated the current board state');
1583
1583
 
1584
1584
  console.log('\n=== TS: one-shot, raw framing, replay, delta ordering, and chat hydration ===');
1585
- const tsExpectedChatRes = await httpMcp('inspect.chat-messages-on-cards', { card_id: CHAT_CARD_ID, all_turns: true });
1585
+ const tsExpectedChatRes = await httpMcp('inspect.chat-messages-on-cards', { card_id: CHAT_CARD_ID, tail_turns: 1 });
1586
1586
  assert(tsExpectedChatRes.status === 200, `TS inspect.chat-messages-on-cards returned ${tsExpectedChatRes.status}`);
1587
1587
  const tsExpectedChatMessages = normalizeHydratedChatMessages(tsExpectedChatRes.data?.data?.messages || []);
1588
1588
 
@@ -1488,7 +1488,7 @@ try {
1488
1488
  console.log('[T3c] ok: fresh /sse first payload hydrated the current board state');
1489
1489
 
1490
1490
  console.log('\n=== TS: one-shot, raw framing, replay, delta ordering, and chat hydration ===');
1491
- const tsExpectedChatRes = await httpMcp('inspect.chat-messages-on-cards', { card_id: CHAT_CARD_ID, all_turns: true });
1491
+ const tsExpectedChatRes = await httpMcp('inspect.chat-messages-on-cards', { card_id: CHAT_CARD_ID, tail_turns: 1 });
1492
1492
  assert(tsExpectedChatRes.status === 200, `TS inspect.chat-messages-on-cards returned ${tsExpectedChatRes.status}`);
1493
1493
  const tsExpectedChatMessages = normalizeHydratedChatMessages(tsExpectedChatRes.data?.data?.messages || []);
1494
1494
 
@@ -2,8 +2,8 @@ import { a as ArtifactsStore } from './artifacts-store-lib-CqkJEgbx.cjs';
2
2
  export { c as createArtifactsStore, b as createCardFileMetadataStore, d as createFileArtifactsStore } from './artifacts-store-lib-CqkJEgbx.cjs';
3
3
  import { ExecutionRef, ArgsMassaging } from './execution-refs.cjs';
4
4
  export { executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef } from './execution-refs.cjs';
5
- import { c as BoardRuntimeNonCorePublic, i as BoardWorkerStore, f as BoardWorkerRequest, I as InvocationAdapter } from './types-DxhB6Toz.cjs';
6
- export { j as BoardWorkerDeadLetterRequest, k as BoardWorkerLeasedRequest, l as BoardWorkerQueuedRequest, D as DescribeEnvelope, m as createBoardWorkerStore } from './types-DxhB6Toz.cjs';
5
+ import { c as BoardRuntimeNonCorePublic, i as BoardWorkerStore, f as BoardWorkerRequest, I as InvocationAdapter } from './types-gTf9pAyC.cjs';
6
+ export { j as BoardWorkerDeadLetterRequest, k as BoardWorkerLeasedRequest, l as BoardWorkerQueuedRequest, D as DescribeEnvelope, m as createBoardWorkerStore } from './types-gTf9pAyC.cjs';
7
7
  import { a as KindValueRef, B as BlobStorage, Q as QueueStorage } from './storage-interface-DogVPooM.cjs';
8
8
  export { p as parseRef, s as serializeRef } from './storage-interface-DogVPooM.cjs';
9
9
  import { C as ChatStorage, B as BoardCallbackTransport } from './board-callback-transport-kP0K6UMq.cjs';
@@ -2,8 +2,8 @@ import { a as ArtifactsStore } from './artifacts-store-lib-D6Bo4yFN.js';
2
2
  export { c as createArtifactsStore, b as createCardFileMetadataStore, d as createFileArtifactsStore } from './artifacts-store-lib-D6Bo4yFN.js';
3
3
  import { ExecutionRef, ArgsMassaging } from './execution-refs.js';
4
4
  export { executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef } from './execution-refs.js';
5
- import { c as BoardRuntimeNonCorePublic, i as BoardWorkerStore, f as BoardWorkerRequest, I as InvocationAdapter } from './types-BsqzUZNl.js';
6
- export { j as BoardWorkerDeadLetterRequest, k as BoardWorkerLeasedRequest, l as BoardWorkerQueuedRequest, D as DescribeEnvelope, m as createBoardWorkerStore } from './types-BsqzUZNl.js';
5
+ import { c as BoardRuntimeNonCorePublic, i as BoardWorkerStore, f as BoardWorkerRequest, I as InvocationAdapter } from './types-B8Yieskx.js';
6
+ export { j as BoardWorkerDeadLetterRequest, k as BoardWorkerLeasedRequest, l as BoardWorkerQueuedRequest, D as DescribeEnvelope, m as createBoardWorkerStore } from './types-B8Yieskx.js';
7
7
  import { a as KindValueRef, B as BlobStorage, Q as QueueStorage } from './storage-interface-DogVPooM.js';
8
8
  export { p as parseRef, s as serializeRef } from './storage-interface-DogVPooM.js';
9
9
  import { C as ChatStorage, B as BoardCallbackTransport } from './board-callback-transport-Bekq8Gp-.js';
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkYQ4MW72D_cjs=require('./chunk-YQ4MW72D.cjs');require('./chunk-LFVMX23W.cjs'),require('./chunk-NM6O35RY.cjs'),require('./chunk-NBJTYAYN.cjs'),require('./chunk-NMOUBZXX.cjs');var chunkBQJVCCFU_cjs=require('./chunk-BQJVCCFU.cjs');require('./chunk-BQUQTOPB.cjs'),require('./chunk-GPCMBPLK.cjs'),require('./chunk-7FGPOGRV.cjs'),require('./chunk-LPXVVMQT.cjs'),require('./chunk-272IYUKT.cjs'),require('./chunk-HVLWVMG6.cjs'),require('./chunk-WRMOGPRG.cjs'),require('./chunk-BAG7MHZP.cjs'),require('./chunk-7JVHYHT2.cjs'),require('./chunk-VQCIOKJV.cjs'),require('./chunk-G4XXRHL2.cjs'),require('./chunk-LODXIALE.cjs'),require('./chunk-GHUW6P4G.cjs'),require('./chunk-QBEQL4TL.cjs'),require('./chunk-QEHKMLHA.cjs'),require('./chunk-UJ7ZTV4J.cjs'),require('./chunk-5XLFPPTY.cjs'),require('./chunk-SDJ3747Q.cjs'),require('./chunk-OF4FPYNI.cjs'),require('./chunk-2RIHC5TZ.cjs'),require('./chunk-GNFE24S7.cjs');Object.defineProperty(exports,"createMultiBoardServerRuntime",{enumerable:true,get:function(){return chunkYQ4MW72D_cjs.b}});Object.defineProperty(exports,"createSingleBoardServerRuntime",{enumerable:true,get:function(){return chunkYQ4MW72D_cjs.a}});Object.defineProperty(exports,"createHostedBoardQueueLaneRegistry",{enumerable:true,get:function(){return chunkBQJVCCFU_cjs.a}});//# sourceMappingURL=board-live-cards-server-runtime.cjs.map
1
+ 'use strict';var chunkMQAVZUXB_cjs=require('./chunk-MQAVZUXB.cjs');require('./chunk-LFVMX23W.cjs'),require('./chunk-NM6O35RY.cjs'),require('./chunk-NBJTYAYN.cjs'),require('./chunk-LRO5AL75.cjs');var chunkBQJVCCFU_cjs=require('./chunk-BQJVCCFU.cjs');require('./chunk-BQUQTOPB.cjs'),require('./chunk-GPCMBPLK.cjs'),require('./chunk-7FGPOGRV.cjs'),require('./chunk-LPXVVMQT.cjs'),require('./chunk-272IYUKT.cjs'),require('./chunk-HVLWVMG6.cjs'),require('./chunk-WRMOGPRG.cjs'),require('./chunk-BAG7MHZP.cjs'),require('./chunk-7JVHYHT2.cjs'),require('./chunk-VQCIOKJV.cjs'),require('./chunk-G4XXRHL2.cjs'),require('./chunk-LODXIALE.cjs'),require('./chunk-GHUW6P4G.cjs'),require('./chunk-QBEQL4TL.cjs'),require('./chunk-QEHKMLHA.cjs'),require('./chunk-UJ7ZTV4J.cjs'),require('./chunk-5XLFPPTY.cjs'),require('./chunk-SDJ3747Q.cjs'),require('./chunk-OF4FPYNI.cjs'),require('./chunk-2RIHC5TZ.cjs'),require('./chunk-GNFE24S7.cjs');Object.defineProperty(exports,"createMultiBoardServerRuntime",{enumerable:true,get:function(){return chunkMQAVZUXB_cjs.b}});Object.defineProperty(exports,"createSingleBoardServerRuntime",{enumerable:true,get:function(){return chunkMQAVZUXB_cjs.a}});Object.defineProperty(exports,"createHostedBoardQueueLaneRegistry",{enumerable:true,get:function(){return chunkBQJVCCFU_cjs.a}});//# sourceMappingURL=board-live-cards-server-runtime.cjs.map
2
2
  //# sourceMappingURL=board-live-cards-server-runtime.cjs.map
@@ -1,4 +1,4 @@
1
- export { A as Awaitable, B as BoardContextConfig, c as BoardRuntimeNonCorePublic, d as BoardRuntimePlatformAdapter, e as BoardRuntimePublic, f as BoardWorkerRequest, C as ChatHandlerFlowRunner, D as DescribeEnvelope, H as HostedBoardQueueLaneTuning, I as InvocationAdapter, a as MultiBoardRuntime, M as MultiBoardRuntimeOptions, N as NotificationTransport, Q as QueueLaneRuntimeTuning, R as RuntimeLogger, g as RuntimeRequest, h as RuntimeResponse, b as SingleBoardRuntime, S as SingleBoardRuntimeOptions } from './types-DxhB6Toz.cjs';
1
+ export { A as Awaitable, B as BoardContextConfig, c as BoardRuntimeNonCorePublic, d as BoardRuntimePlatformAdapter, e as BoardRuntimePublic, f as BoardWorkerRequest, C as ChatHandlerFlowRunner, D as DescribeEnvelope, H as HostedBoardQueueLaneTuning, I as InvocationAdapter, a as MultiBoardRuntime, M as MultiBoardRuntimeOptions, N as NotificationTransport, Q as QueueLaneRuntimeTuning, R as RuntimeLogger, g as RuntimeRequest, h as RuntimeResponse, b as SingleBoardRuntime, S as SingleBoardRuntimeOptions } from './types-gTf9pAyC.cjs';
2
2
  export { HostedBoardQueueLaneRegistryOptions, createHostedBoardQueueLaneRegistry } from './server-jobs-queue-runner/index.cjs';
3
3
  export { A as AsyncBoardLiveCardsPublic } from './board-live-cards-public-async-Cl0M3j5P.cjs';
4
4
  export { A as AsyncBoardPlatformAdapter } from './board-platform-adapter-async-DjBwE0m9.cjs';
@@ -1,4 +1,4 @@
1
- export { A as Awaitable, B as BoardContextConfig, c as BoardRuntimeNonCorePublic, d as BoardRuntimePlatformAdapter, e as BoardRuntimePublic, f as BoardWorkerRequest, C as ChatHandlerFlowRunner, D as DescribeEnvelope, H as HostedBoardQueueLaneTuning, I as InvocationAdapter, a as MultiBoardRuntime, M as MultiBoardRuntimeOptions, N as NotificationTransport, Q as QueueLaneRuntimeTuning, R as RuntimeLogger, g as RuntimeRequest, h as RuntimeResponse, b as SingleBoardRuntime, S as SingleBoardRuntimeOptions } from './types-BsqzUZNl.js';
1
+ export { A as Awaitable, B as BoardContextConfig, c as BoardRuntimeNonCorePublic, d as BoardRuntimePlatformAdapter, e as BoardRuntimePublic, f as BoardWorkerRequest, C as ChatHandlerFlowRunner, D as DescribeEnvelope, H as HostedBoardQueueLaneTuning, I as InvocationAdapter, a as MultiBoardRuntime, M as MultiBoardRuntimeOptions, N as NotificationTransport, Q as QueueLaneRuntimeTuning, R as RuntimeLogger, g as RuntimeRequest, h as RuntimeResponse, b as SingleBoardRuntime, S as SingleBoardRuntimeOptions } from './types-B8Yieskx.js';
2
2
  export { HostedBoardQueueLaneRegistryOptions, createHostedBoardQueueLaneRegistry } from './server-jobs-queue-runner/index.js';
3
3
  export { A as AsyncBoardLiveCardsPublic } from './board-live-cards-public-async-U98IXUBx.js';
4
4
  export { A as AsyncBoardPlatformAdapter } from './board-platform-adapter-async-ByBRFn1G.js';
@@ -1,2 +1,2 @@
1
- export{b as createMultiBoardServerRuntime,a as createSingleBoardServerRuntime}from'./chunk-SEUSFOMM.js';import'./chunk-JB4Q2W7I.js';import'./chunk-XYN5D3GL.js';import'./chunk-O5UYCGIN.js';import'./chunk-CZ6ZFWFT.js';export{a as createHostedBoardQueueLaneRegistry}from'./chunk-7UJQMFVS.js';import'./chunk-FOFGEABN.js';import'./chunk-RKKSVOP2.js';import'./chunk-NTICU4OK.js';import'./chunk-O7NOHKVR.js';import'./chunk-ZJ5M5COT.js';import'./chunk-5VTIOM2U.js';import'./chunk-6MD6FVE3.js';import'./chunk-EZOXABJ2.js';import'./chunk-ANKA7HEJ.js';import'./chunk-44L64VQ2.js';import'./chunk-VGT3TRQG.js';import'./chunk-WDPOGXTY.js';import'./chunk-6M3RIGUH.js';import'./chunk-ATOQP3BD.js';import'./chunk-YT76JNKE.js';import'./chunk-MNEOJWPS.js';import'./chunk-7QNEV5S3.js';import'./chunk-BJGK5FNL.js';import'./chunk-NIBLKYXN.js';import'./chunk-UGB7PC4P.js';import'./chunk-FW4363Y4.js';//# sourceMappingURL=board-live-cards-server-runtime.js.map
1
+ export{b as createMultiBoardServerRuntime,a as createSingleBoardServerRuntime}from'./chunk-WHKT5HN4.js';import'./chunk-JB4Q2W7I.js';import'./chunk-XYN5D3GL.js';import'./chunk-O5UYCGIN.js';import'./chunk-37JSBRZO.js';export{a as createHostedBoardQueueLaneRegistry}from'./chunk-7UJQMFVS.js';import'./chunk-FOFGEABN.js';import'./chunk-RKKSVOP2.js';import'./chunk-NTICU4OK.js';import'./chunk-O7NOHKVR.js';import'./chunk-ZJ5M5COT.js';import'./chunk-5VTIOM2U.js';import'./chunk-6MD6FVE3.js';import'./chunk-EZOXABJ2.js';import'./chunk-ANKA7HEJ.js';import'./chunk-44L64VQ2.js';import'./chunk-VGT3TRQG.js';import'./chunk-WDPOGXTY.js';import'./chunk-6M3RIGUH.js';import'./chunk-ATOQP3BD.js';import'./chunk-YT76JNKE.js';import'./chunk-MNEOJWPS.js';import'./chunk-7QNEV5S3.js';import'./chunk-BJGK5FNL.js';import'./chunk-NIBLKYXN.js';import'./chunk-UGB7PC4P.js';import'./chunk-FW4363Y4.js';//# sourceMappingURL=board-live-cards-server-runtime.js.map
2
2
  //# sourceMappingURL=board-live-cards-server-runtime.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkFFHG3CFU_cjs=require('../chunk-FFHG3CFU.cjs');require('../chunk-G4XXRHL2.cjs'),require('../chunk-LODXIALE.cjs'),require('../chunk-QBEQL4TL.cjs'),require('../chunk-QEHKMLHA.cjs'),require('../chunk-UJ7ZTV4J.cjs'),require('../chunk-GNFE24S7.cjs');Object.defineProperty(exports,"LocalStorageService",{enumerable:true,get:function(){return chunkFFHG3CFU_cjs.a}});Object.defineProperty(exports,"buildBrowserArtifactsFromRuntime",{enumerable:true,get:function(){return chunkFFHG3CFU_cjs.e}});Object.defineProperty(exports,"createBoardLiveGraphRuntime",{enumerable:true,get:function(){return chunkFFHG3CFU_cjs.b}});Object.defineProperty(exports,"selectAllLiveCardModels",{enumerable:true,get:function(){return chunkFFHG3CFU_cjs.d}});Object.defineProperty(exports,"selectLiveCardModel",{enumerable:true,get:function(){return chunkFFHG3CFU_cjs.c}});//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunkZ26U6RSG_cjs=require('../chunk-Z26U6RSG.cjs');require('../chunk-G4XXRHL2.cjs'),require('../chunk-LODXIALE.cjs'),require('../chunk-QBEQL4TL.cjs'),require('../chunk-QEHKMLHA.cjs'),require('../chunk-UJ7ZTV4J.cjs'),require('../chunk-GNFE24S7.cjs');Object.defineProperty(exports,"LocalStorageService",{enumerable:true,get:function(){return chunkZ26U6RSG_cjs.a}});Object.defineProperty(exports,"buildBrowserArtifactsFromRuntime",{enumerable:true,get:function(){return chunkZ26U6RSG_cjs.e}});Object.defineProperty(exports,"createBoardLiveGraphRuntime",{enumerable:true,get:function(){return chunkZ26U6RSG_cjs.b}});Object.defineProperty(exports,"selectAllLiveCardModels",{enumerable:true,get:function(){return chunkZ26U6RSG_cjs.d}});Object.defineProperty(exports,"selectLiveCardModel",{enumerable:true,get:function(){return chunkZ26U6RSG_cjs.c}});//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -121,6 +121,7 @@ interface BoardRuntimeArtifactsPayload {
121
121
  role: string;
122
122
  text: string;
123
123
  files?: unknown[];
124
+ turn?: string;
124
125
  }>;
125
126
  receiving?: boolean;
126
127
  processing?: boolean;
@@ -121,6 +121,7 @@ interface BoardRuntimeArtifactsPayload {
121
121
  role: string;
122
122
  text: string;
123
123
  files?: unknown[];
124
+ turn?: string;
124
125
  }>;
125
126
  receiving?: boolean;
126
127
  processing?: boolean;
@@ -1,2 +1,2 @@
1
- export{a as LocalStorageService,e as buildBrowserArtifactsFromRuntime,b as createBoardLiveGraphRuntime,d as selectAllLiveCardModels,c as selectLiveCardModel}from'../chunk-ZCU5O2LR.js';import'../chunk-VGT3TRQG.js';import'../chunk-WDPOGXTY.js';import'../chunk-ATOQP3BD.js';import'../chunk-YT76JNKE.js';import'../chunk-MNEOJWPS.js';import'../chunk-FW4363Y4.js';//# sourceMappingURL=index.js.map
1
+ export{a as LocalStorageService,e as buildBrowserArtifactsFromRuntime,b as createBoardLiveGraphRuntime,d as selectAllLiveCardModels,c as selectLiveCardModel}from'../chunk-4BEQXKRF.js';import'../chunk-VGT3TRQG.js';import'../chunk-WDPOGXTY.js';import'../chunk-ATOQP3BD.js';import'../chunk-YT76JNKE.js';import'../chunk-MNEOJWPS.js';import'../chunk-FW4363Y4.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import {a as a$1}from'./chunk-FOFGEABN.js';import {a,c,d,e,b,f}from'./chunk-O7NOHKVR.js';import {b as b$1}from'./chunk-44L64VQ2.js';import {a as a$2}from'./chunk-6M3RIGUH.js';function M(a){if(!a||typeof a!="object")return false;let t=a;return typeof t.kind=="string"&&t.kind.length>0}function J(a){if(!a||typeof a!="object")return [];let t=a;return t.kind==="notification-batch"?Array.isArray(t.notifications)?t.notifications.filter(M):[]:M(a)?[a]:[]}function X(a,t,i){let c=0;return {accepted:a.filter(_=>{if(!M(_))return c++,false;let S=_;return typeof S.sentAtMs=="number"&&t-S.sentAtMs>i?(c++,false):true}),rejected:c}}function Q(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function z(a){if(!a||typeof a!="object")return false;let t=a.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function W(a){if(!a||typeof a!="object")return false;let t=a;return t.kind==="notification-batch"&&Array.isArray(t.notifications)}function V(a,t){if(t.kind==="status"){z(t.status)&&(a.status=t.status);return}if(t.kind==="computed_values"){a.computedValues[t.cardId]=t.values;return}if(t.kind==="data_object"){a.dataObjects[t.key]=t.payload;return}if(t.kind==="card_refreshed"){a.cards[t.cardId]=t.card;return}t.kind==="card_removed"&&(delete a.cards[t.cardId],delete a.computedValues[t.cardId]);}function Y(a,t){if(W(t)){for(let i of t.notifications)M(i)&&V(a,i);return}M(t)&&V(a,t);}function j(a,t){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?Object.assign(new Error(a.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function N(a,t){return j(await a,t)}function T(a$1){let t=a(a$1,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let i=t.split(".");if(!(i.length>=2&&i.every(g=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(g))))throw Object.assign(new Error("MCP tool requires a card private key with at least two identifier segments (e.g. chat.foundry_thread_id)"),{statusCode:400});return t}function q(a,t){let i=a.__private;for(let c of t.split(".")){if(!i||typeof i!="object"||Array.isArray(i)||!Object.prototype.hasOwnProperty.call(i,c))return {exists:false,value:null};i=i[c];}return {exists:true,value:i}}function ot(a$1){let{boardId:t,bootstrapBoard:i,sseHub:c,onChannelSubscribed:g,onChannelUnsubscribed:_,getMcpFacade:S,getMcpCardStoreFacade:n}=a$1;function f(s){let d=a(s,"board_id");if(!d)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(d!==t)throw Object.assign(new Error(`Unknown board_id: ${d}`),{statusCode:400})}function h(s){let d=a(s,"client_id");if(!d)throw Object.assign(new Error("MCP tool requires client_id"),{statusCode:400});return d}function w(s){f(s);let d=h(s),e=a(s,"channel_name"),r=a(s,"card_id")||void 0;if(!e)throw Object.assign(new Error("MCP tool requires channel_name"),{statusCode:400});return {clientId:d,channelName:e,...r?{cardId:r}:{}}}function R(s){f(s);let d=a(s,"card_id");if(!d)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});return {cardId:d}}async function I(s){await i();let{cardId:d}=R(s),e=h(s);if(!await c.subscribeChat(e,d))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return {status:"success",data:{boardId:t,cardId:d,clientId:e,subscribed:true}}}async function u(s){await i();let{cardId:d}=R(s),e=h(s);if(!c.unsubscribeChat(e,d))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return {status:"success",data:{boardId:t,cardId:d,clientId:e,subscribed:false}}}async function b(s,d){await i();let{clientId:e,channelName:r,cardId:o}=w(s);if(!c.has(e))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return d?(c.subscribeChannel(e,r,o),g?.(e,r,o?{cardId:o}:{})):(c.unsubscribeChannel(e,r,o),_?.(e,r,o?{cardId:o}:{})),{status:"success",data:{boardId:t,clientId:e,channelName:r,subscribed:d,...o?{cardId:o}:{}}}}async function m(s,d){let{cardId:e}=R(s);return await S().setChatProcessing({cardId:e,active:d}),{status:"success",data:{boardId:t,cardId:e,active:d}}}async function p(s){let{cardId:d}=R(s),e=await S().getChatProcessing({cardId:d});return {status:"success",data:{boardId:t,cardId:d,active:e.active}}}async function y(s){let{cardId:d}=R(s),e=T(s);if(!Object.prototype.hasOwnProperty.call(s,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(e.split(".").includes("visible_controlplane_only")){let r=await N(n().get({params:{id:d}}),"cardStore.get"),o=Array.isArray(r.cards)&&r.cards.length>0&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null,k=o?q(o,"visible_controlplane_only").value:void 0;if(s.value!==k)throw Object.assign(new Error("MCP tool cannot change the reserved private flag visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:d,key:e}}}return j(await n().patch({params:{id:d,path:`__private.${e}`},body:{value:s.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:d,key:e}}}async function C(s){let{cardId:d}=R(s),e=T(s),r=await N(n().get({params:{id:d}}),"cardStore.get"),o=Array.isArray(r.cards)&&r.cards.length>0&&r.cards[0]&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null;if(!o)throw Object.assign(new Error(`Card "${d}" not found`),{statusCode:404});let k=q(o,e);return {status:"success",data:{boardId:t,cardId:d,key:e,exists:k.exists,value:k.value}}}return {requireCardArgs:R,subscribeChat:I,unsubscribeChat:u,watchChannel:b,setChatProcessing:m,getChatProcessing:p,setCardMeta:y,getCardMeta:C}}function it(a){let{boardId:t,boardContexts:i,readChatRecords:c,getChatProcessing:g}=a,_=Number.isInteger(a.chatBootstrapTailTurns)&&a.chatBootstrapTailTurns>0?a.chatBootstrapTailTurns:1;function S(u){return {role:String(u.role||"system"),text:String(u.text||""),files:Array.isArray(u.files)?u.files:[],...typeof u.turn=="string"&&u.turn?{turn:u.turn}:{}}}function n(u){if(u.length===0)return null;if(u.length===1)return u[0];let b=[],m=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],p={};for(let C of m)p[C]=0;for(let C of u){let s=C,d=Array.isArray(s.cards)?s.cards:[];b.push(...d);for(let e of m)p[e]+=Number(s?.summary?.[e]||0);}let y=u[0];return {...y,cards:b,summary:{...y.summary||{},card_count:b.length,...p}}}async function f(){let u=[];for(let b of i)try{let m=await b.boardOps.buildSseOneShotPayload({});m.status==="success"&&m.data&&u.push(m.data);}catch{}return u}async function h(){let b=(await f()).map(m=>m.statusSnapshot).filter(Boolean);if(b.length===0){let m=i.map(p=>p.notification.status).filter(Boolean);return n(m)}return n(b)}async function w(){let u={},b=await f();for(let m of b)Object.assign(u,m.cardRuntimeById||{});if(Object.keys(u).length>0)return u;for(let m of i)for(let[p,y]of Object.entries(m.notification.computedValues)){let C=m.notification.cards[p];u[p]={schema_version:"v1",card_id:p,card_data:C?.card_data??{},computed_values:y??{}};}return u}async function R(){let u={},b=await f();for(let m of b)Object.assign(u,m.dataObjectsByToken||{});if(Object.keys(u).length===0)for(let m of i)Object.assign(u,m.notification.dataObjects||{});return u}async function I(){let u=await f(),b=u.flatMap(C=>Array.isArray(C.cardDefinitions)?C.cardDefinitions:[]),m={},p={};for(let C of u)Object.assign(m,C.dataObjectsByToken||{}),Object.assign(p,C.cardRuntimeById||{});let y={};for(let C of b){if(!C?.id)continue;let s=C.id;try{let d=await c(s,{tailTurns:_}),e=await g(s);(d.length>0||e)&&(y[s]={messages:d.map(r=>S(r)),receiving:!1,processing:e});}catch{}}return {boardId:t,cardDefinitions:b,statusSnapshot:await h(),dataObjectsByToken:m,cardRuntimeById:p,cardChatsByCardId:y}}return {readStatusSnapshot:h,readCardRuntimeArtifacts:w,readDataObjectsByToken:R,buildPublishedRuntimePayload:I}}function K(a){let t=String(a||"").trim();if(!t)return "upload.bin";let i=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (i>=0?t.slice(i+1):t)||"upload.bin"}function ct(a){let{safeCardId:t,artifactsStores:i,cardFileMetadataStore:c,readCardFromStore:g,updateCardLocalOnly:_,writeChatRecord:S}=a;async function n(w){let R=[];try{let I=await g(w);if(!I)return R;let u=c().read(I.card_data&&typeof I.card_data=="object"?I.card_data:null);for(let b of u)R.push(String(b.stored_name??""));}catch{}return R}async function f(w,R,I,u){let b=t(w),m=i(w),p=K(R),y=await n(w),s=`${String(y.length+1).padStart(3,"0")}-${p}`.slice(-36);if(!m.files)throw Object.assign(new Error(`artifactsStoreRef is not configured for card uploads: ${w}`),{statusCode:500});return await m.files.putBytes(`${b}/${s}`,new Uint8Array(u),I||"application/octet-stream"),{name:p,stored_name:s,size:u.length,mime_type:I||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function h(w,R,I,u,b){if(!u.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let m=b?.inChat===true,p=await f(w,R,I,u),y=null;if(await _(w,C=>{let s=new Date().toISOString(),d=C.card_data&&typeof C.card_data=="object"?C.card_data:{};C.card_data=d;let e=c().normalizeIncoming([{name:p.name,stored_name:p.stored_name,size:p.size,mime_type:p.mime_type,uploaded_at:p.uploaded_at||s,chat:m}],s);return y=c().merge(d,e).findIndex(o=>o.stored_name===p.stored_name),C}),m&&b?.suppressChatRecordWrite!==true){let C=typeof y=="number"&&y>=0?` #${y}`:"";await S(w,"system",`file uploaded: ${p.name} as ${p.stored_name}${C}`,[],b?.turnId??"");}return {ok:true,file:{...p,...typeof y=="number"&&y>=0?{file_idx:y}:{},chat:m},...typeof y=="number"&&y>=0?{file_idx:y}:{}}}return {uploadCardFile:h,readCardStoredFileNames:n}}function pt(a$1){return {"discover.source-kinds":()=>a$1.discoverSourceKinds(),"inspect.board-runtime-status":()=>a$1.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>a$1.inspectCardDefinitionAndRuntime({cardId:a(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let i=b(t,"tail_turns"),c=b(t,"tail"),g=a(t,"turn_id"),_=t.all_turns===true,S=a(t,"tail_turns_before_id");return a$1.inspectChatMessagesOnCards({cardId:a(t,"card_id"),...i!==void 0?{lastUserTurns:i}:{},...c!==void 0?{tail:c}:{},...g?{turnId:g}:{},..._?{allTurns:true}:{},...S?{tailTurnsBeforeId:S}:{}})},"inspect.file-contents":t=>a$1.inspectFileContents({cardId:a(t,"card_id"),fileIdx:Number(b(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>a$1.preflightValidateCandidateCardDefinition({candidateCardContent:d(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>a$1.preflightMaterializeCandidateCard({candidateCardContent:d(t,"candidate_card_content","candidate_card_content"),mockRequires:d(t,"mock_requires","mock_requires"),mockFetchedSources:d(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>a$1.preflightProbeSingleSourceInCandidateCard({candidateCardContent:d(t,"candidate_card_content","candidate_card_content"),mockProjections:c(t,"mock_projections"),sourceIdx:e(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>a$1.preflightRunSingleSourceInCandidateCard({candidateCardContent:d(t,"candidate_card_content","candidate_card_content"),mockProjections:c(t,"mock_projections"),sourceIdx:e(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>a$1.preflightRunSingleSourceInLiveCard({cardId:a(t,"card_id"),sourceIdx:e(t,"source_idx","source_idx"),mockRequires:d(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>a$1.preflightRunOneCycleWithCandidateCard({candidateCardContent:d(t,"candidate_card_content","candidate_card_content"),mockRequires:c(t,"mock_requires")}),"manage.read-card":t=>a$1.manageReadCard({cardId:a(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let i=a(t,"turn_id");if(!i)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return a$1.manageAddChatEntryAndAnyAttachments({cardId:a(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...i?{turn:i}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"stage-ai-failure-message":t=>{let i=a(t,"turn_id"),c=a(t,"failure");if(!i)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty turn_id"),{statusCode:400});if(!c)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty failure"),{statusCode:400});return a$1.manageAddChatEntryAndAnyAttachments({cardId:a(t,"card_id"),role:"system",text:c,turn:i})},"manage.upsert-card":t=>a$1.manageUpsertCard({cardId:a(t,"card_id"),candidateCardContent:c(t,"candidate_card_content")}),"manage.remove-card":t=>a$1.manageRemoveCard({cardId:a(t,"card_id")})}}function mt(a$1){return {"webhook.process-accumulated":()=>a$1.webhookProcessAccumulated(),"webhook.source-fetch-done":t=>a$1.webhookSourceFetchDone({token:a(t,"token"),ref:a(t,"ref")}),"webhook.source-fetch-failed":t=>a$1.webhookSourceFetchFailed({token:a(t,"token"),reason:a(t,"reason")})}}function ft(a$1){let{boardId:t,uploadCardFile:i,getMcpFacade:c$1,controlplane:g}=a$1;function _(n,f){let h=a(n,"board_id");if(!h)throw Object.assign(new Error(`${f} requires board_id`),{statusCode:400});if(h!==t)throw Object.assign(new Error(`Unknown board_id: ${h}`),{statusCode:400})}function S(n,f){let{cardId:h}=g.requireCardArgs(n),w=a(n,"turn_id");return _(n,f),c$1().manageAddChatAttachment({cardId:h,role:a(n,"role")||"user",...w?{turn:w}:{},files:[{file_name:a(n,"file_name"),content_type:a(n,"content_type")||"application/octet-stream",...typeof n.text=="string"?{text:n.text}:{},...typeof n.base64=="string"?{base64:n.base64}:{},...Array.isArray(n.bytes)?{bytes:n.bytes}:{}}]})}return {"list-runtime-cards":n=>(_(n,"list-runtime-cards"),c$1().listRuntimeCards()),"sse.subscribe-chat":n=>g.subscribeChat(n),"sse.unsubscribe-chat":n=>g.unsubscribeChat(n),"sse.watch-channel":n=>g.watchChannel(n,true),"sse.unwatch-channel":n=>g.watchChannel(n,false),"getstate.is-chat-processing":n=>g.getChatProcessing(n),"setstate.chat-processing-started":n=>g.setChatProcessing(n,true),"setstate.chat-processing-done":n=>g.setChatProcessing(n,false),"getstate.card-private":n=>g.getCardMeta(n),"setstate.card-private":n=>g.setCardMeta(n),"manage.upload-card-file":n=>{let f$1=a(n,"card_id"),h=a(n,"file_name"),w=a(n,"content_type")||"application/octet-stream",R=f(n);if(_(n,"manage.upload-card-file"),!f$1)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!h)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!R)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return i(f$1,h,w,R,{inChat:false})},"manage.add-chat-attachment":n=>S(n,"manage.add-chat-attachment"),"manage.add-chat-attachement":n=>S(n,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":n=>{let{cardId:f}=g.requireCardArgs(n),h=a(n,"role")||"user",w=a(n,"turn_id");return _(n,"manage.add-chat-entry-and-any-attachments"),c$1().manageAddChatEntryAndAnyAttachments({cardId:f,role:h,...typeof n.text=="string"?{text:n.text}:{},...w?{turn:w}:{},...Array.isArray(n.files)?{files:n.files}:{}})},"manage.patch-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.patch-card"),c$1().managePatchCard({cardId:f,patch:c(n,"patch")},{allowControlplaneOnlyCards:true})},"manage.upsert-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.upsert-card"),c$1().manageUpsertCard({cardId:f,candidateCardContent:c(n,"candidate_card_content")},{allowControlplaneOnlyCards:true})},"manage.remove-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.remove-card"),c$1().manageRemoveCard({cardId:f},{allowControlplaneOnlyCards:true})},"manage.admin-read-card":async n=>{let{cardId:f}=g.requireCardArgs(n);return {status:"success",data:{cards:await c$1().adminReadCard({cardId:f})}}},"manage.admin-upsert-card":n=>{let f=a(n,"board_id"),h=a(n,"card_id");if(!f)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!h)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(f!==t)throw Object.assign(new Error(`Unknown board_id: ${f}`),{statusCode:400});return c$1().adminUpsertCard({cardId:h,candidateCardContent:c(n,"candidate_card_content")})}}}function yt(a){let{boardContexts:t,cardOwnerIndex:i,cardContextForCard:c,readStatusSnapshot:g,readDataObjectsByToken:_,readCardRuntimeArtifacts:S,readCardFromStore:n,readCardDefinitions:f,processAccumulatedLaneInternal:h,reportSourceFetched:w,reportSourceFetchFailure:R,uploadCardFile:I,chatStorePublic:u,serverUrl:b,apiBasePath:m}=a;function p(){return t[0]??null}function y(){return {async status(){let e=await g();return e==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:e}},async getOutputsDataObject(e){let r=e?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(e){let r=e?.params?.key;return r?{status:"success",data:(await S())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(e){let r=e?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let o=c(r)??p();return o?o.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(e){let r=e?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let o=c(r)??p();return o?o.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(e){let r=e?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let o=c(r)??p();if(!o)return {status:"fail",error:"Board context is unavailable"};let k=await o.boardOps.upsertCard({params:{cardId:r,restart:e.params.restart===true}});if(k.status!=="success")return k;if(a$1(o.boardAdapter)){let P=await h(true);if(P.status!=="success")return P}return k}}}function C(){let e=()=>{let r=p();if(!r?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return r.nonCore};return {describeTaskExecutorCapabilities(r){return e().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return e().validateCardPreflight(r)},evalCardCompute(r){return e().evalCardCompute(r)},probeSourcePreflight(r){return e().probeSourcePreflight(r)},runSourcePreflight(r){return e().runSourcePreflight(r)},simulateCardCycle(r){return e().simulateCardCycle(r)}}}function s(){return {async get(e){let r=typeof e.params?.id=="string"?e.params.id:void 0;if(r){let o=await n(r);return o?{status:"success",data:{cards:[o]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await f()}}},async set(e){let r=e.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let o=Array.isArray(r)?r:[r];for(let k of o){let P=k,A=typeof P.id=="string"?P.id:"";if(!A)return {status:"fail",error:"each card must have a string `id` field"};let E=i.get(A)??0,D=t[E]??p();if(!D)return {status:"fail",error:"Board context is unavailable"};let L=await D.cardStoreOps.set({body:P});if(L.status!=="success")return L;i.set(A,E);}return {status:"success",data:{count:o.length}}},async del(e){let r=[e.params?.id,...e.body?.ids??[]].filter(o=>typeof o=="string"&&!!o);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let o of r){let k=c(o)??p();if(!k)return {status:"fail",error:"Board context is unavailable"};let P=await k.cardStoreOps.del({params:{id:o}});if(P.status!=="success")return P;i.delete(o);}return {status:"success",data:{count:r.length}}},async patch(e){let r=typeof e.params?.id=="string"?e.params.id:void 0,o=typeof e.params?.path=="string"?e.params.path:void 0;if(!r||!o)return {status:"fail",error:"patch requires params.id and params.path"};let k=c(r)??p();return k?k.cardStoreOps.patch(e):{status:"fail",error:"Board context is unavailable"}},async appendFiles(e){let r=typeof e.params?.id=="string"?e.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let o=c(r)??p();return o?o.cardStoreOps.appendFiles(e):{status:"fail",error:"Board context is unavailable"}}}}function d(){return a$2({board:y(),nonCore:C(),cardStore:s(),chatStore:u,processAccumulated:()=>h(true),sourceFetchDone:({token:e,ref:r})=>w(e,r),sourceFetchFailed:({token:e,reason:r})=>R(e,r),uploadCardFile({cardId:e,fileName:r,contentType:o,bytes:k,suppressChatRecordWrite:P}){return I(e,r,o,k,{inChat:true,...P===true?{suppressChatRecordWrite:true}:{}})},buildFileDownloadUrl({cardId:e,fileIdx:r,storedName:o}){let k=`${b||""}${m}/cards/${encodeURIComponent(e)}/files/${r}`;return o?`${k}?sn=${encodeURIComponent(o)}`:k},readFetchedSourceJsonByRef({cardId:e,ref:r}){let o=c(e)??p();if(!o||a$1(o.boardAdapter))return null;let A=o.boardAdapter.resolveBlob(b$1(r)).trim();return A?JSON.parse(A):null}})}return {mcpBoardFacade:y,mcpNonCoreFacade:C,mcpCardStoreFacade:s,createMcpFacade:d}}export{J as a,X as b,Q as c,z as d,Y as e,j as f,N as g,T as h,q as i,ot as j,it as k,ct as l,pt as m,mt as n,ft as o,yt as p};//# sourceMappingURL=chunk-37JSBRZO.js.map
2
+ //# sourceMappingURL=chunk-37JSBRZO.js.map
@@ -1,2 +1,2 @@
1
- import {u}from'./chunk-VGT3TRQG.js';import {a}from'./chunk-ATOQP3BD.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u$1=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u$1){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=u(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-ZCU5O2LR.js.map
2
- //# sourceMappingURL=chunk-ZCU5O2LR.js.map
1
+ import {u}from'./chunk-VGT3TRQG.js';import {a}from'./chunk-ATOQP3BD.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u$1=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u$1){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=u(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-4BEQXKRF.js.map
2
+ //# sourceMappingURL=chunk-4BEQXKRF.js.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkBQUQTOPB_cjs=require('./chunk-BQUQTOPB.cjs'),chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunkVQCIOKJV_cjs=require('./chunk-VQCIOKJV.cjs'),chunkGHUW6P4G_cjs=require('./chunk-GHUW6P4G.cjs');function M(a){if(!a||typeof a!="object")return false;let t=a;return typeof t.kind=="string"&&t.kind.length>0}function J(a){if(!a||typeof a!="object")return [];let t=a;return t.kind==="notification-batch"?Array.isArray(t.notifications)?t.notifications.filter(M):[]:M(a)?[a]:[]}function X(a,t,i){let c=0;return {accepted:a.filter(_=>{if(!M(_))return c++,false;let S=_;return typeof S.sentAtMs=="number"&&t-S.sentAtMs>i?(c++,false):true}),rejected:c}}function Q(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function z(a){if(!a||typeof a!="object")return false;let t=a.summary;return !t||typeof t!="object"?false:Number(t.card_count||0)>0}function W(a){if(!a||typeof a!="object")return false;let t=a;return t.kind==="notification-batch"&&Array.isArray(t.notifications)}function V(a,t){if(t.kind==="status"){z(t.status)&&(a.status=t.status);return}if(t.kind==="computed_values"){a.computedValues[t.cardId]=t.values;return}if(t.kind==="data_object"){a.dataObjects[t.key]=t.payload;return}if(t.kind==="card_refreshed"){a.cards[t.cardId]=t.card;return}t.kind==="card_removed"&&(delete a.cards[t.cardId],delete a.computedValues[t.cardId]);}function Y(a,t){if(W(t)){for(let i of t.notifications)M(i)&&V(a,i);return}M(t)&&V(a,t);}function j(a,t){if(a?.status==="success")return Object.prototype.hasOwnProperty.call(a,"data")?a.data:void 0;throw a?.status==="fail"||a?.status==="error"?Object.assign(new Error(a.error||`${t} failed`),{statusCode:400}):Object.assign(new Error(`${t} returned an unexpected response`),{statusCode:500})}async function N(a,t){return j(await a,t)}function T(a){let t=chunkLPXVVMQT_cjs.a(a,"key");if(!t)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let i=t.split(".");if(!(i.length>=2&&i.every(g=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(g))))throw Object.assign(new Error("MCP tool requires a card private key with at least two identifier segments (e.g. chat.foundry_thread_id)"),{statusCode:400});return t}function q(a,t){let i=a.__private;for(let c of t.split(".")){if(!i||typeof i!="object"||Array.isArray(i)||!Object.prototype.hasOwnProperty.call(i,c))return {exists:false,value:null};i=i[c];}return {exists:true,value:i}}function ot(a){let{boardId:t,bootstrapBoard:i,sseHub:c,onChannelSubscribed:g,onChannelUnsubscribed:_,getMcpFacade:S,getMcpCardStoreFacade:n}=a;function f(s){let d=chunkLPXVVMQT_cjs.a(s,"board_id");if(!d)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(d!==t)throw Object.assign(new Error(`Unknown board_id: ${d}`),{statusCode:400})}function h(s){let d=chunkLPXVVMQT_cjs.a(s,"client_id");if(!d)throw Object.assign(new Error("MCP tool requires client_id"),{statusCode:400});return d}function w(s){f(s);let d=h(s),e=chunkLPXVVMQT_cjs.a(s,"channel_name"),r=chunkLPXVVMQT_cjs.a(s,"card_id")||void 0;if(!e)throw Object.assign(new Error("MCP tool requires channel_name"),{statusCode:400});return {clientId:d,channelName:e,...r?{cardId:r}:{}}}function R(s){f(s);let d=chunkLPXVVMQT_cjs.a(s,"card_id");if(!d)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});return {cardId:d}}async function I(s){await i();let{cardId:d}=R(s),e=h(s);if(!await c.subscribeChat(e,d))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return {status:"success",data:{boardId:t,cardId:d,clientId:e,subscribed:true}}}async function u(s){await i();let{cardId:d}=R(s),e=h(s);if(!c.unsubscribeChat(e,d))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return {status:"success",data:{boardId:t,cardId:d,clientId:e,subscribed:false}}}async function b(s,d){await i();let{clientId:e,channelName:r,cardId:o}=w(s);if(!c.has(e))throw Object.assign(new Error(`SSE client not connected: ${e}`),{statusCode:404});return d?(c.subscribeChannel(e,r,o),g?.(e,r,o?{cardId:o}:{})):(c.unsubscribeChannel(e,r,o),_?.(e,r,o?{cardId:o}:{})),{status:"success",data:{boardId:t,clientId:e,channelName:r,subscribed:d,...o?{cardId:o}:{}}}}async function m(s,d){let{cardId:e}=R(s);return await S().setChatProcessing({cardId:e,active:d}),{status:"success",data:{boardId:t,cardId:e,active:d}}}async function p(s){let{cardId:d}=R(s),e=await S().getChatProcessing({cardId:d});return {status:"success",data:{boardId:t,cardId:d,active:e.active}}}async function y(s){let{cardId:d}=R(s),e=T(s);if(!Object.prototype.hasOwnProperty.call(s,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(e.split(".").includes("visible_controlplane_only")){let r=await N(n().get({params:{id:d}}),"cardStore.get"),o=Array.isArray(r.cards)&&r.cards.length>0&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null,k=o?q(o,"visible_controlplane_only").value:void 0;if(s.value!==k)throw Object.assign(new Error("MCP tool cannot change the reserved private flag visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:t,cardId:d,key:e}}}return j(await n().patch({params:{id:d,path:`__private.${e}`},body:{value:s.value}}),"cardStore.patch"),{status:"success",data:{boardId:t,cardId:d,key:e}}}async function C(s){let{cardId:d}=R(s),e=T(s),r=await N(n().get({params:{id:d}}),"cardStore.get"),o=Array.isArray(r.cards)&&r.cards.length>0&&r.cards[0]&&typeof r.cards[0]=="object"&&!Array.isArray(r.cards[0])?r.cards[0]:null;if(!o)throw Object.assign(new Error(`Card "${d}" not found`),{statusCode:404});let k=q(o,e);return {status:"success",data:{boardId:t,cardId:d,key:e,exists:k.exists,value:k.value}}}return {requireCardArgs:R,subscribeChat:I,unsubscribeChat:u,watchChannel:b,setChatProcessing:m,getChatProcessing:p,setCardMeta:y,getCardMeta:C}}function it(a){let{boardId:t,boardContexts:i,readChatRecords:c,getChatProcessing:g}=a,_=Number.isInteger(a.chatBootstrapTailTurns)&&a.chatBootstrapTailTurns>0?a.chatBootstrapTailTurns:1;function S(u){return {role:String(u.role||"system"),text:String(u.text||""),files:Array.isArray(u.files)?u.files:[],...typeof u.turn=="string"&&u.turn?{turn:u.turn}:{}}}function n(u){if(u.length===0)return null;if(u.length===1)return u[0];let b=[],m=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],p={};for(let C of m)p[C]=0;for(let C of u){let s=C,d=Array.isArray(s.cards)?s.cards:[];b.push(...d);for(let e of m)p[e]+=Number(s?.summary?.[e]||0);}let y=u[0];return {...y,cards:b,summary:{...y.summary||{},card_count:b.length,...p}}}async function f(){let u=[];for(let b of i)try{let m=await b.boardOps.buildSseOneShotPayload({});m.status==="success"&&m.data&&u.push(m.data);}catch{}return u}async function h(){let b=(await f()).map(m=>m.statusSnapshot).filter(Boolean);if(b.length===0){let m=i.map(p=>p.notification.status).filter(Boolean);return n(m)}return n(b)}async function w(){let u={},b=await f();for(let m of b)Object.assign(u,m.cardRuntimeById||{});if(Object.keys(u).length>0)return u;for(let m of i)for(let[p,y]of Object.entries(m.notification.computedValues)){let C=m.notification.cards[p];u[p]={schema_version:"v1",card_id:p,card_data:C?.card_data??{},computed_values:y??{}};}return u}async function R(){let u={},b=await f();for(let m of b)Object.assign(u,m.dataObjectsByToken||{});if(Object.keys(u).length===0)for(let m of i)Object.assign(u,m.notification.dataObjects||{});return u}async function I(){let u=await f(),b=u.flatMap(C=>Array.isArray(C.cardDefinitions)?C.cardDefinitions:[]),m={},p={};for(let C of u)Object.assign(m,C.dataObjectsByToken||{}),Object.assign(p,C.cardRuntimeById||{});let y={};for(let C of b){if(!C?.id)continue;let s=C.id;try{let d=await c(s,{tailTurns:_}),e=await g(s);(d.length>0||e)&&(y[s]={messages:d.map(r=>S(r)),receiving:!1,processing:e});}catch{}}return {boardId:t,cardDefinitions:b,statusSnapshot:await h(),dataObjectsByToken:m,cardRuntimeById:p,cardChatsByCardId:y}}return {readStatusSnapshot:h,readCardRuntimeArtifacts:w,readDataObjectsByToken:R,buildPublishedRuntimePayload:I}}function K(a){let t=String(a||"").trim();if(!t)return "upload.bin";let i=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return (i>=0?t.slice(i+1):t)||"upload.bin"}function ct(a){let{safeCardId:t,artifactsStores:i,cardFileMetadataStore:c,readCardFromStore:g,updateCardLocalOnly:_,writeChatRecord:S}=a;async function n(w){let R=[];try{let I=await g(w);if(!I)return R;let u=c().read(I.card_data&&typeof I.card_data=="object"?I.card_data:null);for(let b of u)R.push(String(b.stored_name??""));}catch{}return R}async function f(w,R,I,u){let b=t(w),m=i(w),p=K(R),y=await n(w),s=`${String(y.length+1).padStart(3,"0")}-${p}`.slice(-36);if(!m.files)throw Object.assign(new Error(`artifactsStoreRef is not configured for card uploads: ${w}`),{statusCode:500});return await m.files.putBytes(`${b}/${s}`,new Uint8Array(u),I||"application/octet-stream"),{name:p,stored_name:s,size:u.length,mime_type:I||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function h(w,R,I,u,b){if(!u.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let m=b?.inChat===true,p=await f(w,R,I,u),y=null;if(await _(w,C=>{let s=new Date().toISOString(),d=C.card_data&&typeof C.card_data=="object"?C.card_data:{};C.card_data=d;let e=c().normalizeIncoming([{name:p.name,stored_name:p.stored_name,size:p.size,mime_type:p.mime_type,uploaded_at:p.uploaded_at||s,chat:m}],s);return y=c().merge(d,e).findIndex(o=>o.stored_name===p.stored_name),C}),m&&b?.suppressChatRecordWrite!==true){let C=typeof y=="number"&&y>=0?` #${y}`:"";await S(w,"system",`file uploaded: ${p.name} as ${p.stored_name}${C}`,[],b?.turnId??"");}return {ok:true,file:{...p,...typeof y=="number"&&y>=0?{file_idx:y}:{},chat:m},...typeof y=="number"&&y>=0?{file_idx:y}:{}}}return {uploadCardFile:h,readCardStoredFileNames:n}}function pt(a){return {"discover.source-kinds":()=>a.discoverSourceKinds(),"inspect.board-runtime-status":()=>a.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":t=>a.inspectCardDefinitionAndRuntime({cardId:chunkLPXVVMQT_cjs.a(t,"card_id")}),"inspect.chat-messages-on-cards":t=>{let i=chunkLPXVVMQT_cjs.b(t,"tail_turns"),c=chunkLPXVVMQT_cjs.b(t,"tail"),g=chunkLPXVVMQT_cjs.a(t,"turn_id"),_=t.all_turns===true,S=chunkLPXVVMQT_cjs.a(t,"tail_turns_before_id");return a.inspectChatMessagesOnCards({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),...i!==void 0?{lastUserTurns:i}:{},...c!==void 0?{tail:c}:{},...g?{turnId:g}:{},..._?{allTurns:true}:{},...S?{tailTurnsBeforeId:S}:{}})},"inspect.file-contents":t=>a.inspectFileContents({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),fileIdx:Number(chunkLPXVVMQT_cjs.b(t,"file_idx"))}),"preflight.validate-candidate-card-definition":t=>a.preflightValidateCandidateCardDefinition({candidateCardContent:chunkLPXVVMQT_cjs.d(t,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":t=>a.preflightMaterializeCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(t,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.d(t,"mock_requires","mock_requires"),mockFetchedSources:chunkLPXVVMQT_cjs.d(t,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":t=>a.preflightProbeSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(t,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(t,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(t,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":t=>a.preflightRunSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(t,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(t,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(t,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":t=>a.preflightRunSingleSourceInLiveCard({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),sourceIdx:chunkLPXVVMQT_cjs.e(t,"source_idx","source_idx"),mockRequires:chunkLPXVVMQT_cjs.d(t,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":t=>a.preflightRunOneCycleWithCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(t,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.c(t,"mock_requires")}),"manage.read-card":t=>a.manageReadCard({cardId:chunkLPXVVMQT_cjs.a(t,"card_id")}),"stage-ai-response-and-any-attachments":t=>{let i=chunkLPXVVMQT_cjs.a(t,"turn_id");if(!i)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return a.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),role:"assistant",...typeof t.text=="string"?{text:t.text}:{},...i?{turn:i}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"stage-ai-failure-message":t=>{let i=chunkLPXVVMQT_cjs.a(t,"turn_id"),c=chunkLPXVVMQT_cjs.a(t,"failure");if(!i)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty turn_id"),{statusCode:400});if(!c)throw Object.assign(new Error("stage-ai-failure-message requires a non-empty failure"),{statusCode:400});return a.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),role:"system",text:c,turn:i})},"manage.upsert-card":t=>a.manageUpsertCard({cardId:chunkLPXVVMQT_cjs.a(t,"card_id"),candidateCardContent:chunkLPXVVMQT_cjs.c(t,"candidate_card_content")}),"manage.remove-card":t=>a.manageRemoveCard({cardId:chunkLPXVVMQT_cjs.a(t,"card_id")})}}function mt(a){return {"webhook.process-accumulated":()=>a.webhookProcessAccumulated(),"webhook.source-fetch-done":t=>a.webhookSourceFetchDone({token:chunkLPXVVMQT_cjs.a(t,"token"),ref:chunkLPXVVMQT_cjs.a(t,"ref")}),"webhook.source-fetch-failed":t=>a.webhookSourceFetchFailed({token:chunkLPXVVMQT_cjs.a(t,"token"),reason:chunkLPXVVMQT_cjs.a(t,"reason")})}}function ft(a){let{boardId:t,uploadCardFile:i,getMcpFacade:c,controlplane:g}=a;function _(n,f){let h=chunkLPXVVMQT_cjs.a(n,"board_id");if(!h)throw Object.assign(new Error(`${f} requires board_id`),{statusCode:400});if(h!==t)throw Object.assign(new Error(`Unknown board_id: ${h}`),{statusCode:400})}function S(n,f){let{cardId:h}=g.requireCardArgs(n),w=chunkLPXVVMQT_cjs.a(n,"turn_id");return _(n,f),c().manageAddChatAttachment({cardId:h,role:chunkLPXVVMQT_cjs.a(n,"role")||"user",...w?{turn:w}:{},files:[{file_name:chunkLPXVVMQT_cjs.a(n,"file_name"),content_type:chunkLPXVVMQT_cjs.a(n,"content_type")||"application/octet-stream",...typeof n.text=="string"?{text:n.text}:{},...typeof n.base64=="string"?{base64:n.base64}:{},...Array.isArray(n.bytes)?{bytes:n.bytes}:{}}]})}return {"list-runtime-cards":n=>(_(n,"list-runtime-cards"),c().listRuntimeCards()),"sse.subscribe-chat":n=>g.subscribeChat(n),"sse.unsubscribe-chat":n=>g.unsubscribeChat(n),"sse.watch-channel":n=>g.watchChannel(n,true),"sse.unwatch-channel":n=>g.watchChannel(n,false),"getstate.is-chat-processing":n=>g.getChatProcessing(n),"setstate.chat-processing-started":n=>g.setChatProcessing(n,true),"setstate.chat-processing-done":n=>g.setChatProcessing(n,false),"getstate.card-private":n=>g.getCardMeta(n),"setstate.card-private":n=>g.setCardMeta(n),"manage.upload-card-file":n=>{let f=chunkLPXVVMQT_cjs.a(n,"card_id"),h=chunkLPXVVMQT_cjs.a(n,"file_name"),w=chunkLPXVVMQT_cjs.a(n,"content_type")||"application/octet-stream",R=chunkLPXVVMQT_cjs.f(n);if(_(n,"manage.upload-card-file"),!f)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!h)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!R)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return i(f,h,w,R,{inChat:false})},"manage.add-chat-attachment":n=>S(n,"manage.add-chat-attachment"),"manage.add-chat-attachement":n=>S(n,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":n=>{let{cardId:f}=g.requireCardArgs(n),h=chunkLPXVVMQT_cjs.a(n,"role")||"user",w=chunkLPXVVMQT_cjs.a(n,"turn_id");return _(n,"manage.add-chat-entry-and-any-attachments"),c().manageAddChatEntryAndAnyAttachments({cardId:f,role:h,...typeof n.text=="string"?{text:n.text}:{},...w?{turn:w}:{},...Array.isArray(n.files)?{files:n.files}:{}})},"manage.patch-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.patch-card"),c().managePatchCard({cardId:f,patch:chunkLPXVVMQT_cjs.c(n,"patch")},{allowControlplaneOnlyCards:true})},"manage.upsert-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.upsert-card"),c().manageUpsertCard({cardId:f,candidateCardContent:chunkLPXVVMQT_cjs.c(n,"candidate_card_content")},{allowControlplaneOnlyCards:true})},"manage.remove-card":n=>{let{cardId:f}=g.requireCardArgs(n);return _(n,"manage.remove-card"),c().manageRemoveCard({cardId:f},{allowControlplaneOnlyCards:true})},"manage.admin-read-card":async n=>{let{cardId:f}=g.requireCardArgs(n);return {status:"success",data:{cards:await c().adminReadCard({cardId:f})}}},"manage.admin-upsert-card":n=>{let f=chunkLPXVVMQT_cjs.a(n,"board_id"),h=chunkLPXVVMQT_cjs.a(n,"card_id");if(!f)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!h)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(f!==t)throw Object.assign(new Error(`Unknown board_id: ${f}`),{statusCode:400});return c().adminUpsertCard({cardId:h,candidateCardContent:chunkLPXVVMQT_cjs.c(n,"candidate_card_content")})}}}function yt(a){let{boardContexts:t,cardOwnerIndex:i,cardContextForCard:c,readStatusSnapshot:g,readDataObjectsByToken:_,readCardRuntimeArtifacts:S,readCardFromStore:n,readCardDefinitions:f,processAccumulatedLaneInternal:h,reportSourceFetched:w,reportSourceFetchFailure:R,uploadCardFile:I,chatStorePublic:u,serverUrl:b,apiBasePath:m}=a;function p(){return t[0]??null}function y(){return {async status(){let e=await g();return e==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:e}},async getOutputsDataObject(e){let r=e?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(e){let r=e?.params?.key;return r?{status:"success",data:(await S())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(e){let r=e?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let o=c(r)??p();return o?o.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(e){let r=e?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let o=c(r)??p();return o?o.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(e){let r=e?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let o=c(r)??p();if(!o)return {status:"fail",error:"Board context is unavailable"};let k=await o.boardOps.upsertCard({params:{cardId:r,restart:e.params.restart===true}});if(k.status!=="success")return k;if(chunkBQUQTOPB_cjs.a(o.boardAdapter)){let P=await h(true);if(P.status!=="success")return P}return k}}}function C(){let e=()=>{let r=p();if(!r?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return r.nonCore};return {describeTaskExecutorCapabilities(r){return e().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return e().validateCardPreflight(r)},evalCardCompute(r){return e().evalCardCompute(r)},probeSourcePreflight(r){return e().probeSourcePreflight(r)},runSourcePreflight(r){return e().runSourcePreflight(r)},simulateCardCycle(r){return e().simulateCardCycle(r)}}}function s(){return {async get(e){let r=typeof e.params?.id=="string"?e.params.id:void 0;if(r){let o=await n(r);return o?{status:"success",data:{cards:[o]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await f()}}},async set(e){let r=e.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let o=Array.isArray(r)?r:[r];for(let k of o){let P=k,A=typeof P.id=="string"?P.id:"";if(!A)return {status:"fail",error:"each card must have a string `id` field"};let E=i.get(A)??0,D=t[E]??p();if(!D)return {status:"fail",error:"Board context is unavailable"};let L=await D.cardStoreOps.set({body:P});if(L.status!=="success")return L;i.set(A,E);}return {status:"success",data:{count:o.length}}},async del(e){let r=[e.params?.id,...e.body?.ids??[]].filter(o=>typeof o=="string"&&!!o);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let o of r){let k=c(o)??p();if(!k)return {status:"fail",error:"Board context is unavailable"};let P=await k.cardStoreOps.del({params:{id:o}});if(P.status!=="success")return P;i.delete(o);}return {status:"success",data:{count:r.length}}},async patch(e){let r=typeof e.params?.id=="string"?e.params.id:void 0,o=typeof e.params?.path=="string"?e.params.path:void 0;if(!r||!o)return {status:"fail",error:"patch requires params.id and params.path"};let k=c(r)??p();return k?k.cardStoreOps.patch(e):{status:"fail",error:"Board context is unavailable"}},async appendFiles(e){let r=typeof e.params?.id=="string"?e.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let o=c(r)??p();return o?o.cardStoreOps.appendFiles(e):{status:"fail",error:"Board context is unavailable"}}}}function d(){return chunkGHUW6P4G_cjs.a({board:y(),nonCore:C(),cardStore:s(),chatStore:u,processAccumulated:()=>h(true),sourceFetchDone:({token:e,ref:r})=>w(e,r),sourceFetchFailed:({token:e,reason:r})=>R(e,r),uploadCardFile({cardId:e,fileName:r,contentType:o,bytes:k,suppressChatRecordWrite:P}){return I(e,r,o,k,{inChat:true,...P===true?{suppressChatRecordWrite:true}:{}})},buildFileDownloadUrl({cardId:e,fileIdx:r,storedName:o}){let k=`${b||""}${m}/cards/${encodeURIComponent(e)}/files/${r}`;return o?`${k}?sn=${encodeURIComponent(o)}`:k},readFetchedSourceJsonByRef({cardId:e,ref:r}){let o=c(e)??p();if(!o||chunkBQUQTOPB_cjs.a(o.boardAdapter))return null;let A=o.boardAdapter.resolveBlob(chunkVQCIOKJV_cjs.b(r)).trim();return A?JSON.parse(A):null}})}return {mcpBoardFacade:y,mcpNonCoreFacade:C,mcpCardStoreFacade:s,createMcpFacade:d}}exports.a=J;exports.b=X;exports.c=Q;exports.d=z;exports.e=Y;exports.f=j;exports.g=N;exports.h=T;exports.i=q;exports.j=ot;exports.k=it;exports.l=ct;exports.m=pt;exports.n=mt;exports.o=ft;exports.p=yt;//# sourceMappingURL=chunk-LRO5AL75.cjs.map
2
+ //# sourceMappingURL=chunk-LRO5AL75.cjs.map
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkLFVMX23W_cjs=require('./chunk-LFVMX23W.cjs'),chunkNM6O35RY_cjs=require('./chunk-NM6O35RY.cjs'),chunkNBJTYAYN_cjs=require('./chunk-NBJTYAYN.cjs'),chunkLRO5AL75_cjs=require('./chunk-LRO5AL75.cjs'),chunkBQUQTOPB_cjs=require('./chunk-BQUQTOPB.cjs'),chunkGPCMBPLK_cjs=require('./chunk-GPCMBPLK.cjs'),chunk7FGPOGRV_cjs=require('./chunk-7FGPOGRV.cjs'),chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs'),chunkHVLWVMG6_cjs=require('./chunk-HVLWVMG6.cjs'),chunkWRMOGPRG_cjs=require('./chunk-WRMOGPRG.cjs'),chunkBAG7MHZP_cjs=require('./chunk-BAG7MHZP.cjs'),chunk5XLFPPTY_cjs=require('./chunk-5XLFPPTY.cjs'),chunkSDJ3747Q_cjs=require('./chunk-SDJ3747Q.cjs'),chunkOF4FPYNI_cjs=require('./chunk-OF4FPYNI.cjs'),chunk2RIHC5TZ_cjs=require('./chunk-2RIHC5TZ.cjs');function ce(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=chunkLPXVVMQT_cjs.a(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=chunkLPXVVMQT_cjs.c(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await chunk272IYUKT_cjs.a(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:chunk272IYUKT_cjs.b(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:chunk272IYUKT_cjs.b(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ke=3e4;function Ve(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function ue(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Ve(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=chunkLRO5AL75_cjs.b(T,Date.now(),Ke);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var le={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},de="chat-handler-flow-queue",ot="__probe__echo__probe__";function Mr(g){let w=String(g.apiBasePath||"/api/board").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.queueLaneTuning??{},B=g.boardId||"",$=Number.isInteger(g.chatBootstrapTailTurns)&&g.chatBootstrapTailTurns>0?g.chatBootstrapTailTurns:1,N=g.logger||{info:console.log,warn:console.warn,error:console.error},x=g.invocationAdapter,_=g.chatFlowRunner||null,H=g.notificationTransport||null,E=g.serverUrl||null,T=g.executionExtra||{},S=g.onSseClientConnected,z=g.onSseClientDisconnected,q=g.onChannelSubscribed,K=g.onChannelUnsubscribed,l=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=chunkLFVMX23W_cjs.a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F(t){function e(a){return {...a,queueStorageForRef(d,C){return chunkSDJ3747Q_cjs.a(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function r(a){return {...a,queueStorageForRef(d,C){return chunkHVLWVMG6_cjs.h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c=chunkBQUQTOPB_cjs.a(t.boardAdapter)?r(t.boardAdapter):e(t.boardAdapter),j=t.nonCoreAdapter??(!chunkBQUQTOPB_cjs.a(c)&&P(c)?c:null),h=chunkBQUQTOPB_cjs.a(c)?chunkHVLWVMG6_cjs.i(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}):chunkBAG7MHZP_cjs.F(t.baseRef,c,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i}),M=t.nonCore??(j?chunkBAG7MHZP_cjs.G(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),We=c.chatStorageForRef(t.chatStoreRef),lt,Je=chunkBQUQTOPB_cjs.a(c)?(()=>{let a=chunkHVLWVMG6_cjs.d(chunkHVLWVMG6_cjs.c(chunkHVLWVMG6_cjs.b(c.kvStorageForRef(t.cardStoreRef)),c.hashFn),N.warn),d=chunkHVLWVMG6_cjs.g(a,{emitNotification:i}),C=o(d);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c.kvStorageForRef(t.cardStoreRef),C=chunk5XLFPPTY_cjs.a(chunkBAG7MHZP_cjs.q({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i});return lt=C,n(C)})(),ft;if(chunkBQUQTOPB_cjs.a(c)){let a=c.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c.blobStorageForRef(t.artifactsStoreRef),d=chunkNBJTYAYN_cjs.a(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let ze={async init(a){return h.init(a)},async status(a){return h.status(a)},async getConfig(a){return h.getConfig(a)},async getAllOutputsDataObjects(a){return h.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h.buildSseOneShotPayload(a)},async upsertCard(a){return h.upsertCard(a)},async removeCard(a){return h.removeCard(a)},async sourceDataFetched(a){return h.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h.sourceDataFetchFailure(a)}};return s={label:t.label,board:h,nonCore:M,publicCardStore:lt,boardOps:ze,cardStoreOps:Je,get filesArtifacts(){return ft},get chatStorage(){return We},boardAdapter:c,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:chunkLRO5AL75_cjs.c(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p=g.boards.map(F),f=new Map;function y(t){return f.get(t)??0}function k(t){return t.queueStoreRef}function u(t,e){if(chunkBQUQTOPB_cjs.a(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k(t),e);return chunkWRMOGPRG_cjs.a(n)}let r=t.boardAdapter.queueStorageForRef(k(t),e);return chunkGPCMBPLK_cjs.a(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return chunkNBJTYAYN_cjs.c()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p[0]??void 0}function ct(t,e={}){if(!t||t.length===0)return;let r=chunk2RIHC5TZ_cjs.e(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e.ctx??U(r);if(e.appendState!==false&&o&&chunkLRO5AL75_cjs.e(o.notification,n),e.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function fe(t){if(!t||t.notificationTeardown||!H||!t.notifyRef)return;let e=await H.subscribe(t.notifyRef,r=>{let n=chunkLRO5AL75_cjs.a(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function pe(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await fe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&chunkLRO5AL75_cjs.d(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G(){for(let t of p)await pe(t);}async function at(){await G();for(let t=0;t<p.length;t++)await ut(p[t]),await Rt(p[t],t),await ut(p[t]);}async function yt(t=false){t||await G();for(let e of p){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function me(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p)e.push(...await t(r));return e}function ht(){return p[0]??null}function ge(t){return W(t)??ht()}function L(t){let e=ge(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function Re(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=chunkOF4FPYNI_cjs.a({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=chunkLRO5AL75_cjs.p({boardContexts:p,cardOwnerIndex:f,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Se(),readDataObjectsByToken:()=>Ae(),readCardRuntimeArtifacts:()=>Ce(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>me(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>kt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Pt(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>Ct(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),ye=wt.mcpCardStoreFacade,st=wt.createMcpFacade,he=chunkLRO5AL75_cjs.j({boardId:B,bootstrapBoard:()=>at(),sseHub:l,onChannelSubscribed:q,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>ye()});function we(t){return chunkLRO5AL75_cjs.m(t)}function be(){return chunkLRO5AL75_cjs.n(st())}function bt(){return chunkLRO5AL75_cjs.o({boardId:B,uploadCardFile:Ct,getMcpFacade:()=>st(),controlplane:he})}let it=chunkLRO5AL75_cjs.k({boardId:B,boardContexts:p,readChatRecords:(t,e)=>ve(t,e),getChatProcessing:t=>Re(t),chatBootstrapTailTurns:$}),Se=it.readStatusSnapshot,Ce=it.readCardRuntimeArtifacts,Ae=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function Be(t,e){await St(t,e,{syncBoard:true});}async function ke(t,e){await St(t,e,{syncBoard:false});}async function Pe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Oe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function Fe(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function ve(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=chunkLRO5AL75_cjs.l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>ke(t,e),writeChatRecord:(t,e,r,n,o)=>Fe(t,e,r,n,o)}).uploadCardFile;async function At(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function xe(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Te(t,e,r=false,n="",o=""){try{let s=await At(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:de}}:j;chunkBQUQTOPB_cjs.a(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function Ne(t,e,r){if(e.howToRun==="built-in"&&chunkBQUQTOPB_cjs.b(e)===de){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Ee(t,e=false){e||await G();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await Ne(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function je(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=xe(r?.text),c=i?i.text:r?.text,j=await chunk272IYUKT_cjs.a("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await chunk272IYUKT_cjs.a("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(chunk272IYUKT_cjs.b(M,`chat-send processing update failed for card ${t}`));Te(t,h,true,o,i?.assistant||"");return}await Be(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function Bt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function Me(t,e,r,n){let{fileRecord:o,bytes:s}=await Bt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function _e(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function De(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
+ `)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(chunkBQUQTOPB_cjs.d(e)).trim();return r?JSON.parse(r):{}}async function kt(t,e){let r=typeof e.ref=="string"?e.ref.trim():"";if(!r)return {status:"fail",error:"board-worker success callback requires body.ref"};let n=p[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function Pt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=p[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Ie=chunkLFVMX23W_cjs.b({sseHub:l,queueSseHub:R,corsHeaders:b,json:et,buildPublishedRuntimePayload:()=>dt(),onSseClientConnected:S,onChannelSubscribed:q,onChannelUnsubscribed:K,apiBasePath:w,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),bootstrapBoard:()=>at(),boardContexts:p,publishPersistedStateSnapshot:t=>ut(t),upsertCardsFromSource:(t,e)=>Rt(t,e)}).handleWatchersRoutes,qe=chunk7FGPOGRV_cjs.a({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpFacade:()=>st(),createMcpToolRegistry:t=>we(t),resolveCardFileDownloadPayload:(t,e,r)=>Bt(t,e,r),isLikelyTextMimeType:t=>_e(t),sliceTextByLines:(t,e,r)=>De(t,e,r)}).handleAgentfaceApi,$e=chunkNM6O35RY_cjs.a({apiBasePath:w,json:et,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),createMcpWebhookToolRegistry:()=>be()}).handleWebhooksApi,He=ce({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpControlplaneToolRegistry:()=>bt(),retriggerCard:t=>Pe(t),applyCardAction:(t,e,r)=>je(t,e,r),resolveChatHandlerTarget:t=>At(t),sendCardFileDownloadResponse:(t,e,r,n)=>Me(t,e,r,n)}).handleRuntimeApi,Le=ue({apiBasePath:w,emitNotifications:t=>V(t),readJsonBody:t=>rt(t),json:(t,e,r)=>et(t,e,r)}).handleNotifyRoute;async function Ue(t,e,r){return !!(await qe(t,e,r)||await $e(t,e,r)||await Ie(t,e,r)||await Le(t,e,r)||await He(t,e,r))}return {get apiBasePath(){return w},get corsHeaders(){return b},get queueLaneTuning(){return I},handleRuntimeApi:Ue,emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);},buildPublishedRuntimePayload:dt,__drainProcessAccumulatedLane:yt,handleChatAgentRequest:Ee,clearChatRecords:Oe,reportSourceFetched(t,e){return kt(t,{ref:e})},reportSourceFetchFailure(t,e){return Pt(t,{reason:e})},get cardStore(){return p[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function _r(g){let w=String(g.apiBasePath||"/api/boards").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.serverMetaStore,B=g.boardRuntimeFactory,$=new Map,N="boards-config.json";function x(){let l=I.getText(N);if(!l)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(l)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function _(l){I.putText(N,JSON.stringify(l,null,2));}function H(l){let R=String(l||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return R.length>0&&R.length<=64?R:null}function E(l){if($.has(l))return $.get(l);let F=x().boards.find(f=>f.id===l)||{},p=B(l,F);return $.set(l,p),p}function T(l,R,F){let p=JSON.stringify(F),f=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;l.writeHead(R,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":f}),l.end(p);}async function S(l,R,F){let p=l.method||"GET",f=F.pathname;if(p==="GET"&&f===w)return T(R,200,{ok:true,boards:x().boards}),true;if(p==="POST"&&f===w){let y=[];for await(let O of l)y.push(O);let k=typeof Buffer<"u"?Buffer.concat(y).toString("utf-8").trim():new TextDecoder().decode(chunkBQUQTOPB_cjs.d(y)).trim(),u={};try{u=k?JSON.parse(k):{};}catch{u={};}let P=H(u.id);if(!P)return T(R,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let v=x();if(v.boards.some(O=>O.id===P))return T(R,409,{error:`Board "${P}" is already registered`}),true;let A=typeof u.label=="string"&&u.label.trim()?u.label.trim():P,D={id:P,label:A};for(let[O,U]of Object.entries(u))O==="id"||O==="label"||U!=null&&(D[O]=U);return v.boards.push(D),_(v),T(R,200,{ok:true,board:D}),true}return false}async function z(l,R,F){let f=F.pathname.match(new RegExp(`^${chunkBQUQTOPB_cjs.c(w)}/([^/]+)(/|$)`));if(!f)return false;let y=H(decodeURIComponent(f[1]));return y?x().boards.some(P=>P.id===y)?!!await E(y).handleRuntimeApi(l,R,F):(T(R,404,{error:`Board "${y}" not registered. POST ${w} with {id} to register it first.`}),true):(T(R,400,{error:"Invalid board id"}),true)}async function q(l,R,F){return !!(await S(l,R,F)||await z(l,R,F))}function K(l){if(!x().boards.some(F=>F.id===l))throw Object.assign(new Error(`Board "${l}" not registered`),{statusCode:404});return {service:E(l)}}return {get apiBasePath(){return w},get corsHeaders(){return b},handleApi:q,requireBoardService:K}}exports.a=Mr;exports.b=_r;//# sourceMappingURL=chunk-MQAVZUXB.cjs.map
3
+ //# sourceMappingURL=chunk-MQAVZUXB.cjs.map
@@ -0,0 +1,3 @@
1
+ import {a,b}from'./chunk-JB4Q2W7I.js';import {a as a$3}from'./chunk-XYN5D3GL.js';import {a as a$6,c as c$2}from'./chunk-O5UYCGIN.js';import {p,j,k,l,c as c$1,d as d$1,m,n,e as e$1,a as a$8,b as b$3,o}from'./chunk-37JSBRZO.js';import {a as a$4,d as d$2,b as b$2,c as c$3}from'./chunk-FOFGEABN.js';import {a as a$c}from'./chunk-RKKSVOP2.js';import {a as a$2}from'./chunk-NTICU4OK.js';import {a as a$9,c as c$4}from'./chunk-O7NOHKVR.js';import {a as a$a,b as b$4}from'./chunk-ZJ5M5COT.js';import {i,d,c,b as b$1,g,h}from'./chunk-5VTIOM2U.js';import {a as a$b}from'./chunk-6MD6FVE3.js';import {F,G,q}from'./chunk-EZOXABJ2.js';import {a as a$5}from'./chunk-7QNEV5S3.js';import {a as a$7}from'./chunk-BJGK5FNL.js';import {a as a$1}from'./chunk-NIBLKYXN.js';import {e}from'./chunk-UGB7PC4P.js';function ce(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=a$9(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=c$4(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await a$a(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:b$4(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:b$4(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ke=3e4;function Ve(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function ue(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Ve(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=b$3(T,Date.now(),Ke);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var le={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},de="chat-handler-flow-queue",ot="__probe__echo__probe__";function Mr(g$1){let w=String(g$1.apiBasePath||"/api/board").replace(/\/$/,""),b$3={...le,...g$1.corsHeaders||{}},I=g$1.queueLaneTuning??{},B=g$1.boardId||"",$=Number.isInteger(g$1.chatBootstrapTailTurns)&&g$1.chatBootstrapTailTurns>0?g$1.chatBootstrapTailTurns:1,N=g$1.logger||{info:console.log,warn:console.warn,error:console.error},x=g$1.invocationAdapter,_=g$1.chatFlowRunner||null,H=g$1.notificationTransport||null,E=g$1.serverUrl||null,T=g$1.executionExtra||{},S=g$1.onSseClientConnected,z=g$1.onSseClientDisconnected,q$1=g$1.onChannelSubscribed,K=g$1.onChannelUnsubscribed,l$1=a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F$1(t){function e(a){return {...a,queueStorageForRef(d,C){return a$7(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function r(a){return {...a,queueStorageForRef(d,C){return h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i$1(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c$2=a$4(t.boardAdapter)?r(t.boardAdapter):e(t.boardAdapter),j=t.nonCoreAdapter??(!a$4(c$2)&&P(c$2)?c$2:null),h$1=a$4(c$2)?i(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}):F(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}),M=t.nonCore??(j?G(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),We=c$2.chatStorageForRef(t.chatStoreRef),lt,Je=a$4(c$2)?(()=>{let a=d(c(b$1(c$2.kvStorageForRef(t.cardStoreRef)),c$2.hashFn),N.warn),d$1=g(a,{emitNotification:i$1}),C=o(d$1);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c$2.kvStorageForRef(t.cardStoreRef),C=a$5(q({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i$1});return lt=C,n(C)})(),ft;if(a$4(c$2)){let a=c$2.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c$2.blobStorageForRef(t.artifactsStoreRef),d=a$6(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let ze={async init(a){return h$1.init(a)},async status(a){return h$1.status(a)},async getConfig(a){return h$1.getConfig(a)},async getAllOutputsDataObjects(a){return h$1.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h$1.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h$1.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h$1.buildSseOneShotPayload(a)},async upsertCard(a){return h$1.upsertCard(a)},async removeCard(a){return h$1.removeCard(a)},async sourceDataFetched(a){return h$1.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h$1.sourceDataFetchFailure(a)}};return s={label:t.label,board:h$1,nonCore:M,publicCardStore:lt,boardOps:ze,cardStoreOps:Je,get filesArtifacts(){return ft},get chatStorage(){return We},boardAdapter:c$2,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:c$1(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p$1=g$1.boards.map(F$1),f=new Map;function y(t){return f.get(t)??0}function k$1(t){return t.queueStoreRef}function u(t,e){if(a$4(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$b(n)}let r=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$c(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p$1[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return c$2()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p$1[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p$1[0]??void 0}function ct(t,e$2={}){if(!t||t.length===0)return;let r=e(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e$2.ctx??U(r);if(e$2.appendState!==false&&o&&e$1(o.notification,n),e$2.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l$1.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e$2.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function fe(t){if(!t||t.notificationTeardown||!H||!t.notifyRef)return;let e=await H.subscribe(t.notifyRef,r=>{let n=a$8(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function pe(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await fe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&d$1(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G$1(){for(let t of p$1)await pe(t);}async function at(){await G$1();for(let t=0;t<p$1.length;t++)await ut(p$1[t]),await Rt(p$1[t],t),await ut(p$1[t]);}async function yt(t=false){t||await G$1();for(let e of p$1){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p$1[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function me(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p$1)e.push(...await t(r));return e}function ht(){return p$1[0]??null}function ge(t){return W(t)??ht()}function L(t){let e=ge(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function Re(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=a$1({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=p({boardContexts:p$1,cardOwnerIndex:f,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Se(),readDataObjectsByToken:()=>Ae(),readCardRuntimeArtifacts:()=>Ce(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>me(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>kt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Pt(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>Ct(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),ye=wt.mcpCardStoreFacade,st=wt.createMcpFacade,he=j({boardId:B,bootstrapBoard:()=>at(),sseHub:l$1,onChannelSubscribed:q$1,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>ye()});function we(t){return m(t)}function be(){return n(st())}function bt(){return o({boardId:B,uploadCardFile:Ct,getMcpFacade:()=>st(),controlplane:he})}let it=k({boardId:B,boardContexts:p$1,readChatRecords:(t,e)=>ve(t,e),getChatProcessing:t=>Re(t),chatBootstrapTailTurns:$}),Se=it.readStatusSnapshot,Ce=it.readCardRuntimeArtifacts,Ae=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function Be(t,e){await St(t,e,{syncBoard:true});}async function ke(t,e){await St(t,e,{syncBoard:false});}async function Pe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Oe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function Fe(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function ve(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>ke(t,e),writeChatRecord:(t,e,r,n,o)=>Fe(t,e,r,n,o)}).uploadCardFile;async function At(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function xe(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Te(t,e,r=false,n="",o=""){try{let s=await At(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:de}}:j;a$4(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function Ne(t,e,r){if(e.howToRun==="built-in"&&b$2(e)===de){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Ee(t,e=false){e||await G$1();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await Ne(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function je(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=xe(r?.text),c=i?i.text:r?.text,j=await a$a("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(b$4(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await a$a("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(b$4(M,`chat-send processing update failed for card ${t}`));Te(t,h,true,o,i?.assistant||"");return}await Be(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b$3,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function Bt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function Me(t,e,r,n){let{fileRecord:o,bytes:s}=await Bt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function _e(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function De(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
+ `)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(d$2(e)).trim();return r?JSON.parse(r):{}}async function kt(t,e){let r=typeof e.ref=="string"?e.ref.trim():"";if(!r)return {status:"fail",error:"board-worker success callback requires body.ref"};let n=p$1[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function Pt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=p$1[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Ie=b({sseHub:l$1,queueSseHub:R,corsHeaders:b$3,json:et,buildPublishedRuntimePayload:()=>dt(),onSseClientConnected:S,onChannelSubscribed:q$1,onChannelUnsubscribed:K,apiBasePath:w,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G$1(),bootstrapBoard:()=>at(),boardContexts:p$1,publishPersistedStateSnapshot:t=>ut(t),upsertCardsFromSource:(t,e)=>Rt(t,e)}).handleWatchersRoutes,qe=a$2({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpFacade:()=>st(),createMcpToolRegistry:t=>we(t),resolveCardFileDownloadPayload:(t,e,r)=>Bt(t,e,r),isLikelyTextMimeType:t=>_e(t),sliceTextByLines:(t,e,r)=>De(t,e,r)}).handleAgentfaceApi,$e=a$3({apiBasePath:w,json:et,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G$1(),createMcpWebhookToolRegistry:()=>be()}).handleWebhooksApi,He=ce({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpControlplaneToolRegistry:()=>bt(),retriggerCard:t=>Pe(t),applyCardAction:(t,e,r)=>je(t,e,r),resolveChatHandlerTarget:t=>At(t),sendCardFileDownloadResponse:(t,e,r,n)=>Me(t,e,r,n)}).handleRuntimeApi,Le=ue({apiBasePath:w,emitNotifications:t=>V(t),readJsonBody:t=>rt(t),json:(t,e,r)=>et(t,e,r)}).handleNotifyRoute;async function Ue(t,e,r){return !!(await qe(t,e,r)||await $e(t,e,r)||await Ie(t,e,r)||await Le(t,e,r)||await He(t,e,r))}return {get apiBasePath(){return w},get corsHeaders(){return b$3},get queueLaneTuning(){return I},handleRuntimeApi:Ue,emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);},buildPublishedRuntimePayload:dt,__drainProcessAccumulatedLane:yt,handleChatAgentRequest:Ee,clearChatRecords:Oe,reportSourceFetched(t,e){return kt(t,{ref:e})},reportSourceFetchFailure(t,e){return Pt(t,{reason:e})},get cardStore(){return p$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function _r(g){let w=String(g.apiBasePath||"/api/boards").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.serverMetaStore,B=g.boardRuntimeFactory,$=new Map,N="boards-config.json";function x(){let l=I.getText(N);if(!l)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(l)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function _(l){I.putText(N,JSON.stringify(l,null,2));}function H(l){let R=String(l||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return R.length>0&&R.length<=64?R:null}function E(l){if($.has(l))return $.get(l);let F=x().boards.find(f=>f.id===l)||{},p=B(l,F);return $.set(l,p),p}function T(l,R,F){let p=JSON.stringify(F),f=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;l.writeHead(R,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":f}),l.end(p);}async function S(l,R,F){let p=l.method||"GET",f=F.pathname;if(p==="GET"&&f===w)return T(R,200,{ok:true,boards:x().boards}),true;if(p==="POST"&&f===w){let y=[];for await(let O of l)y.push(O);let k=typeof Buffer<"u"?Buffer.concat(y).toString("utf-8").trim():new TextDecoder().decode(d$2(y)).trim(),u={};try{u=k?JSON.parse(k):{};}catch{u={};}let P=H(u.id);if(!P)return T(R,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let v=x();if(v.boards.some(O=>O.id===P))return T(R,409,{error:`Board "${P}" is already registered`}),true;let A=typeof u.label=="string"&&u.label.trim()?u.label.trim():P,D={id:P,label:A};for(let[O,U]of Object.entries(u))O==="id"||O==="label"||U!=null&&(D[O]=U);return v.boards.push(D),_(v),T(R,200,{ok:true,board:D}),true}return false}async function z(l,R,F){let f=F.pathname.match(new RegExp(`^${c$3(w)}/([^/]+)(/|$)`));if(!f)return false;let y=H(decodeURIComponent(f[1]));return y?x().boards.some(P=>P.id===y)?!!await E(y).handleRuntimeApi(l,R,F):(T(R,404,{error:`Board "${y}" not registered. POST ${w} with {id} to register it first.`}),true):(T(R,400,{error:"Invalid board id"}),true)}async function q(l,R,F){return !!(await S(l,R,F)||await z(l,R,F))}function K(l){if(!x().boards.some(F=>F.id===l))throw Object.assign(new Error(`Board "${l}" not registered`),{statusCode:404});return {service:E(l)}}return {get apiBasePath(){return w},get corsHeaders(){return b},handleApi:q,requireBoardService:K}}export{Mr as a,_r as b};//# sourceMappingURL=chunk-WHKT5HN4.js.map
3
+ //# sourceMappingURL=chunk-WHKT5HN4.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkG4XXRHL2_cjs=require('./chunk-G4XXRHL2.cjs'),chunkQBEQL4TL_cjs=require('./chunk-QBEQL4TL.cjs');function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a=o.get(t);if(!a)return "task-initiate-failure";let w={};for(let R of a.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a.source_defs&&a.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a,input:g}):R?await R({card:a,input:g}):void 0;if(y&&typeof y=="object")for(let k of a.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a.id,card_data:b(a.card_data??{}),requires:w,source_defs:a.source_defs,compute:a.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await chunkQBEQL4TL_cjs.a.run(c,{sourcesData:p});let T={};if(a.provides&&a.provides.length>0)for(let{bindTo:R,ref:y}of a.provides)T[R]=chunkQBEQL4TL_cjs.a.resolve(c,y);else T[a.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=chunkG4XXRHL2_cjs.u(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}exports.a=F;exports.b=H;exports.c=P;exports.d=$;exports.e=J;//# sourceMappingURL=chunk-FFHG3CFU.cjs.map
2
- //# sourceMappingURL=chunk-FFHG3CFU.cjs.map
1
+ 'use strict';var chunkG4XXRHL2_cjs=require('./chunk-G4XXRHL2.cjs'),chunkQBEQL4TL_cjs=require('./chunk-QBEQL4TL.cjs');function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a=o.get(t);if(!a)return "task-initiate-failure";let w={};for(let R of a.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a.source_defs&&a.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a,input:g}):R?await R({card:a,input:g}):void 0;if(y&&typeof y=="object")for(let k of a.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a.id,card_data:b(a.card_data??{}),requires:w,source_defs:a.source_defs,compute:a.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await chunkQBEQL4TL_cjs.a.run(c,{sourcesData:p});let T={};if(a.provides&&a.provides.length>0)for(let{bindTo:R,ref:y}of a.provides)T[R]=chunkQBEQL4TL_cjs.a.resolve(c,y);else T[a.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=chunkG4XXRHL2_cjs.u(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}exports.a=F;exports.b=H;exports.c=P;exports.d=$;exports.e=J;//# sourceMappingURL=chunk-Z26U6RSG.cjs.map
2
+ //# sourceMappingURL=chunk-Z26U6RSG.cjs.map