yaml-flow 8.6.4 → 8.7.0

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 (146) hide show
  1. package/browser/adapters/firebase-storage.js +3 -0
  2. package/browser/adapters/firestore-storage.js +3 -0
  3. package/browser/adapters/localstorage-storage.js +4 -0
  4. package/browser/asset-integrity.json +20 -4
  5. package/browser/server-runtime-controlface.js +8 -0
  6. package/examples/ARCHITECTURE.md +5 -32
  7. package/examples/board/demo-shell-with-server.html +2 -2
  8. package/examples/board/doc.html +2 -2
  9. package/examples/board/server/board-server.js +4 -2
  10. package/examples/board-firestore/README.md +81 -0
  11. package/examples/board-firestore/browser/board-runtime.js +263 -0
  12. package/examples/board-firestore/firestore.indexes.json +29 -0
  13. package/examples/board-firestore/package.json +14 -0
  14. package/examples/board-firestore/server/adapters/firestore-archive-factory.js +59 -0
  15. package/examples/board-firestore/server/adapters/firestore-blob-storage.js +82 -0
  16. package/examples/board-firestore/server/adapters/firestore-board-adapter.js +127 -0
  17. package/examples/board-firestore/server/adapters/firestore-journal-storage.js +54 -0
  18. package/examples/board-firestore/server/adapters/firestore-kv-storage.js +47 -0
  19. package/examples/board-firestore/server/adapters/firestore-lock.js +62 -0
  20. package/examples/board-firestore/server/adapters/firestore-queue-storage.js +186 -0
  21. package/examples/board-firestore/server/adapters/firestore-scratch-storage.js +50 -0
  22. package/examples/board-firestore/server/worker.js +146 -0
  23. package/lib/{artifacts-store-lib-BR-Samty.d.cts → artifacts-store-lib-D9nMkVcE.d.cts} +1 -1
  24. package/lib/{artifacts-store-lib-DT7XlWUL.d.ts → artifacts-store-lib-DSSMqVL2.d.ts} +1 -1
  25. package/lib/artifacts-store-public.d.cts +2 -2
  26. package/lib/artifacts-store-public.d.ts +2 -2
  27. package/lib/board-live-cards-mcp.cjs +1 -1
  28. package/lib/board-live-cards-mcp.d.cts +50 -3
  29. package/lib/board-live-cards-mcp.d.ts +50 -3
  30. package/lib/board-live-cards-mcp.js +1 -1
  31. package/lib/board-live-cards-node.cjs +8 -8
  32. package/lib/board-live-cards-node.d.cts +13 -9
  33. package/lib/board-live-cards-node.d.ts +13 -9
  34. package/lib/board-live-cards-node.js +8 -8
  35. package/lib/{board-live-cards-public-BMUIPOrc.d.ts → board-live-cards-public-D-DJek3X.d.ts} +1 -1
  36. package/lib/{board-live-cards-public-wkNmBIRC.d.cts → board-live-cards-public-DQzPe7A9.d.cts} +1 -1
  37. package/lib/board-live-cards-public-async-3hUuHxDx.d.ts +55 -0
  38. package/lib/board-live-cards-public-async-CgMCYYft.d.cts +55 -0
  39. package/lib/board-live-cards-public.d.cts +1 -1
  40. package/lib/board-live-cards-public.d.ts +1 -1
  41. package/lib/board-live-cards-server-runtime.cjs +1 -1
  42. package/lib/board-live-cards-server-runtime.d.cts +10 -6
  43. package/lib/board-live-cards-server-runtime.d.ts +10 -6
  44. package/lib/board-live-cards-server-runtime.js +1 -1
  45. package/lib/board-platform-adapter-async-DOfEq_HC.d.cts +129 -0
  46. package/lib/board-platform-adapter-async-JZPCzZnH.d.ts +129 -0
  47. package/lib/board-worker-adapter.cjs +3 -3
  48. package/lib/board-worker-adapter.js +3 -3
  49. package/lib/card-store-public.d.cts +1 -1
  50. package/lib/card-store-public.d.ts +1 -1
  51. package/lib/{chat-storage-lib-BIUbE-fM.d.cts → chat-storage-lib-B9Q34Dyv.d.cts} +1 -1
  52. package/lib/{chat-storage-lib-BlG-sobS.d.ts → chat-storage-lib-DB9iSai2.d.ts} +1 -1
  53. package/lib/chat-store-public.d.cts +2 -2
  54. package/lib/chat-store-public.d.ts +2 -2
  55. package/lib/chunk-272IYUKT.cjs +2 -0
  56. package/lib/chunk-5XHOHTLZ.cjs +2 -0
  57. package/lib/chunk-6APH25VI.js +2 -0
  58. package/lib/chunk-7FGPOGRV.cjs +2 -0
  59. package/lib/chunk-7ICPAABP.cjs +7 -0
  60. package/lib/chunk-CPAXTVBQ.cjs +2 -0
  61. package/lib/chunk-DDYSXP2A.cjs +3 -0
  62. package/lib/chunk-EGRHWZRV.js +2 -0
  63. package/lib/chunk-GL2OHR2E.cjs +2 -0
  64. package/lib/chunk-IPLSRN6P.cjs +4 -0
  65. package/lib/chunk-J5J6BG7B.js +2 -0
  66. package/lib/chunk-KAWQPLIE.cjs +2 -0
  67. package/lib/chunk-LPXVVMQT.cjs +2 -0
  68. package/lib/chunk-M3OU6IS5.cjs +2 -0
  69. package/lib/chunk-M6STQR5F.cjs +2 -0
  70. package/lib/chunk-NJJ7WEDT.cjs +2 -0
  71. package/lib/chunk-NKIQRCOM.cjs +2 -0
  72. package/lib/chunk-NM6O35RY.cjs +2 -0
  73. package/lib/chunk-NTICU4OK.js +2 -0
  74. package/lib/chunk-O7NOHKVR.js +2 -0
  75. package/lib/chunk-PRHQBGPT.js +2 -0
  76. package/lib/chunk-S44QZUDX.js +2 -0
  77. package/lib/chunk-SGV7PU4H.js +2 -0
  78. package/lib/chunk-TSN3RTXT.js +4 -0
  79. package/lib/chunk-VXJHBWK3.js +2 -0
  80. package/lib/chunk-WHDEBJLT.js +7 -0
  81. package/lib/chunk-XYN5D3GL.js +2 -0
  82. package/lib/chunk-YGALANRO.js +2 -0
  83. package/lib/chunk-ZJ5M5COT.js +2 -0
  84. package/lib/chunk-ZXQR7GHT.js +3 -0
  85. package/lib/cloud-storage.cjs +1 -1
  86. package/lib/cloud-storage.d.cts +5 -3
  87. package/lib/cloud-storage.d.ts +5 -3
  88. package/lib/cloud-storage.js +1 -1
  89. package/lib/firebase-storage/index.cjs +3 -0
  90. package/lib/firebase-storage/index.d.cts +57 -0
  91. package/lib/firebase-storage/index.d.ts +57 -0
  92. package/lib/firebase-storage/index.js +3 -0
  93. package/lib/firestore-storage/index.cjs +3 -0
  94. package/lib/firestore-storage/index.d.cts +98 -0
  95. package/lib/firestore-storage/index.d.ts +98 -0
  96. package/lib/firestore-storage/index.js +3 -0
  97. package/lib/localstorage-storage/index.cjs +2 -0
  98. package/lib/localstorage-storage/index.d.cts +39 -0
  99. package/lib/localstorage-storage/index.d.ts +39 -0
  100. package/lib/localstorage-storage/index.js +2 -0
  101. package/lib/mcp-tool-registries-BBObLYga.d.ts +41 -0
  102. package/lib/mcp-tool-registries-W3TRj6O5.d.cts +41 -0
  103. package/lib/queue-lane-registry-PaZuFpwp.d.cts +30 -0
  104. package/lib/queue-lane-registry-PaZuFpwp.d.ts +30 -0
  105. package/lib/server-jobs-queue-runner/index.cjs +2 -0
  106. package/lib/server-jobs-queue-runner/index.d.cts +22 -0
  107. package/lib/server-jobs-queue-runner/index.d.ts +22 -0
  108. package/lib/server-jobs-queue-runner/index.js +2 -0
  109. package/lib/server-runtime/index.cjs +1 -1
  110. package/lib/server-runtime/index.d.cts +11 -17
  111. package/lib/server-runtime/index.d.ts +11 -17
  112. package/lib/server-runtime/index.js +1 -1
  113. package/lib/server-runtime-agentface/index.cjs +2 -0
  114. package/lib/server-runtime-agentface/index.d.cts +53 -0
  115. package/lib/server-runtime-agentface/index.d.ts +53 -0
  116. package/lib/server-runtime-agentface/index.js +2 -0
  117. package/lib/server-runtime-controlface/index.cjs +2 -0
  118. package/lib/server-runtime-controlface/index.d.cts +80 -0
  119. package/lib/server-runtime-controlface/index.d.ts +80 -0
  120. package/lib/server-runtime-controlface/index.js +2 -0
  121. package/lib/server-runtime-core/index.cjs +2 -0
  122. package/lib/server-runtime-core/index.d.cts +376 -0
  123. package/lib/server-runtime-core/index.d.ts +376 -0
  124. package/lib/server-runtime-core/index.js +2 -0
  125. package/lib/server-runtime-watchers/index.cjs +2 -0
  126. package/lib/server-runtime-watchers/index.d.cts +127 -0
  127. package/lib/server-runtime-watchers/index.d.ts +127 -0
  128. package/lib/server-runtime-watchers/index.js +2 -0
  129. package/lib/server-runtime-webhooks/index.cjs +2 -0
  130. package/lib/server-runtime-webhooks/index.d.cts +34 -0
  131. package/lib/server-runtime-webhooks/index.d.ts +34 -0
  132. package/lib/server-runtime-webhooks/index.js +2 -0
  133. package/lib/storage-async-interface-BRR4eBjx.d.cts +81 -0
  134. package/lib/storage-async-interface-DhlOVPSp.d.ts +81 -0
  135. package/lib/{queue-lane-registry-BPKWWgd4.d.cts → types-BzQY45dH.d.cts} +8 -34
  136. package/lib/{queue-lane-registry-Be6c0ftj.d.ts → types-CF2xUcZW.d.ts} +8 -34
  137. package/package.json +46 -2
  138. package/examples/board-local/demo-shell-localstorage.html +0 -843
  139. package/lib/board-live-cards-public-async-DKZqbJVU.d.ts +0 -256
  140. package/lib/board-live-cards-public-async-dMWNbWq6.d.cts +0 -256
  141. package/lib/chunk-KXWT3CY6.cjs +0 -8
  142. package/lib/chunk-MLVTJASJ.js +0 -2
  143. package/lib/chunk-OJLA6NLU.js +0 -8
  144. package/lib/chunk-R5L5WUKN.js +0 -2
  145. package/lib/chunk-WOALA3V5.cjs +0 -2
  146. package/lib/chunk-YEB5QHGE.cjs +0 -2
@@ -0,0 +1,129 @@
1
+ import { h as BoardCallbackTransport, B as BoardChangeNotification } from './board-live-cards-public-D-DJek3X.js';
2
+ import { ExecutionRef } from './execution-refs.js';
3
+ import { a as KindValueRef } from './storage-interface-BFiD3kyB.js';
4
+ import { c as AsyncKVStorage, a as AsyncBlobStorage, f as AsyncScratchStorage, A as AsyncArchiveFactory, b as AsyncJournalStorage, e as AsyncQueueStorage, d as AsyncAtomicRelayLock } from './storage-async-interface-DhlOVPSp.js';
5
+
6
+ interface AsyncBoardWorkerRequest {
7
+ boardId?: string;
8
+ ref: ExecutionRef;
9
+ args: Record<string, unknown>;
10
+ }
11
+ interface AsyncBoardWorkerQueuedRequest {
12
+ messageId: string;
13
+ enqueuedAt: string;
14
+ attempt: number;
15
+ request: AsyncBoardWorkerRequest;
16
+ }
17
+ interface AsyncBoardWorkerLeasedRequest extends AsyncBoardWorkerQueuedRequest {
18
+ leaseToken: string;
19
+ leaseExpiresAt: string;
20
+ }
21
+ interface AsyncBoardWorkerDeadLetterRequest extends AsyncBoardWorkerQueuedRequest {
22
+ reason?: string;
23
+ }
24
+ interface AsyncBoardWorkerStore {
25
+ enqueueRequest(request: AsyncBoardWorkerRequest): Promise<string>;
26
+ leaseRequests(opts?: {
27
+ max?: number;
28
+ visibilityMs?: number;
29
+ }): Promise<AsyncBoardWorkerLeasedRequest[]>;
30
+ ackRequest(messageId: string, leaseToken: string): Promise<boolean>;
31
+ nackRequest(messageId: string, leaseToken: string, opts?: {
32
+ dead?: boolean;
33
+ reason?: string;
34
+ }): Promise<boolean>;
35
+ peekActive(): Promise<AsyncBoardWorkerQueuedRequest[]>;
36
+ peekDeadLetter(): Promise<AsyncBoardWorkerDeadLetterRequest[]>;
37
+ }
38
+ interface AsyncBoardConfigStore {
39
+ readTaskExecutorRef(): Promise<ExecutionRef | undefined>;
40
+ writeTaskExecutorRef(ref: ExecutionRef): Promise<void>;
41
+ readChatHandlerFlow(): Promise<unknown>;
42
+ writeChatHandlerFlow(flow: unknown): Promise<void>;
43
+ readCardStoreRef(): Promise<string | null>;
44
+ writeCardStoreRef(ref: string): Promise<void>;
45
+ readOutputsStoreRef(): Promise<string | null>;
46
+ writeOutputsStoreRef(ref: string): Promise<void>;
47
+ readScratchStoreRef(): Promise<string | null>;
48
+ writeScratchStoreRef(ref: string): Promise<void>;
49
+ readArchiveStoreRef(): Promise<string | null>;
50
+ writeArchiveStoreRef(ref: string): Promise<void>;
51
+ readChatStoreRef(): Promise<string | null>;
52
+ writeChatStoreRef(ref: string): Promise<void>;
53
+ readArtifactsStoreRef(): Promise<string | null>;
54
+ writeArtifactsStoreRef(ref: string): Promise<void>;
55
+ }
56
+ interface AsyncBoardPlatformAdapter {
57
+ kvStorage(namespace: string): AsyncKVStorage;
58
+ kvStorageForRef(ref: string): AsyncKVStorage;
59
+ blobStorage(namespace: string): AsyncBlobStorage;
60
+ scratchStorage(): AsyncScratchStorage;
61
+ scratchStorageForRef(ref: string): AsyncScratchStorage;
62
+ archiveFactory(): AsyncArchiveFactory;
63
+ archiveFactoryForRef(ref: string): AsyncArchiveFactory;
64
+ journalStorage(): AsyncJournalStorage;
65
+ boardWorkerStore(): AsyncBoardWorkerStore;
66
+ chatAgentStore(): AsyncBoardWorkerStore;
67
+ processAccumulatedStore(): AsyncQueueStorage;
68
+ lock: AsyncAtomicRelayLock;
69
+ callbackTransport?: BoardCallbackTransport;
70
+ dispatchExecution(ref: ExecutionRef, args: Record<string, unknown>): Promise<{
71
+ dispatched: boolean;
72
+ error?: string;
73
+ }>;
74
+ supportsDirectSourceOutput?(ref: ExecutionRef): boolean;
75
+ resolveBlob(ref: KindValueRef): Promise<string>;
76
+ hashFn(value: unknown): string;
77
+ genId(): string;
78
+ requestProcessAccumulated?(): void | Promise<void>;
79
+ publishBoardChangeNotifications?(notifications: BoardChangeNotification[]): void | Promise<void>;
80
+ warn?: (msg: string) => void;
81
+ }
82
+ interface HostedFetchResponseLike {
83
+ ok: boolean;
84
+ status: number;
85
+ text(): Promise<string>;
86
+ }
87
+ interface HostedFetchLike {
88
+ (input: string, init: {
89
+ method: string;
90
+ headers: Record<string, string>;
91
+ body: string;
92
+ }): Promise<HostedFetchResponseLike>;
93
+ }
94
+ interface HostedAsyncBoardPlatformAdapterOptions {
95
+ boardId?: string;
96
+ kvStorage(namespace: string): AsyncKVStorage;
97
+ kvStorageForRef(ref: string): AsyncKVStorage;
98
+ blobStorage(namespace: string): AsyncBlobStorage;
99
+ scratchStorage(): AsyncScratchStorage;
100
+ scratchStorageForRef(ref: string): AsyncScratchStorage;
101
+ archiveFactory(): AsyncArchiveFactory;
102
+ archiveFactoryForRef(ref: string): AsyncArchiveFactory;
103
+ journalStorage(): AsyncJournalStorage;
104
+ queueStorage?: AsyncQueueStorage;
105
+ boardWorkerStore?: AsyncBoardWorkerStore;
106
+ chatAgentQueueStorage?: AsyncQueueStorage;
107
+ chatAgentStore?: AsyncBoardWorkerStore;
108
+ processAccumulatedQueueStorage?: AsyncQueueStorage;
109
+ processAccumulatedStore?: AsyncQueueStorage;
110
+ lock: AsyncAtomicRelayLock;
111
+ callbackTransport?: BoardCallbackTransport;
112
+ fetch?: HostedFetchLike;
113
+ dispatchExecution?: (ref: ExecutionRef, args: Record<string, unknown>) => Promise<{
114
+ dispatched: boolean;
115
+ error?: string;
116
+ }>;
117
+ supportsDirectSourceOutput?: (ref: ExecutionRef) => boolean;
118
+ resolveBlob?: (ref: KindValueRef) => Promise<string>;
119
+ hashFn: (value: unknown) => string;
120
+ genId: () => string;
121
+ requestProcessAccumulated?: () => void | Promise<void>;
122
+ publishBoardChangeNotifications?: (notifications: BoardChangeNotification[]) => void | Promise<void>;
123
+ onWarn?: (msg: string) => void;
124
+ }
125
+ declare function createAsyncBoardWorkerStore(queue: AsyncQueueStorage): AsyncBoardWorkerStore;
126
+ declare function createAsyncBoardConfigStore(kv: AsyncKVStorage): AsyncBoardConfigStore;
127
+ declare function createHostedAsyncBoardPlatformAdapter(options: HostedAsyncBoardPlatformAdapterOptions): AsyncBoardPlatformAdapter;
128
+
129
+ export { type AsyncBoardPlatformAdapter as A, type HostedAsyncBoardPlatformAdapterOptions as H, type AsyncBoardConfigStore as a, type AsyncBoardWorkerDeadLetterRequest as b, type AsyncBoardWorkerLeasedRequest as c, type AsyncBoardWorkerQueuedRequest as d, type AsyncBoardWorkerRequest as e, type AsyncBoardWorkerStore as f, type HostedFetchLike as g, type HostedFetchResponseLike as h, createAsyncBoardConfigStore as i, createAsyncBoardWorkerStore as j, createHostedAsyncBoardPlatformAdapter as k };
@@ -1,4 +1,4 @@
1
- 'use strict';require('./chunk-GNFE24S7.cjs');var l=require('fs'),a=require('path'),child_process=require('child_process'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var l__namespace=/*#__PURE__*/_interopNamespace(l);var a__namespace=/*#__PURE__*/_interopNamespace(a);var p=new Map;function C(r,e){let t=String(r||"").trim();if(!t)throw new Error("registerInProcessBoardWorkerCallback: key is required");p.set(t,e);}function v(r){let e=String(r||"").trim();e&&p.delete(e);}async function f(r,e){let t=String(e||"").trim();if(!t)throw new Error("in-process-loop callback requires a non-empty handler key");let o=p.get(t);if(!o)throw new Error(`in-process-loop callback handler not registered: ${t}`);let n=await o(r);if(n&&n.status&&n.status!=="success")throw new Error(n.error||`in-process-loop callback failed with status: ${n.status}`)}function g(r,e,t){w(m(r,e,"success"),JSON.stringify({ref:t}));}function h(r,e,t){w(m(r,e,"failure"),JSON.stringify({reason:t}));}function m(r,e,t){return `${String(r||"").replace(/\/+$/,"")}/${encodeURIComponent(e)}/${t}`}function w(r,e){let t=`
1
+ 'use strict';require('./chunk-GNFE24S7.cjs');var l=require('fs'),a=require('path'),child_process=require('child_process'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var l__namespace=/*#__PURE__*/_interopNamespace(l);var a__namespace=/*#__PURE__*/_interopNamespace(a);var p=new Map;function v(r,e){let t=String(r||"").trim();if(!t)throw new Error("registerInProcessBoardWorkerCallback: key is required");p.set(t,e);}function B(r){let e=String(r||"").trim();e&&p.delete(e);}async function f(r,e){let t=String(e||"").trim();if(!t)throw new Error("in-process-loop callback requires a non-empty handler key");let o=p.get(t);if(!o)throw new Error(`in-process-loop callback handler not registered: ${t}`);let n=await o(r);if(n&&n.status&&n.status!=="success")throw new Error(n.error||`in-process-loop callback failed with status: ${n.status}`)}function g(r,e,t){w(m(r),JSON.stringify({tool:"webhook.source-fetch-done",args:{token:e,ref:t}}));}function h(r,e,t){w(m(r),JSON.stringify({tool:"webhook.source-fetch-failed",args:{token:e,reason:t}}));}function m(r){return String(r||"").replace(/\/+$/,"")}function w(r,e){let t=`
2
2
  const rawUrl = ${JSON.stringify(r)};
3
3
  const rawBody = ${JSON.stringify(e)};
4
4
  const u = new URL(rawUrl);
@@ -20,6 +20,6 @@
20
20
  req.on('error', e => { process.stderr.write(e.message); process.exit(1); });
21
21
  req.write(rawBody);
22
22
  req.end();
23
- `,o=child_process.spawnSync(process.execPath,["-e",t],{encoding:"utf-8",windowsHide:true});if(o.status!==0)throw new Error(`http-post failed: ${o.stderr?.trim()}`)}var I=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('board-worker-adapter.cjs', document.baseURI).href)));function b(r,e,t){x(r,["source-data-fetched","--ref",t,"--token",e],"reportComplete");}function y(r,e,t){x(r,["source-data-fetch-failure","--token",e,"--reason",t],"reportFailed");}function x(r,e,t){let o=S(r.whatToRun),{cmd:n,args:s}=$(o),i=P(r),u=child_process.spawnSync(n,[...s,...e,...i?["--notify-channel",i]:[]],{encoding:"utf-8",windowsHide:true});if(u.status!==0)throw new Error(`${t}: board CLI exited ${u.status}: ${u.stderr?.trim()}`)}function S(r){let e=T(r);if(e.kind==="yaml-flow-cli"){let t=a__namespace.basename(e.value.trim());if(!t)throw new Error(`Invalid yaml-flow-cli ref: expected non-empty cli file name, got ${JSON.stringify(e.value)}`);let o=a__namespace.dirname(I.resolve("yaml-flow/package.json")),n=t.replace(/\.[^.]+$/,""),s=a__namespace.join(o,"cli","bundled",`${n}.mjs`);if(l__namespace.existsSync(s))return s;let i=a__namespace.join(o,"cli","node",t);if(l__namespace.existsSync(i))return i;throw new Error(`Invalid yaml-flow-cli ref: could not find ${t} under cli/bundled or cli/node in ${o}`)}return e.value}function P(r){let e=r.extra?.notifyChannel;return typeof e=="string"&&e.length>0?e:void 0}function $(r){if(!r.endsWith(".ts"))return {cmd:process.execPath,args:[r]};let e=a__namespace.dirname(r),t=[];for(let n=1;n<=5;n++){let s=a__namespace.join(e,...Array(n).fill(".."),"node_modules");t.push(a__namespace.join(s,"tsx","dist","cli.mjs")),t.push(a__namespace.join(s,".bin","tsx"));}let o=t.find(n=>l__namespace.existsSync(n));return o?{cmd:process.execPath,args:[o,r]}:{cmd:"npx",args:["tsx",r]}}function T(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function d(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function k(r){return `b64:${Buffer.from(JSON.stringify(r),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function N(){return {read(r){if(!l__namespace.default.existsSync(r))return null;try{return l__namespace.default.readFileSync(r,"utf-8")}catch{return null}},write(r,e){l__namespace.default.mkdirSync(a__namespace.default.dirname(r),{recursive:true}),l__namespace.default.writeFileSync(r,e,"utf-8");}}}function _(r){if(r.kind==="fs-path")return N();throw new Error(`Unsupported storage kind: "${r.kind}". Supported kinds: fs-path`)}function M(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){b(o,t,k(e));return}if(o.howToRun==="http:post"){g(d(o.whatToRun).value,t,k(e));return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"success",ref:k(e)},d(o.whatToRun).value);return}throw new Error(`reportComplete: unsupported via.howToRun "${o.howToRun}"`)}function A(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){y(o,t,e);return}if(o.howToRun==="http:post"){h(d(o.whatToRun).value,t,e);return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"failure",reason:e},d(o.whatToRun).value);return}throw new Error(`reportFailed: unsupported via.howToRun "${o.howToRun}"`)}
24
- exports.blobStorageForRef=_;exports.parseRef=d;exports.registerInProcessBoardWorkerCallback=C;exports.reportComplete=M;exports.reportFailed=A;exports.serializeRef=k;exports.unregisterInProcessBoardWorkerCallback=v;//# sourceMappingURL=board-worker-adapter.cjs.map
23
+ `,o=child_process.spawnSync(process.execPath,["-e",t],{encoding:"utf-8",windowsHide:true});if(o.status!==0)throw new Error(`http-post failed: ${o.stderr?.trim()}`)}var S=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('board-worker-adapter.cjs', document.baseURI).href)));function b(r,e,t){x(r,["source-data-fetched","--ref",t,"--token",e],"reportComplete");}function y(r,e,t){x(r,["source-data-fetch-failure","--token",e,"--reason",t],"reportFailed");}function x(r,e,t){let o=I(r.whatToRun),{cmd:n,args:s}=T(o),i=P(r),u=child_process.spawnSync(n,[...s,...e,...i?["--notify-channel",i]:[]],{encoding:"utf-8",windowsHide:true});if(u.status!==0)throw new Error(`${t}: board CLI exited ${u.status}: ${u.stderr?.trim()}`)}function I(r){let e=E(r);if(e.kind==="yaml-flow-cli"){let t=a__namespace.basename(e.value.trim());if(!t)throw new Error(`Invalid yaml-flow-cli ref: expected non-empty cli file name, got ${JSON.stringify(e.value)}`);let o=a__namespace.dirname(S.resolve("yaml-flow/package.json")),n=t.replace(/\.[^.]+$/,""),s=a__namespace.join(o,"cli","bundled",`${n}.mjs`);if(l__namespace.existsSync(s))return s;let i=a__namespace.join(o,"cli","node",t);if(l__namespace.existsSync(i))return i;throw new Error(`Invalid yaml-flow-cli ref: could not find ${t} under cli/bundled or cli/node in ${o}`)}return e.value}function P(r){let e=r.extra?.notifyChannel;return typeof e=="string"&&e.length>0?e:void 0}function T(r){if(!r.endsWith(".ts"))return {cmd:process.execPath,args:[r]};let e=a__namespace.dirname(r),t=[];for(let n=1;n<=5;n++){let s=a__namespace.join(e,...Array(n).fill(".."),"node_modules");t.push(a__namespace.join(s,"tsx","dist","cli.mjs")),t.push(a__namespace.join(s,".bin","tsx"));}let o=t.find(n=>l__namespace.existsSync(n));return o?{cmd:process.execPath,args:[o,r]}:{cmd:"npx",args:["tsx",r]}}function E(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function d(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function k(r){return `b64:${Buffer.from(JSON.stringify(r),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function N(){return {read(r){if(!l__namespace.default.existsSync(r))return null;try{return l__namespace.default.readFileSync(r,"utf-8")}catch{return null}},write(r,e){l__namespace.default.mkdirSync(a__namespace.default.dirname(r),{recursive:true}),l__namespace.default.writeFileSync(r,e,"utf-8");}}}function _(r){if(r.kind==="fs-path")return N();throw new Error(`Unsupported storage kind: "${r.kind}". Supported kinds: fs-path`)}function M(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){b(o,t,k(e));return}if(o.howToRun==="http:post"){g(d(o.whatToRun).value,t,k(e));return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"success",ref:k(e)},d(o.whatToRun).value);return}throw new Error(`reportComplete: unsupported via.howToRun "${o.howToRun}"`)}function A(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){y(o,t,e);return}if(o.howToRun==="http:post"){h(d(o.whatToRun).value,t,e);return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"failure",reason:e},d(o.whatToRun).value);return}throw new Error(`reportFailed: unsupported via.howToRun "${o.howToRun}"`)}
24
+ exports.blobStorageForRef=_;exports.parseRef=d;exports.registerInProcessBoardWorkerCallback=v;exports.reportComplete=M;exports.reportFailed=A;exports.serializeRef=k;exports.unregisterInProcessBoardWorkerCallback=B;//# sourceMappingURL=board-worker-adapter.cjs.map
25
25
  //# sourceMappingURL=board-worker-adapter.cjs.map
@@ -1,4 +1,4 @@
1
- import'./chunk-FW4363Y4.js';import*as l from'fs';import l__default from'fs';import*as a from'path';import a__default from'path';import {spawnSync}from'child_process';import {createRequire}from'module';var p=new Map;function C(r,e){let t=String(r||"").trim();if(!t)throw new Error("registerInProcessBoardWorkerCallback: key is required");p.set(t,e);}function v(r){let e=String(r||"").trim();e&&p.delete(e);}async function f(r,e){let t=String(e||"").trim();if(!t)throw new Error("in-process-loop callback requires a non-empty handler key");let o=p.get(t);if(!o)throw new Error(`in-process-loop callback handler not registered: ${t}`);let n=await o(r);if(n&&n.status&&n.status!=="success")throw new Error(n.error||`in-process-loop callback failed with status: ${n.status}`)}function g(r,e,t){w(m(r,e,"success"),JSON.stringify({ref:t}));}function h(r,e,t){w(m(r,e,"failure"),JSON.stringify({reason:t}));}function m(r,e,t){return `${String(r||"").replace(/\/+$/,"")}/${encodeURIComponent(e)}/${t}`}function w(r,e){let t=`
1
+ import'./chunk-FW4363Y4.js';import*as l from'fs';import l__default from'fs';import*as a from'path';import a__default from'path';import {spawnSync}from'child_process';import {createRequire}from'module';var p=new Map;function v(r,e){let t=String(r||"").trim();if(!t)throw new Error("registerInProcessBoardWorkerCallback: key is required");p.set(t,e);}function B(r){let e=String(r||"").trim();e&&p.delete(e);}async function f(r,e){let t=String(e||"").trim();if(!t)throw new Error("in-process-loop callback requires a non-empty handler key");let o=p.get(t);if(!o)throw new Error(`in-process-loop callback handler not registered: ${t}`);let n=await o(r);if(n&&n.status&&n.status!=="success")throw new Error(n.error||`in-process-loop callback failed with status: ${n.status}`)}function g(r,e,t){w(m(r),JSON.stringify({tool:"webhook.source-fetch-done",args:{token:e,ref:t}}));}function h(r,e,t){w(m(r),JSON.stringify({tool:"webhook.source-fetch-failed",args:{token:e,reason:t}}));}function m(r){return String(r||"").replace(/\/+$/,"")}function w(r,e){let t=`
2
2
  const rawUrl = ${JSON.stringify(r)};
3
3
  const rawBody = ${JSON.stringify(e)};
4
4
  const u = new URL(rawUrl);
@@ -20,6 +20,6 @@ import'./chunk-FW4363Y4.js';import*as l from'fs';import l__default from'fs';impo
20
20
  req.on('error', e => { process.stderr.write(e.message); process.exit(1); });
21
21
  req.write(rawBody);
22
22
  req.end();
23
- `,o=spawnSync(process.execPath,["-e",t],{encoding:"utf-8",windowsHide:true});if(o.status!==0)throw new Error(`http-post failed: ${o.stderr?.trim()}`)}var I=createRequire(import.meta.url);function b(r,e,t){x(r,["source-data-fetched","--ref",t,"--token",e],"reportComplete");}function y(r,e,t){x(r,["source-data-fetch-failure","--token",e,"--reason",t],"reportFailed");}function x(r,e,t){let o=S(r.whatToRun),{cmd:n,args:s}=$(o),i=P(r),u=spawnSync(n,[...s,...e,...i?["--notify-channel",i]:[]],{encoding:"utf-8",windowsHide:true});if(u.status!==0)throw new Error(`${t}: board CLI exited ${u.status}: ${u.stderr?.trim()}`)}function S(r){let e=T(r);if(e.kind==="yaml-flow-cli"){let t=a.basename(e.value.trim());if(!t)throw new Error(`Invalid yaml-flow-cli ref: expected non-empty cli file name, got ${JSON.stringify(e.value)}`);let o=a.dirname(I.resolve("yaml-flow/package.json")),n=t.replace(/\.[^.]+$/,""),s=a.join(o,"cli","bundled",`${n}.mjs`);if(l.existsSync(s))return s;let i=a.join(o,"cli","node",t);if(l.existsSync(i))return i;throw new Error(`Invalid yaml-flow-cli ref: could not find ${t} under cli/bundled or cli/node in ${o}`)}return e.value}function P(r){let e=r.extra?.notifyChannel;return typeof e=="string"&&e.length>0?e:void 0}function $(r){if(!r.endsWith(".ts"))return {cmd:process.execPath,args:[r]};let e=a.dirname(r),t=[];for(let n=1;n<=5;n++){let s=a.join(e,...Array(n).fill(".."),"node_modules");t.push(a.join(s,"tsx","dist","cli.mjs")),t.push(a.join(s,".bin","tsx"));}let o=t.find(n=>l.existsSync(n));return o?{cmd:process.execPath,args:[o,r]}:{cmd:"npx",args:["tsx",r]}}function T(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function d(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function k(r){return `b64:${Buffer.from(JSON.stringify(r),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function N(){return {read(r){if(!l__default.existsSync(r))return null;try{return l__default.readFileSync(r,"utf-8")}catch{return null}},write(r,e){l__default.mkdirSync(a__default.dirname(r),{recursive:true}),l__default.writeFileSync(r,e,"utf-8");}}}function _(r){if(r.kind==="fs-path")return N();throw new Error(`Unsupported storage kind: "${r.kind}". Supported kinds: fs-path`)}function M(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){b(o,t,k(e));return}if(o.howToRun==="http:post"){g(d(o.whatToRun).value,t,k(e));return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"success",ref:k(e)},d(o.whatToRun).value);return}throw new Error(`reportComplete: unsupported via.howToRun "${o.howToRun}"`)}function A(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){y(o,t,e);return}if(o.howToRun==="http:post"){h(d(o.whatToRun).value,t,e);return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"failure",reason:e},d(o.whatToRun).value);return}throw new Error(`reportFailed: unsupported via.howToRun "${o.howToRun}"`)}
24
- export{_ as blobStorageForRef,d as parseRef,C as registerInProcessBoardWorkerCallback,M as reportComplete,A as reportFailed,k as serializeRef,v as unregisterInProcessBoardWorkerCallback};//# sourceMappingURL=board-worker-adapter.js.map
23
+ `,o=spawnSync(process.execPath,["-e",t],{encoding:"utf-8",windowsHide:true});if(o.status!==0)throw new Error(`http-post failed: ${o.stderr?.trim()}`)}var S=createRequire(import.meta.url);function b(r,e,t){x(r,["source-data-fetched","--ref",t,"--token",e],"reportComplete");}function y(r,e,t){x(r,["source-data-fetch-failure","--token",e,"--reason",t],"reportFailed");}function x(r,e,t){let o=I(r.whatToRun),{cmd:n,args:s}=T(o),i=P(r),u=spawnSync(n,[...s,...e,...i?["--notify-channel",i]:[]],{encoding:"utf-8",windowsHide:true});if(u.status!==0)throw new Error(`${t}: board CLI exited ${u.status}: ${u.stderr?.trim()}`)}function I(r){let e=E(r);if(e.kind==="yaml-flow-cli"){let t=a.basename(e.value.trim());if(!t)throw new Error(`Invalid yaml-flow-cli ref: expected non-empty cli file name, got ${JSON.stringify(e.value)}`);let o=a.dirname(S.resolve("yaml-flow/package.json")),n=t.replace(/\.[^.]+$/,""),s=a.join(o,"cli","bundled",`${n}.mjs`);if(l.existsSync(s))return s;let i=a.join(o,"cli","node",t);if(l.existsSync(i))return i;throw new Error(`Invalid yaml-flow-cli ref: could not find ${t} under cli/bundled or cli/node in ${o}`)}return e.value}function P(r){let e=r.extra?.notifyChannel;return typeof e=="string"&&e.length>0?e:void 0}function T(r){if(!r.endsWith(".ts"))return {cmd:process.execPath,args:[r]};let e=a.dirname(r),t=[];for(let n=1;n<=5;n++){let s=a.join(e,...Array(n).fill(".."),"node_modules");t.push(a.join(s,"tsx","dist","cli.mjs")),t.push(a.join(s,".bin","tsx"));}let o=t.find(n=>l.existsSync(n));return o?{cmd:process.execPath,args:[o,r]}:{cmd:"npx",args:["tsx",r]}}function E(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function d(r){if(!r.startsWith("b64:"))throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${r}`);let e=r.slice(4),t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),o;try{o=JSON.parse(Buffer.from(t,"base64").toString("utf8"));}catch{throw new Error(`Invalid ref format (malformed base64url/json): ${r}`)}if(!o||typeof o!="object")throw new Error(`Invalid ref format (expected object payload): ${r}`);let n=o;if(typeof n.kind!="string"||typeof n.value!="string")throw new Error(`Invalid ref format (payload must contain string kind/value): ${r}`);return {kind:n.kind,value:n.value}}function k(r){return `b64:${Buffer.from(JSON.stringify(r),"utf8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function N(){return {read(r){if(!l__default.existsSync(r))return null;try{return l__default.readFileSync(r,"utf-8")}catch{return null}},write(r,e){l__default.mkdirSync(a__default.dirname(r),{recursive:true}),l__default.writeFileSync(r,e,"utf-8");}}}function _(r){if(r.kind==="fs-path")return N();throw new Error(`Unsupported storage kind: "${r.kind}". Supported kinds: fs-path`)}function M(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){b(o,t,k(e));return}if(o.howToRun==="http:post"){g(d(o.whatToRun).value,t,k(e));return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"success",ref:k(e)},d(o.whatToRun).value);return}throw new Error(`reportComplete: unsupported via.howToRun "${o.howToRun}"`)}function A(r,e){let{token:t,via:o}=r;if(o.howToRun==="local-node"||o.howToRun==="local-process"){y(o,t,e);return}if(o.howToRun==="http:post"){h(d(o.whatToRun).value,t,e);return}if(o.howToRun==="in-process-loop"){f({token:t,outcome:"failure",reason:e},d(o.whatToRun).value);return}throw new Error(`reportFailed: unsupported via.howToRun "${o.howToRun}"`)}
24
+ export{_ as blobStorageForRef,d as parseRef,v as registerInProcessBoardWorkerCallback,M as reportComplete,A as reportFailed,k as serializeRef,B as unregisterInProcessBoardWorkerCallback};//# sourceMappingURL=board-worker-adapter.js.map
25
25
  //# sourceMappingURL=board-worker-adapter.js.map
@@ -1,4 +1,4 @@
1
- import { a as CommandInput, C as CommandResult, L as LiveCard, b as CardAdminStore } from './board-live-cards-public-wkNmBIRC.cjs';
1
+ import { C as CommandInput, a as CommandResult, L as LiveCard, b as CardAdminStore } from './board-live-cards-public-DQzPe7A9.cjs';
2
2
  import './storage-interface-BFiD3kyB.cjs';
3
3
  import './execution-refs.cjs';
4
4
  import './types-BBhqYGhE.cjs';
@@ -1,4 +1,4 @@
1
- import { a as CommandInput, C as CommandResult, L as LiveCard, b as CardAdminStore } from './board-live-cards-public-BMUIPOrc.js';
1
+ import { C as CommandInput, a as CommandResult, L as LiveCard, b as CardAdminStore } from './board-live-cards-public-D-DJek3X.js';
2
2
  import './storage-interface-BFiD3kyB.js';
3
3
  import './execution-refs.js';
4
4
  import './types-BBhqYGhE.js';
@@ -51,4 +51,4 @@ interface ChatStorage {
51
51
  declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
52
52
  declare function createInMemoryChatStorage(): ChatStorage;
53
53
 
54
- export { type ChatRecord as C, type ChatReadAfterResult as a, type ChatConfig as b, type ChatStorage as c, createChatStorage as d, createInMemoryChatStorage as e };
54
+ export { type ChatStorage as C, type ChatRecord as a, type ChatReadAfterResult as b, type ChatConfig as c, createChatStorage as d, createInMemoryChatStorage as e };
@@ -51,4 +51,4 @@ interface ChatStorage {
51
51
  declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
52
52
  declare function createInMemoryChatStorage(): ChatStorage;
53
53
 
54
- export { type ChatRecord as C, type ChatReadAfterResult as a, type ChatConfig as b, type ChatStorage as c, createChatStorage as d, createInMemoryChatStorage as e };
54
+ export { type ChatStorage as C, type ChatRecord as a, type ChatReadAfterResult as b, type ChatConfig as c, createChatStorage as d, createInMemoryChatStorage as e };
@@ -1,5 +1,5 @@
1
- import { a as CommandInput, C as CommandResult } from './board-live-cards-public-wkNmBIRC.cjs';
2
- import { C as ChatRecord, a as ChatReadAfterResult, b as ChatConfig, c as ChatStorage } from './chat-storage-lib-BIUbE-fM.cjs';
1
+ import { C as CommandInput, a as CommandResult } from './board-live-cards-public-DQzPe7A9.cjs';
2
+ import { a as ChatRecord, b as ChatReadAfterResult, c as ChatConfig, C as ChatStorage } from './chat-storage-lib-B9Q34Dyv.cjs';
3
3
  import './storage-interface-BFiD3kyB.cjs';
4
4
  import './execution-refs.cjs';
5
5
  import './types-BBhqYGhE.cjs';
@@ -1,5 +1,5 @@
1
- import { a as CommandInput, C as CommandResult } from './board-live-cards-public-BMUIPOrc.js';
2
- import { C as ChatRecord, a as ChatReadAfterResult, b as ChatConfig, c as ChatStorage } from './chat-storage-lib-BlG-sobS.js';
1
+ import { C as CommandInput, a as CommandResult } from './board-live-cards-public-D-DJek3X.js';
2
+ import { a as ChatRecord, b as ChatReadAfterResult, c as ChatConfig, C as ChatStorage } from './chat-storage-lib-DB9iSai2.js';
3
3
  import './storage-interface-BFiD3kyB.js';
4
4
  import './execution-refs.js';
5
5
  import './types-BBhqYGhE.js';
@@ -0,0 +1,2 @@
1
+ 'use strict';async function u(t,i,o){let s=o[t];if(!s)throw Object.assign(new Error(`Unknown MCP tool: ${t}`),{statusCode:400});let r=await s(i);if(r&&typeof r=="object"&&!Array.isArray(r)){let n=r,e=n.status;if(e==="success")return Object.prototype.hasOwnProperty.call(n,"data")?r:{status:"success",data:{}};if(e==="fail"||e==="error")return r}return {status:"success",data:r}}function f(t,i){if(!t||typeof t!="object"||Array.isArray(t))return i;let o=t;if(typeof o.error=="string"&&o.error.trim())return o.error;if(o.step==="validate"){let s=o.validation;if(s&&typeof s=="object"&&!Array.isArray(s)){let n=s.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n.issues;if(Array.isArray(e)){let c=e.find(d=>typeof d=="string"&&d.trim());if(typeof c=="string")return `Validation failed: ${c}`}let a=n.errors;if(Array.isArray(a)&&a.length>0)return "Validation failed"}}return "Validation failed"}return i}exports.a=u;exports.b=f;//# sourceMappingURL=chunk-272IYUKT.cjs.map
2
+ //# sourceMappingURL=chunk-272IYUKT.cjs.map
@@ -0,0 +1,2 @@
1
+ 'use strict';function T(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.code=="number")return t.code}function c(e,t){return T(e)===t}function l(e,t,r){return t?typeof t=="function"?t(e):t:r}function b(e){return (e?.()??new Date).toISOString()}function L(e,t){if(t)return t();let r=String((e?.()??new Date).getTime()).padStart(13,"0"),n=Math.random().toString(36).slice(2,10).padEnd(8,"0");return `${r}-${n}`}function p(e){return {id:e.id,payload:e.payload}}function B(e,t={}){return {async read(r){let n=l(r,t.partitionKey,"kv");try{return (await e.item(r,n).read()).resource?.value??null}catch(o){if(c(o,404))return null;throw o}},async write(r,n){let o=l(r,t.partitionKey,"kv");await e.items.upsert({id:r,pk:o,kind:"kv",value:n});},async delete(r){let n=l(r,t.partitionKey,"kv");try{await e.item(r,n).delete();}catch(o){if(!c(o,404))throw o}},async listKeys(r=""){let{resources:n}=await e.items.query({query:"SELECT c.id FROM c WHERE c.kind = @kind AND STARTSWITH(c.id, @prefix)",parameters:[{name:"@kind",value:"kv"},{name:"@prefix",value:r}]}).fetchAll();return n.map(o=>o.id).sort()}}}function x(e,t,r={}){let n=l(t,r.partitionKey,`journal:${t}`);return {async append(o){let s={id:L(r.now,r.idFactory),pk:n,kind:"journal",streamKey:t,createdAt:b(r.now),payload:o};return await e.items.create(s),p(s)},async readAll(){let{resources:o}=await e.items.query({query:"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey ORDER BY c.id",parameters:[{name:"@kind",value:"journal"},{name:"@pk",value:n},{name:"@streamKey",value:t}]}).fetchAll();return o.sort((s,a)=>s.id.localeCompare(a.id)).map(p)},async readAfter(o){let{resources:s}=await e.items.query({query:o?"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey AND c.id > @cursor ORDER BY c.id":"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey ORDER BY c.id",parameters:[{name:"@kind",value:"journal"},{name:"@pk",value:n},{name:"@streamKey",value:t},...o?[{name:"@cursor",value:o}]:[]]}).fetchAll(),a=s.sort((m,g)=>m.id.localeCompare(g.id));return {entries:a.map(p),newCursor:a.length>0?a[a.length-1].id:o}},async clear(){let o=await this.readAll();await Promise.all(o.map(s=>e.item(s.id,n).delete()));}}}function D(e,t,r={}){let n=r.partitionKey??"lock",o=r.holderId??`holder-${Math.random().toString(36).slice(2,10)}`,s=r.now,a=r.ttlMs??3e4;function m(){let i=s?.()??new Date;return {id:t,pk:n,kind:"lock",held:true,holderId:o,expiresAt:new Date(i.getTime()+a).toISOString(),updatedAt:i.toISOString()}}function g(i){return {...i??{id:t,pk:n,kind:"lock"},kind:"lock",held:false,holderId:o,expiresAt:null,updatedAt:b(s)}}async function k(){try{return (await e.item(t,n).read()).resource??null}catch(i){if(c(i,404))return null;throw i}}function S(i){return i?.held?i.expiresAt?Date.parse(i.expiresAt)>(s?.()??new Date).getTime():true:false}return {async tryAcquire(){let i=await k(),A=m();if(i){if(S(i))return null;try{await e.item(t,n).replace(A,i._etag?{accessCondition:{type:"IfMatch",condition:i._etag}}:void 0);}catch(u){if(c(u,412)||c(u,409))return null;throw u}}else try{await e.items.create(A);}catch(u){if(c(u,409))return null;throw u}return async()=>{let u=await k();if(!u)return;let w=g(u);try{await e.item(t,n).replace(w,u._etag?{accessCondition:{type:"IfMatch",condition:u._etag}}:void 0);}catch{}}}}}function M(e){return new TextDecoder().decode(e)}function P(e,t={}){return {async read(r){if(!await e.getBlobClient(r).exists())return null;let n=await e.getBlobClient(r).downloadToBuffer();return M(n)},async write(r,n){await e.getBlockBlobClient(r).upload(n,new TextEncoder().encode(n).byteLength,{blobHTTPHeaders:{blobContentType:t.defaultContentType??"application/json; charset=utf-8"}});},exists(r){return e.getBlobClient(r).exists()},async remove(r){await e.getBlobClient(r).deleteIfExists();},async readBytes(r){return await e.getBlobClient(r).exists()?await e.getBlobClient(r).downloadToBuffer():null},async writeBytes(r,n){await e.getBlockBlobClient(r).upload(n,n.byteLength,{blobHTTPHeaders:{blobContentType:t.defaultContentType??"application/octet-stream"}});},async listKeys(r=""){let n=[];for await(let o of e.listBlobsFlat({prefix:r}))n.push(o.name);return n.sort()},async stat(r){if(!await e.getBlobClient(r).exists())return null;let n=await e.getBlobClient(r).getProperties();return {key:r,size:Number(n.contentLength??0),updatedAt:n.lastModified?.toISOString(),contentType:n.contentType}},keyRef(r){return t.keyRef?.(r)??{kind:"azure-blob-key",value:r}}}}function C(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.code=="number")return t.code}function y(e){let t=JSON.stringify(e),r=globalThis.Buffer;if(r)return r.from(t,"utf-8").toString("base64");if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this runtime")}function f(e){let t=e??"",r=globalThis.Buffer;if(r)return JSON.parse(r.from(t,"base64").toString("utf-8"));if(typeof atob=="function")return JSON.parse(atob(t));throw new Error("No base64 decoder available in this runtime")}function d(e,t){return (e??t()).toISOString()}function v(e,t){return {id:String(e.messageId??""),body:f(e.messageText),enqueuedAt:d(e.insertedOn??e.insertionTime,t),attempt:Number(e.dequeueCount??0)}}function h(e,t){return {id:String(e.messageId??""),body:f(e.messageText),enqueuedAt:d(e.insertedOn??e.insertionTime,t),attempt:Number(e.dequeueCount??0),leaseToken:String(e.popReceipt??""),leaseExpiresAt:d(e.nextVisibleOn,t)}}function R(e,t={}){let r=t.now??(()=>new Date);return {async enqueue(n){let o=await e.sendMessage(y(n));return {id:String(o.messageId??""),body:n,enqueuedAt:d(o.insertionTime,r),attempt:0}},async lease(n){return (await e.receiveMessages({numberOfMessages:n?.max,visibilityTimeout:n?.visibilityMs?Math.max(1,Math.ceil(n.visibilityMs/1e3)):void 0})).receivedMessageItems.map(s=>h(s,r))},async ack(n,o){try{return await e.deleteMessage(n,o),!0}catch(s){if(C(s)===404)return false;throw s}},async nack(n,o,s){try{if(s?.dead){if(!t.deadLetterQueueClient)return !1;let a={messageId:n,reason:s.reason??null};return await t.deadLetterQueueClient.sendMessage(y(a)),await e.deleteMessage(n,o),!0}return await e.updateMessage(n,o,y({requeued:!0}),0),!0}catch(a){if(C(a)===404)return false;throw a}},async peekActive(n=""){return (await e.peekMessages({numberOfMessages:32})).peekedMessageItems.map(s=>v(s,r)).filter(s=>!n||s.id.startsWith(n))},async peekDeadLetter(n=""){return t.deadLetterQueueClient?(await t.deadLetterQueueClient.peekMessages({numberOfMessages:32})).peekedMessageItems.map(s=>{let a=f(s.messageText);return {id:String(s.messageId??""),body:a,enqueuedAt:d(s.insertedOn??s.insertionTime,r),attempt:Number(s.dequeueCount??0),reason:typeof a.reason=="string"?a.reason:void 0}}).filter(s=>!n||s.id.startsWith(n)):[]}}}exports.a=B;exports.b=x;exports.c=D;exports.d=P;exports.e=R;//# sourceMappingURL=chunk-5XHOHTLZ.cjs.map
2
+ //# sourceMappingURL=chunk-5XHOHTLZ.cjs.map
@@ -0,0 +1,2 @@
1
+ function p(e){return String(e).replace(/[^a-zA-Z0-9_-]/g,"_")}function m(e){let n=e.payload??{};return {id:e.id,role:typeof n.role=="string"?n.role:"system",text:typeof n.text=="string"?n.text:"",files:Array.isArray(n.files)?n.files:[],turn:typeof n.turn=="string"?n.turn:"",updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function R(e,n){let a=t=>`chats/${p(t)}/processing`,r=t=>`chats/${p(t)}/config`;return {append(t,i,o,u=[],s=""){return e(t).append({role:i,text:o,files:u,turn:s,updated_at:new Date().toISOString()}).id},readAll(t){return e(t).readAll().map(m)},readAfter(t,i){let o=e(t).readAfter(i);return {records:o.entries.map(m),cursor:o.newCursor}},clear(t){e(t).clear?.();},setProcessing(t,i){i?n.write(a(t),true):n.delete(a(t));},isProcessing(t){return n.read(a(t))===true},getConfig(t){return n.read(r(t))??{}},setConfig(t,i){let o=n.read(r(t))??{};n.write(r(t),{...o,...i});}}}function S(){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?String(e.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function $(){let e=new Map,n=new Map;function a(r){return e.has(r)||e.set(r,[]),e.get(r)}return {append(r,t,i,o=[],u=""){let s={id:S(),role:t,text:i,files:o,turn:u,updated_at:new Date().toISOString()};return a(r).push(s),s.id},readAll(r){return a(r).slice()},readAfter(r,t){let i=a(r);if(!t)return {records:i.slice(),cursor:i.length>0?i[i.length-1].id:null};let o=i.findIndex(s=>s.id===t),u=o===-1?i.slice():i.slice(o+1);return {records:u,cursor:u.length>0?u[u.length-1].id:t}},clear(r){e.set(r,[]);},setProcessing(r,t){t?n.set(`p:${r}`,true):n.delete(`p:${r}`);},isProcessing(r){return n.get(`p:${r}`)===true},getConfig(r){return n.get(`c:${r}`)??{}},setConfig(r,t){let i=n.get(`c:${r}`)??{};n.set(`c:${r}`,{...i,...t});}}}function y(){return new Date().toISOString()}function x(e){return new TextEncoder().encode(e).byteLength}function A(e){return e?{key:e.key,size:e.size,updatedAt:e.updatedAt,contentType:e.contentType}:null}function w(e){let n=String(e||"").match(/^(\d+)[-_]/);return n?parseInt(n[1],10):0}function I(e){let n=String(e||"").trim();if(!n)return "upload.bin";let a=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (a>=0?n.slice(a+1):n)||"upload.bin"}function k(e){return String(e||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function z(e){if(!e||e===".")return "";let n=String(e).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return n?`.${n}`:""}function F(e){let n=I(e),a=n.lastIndexOf(".");return a<=0||a===n.length-1?{stem:n,ext:""}:{stem:n.slice(0,a),ext:n.slice(a)}}function M(e){let n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function L(e){function n(a){let r=e.stat?A(e.stat(a)):null;if(r)return r;if(!e.exists(a))return null;let t=e.read(a);return t===null?{key:a}:{key:a,size:x(t)}}return {exists(a){return e.exists(a)},putText(a,r,t="text/plain; charset=utf-8"){e.write(a,r);let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??x(r),i},putBytes(a,r,t="application/octet-stream"){if(e.writeBytes)e.writeBytes(a,r);else {let o=JSON.stringify({__kind:"bytes-array",data:[...r]});e.write(a,o);}let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??r.byteLength,i},getText(a){let r=e.read(a);if(r===null){if(!e.readBytes)return null;let t=e.readBytes(a);return t===null?null:Buffer.from(t).toString("utf-8")}try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new TextDecoder("utf-8").decode(new Uint8Array(t.data))}catch{}return r},getBytes(a){if(e.readBytes){let t=e.readBytes(a);if(t!==null)return t}let r=e.read(a);if(r===null)return null;try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new Uint8Array(t.data)}catch{}return new TextEncoder().encode(r)},head:n,list(a=""){return e.listKeys(a).map(r=>n(r)??{key:r}).sort((r,t)=>r.key.localeCompare(t.key))},remove(a){e.remove(a);}}}function b(e){function n(t,i){let o=0,u=[];Array.isArray(i)&&u.push(...i);for(let s of e.list(`${t}/`))u.push(M(s.key));for(let s of u){let l=w(s);Number.isFinite(l)&&l>o&&(o=l);}return o+1}function a(t,i,o){let u=Number(o?.maxLen||32),{stem:s,ext:l}=F(t),h=z(l),C=k(s),d=`${String(i).padStart(3,"0")}-`,g=h,f=u-d.length-g.length;f<1&&(g="",f=u-d.length);let _=C.slice(0,Math.max(1,f)),c=`${d}${_}${g}`;return c.length>u&&(c=c.slice(0,u).replace(/\.$/,"")),c}function r(t,i,o){let u=n(t,o?.seedNames),s=a(i,u,{maxLen:o?.maxLen});for(;e.exists(`${t}/${s}`);)u+=1,s=a(i,u,{maxLen:o?.maxLen});return s}return {nextSerial:n,buildStoredName:a,allocateStoredName:r}}function N(){function e(t,i){if(!Array.isArray(t))return [];let o=[];for(let u of t){if(!u||typeof u!="object")continue;let s=u;typeof s.stored_name=="string"&&o.push({name:typeof s.name=="string"?s.name:s.stored_name,stored_name:s.stored_name,size:typeof s.size=="number"&&Number.isFinite(s.size)?s.size:null,mime_type:typeof s.mime_type=="string"?s.mime_type:null,uploaded_at:typeof s.uploaded_at=="string"?s.uploaded_at:i||null,chat:s.chat===true});}return o}function n(t){return !t||typeof t!="object"?[]:e(t.files,void 0)}function a(t,i){let o=n(t);if(i.length===0)return t.files=o,o;let u=new Set(o.map(s=>s.stored_name));for(let s of i)u.has(s.stored_name)||(o.push(s),u.add(s.stored_name));return t.files=o,o}function r(t,i,o){let u=n(t);if(!Number.isInteger(i)||i<0||i>=u.length)return {ok:false,reason:"index_out_of_range"};let s=u[i];return !s||!s.stored_name?{ok:false,reason:"missing_stored_name"}:o&&o!==s.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:s}}return {read:n,normalizeIncoming:e,merge:a,resolve:r}}export{R as a,$ as b,L as c,b as d,N as e};//# sourceMappingURL=chunk-6APH25VI.js.map
2
+ //# sourceMappingURL=chunk-6APH25VI.js.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs');function G(q){let{apiBasePath:x,json:r,readJsonBody:k,bootstrapBoard:T,createMcpFacade:B,createMcpToolRegistry:I,resolveCardFileDownloadPayload:j,isLikelyTextMimeType:v,sliceTextByLines:C}=q;async function D(b,e,N){let A=b.method||"GET",M=N,L=M.pathname;try{if(A==="POST"&&L===`${x}/mcp`){await T();let t=await k(b),i=typeof t.tool=="string"?t.tool.trim():"",a=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i==="inspect.file-contents")return r(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let n=await chunk272IYUKT_cjs.a(i,a,I(B()));if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;if(s.status==="fail")return r(e,400,{error:chunk272IYUKT_cjs.b(n,"Request failed")}),!0;if(s.status==="error")return r(e,500,{error:chunk272IYUKT_cjs.b(n,"Internal error")}),!0}r(e,200,n);}catch(n){let s=typeof n?.statusCode=="number"?Number(n.statusCode):500,d=n instanceof Error?n.message:String(n);r(e,s,{error:d});}return !0}if(A==="POST"&&L===`${x}/mcp-raw`){await T();let t=await k(b),i=typeof t.tool=="string"?t.tool.trim():"",a=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i!=="inspect.file-contents")return r(e,400,{error:`Tool does not support raw response: ${i}`}),!0;let n=chunkLPXVVMQT_cjs.a(a,"card_id","cardId"),s=chunkLPXVVMQT_cjs.b(a,"file_idx","fileIdx"),d=chunkLPXVVMQT_cjs.b(a,"head-lines","headLines"),m=chunkLPXVVMQT_cjs.b(a,"tail-lines","tailLines"),f=chunkLPXVVMQT_cjs.b(a,"head-bytes","headBytes"),y=chunkLPXVVMQT_cjs.b(a,"tail-bytes","tailBytes");if(!n)return r(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(s===void 0||!Number.isInteger(s)||s<0)return r(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([d,m,f,y].filter(o=>o!==void 0).length>1)return r(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[o,u]of [["head-lines",d],["tail-lines",m],["head-bytes",f],["tail-bytes",y]])if(u!==void 0&&(!Number.isInteger(u)||u<0))return r(e,400,{error:`inspect.file-contents requires ${o} to be a non-negative integer`}),!0;let F=await B().inspectFileContents({cardId:n,fileIdx:s}),$=typeof F?.stored_name=="string"?F.stored_name:null,{fileRecord:R,bytes:p}=await j(n,s,$),P=String(R.name||R.stored_name||"download.bin"),w=String(R.mime_type||"application/octet-stream"),g=(M.searchParams.get("resp")||"").trim().toLowerCase();if(g&&g!=="json-b64")return r(e,400,{error:`unsupported resp mode: ${g}`}),!0;let U=g==="json-b64",c;if(d!==void 0||m!==void 0){if(!v(w))return r(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let o=new TextDecoder().decode(p),u=d!==void 0?C(o,"head",d):C(o,"tail",m);c=typeof Buffer<"u"?Buffer.from(u,"utf8"):new TextEncoder().encode(u);}else if(f!==void 0||y!==void 0){let o=f??y;c=f!==void 0?p.slice(0,o):p.slice(Math.max(0,p.length-o));}else c=p;if(U){let o=typeof Buffer<"u"?Buffer.from(c).toString("base64"):btoa(String.fromCharCode(...c));return r(e,200,{bodyBase64:o,mimeType:w,filename:P,byteLength:c.length}),!0}return e.writeHead(200,{"Content-Type":w,"Content-Disposition":`attachment; filename="${P}"`,"Content-Length":c.length}),e.end(c),!0}return !1}catch(t){let i=t?.statusCode||500;return r(e,i,{error:String(t?.message||t)}),true}}return {handleAgentfaceApi:D}}exports.a=G;//# sourceMappingURL=chunk-7FGPOGRV.cjs.map
2
+ //# sourceMappingURL=chunk-7FGPOGRV.cjs.map
@@ -0,0 +1,7 @@
1
+ 'use strict';var chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs');function A(h){let r=new Map,a=new Map,d=new Map,I=0,b=null;function g(e){let t=JSON.stringify(e);return I++,`id: ${I}
2
+ data: ${t}
3
+
4
+ `}function C(e){let t=e;try{t.flushHeaders?.();}catch{}try{t.flush?.();}catch{}try{t.socket?.setNoDelay?.(!0);}catch{}try{t.socket?.uncork?.();}catch{}}function y(e,t){let s=r.get(e);if(s&&!(t&&s.res!==t)){r.delete(e),w();try{h.onSseClientDisconnected?.(e);}catch{}try{s.res.end();}catch{}}}function v(e,t,s){let n=r.get(e);n&&y(e,n.res),r.set(e,{res:t,subscribedChatCardIds:s??new Set});}function f(e,t){let s=r.get(e);if(!s)return;let n=g(t);try{s.res.write(n),C(s.res);}catch{y(e,s.res);}}function c(){let e=new Set;for(let t of r.values())for(let s of t.subscribedChatCardIds)e.add(s);return Array.from(e)}function l(e){let t=a.has(e)?a.get(e):null,{cursor:s}=h.chatStorage.readAfter(e,t),n=h.chatStorage.isProcessing(e),o=n!==(d.get(e)??false),S=s!==t;return S&&a.set(e,s),d.set(e,n),S||o}function u(e,t){let s=h.readChatRecords(e),n=Date.now();return {kind:"card_chats",cardId:e,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:s.map(o=>({role:String(o.role||"system"),text:String(o.text||""),files:Array.isArray(o.files)?o.files:[]})),receiving:t,processing:h.chatStorage.isProcessing(e)}}function i(e,t=true){let s={kind:"notification-batch",notifications:[u(e,t)]};for(let[n,o]of r.entries())o.subscribedChatCardIds.has(e)&&f(n,s);}function w(){c().length>0||(b&&(clearInterval(b),b=null),a.clear(),d.clear());}function p(){if(b)return;let e=()=>{let t=c();if(t.length===0){w();return}let s=new Set(t);for(let n of Array.from(a.keys()))s.has(n)||a.delete(n);for(let n of Array.from(d.keys()))s.has(n)||d.delete(n);for(let n of t)l(n)&&i(n,true);};e(),b=setInterval(e,1e3);}function k(e,t){let s=r.get(e);if(!s)return false;s.subscribedChatCardIds.add(t);let{cursor:n}=h.chatStorage.readAfter(t,null);return a.set(t,n),d.set(t,h.chatStorage.isProcessing(t)),p(),f(e,{kind:"notification-batch",notifications:[u(t,true)]}),true}function m(e,t){let s=r.get(e);return s?(s.subscribedChatCardIds.delete(t),c().includes(t)||(a.delete(t),d.delete(t)),w(),true):false}function R(e){if(!e||typeof e!="object")return false;let t=e.kind;return t==="card_chats"||t==="chat_messages"}function P(e){if(!e||e.length===0)return;let t=[],s=new Set;for(let n of e)R(n)&&typeof n.cardId=="string"?s.add(String(n.cardId)):t.push(n);if(t.length>0){let n={kind:"notification-batch",notifications:t};for(let o of r.keys())f(o,n);}for(let n of s)i(n,true);}return {size:()=>r.size,has:e=>r.has(e),get:e=>r.get(e),buildFrame:g,flushTransport:C,register:v,disconnect:y,writeFrame:f,subscribeChat:k,unsubscribeChat:m,broadcastNotificationBatch:P,broadcastCardChats:i}}function D(h){let{sseHub:r,corsHeaders:a,json:d,buildPublishedRuntimePayload:I,onSseClientConnected:b,onChannelSubscribed:g,onChannelUnsubscribed:C}=h;function y(f,c,l,u,i){if(!r.has(c)){d(f,404,{error:`SSE client not connected: ${c}`});return}i?g?.(c,l,u):C?.(c,l,u),d(f,200,{ok:true,clientId:c,channelName:l,...u.cardId?{cardId:u.cardId}:{},subscribed:i});}async function v(f,c,l){let u=r.get(l),i=u?new Set(u.subscribedChatCardIds):new Set;c.writeHead(200,{...a,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushTransport(c),r.register(l,c,i);let w=await I(),p=r.buildFrame(w);c.write(p);try{b?.(l,m=>{r.writeFrame(l,m);});}catch{}let k=setInterval(()=>{try{c.write(`: keepalive
5
+
6
+ `);}catch{}},15e3);f.on("close",()=>{clearInterval(k),r.disconnect(l,c);});}return {handleChannelSubscription:y,handleSse:v}}function T(h){let{apiBasePath:r,json:a,readJsonBody:d,initBoardAndSetup:I,bootstrapBoard:b,boardContexts:g,publishPersistedStateSnapshot:C,upsertCardsFromSource:y,sseHub:v}=h,{handleSse:f,handleChannelSubscription:c}=D(h);async function l(u,i,w){let p=u.method||"GET",k=w,m=k.pathname;try{if(p==="GET"&&m===`${r}/sse`){await I();let s=String(k.searchParams.get("clientId")||"").trim();if(!s)return a(i,400,{error:"clientId query param is required for SSE"}),!0;await f(u,i,s);for(let n=0;n<g.length;n++)await C(g[n]),await y(g[n],n),await C(g[n]);return !0}let R=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/chats/subscribe-sse$`));if(p==="POST"&&R){await b();let s=decodeURIComponent(R[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.subscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!0}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let P=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(p==="POST"&&P){await b();let s=decodeURIComponent(P[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.unsubscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!1}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let e=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&e){await b();let s=decodeURIComponent(e[1]),n=e[2]==="subscribe",o=await d(u),S=typeof o?.clientId=="string"?o.clientId.trim():"";return S?(c(i,S,s,{},n),!0):(a(i,400,{error:"clientId is required"}),!0)}let t=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&t){await b();let s=decodeURIComponent(t[1]),n=decodeURIComponent(t[2]),o=t[3]==="subscribe",S=await d(u),H=typeof S?.clientId=="string"?S.clientId.trim():"";return H?(c(i,H,n,{cardId:s},o),!0):(a(i,400,{error:"clientId is required"}),!0)}return !1}catch(R){let P=R?.statusCode||500;return a(i,P,{error:String(R?.message||R)}),true}}return {handleWatchersRoutes:l,handleSse:f,handleChannelSubscription:c}}exports.a=A;exports.b=T;//# sourceMappingURL=chunk-7ICPAABP.cjs.map
7
+ //# sourceMappingURL=chunk-7ICPAABP.cjs.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkGL2OHR2E_cjs=require('./chunk-GL2OHR2E.cjs');function d(a,e){return e?{...a,...e.pollIntervalMs!=null?{pollIntervalMs:e.pollIntervalMs}:{},...e.visibilityMs!=null?{visibilityMs:e.visibilityMs}:{},...e.concurrency!=null?{concurrency:e.concurrency}:{},...e.maxAttempts!=null?{maxAttempts:e.maxAttempts}:{}}:a}function p(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.leaseRequests(o))).map(r=>({id:r.messageId,attempt:r.attempt,message:r.request,ack:()=>Promise.resolve(e.ackRequest(r.messageId,r.leaseToken)),nack:t=>Promise.resolve(e.nackRequest(r.messageId,r.leaseToken,t))}))},async handle(o){await c(o.args,o);},onError:s?(o,u)=>s(o,u.attempt,u.message):void 0}}function l(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.lease(o))).map(r=>({id:r.id,attempt:r.attempt,message:r.body,ack:()=>Promise.resolve(e.ack(r.id,r.leaseToken)),nack:t=>Promise.resolve(e.nack(r.id,r.leaseToken,t))}))},async handle(){await c();},onError:s?(o,u)=>s(o,u.attempt):void 0}}function y(a){let e=a.logger??{info(){},warn(){},error(){}},c=a.boardAdapter,s=a.runtime.queueLaneTuning??{},o=c.processAccumulatedStore(),u=c.chatAgentStore(),r=[];if(r.push(d(l("process-accumulated",o,async()=>{let t=await a.runtime.processAccumulatedLane();if(t.status!=="success")throw new Error(t.error||`processAccumulatedLane returned ${t.status}`)},(t,n)=>{e.error(`[board-server] queued process-accumulated failed for ${a.boardId} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.processAccumulated)),r.push(d(p("chat-agent",u,async(t,n)=>{await a.runtime.handleChatAgentRequest(n);},(t,n,i)=>{let m=typeof i.args?.cardId=="string"?i.args.cardId:"";e.error(`[board-server] queued chat-agent failed for ${a.boardId}${m?`/${m}`:""} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.chatAgent)),a.executeTaskExecutorRequest){let t=c.boardWorkerStore();r.push(d(p("task-executor",t,a.executeTaskExecutorRequest,(n,i)=>{e.error(`[board-server] queued board-worker failed for ${a.boardId} (attempt ${i}): ${String(n&&n.message||n)}`);}),s.taskExecutor));}return chunkGL2OHR2E_cjs.a(r)}exports.a=y;//# sourceMappingURL=chunk-CPAXTVBQ.cjs.map
2
+ //# sourceMappingURL=chunk-CPAXTVBQ.cjs.map
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkM3OU6IS5_cjs=require('./chunk-M3OU6IS5.cjs'),chunk7FGPOGRV_cjs=require('./chunk-7FGPOGRV.cjs'),chunk7ICPAABP_cjs=require('./chunk-7ICPAABP.cjs'),chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs'),chunkNM6O35RY_cjs=require('./chunk-NM6O35RY.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs'),chunkNJJ7WEDT_cjs=require('./chunk-NJJ7WEDT.cjs'),chunkH5HBXPOI_cjs=require('./chunk-H5HBXPOI.cjs'),chunkOEFTOO47_cjs=require('./chunk-OEFTOO47.cjs'),chunkYMEIPKLW_cjs=require('./chunk-YMEIPKLW.cjs'),chunkGYQXDNNI_cjs=require('./chunk-GYQXDNNI.cjs');function te(S){let{apiBasePath:v,json:h,readJsonBody:Z,readRawBody:V,initBoardAndSetup:N,bootstrapBoard:$,buildPublishedRuntimePayload:K,createMcpControlplaneToolRegistry:Q,readCardFromStore:tt,patchCard:nt,retriggerCard:U,applyCardAction:ot,resolveChatHandlerTarget:it,createMcpFacade:ct,chatStorePublic:dt,uploadCardFile:m,sendCardFileDownloadResponse:C}=S;async function I(d,u,q){let x=d.method||"GET",O=q,P=O.pathname;try{if(x==="GET"&&P===`${v}/init-board`)return await N(),h(u,200,await K()),!0;if(x==="GET"&&P===`${v}/board-status`)return h(u,200,await K()),!0;if(x==="POST"&&P===`${v}/mcp-controlplane`){await $();let f=await Z(d),c=typeof f.tool=="string"?f.tool.trim():"",j=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!c)return h(u,400,{error:"tool is required"}),!0;try{let l=await chunk272IYUKT_cjs.a(c,j,Q());if(l&&typeof l=="object"&&!Array.isArray(l)){let k=l;if(k.status==="fail")return h(u,400,{error:chunk272IYUKT_cjs.b(l,"Request failed")}),!0;if(k.status==="error")return h(u,500,{error:chunk272IYUKT_cjs.b(l,"Internal error")}),!0}h(u,200,l);}catch(l){let k=typeof l?.statusCode=="number"?Number(l.statusCode):500,L=l instanceof Error?l.message:String(l);h(u,k,{error:L});}return !0}let D=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)$`));if(x==="GET"&&D){await $();let f=decodeURIComponent(D[1]),c=await tt(f);return c?(h(u,200,c),!0):(h(u,404,{error:`card not found: ${f}`}),!0)}if(x==="PATCH"&&D){await $();let f=decodeURIComponent(D[1]),c=await Z(d);return await nt(f,c),h(u,200,{ok:!0}),!0}let et=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/retrigger$`));if(x==="POST"&&et){await $();let f=decodeURIComponent(et[1]);return await U(f),h(u,200,{ok:!0}),!0}let rt=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/actions$`));if(x==="POST"&&rt){await $();let f=decodeURIComponent(rt[1]),c=Date.now(),j=new Date(c).toISOString(),l=await Z(d),k=l?.actionType;if(k==="chat-send"&&!await it(f)){let T=Date.now();return h(u,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(T).toISOString(),responseSentAtMs:T,responseStatus:409}),!0}if(k==="chat-send"){let T=l?.payload??{},W=typeof T["turn-id"]=="string"?T["turn-id"]:typeof T.turnId=="string"?T.turnId:typeof T.turn=="string"?T.turn:"";if(!W||!String(W).trim()){let ut=Date.now();return h(u,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(ut).toISOString(),responseSentAtMs:ut,responseStatus:400}),!0}}await ot(f,k,l?.payload);let L=Date.now();return h(u,200,{ok:!0,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(L).toISOString(),responseSentAtMs:L,responseStatus:200}),!0}let M=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/chats$`));if(x==="GET"&&M){await $();let f=decodeURIComponent(M[1]),c=String(O.searchParams.get("turn-id")||""),j=String(O.searchParams.get("all-turns")||"").toLowerCase()==="true",l=String(O.searchParams.get("tail-turns-before-id")||""),k=O.searchParams.get("tail-turns"),L=k==null||k===""?j||c?void 0:1:Number.parseInt(k,10),T=dt.readAll({params:{cardId:f},body:{...L===void 0?{}:{tailTurns:L},...c?{turnId:c}:{},...j?{allTurns:!0}:{},...l?{tailTurnsBeforeId:l}:{}}});if(T.status!=="success")return h(u,400,{error:T.error||"Failed to read chats"}),!0;let W=T.data.records;return h(u,200,{ok:!0,messages:W}),!0}if(x==="POST"&&M){await $();let f=decodeURIComponent(M[1]),c=await Z(d),j=typeof c?.role=="string"?c.role:"assistant",l=typeof c?.text=="string"?c.text:"",k=Array.isArray(c?.files)?c.files:[],L=typeof c?.turn=="string"?c.turn:typeof c?.["turn-id"]=="string"?c["turn-id"]:typeof c?.turnId=="string"?c.turnId:"",T=c?.done===!0,W=ct(),G=(await W.manageAddChatEntryAndAnyAttachments({cardId:f,role:j,text:l,files:k,turn:L})).data.id;return T&&W.setChatProcessing({cardId:f,active:!1}),h(u,200,{ok:!0,id:G}),!0}let X=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/files$`));if(x==="POST"&&X){await $();let f=decodeURIComponent(X[1]),c=String(O.searchParams.get("inChat")||"").toLowerCase()==="true",j=String(O.searchParams.get("turn-id")||"").trim();if(c&&!j)return h(u,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${f}`}),!0;let l=d.headers["x-file-name"],k=String(d.headers["content-type"]||"application/octet-stream"),L=Array.isArray(l)?l[0]:l,T=L?decodeURIComponent(String(L)):"upload.bin",W=await V(d);return h(u,200,await m(f,T,k,W,{inChat:c,turnId:j})),!0}let z=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/files/(\\d+)$`));if(x==="GET"&&z){let f=decodeURIComponent(z[1]),c=parseInt(z[2],10),j=O.searchParams.get("sn");return await C(u,f,c,j),!0}return !1}catch(D){let et=D?.statusCode||500;return h(u,et,{error:String(D?.message||D)}),true}}return {handleRuntimeApi:I}}var re={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},ee="chat-handler-flow-queue";function or(S){let v=String(S.apiBasePath||"/api/board").replace(/\/$/,""),h={...re,...S.corsHeaders||{}},Z=S.queueLaneTuning??{},V=S.boardId||"",N=S.logger||{info:console.log,warn:console.warn,error:console.error},$=S.invocationAdapter,K=S.chatFlowRunner||null,Q=S.chatStorage??chunkNJJ7WEDT_cjs.b(),tt=chunkGYQXDNNI_cjs.a(Q),nt=S.notificationTransport||null,U=S.serverUrl||null,ot=S.executionExtra||{},it=S.onSseClientConnected,ct=S.onSseClientDisconnected,dt=S.onChannelSubscribed,m=S.onChannelUnsubscribed,C=chunk7ICPAABP_cjs.a({chatStorage:Q,readChatRecords:t=>bt(t),onSseClientDisconnected:ct});function I(t){function e(o){if(Array.isArray(o))return o;if(o&&typeof o=="object"){let i=o;return Array.isArray(i.files)?i.files:[o]}return null}function r(o){return {async get(i){return o.get(i)},async set(i){return o.set(i)},async del(i){return o.del(i)},async patch(i){return o.patch(i)},async appendFiles(i){return o.appendFiles(i)}}}function a(o){function i(b){return {status:"success",data:b}}function g(b){return {status:"fail",error:b}}function p(b){return {status:"error",error:b instanceof Error?b.message:String(b)}}return {async get(b){try{let R=b.params?.id;if(R){let E=await o.readCard(R);return E?i({cards:[E]}):g(`card "${R}" not found`)}return i({cards:await o.readAllCards()})}catch(R){return p(R)}},async set(b){try{let R=b.body;if(R==null)return g("set requires a body (card object or array of cards)");let E=Array.isArray(R)?R:[R];for(let _ of E){if(typeof _.id!="string")return g("each card must have a string `id` field");await o.writeCard(_.id,_);}return i({count:E.length})}catch(R){return p(R)}},async del(b){try{let R=b.body?.ids??[],E=b.params?.id,_=E?[...R,E]:R;if(_.length===0)return g("del requires body.ids (string[]) or params.id");for(let st of _)await o.removeCard(st);return i({count:_.length})}catch(R){return p(R)}},async patch(b){try{let R=b.params?.id,E=b.params?.path;if(!R)return g("patch requires params.id");if(!E)return g("patch requires params.path");let _=b.body,st=_&&Object.prototype.hasOwnProperty.call(_,"value")?_.value:b.body;return await o.patchCard(R,E,st),i({count:1})}catch(R){return p(R)}},async appendFiles(b){try{let R=b.params?.id;if(!R)return g("appendFiles requires params.id");let E=await o.readCard(R);if(!E)return g(`card "${R}" not found`);let _=e(b.body);if(!_||_.length===0)return g("appendFiles requires a file metadata object, array, or body.files array");let st=E.card_data&&typeof E.card_data=="object"&&!Array.isArray(E.card_data)?E.card_data:{},Bt=Array.isArray(st.files)?st.files:[],Fe=[...Bt,..._];return await o.patchCard(R,"card_data.files",Fe),i({files_added:_.map((Oe,Te)=>({idx:Bt.length+Te,entry:Oe}))})}catch(R){return p(R)}}}}let n=chunkKAWQPLIE_cjs.a(t.boardAdapter)?chunkH5HBXPOI_cjs.j(t.baseRef,t.boardAdapter):chunkOEFTOO47_cjs.y(t.baseRef,t.boardAdapter),s=t.nonCoreAdapter??(!chunkKAWQPLIE_cjs.a(t.boardAdapter)&&x(t.boardAdapter)?t.boardAdapter:null),y=s?chunkOEFTOO47_cjs.z(t.baseRef,s):null,B,w=chunkKAWQPLIE_cjs.a(t.boardAdapter)?(()=>{let o=chunkH5HBXPOI_cjs.d(chunkH5HBXPOI_cjs.c(chunkH5HBXPOI_cjs.b(t.boardAdapter.kvStorageForRef(t.cardStoreRef)),t.boardAdapter.hashFn),N.warn),i=a(o);return B={get(g){return i.get(g)},set(g){return i.set(g)}},i})():(()=>{let o=t.boardAdapter.kvStorageForRef(t.cardStoreRef),g=chunkYMEIPKLW_cjs.a(chunkOEFTOO47_cjs.l({readIndex:()=>o.read("_index"),writeIndex:p=>o.write("_index",p),readCard:p=>o.read(p),writeCard:(p,b)=>(o.write(p,b),p),removeCard:p=>{o.delete(p);},cardExists:p=>o.read(p)!==null,defaultCardKey:p=>p},N.warn));return B=g,r(g)})(),F=t.artifactsAdapter||t.boardAdapter,A=t.filesArtifactsStore??null,H=A?{putBytes(o,i,g){A.putBytes(o,i,g);},getBytes(o){return A.getBytes(o)},listKeys(o){return A.list(o).map(i=>i.key)}}:null;if(!H&&!chunkKAWQPLIE_cjs.a(F)){let o=t.artifactsAdapter?F.blobStorage(""):F.blobStorage("files"),i=chunkNJJ7WEDT_cjs.c(o);H={putBytes(g,p,b){i.putBytes(g,p,b);},getBytes(g){return i.getBytes(g)},listKeys(g){return i.list(g).map(p=>p.key)}};}else if(!H&&chunkKAWQPLIE_cjs.a(F)){let o=t.artifactsAdapter?F.blobStorage(""):F.blobStorage("files");H={async putBytes(i,g){if(o.writeBytes){await o.writeBytes(i,g);return}let p=JSON.stringify({__kind:"bytes-array",data:[...g]});await o.write(i,p);},async getBytes(i){if(o.readBytes){let p=await o.readBytes(i);if(p!==null)return p}let g=await o.read(i);if(g===null)return null;try{let p=JSON.parse(g);if(p&&p.__kind==="bytes-array"&&Array.isArray(p.data))return new Uint8Array(p.data)}catch{}return new TextEncoder().encode(g)},async listKeys(i){return await o.listKeys(i)}};}let J={async init(o){return n.init(o)},async status(o){return n.status(o)},async getConfig(o){return n.getConfig(o)},async getAllOutputsDataObjects(o){return n.getAllOutputsDataObjects(o)},async getAllOutputsComputedValues(o){return n.getAllOutputsComputedValues(o)},async getOutputsFetchedSources(o){return n.getOutputsFetchedSources(o)},async upsertCard(o){return n.upsertCard(o)},async removeCard(o){return n.removeCard(o)},async cardRefreshedNotify(o){return n.cardRefreshedNotify(o)},async sourceDataFetched(o){return n.sourceDataFetched(o)},async sourceDataFetchFailure(o){return n.sourceDataFetchFailure(o)}};return {label:t.label,board:n,nonCore:y,publicCardStore:B,boardOps:J,cardStoreOps:w,get filesArtifacts(){return H},boardAdapter:t.boardAdapter,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,archiveStoreRef:t.archiveStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:chunkM3OU6IS5_cjs.a(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d=S.boards.map(I),u=new Map;function q(t){return u.get(t)??0}function x(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function O(t){let e=d[q(t)];return {files:e?e.filesArtifacts:null}}function P(){return chunkNJJ7WEDT_cjs.e()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function et(t){if(!t||t.notificationTeardown||!nt||!t.notifyRef)return;let e=await nt.subscribe(t.notifyRef,r=>{chunkM3OU6IS5_cjs.c(t.notification,r);let a=r.kind==="notification-batch"?r.notifications:[r];C.broadcastNotificationBatch(a);});t.notificationTeardown=e;}async function rt(t){if(!t||t.initialized)return;let e={cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef};t.artifactsStoreRef&&(e.artifactsStoreRef=t.artifactsStoreRef),t.chatStoreRef&&(e.chatStoreRef=t.chatStoreRef),t.scratchStoreRef&&(e.scratchStoreRef=t.scratchStoreRef),t.archiveStoreRef&&(e.archiveStoreRef=t.archiveStoreRef);let r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow),t.inferenceAdapterRef&&(r["inference-adapter-ref"]=t.inferenceAdapterRef);let a=await t.boardOps.init({params:e,body:r});if(a.status!=="success")throw Object.assign(new Error(a.error||`init failed for ${t.label}`),{statusCode:500});if(await et(t),!t.chatHandlerFlow&&t.chatHandlerRef&&$.describe)try{let n=await $.describe(t.chatHandlerRef);n&&n.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${n.kind}", expected "chat-handler" for ${t.label}`):n&&N.info(`[init] chat-handler validated: ${n.name} (protocol ${n.protocolVersion}) for ${t.label}`);}catch(n){N.warn(`[init] chat-handler describe failed for ${t.label}: ${n?.message||String(n)}`);}t.initialized=true;}async function M(t){if(!t.boardAdapter.publishBoardChangeNotifications)return;let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&chunkM3OU6IS5_cjs.b(r.data)&&e.push({kind:"status",status:r.data});let a=await t.boardOps.getAllOutputsDataObjects({});if(a.status==="success"&&a.data!=null)for(let[s,y]of Object.entries(a.data))s&&e.push({kind:"data_object",key:s,payload:y});let n=await t.boardOps.getAllOutputsComputedValues({});if(n.status==="success"&&n.data!=null)for(let[s,y]of Object.entries(n.data))s&&e.push({kind:"computed_values",cardId:s,values:y});e.length>0&&t.boardAdapter.publishBoardChangeNotifications(e);}async function X(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),a=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let n of a)typeof n.id=="string"&&(u.set(n.id,e),await t.boardOps.upsertCard({params:{cardId:n.id}}));t.cardsBootstrapped=true;}async function z(){for(let t of d)await rt(t);}async function f(){await z();for(let t=0;t<d.length;t++)await M(d[t]),await X(d[t],t),await M(d[t]);}async function c(t=false){t||await z();for(let e of d){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}async function j(){return await z(),c(true)}function l(t){return d[q(t)]??null}async function k(t){let e=l(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let a=Array.isArray(r.data?.cards)?r.data.cards:[];return a.length>0?a[0]:null}async function L(){let t=async r=>{if(!r)return [];let a=await r.cardStoreOps.get({});return a.status!=="success"||!Array.isArray(a.data?.cards)?[]:a.data.cards},e=[];for(let r of d)e.push(...await t(r));return e}function T(){return d[0]??null}let W=chunkM3OU6IS5_cjs.n({boardContexts:d,cardOwnerIndex:u,cardContextForCard:t=>l(t),readStatusSnapshot:()=>ie(),readDataObjectsByToken:()=>de(),readCardRuntimeArtifacts:()=>ce(),readCardFromStore:t=>k(t),readCardDefinitions:()=>L(),processAccumulatedLaneInternal:t=>c(t),reportSourceFetched:(t,e)=>St(t,{ref:e}),reportSourceFetchFailure:(t,e)=>kt(t,{reason:e}),uploadCardFile:(t,e,r,a,n)=>Rt(t,e,r,a,n),chatStorePublic:tt,serverUrl:U,apiBasePath:v}),ut=W.mcpCardStoreFacade,G=W.createMcpFacade,ne=chunkM3OU6IS5_cjs.h({boardId:V,getMcpFacade:()=>G(),getMcpCardStoreFacade:()=>ut()});function ae(t){return chunkM3OU6IS5_cjs.k(t)}function oe(){return chunkM3OU6IS5_cjs.l(G())}function se(){return chunkM3OU6IS5_cjs.m({boardId:V,uploadCardFile:Rt,getMcpFacade:()=>G(),controlplane:ne})}let lt=chunkM3OU6IS5_cjs.i({boardId:V,boardContexts:d,readCardDefinitions:()=>L(),readChatRecords:t=>bt(t),getChatProcessing:t=>G().getChatProcessing({cardId:t}).active}),ie=lt.readStatusSnapshot,ce=lt.readCardRuntimeArtifacts,de=lt.readDataObjectsByToken,gt=lt.buildPublishedRuntimePayload;async function yt(t,e,r){let a=r?.syncBoard!==false,n=r?.restartOnlyIfChanged===true,s=l(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let y=await k(t);if(!y)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let B=n?JSON.stringify(y):null,w=e(y)||y;if(n&&JSON.stringify(w)===B)return;let F=await s.cardStoreOps.set({body:w});if(F.status!=="success")throw Object.assign(new Error(F.error||`Failed to persist card: ${t}`),{statusCode:500});if(a){let A=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(A.status!=="success")throw Object.assign(new Error(A.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function ue(t,e){await yt(t,e,{syncBoard:true});}async function ht(t,e){await yt(t,e,{syncBoard:false});}async function le(t){let e=l(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await k(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let a=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(a.status!=="success")throw Object.assign(new Error(a.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function fe(t,e){await yt(t,r=>{if(!e||typeof e!="object"||Object.keys(e).length===0)return r;function a(n,s,y){let B=String(s||"").split(".").filter(Boolean);if(!B.length)return;let w=n;for(let F=0;F<B.length-1;F++){let A=B[F];(!w[A]||typeof w[A]!="object")&&(w[A]={}),w=w[A];}w[B[B.length-1]]=y;}if(e.fieldValues!==void 0&&e.fieldValues!==null){let n=null,s=r.view;if(s&&Array.isArray(s.elements)){for(let y of s.elements)if(y?.data&&y.data.writeTo){n=y.data.writeTo;break}}n?a(r,n,e.fieldValues):typeof e.fieldValues=="object"&&!Array.isArray(e.fieldValues)&&(r.card_data={...r.card_data||{},...e.fieldValues});}else {if(Array.isArray(e._stagedFiles)&&e._stagedFiles.length>0)return r;for(let[n,s]of Object.entries(e))n!=="_stagedFiles"&&(s!==null&&typeof s=="object"&&!Array.isArray(s)&&r[n]!==null&&typeof r[n]=="object"&&!Array.isArray(r[n])?r[n]={...r[n],...s}:r[n]=s);}return r},{syncBoard:true,restartOnlyIfChanged:true});}function pe(t){Q.clear(t);try{G().setChatProcessing({cardId:t,active:!1});}catch{}}function me(t,e,r,a,n=""){let s=typeof r=="string"?r.trim():"";return Q.append(t,e||"system",s,a,n)}function bt(t){return Q.readAll(t)}let Rt=chunkM3OU6IS5_cjs.j({safeCardId:t=>D(t),artifactsStores:t=>O(t),cardFileMetadataStore:()=>P(),readCardFromStore:t=>k(t),updateCardLocalOnly:(t,e)=>ht(t,e),writeChatRecord:(t,e,r,a,n)=>me(t,e,r,a,n)}).uploadCardFile;async function Ct(t){let e=l(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),a=r.status==="success"?r.data?.value:null,n=e.chatHandlerRef;return a==null&&(!n||typeof n!="object")?null:{ctx:e,handlerFlow:a,handlerRef:n}}async function ge(t,e,r=false,a=""){let n=await Ct(t);if(!n)return;let{ctx:s,handlerFlow:y,handlerRef:B}=n;if(!r)try{G().setChatProcessing({cardId:t,active:!0});}catch{}let w={boardId:V,cardId:String(t),lastChatEntryId:e,...a?{turnId:a}:{},...ot,...U?{serverUrl:U}:{}},F=y!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:ee}}:B;try{chunkKAWQPLIE_cjs.a(s.boardAdapter)?await s.boardAdapter.chatAgentStore().enqueueRequest({boardId:V,ref:F,args:y!=null?{...w,__chatHandlerFlow:y}:w}):s.boardAdapter.chatAgentStore().enqueueRequest({boardId:V,ref:F,args:y!=null?{...w,__chatHandlerFlow:y}:w}),await Promise.resolve(s.boardAdapter.requestProcessAccumulated?.());}catch(A){try{G().setChatProcessing({cardId:t,active:!1});}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${A instanceof Error?A.message:String(A)}`);}}async function ye(t,e,r){if(e.howToRun==="built-in"&&chunkKAWQPLIE_cjs.b(e)===ee){let a=K,n=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,a?a.run(n,s,{boardId:V,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:U,executionExtra:ot}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return $.invoke(e,r)}async function Re(t,e=false){e||await z();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",a=r?l(r):T();if(!a)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let n=await ye(a,t.ref,t.args);if(!n.dispatched){if(r)try{Q.setProcessing(r,!1);}catch{}throw new Error(n.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function we(t,e,r){let a=e==="chat-send"?ht:ue,n;await a(t,s=>{let y=new Date().toISOString(),B=s.card_data&&typeof s.card_data=="object"?s.card_data:{};if(s.card_data=B,e==="chat-send"){let w=r&&typeof r.text=="string"?r.text.trim():"",F=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"",A=[];if(Array.isArray(r?.files)){for(let H of r.files)if(H){if(typeof H=="string"){A.push({name:H});continue}if(typeof H=="object"){let J=H;typeof J.name=="string"&&A.push({name:J.name,size:J.size,mime_type:J.mime_type,uploaded_at:J.uploaded_at,stored_name:J.stored_name,chat:J.chat===true});}}}if(w||A.length>0){let H=tt.runBatch({cardId:t,commands:[{command:"append",role:"user",text:w,files:A,turn:F},{command:"set-processing",active:true}]});if(H.status!=="success")throw new Error(H.error);let J=H.data.results[0]?.data?.id;if(typeof J!="string"||!J)throw new Error(`chat-send did not return an append id for card ${t}`);n={cardId:t,lastEntryId:J,processingAlreadySet:true,turnId:F};try{C.broadcastCardChats(t);}catch{}}return s}if(e==="file-upload"){let w=P().normalizeIncoming(r?.files,y);return w.length>0&&P().merge(B,w),s}if(e==="action"){let w=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!w)return s;B.lastAction={buttonId:w,at:y},B.lastActionText=`${w} @ ${y}`;}return s}),n&&ge(n.cardId,n.lastEntryId,n.processingAlreadySet,n.turnId??"");}function ft(t,e,r){let a=JSON.stringify(r),n=typeof Buffer<"u"?Buffer.byteLength(a):new TextEncoder().encode(a).length;t.writeHead(e,{...h,"Content-Type":"application/json; charset=utf-8","Content-Length":n}),t.end(a);}async function At(t,e,r){let a=await k(t);if(!a)throw Object.assign(new Error("Card not found"),{statusCode:404});let n=P().resolve(a.card_data,e,r);if(!n.ok&&n.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!n.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=n.file,y=D(t),B=O(t),w=String(s.stored_name||""),F=`${y}/${w}`,A=B.files?await B.files.getBytes(F):null;if(!A)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:A}}async function he(t,e,r,a){let{fileRecord:n,bytes:s}=await At(e,r,a),y=String(n.name||n.stored_name||"download.bin"),B=String(n.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":B,"Content-Disposition":`attachment; filename="${y}"`,"Content-Length":s.length}),t.end(s);}function be(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 Ce(t,e,r){let a=t.split(/\r?\n/);return (e==="head"?a.slice(0,r):a.slice(-r)).join(`
2
+ `)}async function pt(t){let e=[];for await(let a of t)e.push(a);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(chunkKAWQPLIE_cjs.d(e)).trim();return r?JSON.parse(r):{}}async function Ae(t){let e=[];for await(let r of t)e.push(r);return typeof Buffer<"u"?Buffer.concat(e):chunkKAWQPLIE_cjs.d(e)}async function St(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 a=d[0];return a?a.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function kt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",a=d[0];return a?a.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Se=chunk7ICPAABP_cjs.b({sseHub:C,corsHeaders:h,json:ft,buildPublishedRuntimePayload:()=>gt(),onSseClientConnected:it,onChannelSubscribed:dt,onChannelUnsubscribed:m,apiBasePath:v,readJsonBody:t=>pt(t),initBoardAndSetup:()=>z(),bootstrapBoard:()=>f(),boardContexts:d,publishPersistedStateSnapshot:t=>M(t),upsertCardsFromSource:(t,e)=>X(t,e)}).handleWatchersRoutes,ke=chunk7FGPOGRV_cjs.a({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),bootstrapBoard:()=>f(),createMcpFacade:()=>G(),createMcpToolRegistry:t=>ae(t),resolveCardFileDownloadPayload:(t,e,r)=>At(t,e,r),isLikelyTextMimeType:t=>be(t),sliceTextByLines:(t,e,r)=>Ce(t,e,r)}).handleAgentfaceApi,Be=chunkNM6O35RY_cjs.a({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),initBoardAndSetup:()=>z(),createMcpWebhookToolRegistry:()=>oe()}).handleWebhooksApi,ve=te({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),readRawBody:t=>Ae(t),initBoardAndSetup:()=>z(),bootstrapBoard:()=>f(),buildPublishedRuntimePayload:()=>gt(),createMcpControlplaneToolRegistry:()=>se(),readCardFromStore:t=>k(t),patchCard:(t,e)=>fe(t,e),retriggerCard:t=>le(t),applyCardAction:(t,e,r)=>we(t,e,r),resolveChatHandlerTarget:t=>Ct(t),createMcpFacade:()=>G(),chatStorePublic:tt,uploadCardFile:(t,e,r,a,n)=>Rt(t,e,r,a,n),sendCardFileDownloadResponse:(t,e,r,a)=>he(t,e,r,a)}).handleRuntimeApi;async function Pe(t,e,r){return !!(await ke(t,e,r)||await Be(t,e,r)||await Se(t,e,r)||await ve(t,e,r))}return {get apiBasePath(){return v},get corsHeaders(){return h},get queueLaneTuning(){return Z},handleRuntimeApi:Pe,buildPublishedRuntimePayload:gt,processAccumulatedEvents:j,processAccumulatedLane:c,handleChatAgentRequest:Re,clearChatRecords:pe,reportSourceFetched(t,e){return St(t,{ref:e})},reportSourceFetchFailure(t,e){return kt(t,{reason:e})},get cardStore(){return d[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function sr(S){let v=String(S.apiBasePath||"/api/boards").replace(/\/$/,""),h={...re,...S.corsHeaders||{}},Z=S.serverMetaStore,V=S.boardRuntimeFactory,N=new Map,$="boards-config.json";function K(){let m=Z.getText($);if(!m)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(m)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function Q(m){Z.putText($,JSON.stringify(m,null,2));}function tt(m){let C=String(m||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return C.length>0&&C.length<=64?C:null}function nt(m){if(N.has(m))return N.get(m);let I=K().boards.find(u=>u.id===m)||{},d=V(m,I);return N.set(m,d),d}function U(m,C,I){let d=JSON.stringify(I),u=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;m.writeHead(C,{...h,"Content-Type":"application/json; charset=utf-8","Content-Length":u}),m.end(d);}async function ot(m,C,I){let d=m.method||"GET",u=I.pathname;if(d==="GET"&&u===v)return U(C,200,{ok:true,boards:K().boards}),true;if(d==="POST"&&u===v){let q=[];for await(let M of m)q.push(M);let x=typeof Buffer<"u"?Buffer.concat(q).toString("utf-8").trim():new TextDecoder().decode(chunkKAWQPLIE_cjs.d(q)).trim(),O={};try{O=x?JSON.parse(x):{};}catch{O={};}let P=tt(O.id);if(!P)return U(C,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let D=K();if(D.boards.some(M=>M.id===P))return U(C,409,{error:`Board "${P}" is already registered`}),true;let et=typeof O.label=="string"&&O.label.trim()?O.label.trim():P,rt={id:P,label:et};for(let[M,X]of Object.entries(O))M==="id"||M==="label"||X!=null&&(rt[M]=X);return D.boards.push(rt),Q(D),U(C,200,{ok:true,board:rt}),true}return false}async function it(m,C,I){let u=I.pathname.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/([^/]+)(/|$)`));if(!u)return false;let q=tt(decodeURIComponent(u[1]));return q?K().boards.some(P=>P.id===q)?!!await nt(q).handleRuntimeApi(m,C,I):(U(C,404,{error:`Board "${q}" not registered. POST ${v} with {id} to register it first.`}),true):(U(C,400,{error:"Invalid board id"}),true)}async function ct(m,C,I){return !!(await ot(m,C,I)||await it(m,C,I))}function dt(m){if(!K().boards.some(I=>I.id===m))throw Object.assign(new Error(`Board "${m}" not registered`),{statusCode:404});return {service:nt(m)}}return {get apiBasePath(){return v},get corsHeaders(){return h},handleApi:ct,requireBoardService:dt}}exports.a=te;exports.b=or;exports.c=sr;//# sourceMappingURL=chunk-DDYSXP2A.cjs.map
3
+ //# sourceMappingURL=chunk-DDYSXP2A.cjs.map
@@ -0,0 +1,2 @@
1
+ //# sourceMappingURL=chunk-EGRHWZRV.js.map
2
+ //# sourceMappingURL=chunk-EGRHWZRV.js.map
@@ -0,0 +1,2 @@
1
+ 'use strict';function a(e){return {lanes:e}}exports.a=a;//# sourceMappingURL=chunk-GL2OHR2E.cjs.map
2
+ //# sourceMappingURL=chunk-GL2OHR2E.cjs.map
@@ -0,0 +1,4 @@
1
+ 'use strict';function k(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return `[${o.map(k).join(",")}]`;let r=o;return `{${Object.keys(r).sort().map(u=>`${JSON.stringify(u)}:${k(r[u])}`).join(",")}}`}function _(o,r){let S=r>>>0;for(let u=0;u<o.length;u++)S^=o.charCodeAt(u),S=Math.imul(S,16777619)>>>0;return S}function K(o){let r=k(o),S=_(r,2166136261),u=_(r,3735928559),h=_(r,19088743),s=_(r,4277009102);return [S,u,h,s].map(i=>i.toString(16).padStart(8,"0")).join("")}function J(o){function r(s){return `${o}:blob:${s}`}let S=new TextEncoder;function u(s){if(typeof btoa=="function"){let i="";for(let n=0;n<s.length;n++)i+=String.fromCharCode(s[n]);return btoa(i)}return ""}function h(s){if(typeof atob=="function"){let i=atob(s),n=new Uint8Array(i.length);for(let a=0;a<i.length;a++)n[a]=i.charCodeAt(a);return n}return new Uint8Array}return {read(s){return globalThis.localStorage.getItem(r(s))},write(s,i){globalThis.localStorage.setItem(r(s),i);},exists(s){return globalThis.localStorage.getItem(r(s))!==null},remove(s){globalThis.localStorage.removeItem(r(s));},readBytes(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;try{let n=JSON.parse(i);if(n&&n.__kind==="bytes-b64"&&typeof n.data=="string")return h(n.data)}catch{}return S.encode(i)},writeBytes(s,i){let n=JSON.stringify({__kind:"bytes-b64",data:u(i)});globalThis.localStorage.setItem(r(s),n);},listKeys(s){let i=r(s??""),n=[];for(let a=0;a<globalThis.localStorage.length;a++){let l=globalThis.localStorage.key(a);l&&l.startsWith(i)&&n.push(l.slice(r("").length));}return n.sort()},stat(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;let n=S.encode(i).byteLength;try{let a=JSON.parse(i);a&&a.__kind==="bytes-b64"&&typeof a.data=="string"&&(n=h(a.data).byteLength);}catch{}return {key:s,size:n}}}}var N=":scratch-marker",C=":scratch-config",A=":scratch:",L=1440*60*1e3,O=720*60*1e3,B=200;function $(o,r){if(!o)return r;let S=o.replace(/[^A-Za-z0-9._-]/g,"_");return S.length>0?S:r}function W(o){let r=`${o}${N}`,S=`${o}${C}`,u=t=>`${o}${A}${t}`,h=t=>`${o}${A}${t}:__ts`,s=globalThis.localStorage.getItem(r)===null;if(s)try{globalThis.localStorage.setItem(r,`scratch-store
2
+ ${new Date().toISOString()}`);}catch{}function i(){let t=globalThis.localStorage.getItem(S);if(t===null)return {};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function n(t){try{globalThis.localStorage.setItem(S,JSON.stringify(t));}catch{}}if(s){let t=i();typeof t["retention.lastSweepAt"]!="number"&&(t["retention.lastSweepAt"]=Date.now(),n(t));}function a(){if(globalThis.localStorage.getItem(r)===null)return;let t=i(),e=typeof t["retention.maxAgeMs"]=="number"?t["retention.maxAgeMs"]:L,c=typeof t["retention.sweepIntervalMs"]=="number"?t["retention.sweepIntervalMs"]:O;if(e<=0||c<=0)return;let g=typeof t["retention.lastSweepAt"]=="number"?t["retention.lastSweepAt"]:0,y=Date.now();if(y-g<c)return;t["retention.lastSweepAt"]=y,n(t);let f=y,m=`${o}${A}`,b=[];for(let p=0;p<globalThis.localStorage.length;p++){let w=globalThis.localStorage.key(p);w&&w.startsWith(m)&&!w.endsWith(":__ts")&&b.push(w);}for(let p of b){if(Date.now()-f>B)break;let w=globalThis.localStorage.getItem(`${p}:__ts`),I=w===null?0:Number(w);if(Number.isFinite(I)&&I>0&&y-I>e){try{globalThis.localStorage.removeItem(p);}catch{}try{globalThis.localStorage.removeItem(`${p}:__ts`);}catch{}}}}function l(t,e){let c=$(t,"scratch"),g=$(e,".json"),y=g.startsWith(".")?g:`.${g}`,f=Math.random().toString(36).slice(2,10);return `${c}-${Date.now()}-${f}${y}`}function d(t,e){globalThis.localStorage.setItem(u(t),e),globalThis.localStorage.setItem(h(t),String(Date.now()));}return {read(t){return globalThis.localStorage.getItem(u(t))},write(t,e){d(t,e);try{a();}catch{}},exists(t){return globalThis.localStorage.getItem(u(t))!==null},remove(t){try{globalThis.localStorage.removeItem(u(t));}catch{}try{globalThis.localStorage.removeItem(h(t));}catch{}},readBytes(t){let e=globalThis.localStorage.getItem(u(t));return e===null?null:new TextEncoder().encode(e)},writeBytes(t,e){let c="";for(let g=0;g<e.length;g++)c+=String.fromCharCode(e[g]);d(t,c);try{a();}catch{}},stat(t){let e=globalThis.localStorage.getItem(u(t));if(e===null)return null;let c=globalThis.localStorage.getItem(h(t)),g=c===null?null:Number(c);return {key:t,size:new TextEncoder().encode(e).byteLength,updatedAt:g!==null&&Number.isFinite(g)?new Date(g).toISOString():void 0}},listKeys(t){let e=`${o}${A}`,c=[];for(let g=0;g<globalThis.localStorage.length;g++){let y=globalThis.localStorage.key(g);if(y&&y.startsWith(e)&&!y.endsWith(":__ts")){let f=y.slice(e.length);(!t||f.startsWith(t))&&c.push(f);}}return c.sort()},getUniqueKey(t,e){return l(t,e)},create(t,e,c){let g=l(e,c);d(g,t);try{a();}catch{}return g},keyRef(t){return {kind:"local-storage-scratch",value:t,extra:{prefix:o}}},config:{get(t){return i()[t]??null},set(t,e){let c=i();e==null?delete c[t]:c[t]=e,n(c);}}}}var M=":archive-marker",R=":archive-config",T=":archive:stream:",v=":archive:blob:";function E(o){let r=o.replace(/[^A-Za-z0-9._-]/g,"_");if(!r)throw new Error("Archive segment name cannot be empty after sanitization");return r}function D(o){let r=`${o}${M}`,S=`${o}${R}`,u=n=>`${o}${T}${n}`;if(globalThis.localStorage.getItem(r)===null)try{globalThis.localStorage.setItem(r,`archive-store
3
+ ${new Date().toISOString()}`);}catch{}function h(){let n=globalThis.localStorage.getItem(S);if(n===null)return {};try{let a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return {}}}function s(n){try{globalThis.localStorage.setItem(S,JSON.stringify(n));}catch{}}function i(){if(globalThis.localStorage.getItem(r)===null)return;let n=h(),a=typeof n["retention.maxAgeMs"]=="number"?n["retention.maxAgeMs"]:0,l=typeof n["retention.sweepIntervalMs"]=="number"?n["retention.sweepIntervalMs"]:0;if(a<=0||l<=0)return;let d=typeof n["retention.lastSweepAt"]=="number"?n["retention.lastSweepAt"]:0,t=Date.now();if(t-d<l)return;n["retention.lastSweepAt"]=t,s(n);let e=`${o}${T}`;for(let c=0;c<globalThis.localStorage.length;c++){let g=globalThis.localStorage.key(c);if(!g||!g.startsWith(e))continue;let y=globalThis.localStorage.getItem(g);if(y)try{let f=JSON.parse(y),m=f.filter(b=>typeof b.__ts!="number"||t-b.__ts<=a);m.length!==f.length&&globalThis.localStorage.setItem(g,JSON.stringify(m));}catch{}}}return {stream(n){let a=E(n),l=u(a);function d(){let e=globalThis.localStorage.getItem(l);if(!e)return [];try{return JSON.parse(e)}catch{return []}}function t(e){try{globalThis.localStorage.setItem(l,JSON.stringify(e));}catch{}}return {append(e){let c={id:globalThis.crypto.randomUUID(),payload:e,__ts:Date.now()},g=d();g.push(c),t(g);try{i();}catch{}return {id:c.id,payload:c.payload}},readAll(){return d().map(e=>({id:e.id,payload:e.payload}))},readAfter(e){let c=d();if(!e){let m=c.map(b=>({id:b.id,payload:b.payload}));return {entries:m,newCursor:m.length>0?m[m.length-1].id:null}}let g=c.findIndex(m=>m.id===e),f=(g===-1?c:c.slice(g+1)).map(m=>({id:m.id,payload:m.payload}));return {entries:f,newCursor:f.length>0?f[f.length-1].id:e}},clear(){try{globalThis.localStorage.removeItem(l);}catch{}}}},blob(n){let a=E(n),l=J(`${o}${v}${a}`);return {read:d=>l.read(d),write:(d,t)=>{l.write(d,t);try{i();}catch{}},exists:d=>l.exists(d),remove:d=>l.remove(d),readBytes:l.readBytes?d=>l.readBytes(d):void 0,writeBytes:l.writeBytes?(d,t)=>{l.writeBytes(d,t);try{i();}catch{}}:void 0,listKeys:d=>l.listKeys(d),stat:l.stat?d=>l.stat(d):void 0}},listStreams(n){let a=`${o}${T}`,l=[];for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length);(!n||e.startsWith(n))&&l.push(e);}return l.sort()},listBlobs(n){let a=`${o}${v}`,l=new Set;for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length),c=e.indexOf(":"),g=c===-1?e:e.slice(0,c);(!n||g.startsWith(n))&&l.add(g);}return Array.from(l).sort()},config:{get(n){return h()[n]??null},set(n,a){let l=h();a==null?delete l[n]:l[n]=a,s(l);}}}}function j(o){function r(S){return `${o}:kv:${S}`}return {read(S){let u=globalThis.localStorage.getItem(r(S));if(u===null)return null;try{return JSON.parse(u)}catch{return null}},write(S,u){globalThis.localStorage.setItem(r(S),JSON.stringify(u));},delete(S){globalThis.localStorage.removeItem(r(S));},listKeys(S){let u=r(S??""),h=[];for(let s=0;s<globalThis.localStorage.length;s++){let i=globalThis.localStorage.key(s);i!==null&&i.startsWith(u)&&h.push(i.slice(r("").length));}return h}}}function H(o){function r(){let u=globalThis.localStorage.getItem(o);if(!u)return [];try{return JSON.parse(u)}catch{return []}}function S(u){globalThis.localStorage.setItem(o,JSON.stringify(u));}return {readAllEntries(){return r()},appendEntry(u){let h=r();h.push(u),S(h);},generateId(){return globalThis.crypto.randomUUID()}}}exports.a=K;exports.b=J;exports.c=W;exports.d=D;exports.e=j;exports.f=H;//# sourceMappingURL=chunk-IPLSRN6P.cjs.map
4
+ //# sourceMappingURL=chunk-IPLSRN6P.cjs.map
@@ -0,0 +1,2 @@
1
+ import {a,c,d,e,b,f}from'./chunk-O7NOHKVR.js';import {a as a$1}from'./chunk-SGV7PU4H.js';import {b as b$1}from'./chunk-BQS3EIEK.js';import {a as a$2}from'./chunk-PRHQBGPT.js';function K(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function V(n){if(!n||typeof n!="object")return false;let e=n.summary;return !e||typeof e!="object"?false:Number(e.card_count||0)>0}function z(n,e){if(!e||typeof e!="object")return;let a=e;if(a.kind==="notification-batch"&&Array.isArray(a.notifications)){for(let l of a.notifications)z(n,l);return}a.kind==="status"&&V(a.status)&&(n.status=a.status),a.kind==="computed_values"&&a.cardId&&(n.computedValues[a.cardId]=a.values),a.kind==="data_object"&&a.key&&(n.dataObjects[a.key]=a.payload),a.kind==="card_refreshed"&&a.cardId&&(n.cards[a.cardId]=a.card),a.kind==="card_removed"&&a.cardId&&(delete n.cards[a.cardId],delete n.computedValues[a.cardId]);}function B(n,e){if(n?.status==="success")return Object.prototype.hasOwnProperty.call(n,"data")?n.data:void 0;throw n?.status==="fail"||n?.status==="error"?Object.assign(new Error(n.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function j(n,e){return B(await n,e)}function D(n){let e=a(n,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let a$1=e.split(".");if(!(a$1.length>=2&&a$1[0]==="chat"&&a$1.every(w=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(w))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function q(n,e){let a=n.meta;for(let l of e.split(".")){if(!a||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,l))return {exists:false,value:null};a=a[l];}return {exists:true,value:a}}function Q(n){let{boardId:e,getMcpFacade:a$1,getMcpCardStoreFacade:l}=n;function w(p){let o=a(p,"board_id"),c=a(p,"card_id");if(!o)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!c)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(o!==e)throw Object.assign(new Error(`Unknown board_id: ${o}`),{statusCode:400});return {cardId:c}}function _(p,o){let{cardId:c}=w(p);return a$1().setChatProcessing({cardId:c,active:o}),{status:"success",data:{boardId:e,cardId:c,active:o}}}function R(p){let{cardId:o}=w(p),c=a$1().getChatProcessing({cardId:o});return {status:"success",data:{boardId:e,cardId:o,active:c.active}}}async function t(p){let{cardId:o}=w(p),c=D(p);if(!Object.prototype.hasOwnProperty.call(p,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(c.split(".").includes("__visible_controlplane_only")){let i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null,h=g?q(g,"__visible_controlplane_only").value:void 0;if(p.value!==h)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:e,cardId:o,key:c}}}return B(await l().patch({params:{id:o,path:`meta.${c}`},body:{value:p.value}}),"cardStore.patch"),{status:"success",data:{boardId:e,cardId:o,key:c}}}async function C(p){let{cardId:o}=w(p),c=D(p),i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&i.cards[0]&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null;if(!g)throw Object.assign(new Error(`Card "${o}" not found`),{statusCode:404});let h=q(g,c);return {status:"success",data:{boardId:e,cardId:o,key:c,exists:h.exists,value:h.value}}}return {requireCardArgs:w,setChatProcessing:_,getChatProcessing:R,setCardMeta:t,getCardMeta:C}}function ee(n){let{boardId:e,boardContexts:a,readCardDefinitions:l,readChatRecords:w,getChatProcessing:_}=n;async function R(){let o=(await Promise.all(a.map(async y=>{try{let u=y.boardAdapter.kvStorageForRef(y.outputsStoreRef),m=await Promise.resolve(u.read("status"));if(m!=null)return m}catch{}return y.notification.status}))).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let c=[],i=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],g={};for(let y of i)g[y]=0;for(let y of o){let u=y,m=Array.isArray(u.cards)?u.cards:[];c.push(...m);for(let k of i)g[k]+=Number(u?.summary?.[k]||0);}let h=o[0];return {...h,cards:c,summary:{...h.summary||{},card_count:c.length,...g}}}async function t(){let o={},c=async i=>{try{let g=await i.boardOps.getAllOutputsComputedValues({});if(g.status==="success"&&g.data&&typeof g.data=="object"){for(let[h,y]of Object.entries(g.data)){let u=i.notification.cards[h];o[h]={schema_version:"v1",card_id:h,card_data:u?.card_data??{},computed_values:y??{}};}return}}catch{}for(let[g,h]of Object.entries(i.notification.computedValues)){let y=i.notification.cards[g];o[g]={schema_version:"v1",card_id:g,card_data:y?.card_data??{},computed_values:h??{}};}};for(let i of a)await c(i);return o}async function C(){let o={};for(let c of a){try{let i=await c.boardOps.getAllOutputsDataObjects({});if(i.status==="success"&&i.data&&typeof i.data=="object"){Object.assign(o,i.data);continue}}catch{}Object.assign(o,c.notification.dataObjects||{});}return o}async function p(){let o=await l(),c=await t(),i=await C(),g={};for(let y of o){if(!y?.id)continue;let u=y.id,m=c[u]||{},k={...m.card_data&&typeof m.card_data=="object"?m.card_data:y.card_data&&typeof y.card_data=="object"?y.card_data:{}};g[u]={schema_version:m.schema_version||"v1",card_id:m.card_id||u,card_data:k,computed_values:m.computed_values&&typeof m.computed_values=="object"?m.computed_values:{}};}let h={};for(let y of o){if(!y?.id)continue;let u=y.id;try{let m=w(u),k=_(u);(m.length>0||k)&&(h[u]={messages:m.map(v=>({role:String(v.role||"system"),text:String(v.text||""),files:Array.isArray(v.files)?v.files:[]})),receiving:!1,processing:k});}catch{}}return {boardId:e,cardDefinitions:o,statusSnapshot:await R(),dataObjectsByToken:i,cardRuntimeById:g,cardChatsByCardId:h}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:t,readDataObjectsByToken:C,buildPublishedRuntimePayload:p}}function H(n){let e=String(n||"").trim();if(!e)return "upload.bin";let a=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (a>=0?e.slice(a+1):e)||"upload.bin"}function re(n){let{safeCardId:e,artifactsStores:a,cardFileMetadataStore:l,readCardFromStore:w,updateCardLocalOnly:_,writeChatRecord:R}=n;async function t(o){let c=[];try{let i=await w(o);if(!i)return c;let g=l().read(i.card_data&&typeof i.card_data=="object"?i.card_data:null);for(let h of g)c.push(String(h.stored_name??""));}catch{}return c}async function C(o,c,i,g){let h=e(o),y=a(o),u=H(c),m=await t(o),v=`${String(m.length+1).padStart(3,"0")}-${u}`.slice(-36);return y.files&&await y.files.putBytes(`${h}/${v}`,new Uint8Array(g),i||"application/octet-stream"),{name:u,stored_name:v,size:g.length,mime_type:i||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function p(o,c,i,g,h){if(!g.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let y=h?.inChat===true,u=await C(o,c,i,g),m=null;if(await _(o,k=>{let v=new Date().toISOString(),A=k.card_data&&typeof k.card_data=="object"?k.card_data:{};k.card_data=A;let s=l().normalizeIncoming([{name:u.name,stored_name:u.stored_name,size:u.size,mime_type:u.mime_type,uploaded_at:u.uploaded_at||v,chat:y}],v);return m=l().merge(A,s).findIndex(d=>d.stored_name===u.stored_name),k}),y){let k=typeof m=="number"&&m>=0?` #${m}`:"";R(o,"system",`file uploaded: ${u.name} as ${u.stored_name}${k}`,[],h?.turnId??"");}return {ok:true,file:{...u,...typeof m=="number"&&m>=0?{file_idx:m}:{},chat:y},...typeof m=="number"&&m>=0?{file_idx:m}:{}}}return {uploadCardFile:p,readCardStoredFileNames:t}}function oe(n){return {"discover.source-kinds":()=>n.discoverSourceKinds(),"inspect.board-runtime-status":()=>n.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>n.inspectCardDefinitionAndRuntime({cardId:a(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let a$1=b(e,"tail_turns"),l=b(e,"tail"),w=a(e,"turn_id"),_=e.all_turns===true,R=a(e,"tail_turns_before_id");return n.inspectChatMessagesOnCards({cardId:a(e,"card_id"),...a$1!==void 0?{lastUserTurns:a$1}:{},...l!==void 0?{tail:l}:{},...w?{turnId:w}:{},..._?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":e=>n.inspectFileContents({cardId:a(e,"card_id"),fileIdx:Number(b(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>n.preflightValidateCandidateCardDefinition({candidateCardContent:d(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>n.preflightMaterializeCandidateCard({candidateCardContent:d(e,"candidate_card_content","candidate_card_content"),mockRequires:d(e,"mock_requires","mock_requires"),mockFetchedSources:d(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e$1=>n.preflightProbeSingleSourceInCandidateCard({candidateCardContent:d(e$1,"candidate_card_content","candidate_card_content"),mockProjections:c(e$1,"mock_projections"),sourceIdx:e(e$1,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e$1=>n.preflightRunSingleSourceInCandidateCard({candidateCardContent:d(e$1,"candidate_card_content","candidate_card_content"),mockProjections:c(e$1,"mock_projections"),sourceIdx:e(e$1,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e$1=>n.preflightRunSingleSourceInLiveCard({cardId:a(e$1,"card_id"),sourceIdx:e(e$1,"source_idx","source_idx"),mockRequires:d(e$1,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>n.preflightRunOneCycleWithCandidateCard({candidateCardContent:d(e,"candidate_card_content","candidate_card_content"),mockRequires:c(e,"mock_requires")}),"manage.read-card":e=>n.manageReadCard({cardId:a(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let a$1=a(e,"turn_id");if(!a$1)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return n.manageAddChatEntryAndAnyAttachments({cardId:a(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...a$1?{turn:a$1}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>n.manageUpsertCard({cardId:a(e,"card_id"),candidateCardContent:c(e,"candidate_card_content")}),"manage.remove-card":e=>n.manageRemoveCard({cardId:a(e,"card_id")})}}function se(n){return {"webhook.process-accumulated":()=>n.webhookProcessAccumulated(),"webhook.source-fetch-done":e=>n.webhookSourceFetchDone({token:a(e,"token"),ref:a(e,"ref")}),"webhook.source-fetch-failed":e=>n.webhookSourceFetchFailed({token:a(e,"token"),reason:a(e,"reason")})}}function de(n){let{boardId:e,uploadCardFile:a$1,getMcpFacade:l,controlplane:w}=n;function _(t,C){let p=a(t,"board_id");if(!p)throw Object.assign(new Error(`${C} requires board_id`),{statusCode:400});if(p!==e)throw Object.assign(new Error(`Unknown board_id: ${p}`),{statusCode:400})}function R(t,C){let{cardId:p}=w.requireCardArgs(t),o=a(t,"turn_id");return _(t,C),l().manageAddChatAttachment({cardId:p,role:a(t,"role")||"user",...o?{turn:o}:{},files:[{file_name:a(t,"file_name"),content_type:a(t,"content_type")||"application/octet-stream",...typeof t.text=="string"?{text:t.text}:{},...typeof t.base64=="string"?{base64:t.base64}:{},...Array.isArray(t.bytes)?{bytes:t.bytes}:{}}]})}return {"list-runtime-cards":t=>(_(t,"list-runtime-cards"),l().listRuntimeCards()),"getstate.is-chat-processing":t=>w.getChatProcessing(t),"setstate.chat-processing-started":t=>w.setChatProcessing(t,true),"setstate.chat-processing-done":t=>w.setChatProcessing(t,false),"getstate.card-meta":t=>w.getCardMeta(t),"setstate.card-meta":t=>w.setCardMeta(t),"manage.upload-card-file":t=>{let C=a(t,"card_id"),p=a(t,"file_name"),o=a(t,"content_type")||"application/octet-stream",c=f(t);if(_(t,"manage.upload-card-file"),!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!c)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return a$1(C,p,o,c,{inChat:false})},"manage.add-chat-attachment":t=>R(t,"manage.add-chat-attachment"),"manage.add-chat-attachement":t=>R(t,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":t=>{let{cardId:C}=w.requireCardArgs(t),p=a(t,"role")||"user",o=a(t,"turn_id");return _(t,"manage.add-chat-entry-and-any-attachments"),l().manageAddChatEntryAndAnyAttachments({cardId:C,role:p,...typeof t.text=="string"?{text:t.text}:{},...o?{turn:o}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.patch-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.patch-card"),l().managePatchCard({cardId:C,patch:c(t,"patch")})},"manage.upsert-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.upsert-card"),l().manageUpsertCard({cardId:C,candidateCardContent:c(t,"candidate_card_content")})},"manage.remove-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.remove-card"),l().manageRemoveCard({cardId:C})},"manage.admin-read-card":async t=>{let{cardId:C}=w.requireCardArgs(t);return {status:"success",data:{cards:await l().adminReadCard({cardId:C})}}},"manage.admin-upsert-card":t=>{let C=a(t,"board_id"),p=a(t,"card_id");if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(C!==e)throw Object.assign(new Error(`Unknown board_id: ${C}`),{statusCode:400});return l().adminUpsertCard({cardId:p,candidateCardContent:c(t,"candidate_card_content")})}}}function pe(n){let{boardContexts:e,cardOwnerIndex:a,cardContextForCard:l,readStatusSnapshot:w,readDataObjectsByToken:_,readCardRuntimeArtifacts:R,readCardFromStore:t,readCardDefinitions:C,processAccumulatedLaneInternal:p,reportSourceFetched:o,reportSourceFetchFailure:c,uploadCardFile:i,chatStorePublic:g,serverUrl:h,apiBasePath:y}=n;function u(){return e[0]??null}function m(){return {async status(){let s=await w();return s==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:s}},async getOutputsDataObject(s){let r=s?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(s){let r=s?.params?.key;return r?{status:"success",data:(await R())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(s){let r=s?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=l(r)??u();return d?d.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(s){let r=s?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let d=l(r)??u();return d?d.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=l(r)??u();return d?d.boardOps.cardRefreshedNotify({params:{cardId:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let d=l(r)??u();if(!d)return {status:"fail",error:"Board context is unavailable"};let b=await d.boardOps.upsertCard({params:{cardId:r,restart:s.params.restart===true}});if(b.status!=="success")return b;if(a$1(d.boardAdapter)){let x=await p(true);if(x.status!=="success")return x}return b}}}function k(){let s=()=>{let r=u();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 s().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return s().validateCardPreflight(r)},evalCardCompute(r){return s().evalCardCompute(r)},probeSourcePreflight(r){return s().probeSourcePreflight(r)},runSourcePreflight(r){return s().runSourcePreflight(r)},simulateCardCycle(r){return s().simulateCardCycle(r)}}}function v(){return {async get(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(r){let d=await t(r);return d?{status:"success",data:{cards:[d]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await C()}}},async set(s){let r=s.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(r)?r:[r];for(let b of d){let x=b,I=typeof x.id=="string"?x.id:"";if(!I)return {status:"fail",error:"each card must have a string `id` field"};let T=a.get(I)??0,L=e[T]??u();if(!L)return {status:"fail",error:"Board context is unavailable"};let N=await L.cardStoreOps.set({body:x});if(N.status!=="success")return N;a.set(I,T);}return {status:"success",data:{count:d.length}}},async del(s){let r=[s.params?.id,...s.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of r){let b=l(d)??u();if(!b)return {status:"fail",error:"Board context is unavailable"};let x=await b.cardStoreOps.del({params:{id:d}});if(x.status!=="success")return x;a.delete(d);}return {status:"success",data:{count:r.length}}},async patch(s){let r=typeof s.params?.id=="string"?s.params.id:void 0,d=typeof s.params?.path=="string"?s.params.path:void 0;if(!r||!d)return {status:"fail",error:"patch requires params.id and params.path"};let b=l(r)??u();return b?b.cardStoreOps.patch(s):{status:"fail",error:"Board context is unavailable"}},async appendFiles(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let d=l(r)??u();return d?d.cardStoreOps.appendFiles(s):{status:"fail",error:"Board context is unavailable"}}}}function A(){return a$2({board:m(),nonCore:k(),cardStore:v(),chatStore:g,processAccumulated:()=>p(true),sourceFetchDone:({token:s,ref:r})=>o(s,r),sourceFetchFailed:({token:s,reason:r})=>c(s,r),uploadCardFile({cardId:s,fileName:r,contentType:d,bytes:b}){return i(s,r,d,b,{inChat:true})},buildFileDownloadUrl({cardId:s,fileIdx:r,storedName:d}){let b=`${h||""}${y}/cards/${encodeURIComponent(s)}/files/${r}`;return d?`${b}?sn=${encodeURIComponent(d)}`:b},readFetchedSourceJsonByRef({cardId:s,ref:r}){let d=l(s)??u();if(!d||a$1(d.boardAdapter))return null;let I=d.boardAdapter.resolveBlob(b$1(r)).trim();return I?JSON.parse(I):null}})}return {mcpBoardFacade:m,mcpNonCoreFacade:k,mcpCardStoreFacade:v,createMcpFacade:A}}export{K as a,V as b,z as c,B as d,j as e,D as f,q as g,Q as h,ee as i,re as j,oe as k,se as l,de as m,pe as n};//# sourceMappingURL=chunk-J5J6BG7B.js.map
2
+ //# sourceMappingURL=chunk-J5J6BG7B.js.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs');function p(t){return typeof t.journalStorage=="function"}function s(t){return typeof t.whatToRun=="string"?t.whatToRun.startsWith("b64:")?chunkSFVO2LB2_cjs.b(t.whatToRun).value:t.whatToRun:t.whatToRun.value}function c(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(t){let a=t.reduce((r,u)=>r+u.length,0),o=new Uint8Array(a),n=0;for(let r of t)o.set(r,n),n+=r.length;return o}exports.a=p;exports.b=s;exports.c=c;exports.d=f;//# sourceMappingURL=chunk-KAWQPLIE.cjs.map
2
+ //# sourceMappingURL=chunk-KAWQPLIE.cjs.map
@@ -0,0 +1,2 @@
1
+ 'use strict';function u(n,...r){for(let e of r)if(typeof n[e]=="string")return String(n[e]);return ""}function s(n,...r){for(let e of r)if(n[e]!==void 0)return Number(n[e])}function c(n,...r){for(let e of r){let t=n[e];if(t&&typeof t=="object"&&!Array.isArray(t))return t}return {}}function f(n,r,...e){for(let t of e){let o=n[t];if(o&&typeof o=="object"&&!Array.isArray(o))return o}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function d(n,r,...e){for(let t of e){let o=n[t];if(o!==void 0){let i=Number(o);if(Number.isFinite(i))return i}}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function g(n){if(Array.isArray(n.bytes))return new Uint8Array(n.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof n.text=="string")return new TextEncoder().encode(n.text);if(typeof n.base64=="string"){let r=String(n.base64).replace(/-/g,"+").replace(/_/g,"/"),e=r+"=".repeat((4-r.length%4)%4),t=atob(e);return Uint8Array.from(t,o=>o.charCodeAt(0))}return null}exports.a=u;exports.b=s;exports.c=c;exports.d=f;exports.e=d;exports.f=g;//# sourceMappingURL=chunk-LPXVVMQT.cjs.map
2
+ //# sourceMappingURL=chunk-LPXVVMQT.cjs.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs'),chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),chunkM6STQR5F_cjs=require('./chunk-M6STQR5F.cjs');function K(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function V(n){if(!n||typeof n!="object")return false;let e=n.summary;return !e||typeof e!="object"?false:Number(e.card_count||0)>0}function z(n,e){if(!e||typeof e!="object")return;let a=e;if(a.kind==="notification-batch"&&Array.isArray(a.notifications)){for(let l of a.notifications)z(n,l);return}a.kind==="status"&&V(a.status)&&(n.status=a.status),a.kind==="computed_values"&&a.cardId&&(n.computedValues[a.cardId]=a.values),a.kind==="data_object"&&a.key&&(n.dataObjects[a.key]=a.payload),a.kind==="card_refreshed"&&a.cardId&&(n.cards[a.cardId]=a.card),a.kind==="card_removed"&&a.cardId&&(delete n.cards[a.cardId],delete n.computedValues[a.cardId]);}function B(n,e){if(n?.status==="success")return Object.prototype.hasOwnProperty.call(n,"data")?n.data:void 0;throw n?.status==="fail"||n?.status==="error"?Object.assign(new Error(n.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function j(n,e){return B(await n,e)}function D(n){let e=chunkLPXVVMQT_cjs.a(n,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let a=e.split(".");if(!(a.length>=2&&a[0]==="chat"&&a.every(w=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(w))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function q(n,e){let a=n.meta;for(let l of e.split(".")){if(!a||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,l))return {exists:false,value:null};a=a[l];}return {exists:true,value:a}}function Q(n){let{boardId:e,getMcpFacade:a,getMcpCardStoreFacade:l}=n;function w(p){let o=chunkLPXVVMQT_cjs.a(p,"board_id"),c=chunkLPXVVMQT_cjs.a(p,"card_id");if(!o)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!c)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(o!==e)throw Object.assign(new Error(`Unknown board_id: ${o}`),{statusCode:400});return {cardId:c}}function _(p,o){let{cardId:c}=w(p);return a().setChatProcessing({cardId:c,active:o}),{status:"success",data:{boardId:e,cardId:c,active:o}}}function R(p){let{cardId:o}=w(p),c=a().getChatProcessing({cardId:o});return {status:"success",data:{boardId:e,cardId:o,active:c.active}}}async function t(p){let{cardId:o}=w(p),c=D(p);if(!Object.prototype.hasOwnProperty.call(p,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(c.split(".").includes("__visible_controlplane_only")){let i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null,h=g?q(g,"__visible_controlplane_only").value:void 0;if(p.value!==h)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:e,cardId:o,key:c}}}return B(await l().patch({params:{id:o,path:`meta.${c}`},body:{value:p.value}}),"cardStore.patch"),{status:"success",data:{boardId:e,cardId:o,key:c}}}async function C(p){let{cardId:o}=w(p),c=D(p),i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&i.cards[0]&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null;if(!g)throw Object.assign(new Error(`Card "${o}" not found`),{statusCode:404});let h=q(g,c);return {status:"success",data:{boardId:e,cardId:o,key:c,exists:h.exists,value:h.value}}}return {requireCardArgs:w,setChatProcessing:_,getChatProcessing:R,setCardMeta:t,getCardMeta:C}}function ee(n){let{boardId:e,boardContexts:a,readCardDefinitions:l,readChatRecords:w,getChatProcessing:_}=n;async function R(){let o=(await Promise.all(a.map(async y=>{try{let u=y.boardAdapter.kvStorageForRef(y.outputsStoreRef),m=await Promise.resolve(u.read("status"));if(m!=null)return m}catch{}return y.notification.status}))).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let c=[],i=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],g={};for(let y of i)g[y]=0;for(let y of o){let u=y,m=Array.isArray(u.cards)?u.cards:[];c.push(...m);for(let k of i)g[k]+=Number(u?.summary?.[k]||0);}let h=o[0];return {...h,cards:c,summary:{...h.summary||{},card_count:c.length,...g}}}async function t(){let o={},c=async i=>{try{let g=await i.boardOps.getAllOutputsComputedValues({});if(g.status==="success"&&g.data&&typeof g.data=="object"){for(let[h,y]of Object.entries(g.data)){let u=i.notification.cards[h];o[h]={schema_version:"v1",card_id:h,card_data:u?.card_data??{},computed_values:y??{}};}return}}catch{}for(let[g,h]of Object.entries(i.notification.computedValues)){let y=i.notification.cards[g];o[g]={schema_version:"v1",card_id:g,card_data:y?.card_data??{},computed_values:h??{}};}};for(let i of a)await c(i);return o}async function C(){let o={};for(let c of a){try{let i=await c.boardOps.getAllOutputsDataObjects({});if(i.status==="success"&&i.data&&typeof i.data=="object"){Object.assign(o,i.data);continue}}catch{}Object.assign(o,c.notification.dataObjects||{});}return o}async function p(){let o=await l(),c=await t(),i=await C(),g={};for(let y of o){if(!y?.id)continue;let u=y.id,m=c[u]||{},k={...m.card_data&&typeof m.card_data=="object"?m.card_data:y.card_data&&typeof y.card_data=="object"?y.card_data:{}};g[u]={schema_version:m.schema_version||"v1",card_id:m.card_id||u,card_data:k,computed_values:m.computed_values&&typeof m.computed_values=="object"?m.computed_values:{}};}let h={};for(let y of o){if(!y?.id)continue;let u=y.id;try{let m=w(u),k=_(u);(m.length>0||k)&&(h[u]={messages:m.map(v=>({role:String(v.role||"system"),text:String(v.text||""),files:Array.isArray(v.files)?v.files:[]})),receiving:!1,processing:k});}catch{}}return {boardId:e,cardDefinitions:o,statusSnapshot:await R(),dataObjectsByToken:i,cardRuntimeById:g,cardChatsByCardId:h}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:t,readDataObjectsByToken:C,buildPublishedRuntimePayload:p}}function H(n){let e=String(n||"").trim();if(!e)return "upload.bin";let a=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (a>=0?e.slice(a+1):e)||"upload.bin"}function re(n){let{safeCardId:e,artifactsStores:a,cardFileMetadataStore:l,readCardFromStore:w,updateCardLocalOnly:_,writeChatRecord:R}=n;async function t(o){let c=[];try{let i=await w(o);if(!i)return c;let g=l().read(i.card_data&&typeof i.card_data=="object"?i.card_data:null);for(let h of g)c.push(String(h.stored_name??""));}catch{}return c}async function C(o,c,i,g){let h=e(o),y=a(o),u=H(c),m=await t(o),v=`${String(m.length+1).padStart(3,"0")}-${u}`.slice(-36);return y.files&&await y.files.putBytes(`${h}/${v}`,new Uint8Array(g),i||"application/octet-stream"),{name:u,stored_name:v,size:g.length,mime_type:i||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function p(o,c,i,g,h){if(!g.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let y=h?.inChat===true,u=await C(o,c,i,g),m=null;if(await _(o,k=>{let v=new Date().toISOString(),A=k.card_data&&typeof k.card_data=="object"?k.card_data:{};k.card_data=A;let s=l().normalizeIncoming([{name:u.name,stored_name:u.stored_name,size:u.size,mime_type:u.mime_type,uploaded_at:u.uploaded_at||v,chat:y}],v);return m=l().merge(A,s).findIndex(d=>d.stored_name===u.stored_name),k}),y){let k=typeof m=="number"&&m>=0?` #${m}`:"";R(o,"system",`file uploaded: ${u.name} as ${u.stored_name}${k}`,[],h?.turnId??"");}return {ok:true,file:{...u,...typeof m=="number"&&m>=0?{file_idx:m}:{},chat:y},...typeof m=="number"&&m>=0?{file_idx:m}:{}}}return {uploadCardFile:p,readCardStoredFileNames:t}}function oe(n){return {"discover.source-kinds":()=>n.discoverSourceKinds(),"inspect.board-runtime-status":()=>n.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>n.inspectCardDefinitionAndRuntime({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let a=chunkLPXVVMQT_cjs.b(e,"tail_turns"),l=chunkLPXVVMQT_cjs.b(e,"tail"),w=chunkLPXVVMQT_cjs.a(e,"turn_id"),_=e.all_turns===true,R=chunkLPXVVMQT_cjs.a(e,"tail_turns_before_id");return n.inspectChatMessagesOnCards({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),...a!==void 0?{lastUserTurns:a}:{},...l!==void 0?{tail:l}:{},...w?{turnId:w}:{},..._?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":e=>n.inspectFileContents({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),fileIdx:Number(chunkLPXVVMQT_cjs.b(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>n.preflightValidateCandidateCardDefinition({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>n.preflightMaterializeCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires"),mockFetchedSources:chunkLPXVVMQT_cjs.d(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>n.preflightProbeSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>n.preflightRunSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>n.preflightRunSingleSourceInLiveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>n.preflightRunOneCycleWithCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.c(e,"mock_requires")}),"manage.read-card":e=>n.manageReadCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let a=chunkLPXVVMQT_cjs.a(e,"turn_id");if(!a)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return n.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...a?{turn:a}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>n.manageUpsertCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),candidateCardContent:chunkLPXVVMQT_cjs.c(e,"candidate_card_content")}),"manage.remove-card":e=>n.manageRemoveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")})}}function se(n){return {"webhook.process-accumulated":()=>n.webhookProcessAccumulated(),"webhook.source-fetch-done":e=>n.webhookSourceFetchDone({token:chunkLPXVVMQT_cjs.a(e,"token"),ref:chunkLPXVVMQT_cjs.a(e,"ref")}),"webhook.source-fetch-failed":e=>n.webhookSourceFetchFailed({token:chunkLPXVVMQT_cjs.a(e,"token"),reason:chunkLPXVVMQT_cjs.a(e,"reason")})}}function de(n){let{boardId:e,uploadCardFile:a,getMcpFacade:l,controlplane:w}=n;function _(t,C){let p=chunkLPXVVMQT_cjs.a(t,"board_id");if(!p)throw Object.assign(new Error(`${C} requires board_id`),{statusCode:400});if(p!==e)throw Object.assign(new Error(`Unknown board_id: ${p}`),{statusCode:400})}function R(t,C){let{cardId:p}=w.requireCardArgs(t),o=chunkLPXVVMQT_cjs.a(t,"turn_id");return _(t,C),l().manageAddChatAttachment({cardId:p,role:chunkLPXVVMQT_cjs.a(t,"role")||"user",...o?{turn:o}:{},files:[{file_name:chunkLPXVVMQT_cjs.a(t,"file_name"),content_type:chunkLPXVVMQT_cjs.a(t,"content_type")||"application/octet-stream",...typeof t.text=="string"?{text:t.text}:{},...typeof t.base64=="string"?{base64:t.base64}:{},...Array.isArray(t.bytes)?{bytes:t.bytes}:{}}]})}return {"list-runtime-cards":t=>(_(t,"list-runtime-cards"),l().listRuntimeCards()),"getstate.is-chat-processing":t=>w.getChatProcessing(t),"setstate.chat-processing-started":t=>w.setChatProcessing(t,true),"setstate.chat-processing-done":t=>w.setChatProcessing(t,false),"getstate.card-meta":t=>w.getCardMeta(t),"setstate.card-meta":t=>w.setCardMeta(t),"manage.upload-card-file":t=>{let C=chunkLPXVVMQT_cjs.a(t,"card_id"),p=chunkLPXVVMQT_cjs.a(t,"file_name"),o=chunkLPXVVMQT_cjs.a(t,"content_type")||"application/octet-stream",c=chunkLPXVVMQT_cjs.f(t);if(_(t,"manage.upload-card-file"),!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!c)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return a(C,p,o,c,{inChat:false})},"manage.add-chat-attachment":t=>R(t,"manage.add-chat-attachment"),"manage.add-chat-attachement":t=>R(t,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":t=>{let{cardId:C}=w.requireCardArgs(t),p=chunkLPXVVMQT_cjs.a(t,"role")||"user",o=chunkLPXVVMQT_cjs.a(t,"turn_id");return _(t,"manage.add-chat-entry-and-any-attachments"),l().manageAddChatEntryAndAnyAttachments({cardId:C,role:p,...typeof t.text=="string"?{text:t.text}:{},...o?{turn:o}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.patch-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.patch-card"),l().managePatchCard({cardId:C,patch:chunkLPXVVMQT_cjs.c(t,"patch")})},"manage.upsert-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.upsert-card"),l().manageUpsertCard({cardId:C,candidateCardContent:chunkLPXVVMQT_cjs.c(t,"candidate_card_content")})},"manage.remove-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.remove-card"),l().manageRemoveCard({cardId:C})},"manage.admin-read-card":async t=>{let{cardId:C}=w.requireCardArgs(t);return {status:"success",data:{cards:await l().adminReadCard({cardId:C})}}},"manage.admin-upsert-card":t=>{let C=chunkLPXVVMQT_cjs.a(t,"board_id"),p=chunkLPXVVMQT_cjs.a(t,"card_id");if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(C!==e)throw Object.assign(new Error(`Unknown board_id: ${C}`),{statusCode:400});return l().adminUpsertCard({cardId:p,candidateCardContent:chunkLPXVVMQT_cjs.c(t,"candidate_card_content")})}}}function pe(n){let{boardContexts:e,cardOwnerIndex:a,cardContextForCard:l,readStatusSnapshot:w,readDataObjectsByToken:_,readCardRuntimeArtifacts:R,readCardFromStore:t,readCardDefinitions:C,processAccumulatedLaneInternal:p,reportSourceFetched:o,reportSourceFetchFailure:c,uploadCardFile:i,chatStorePublic:g,serverUrl:h,apiBasePath:y}=n;function u(){return e[0]??null}function m(){return {async status(){let s=await w();return s==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:s}},async getOutputsDataObject(s){let r=s?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(s){let r=s?.params?.key;return r?{status:"success",data:(await R())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(s){let r=s?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=l(r)??u();return d?d.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(s){let r=s?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let d=l(r)??u();return d?d.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=l(r)??u();return d?d.boardOps.cardRefreshedNotify({params:{cardId:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let d=l(r)??u();if(!d)return {status:"fail",error:"Board context is unavailable"};let b=await d.boardOps.upsertCard({params:{cardId:r,restart:s.params.restart===true}});if(b.status!=="success")return b;if(chunkKAWQPLIE_cjs.a(d.boardAdapter)){let x=await p(true);if(x.status!=="success")return x}return b}}}function k(){let s=()=>{let r=u();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 s().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return s().validateCardPreflight(r)},evalCardCompute(r){return s().evalCardCompute(r)},probeSourcePreflight(r){return s().probeSourcePreflight(r)},runSourcePreflight(r){return s().runSourcePreflight(r)},simulateCardCycle(r){return s().simulateCardCycle(r)}}}function v(){return {async get(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(r){let d=await t(r);return d?{status:"success",data:{cards:[d]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await C()}}},async set(s){let r=s.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(r)?r:[r];for(let b of d){let x=b,I=typeof x.id=="string"?x.id:"";if(!I)return {status:"fail",error:"each card must have a string `id` field"};let T=a.get(I)??0,L=e[T]??u();if(!L)return {status:"fail",error:"Board context is unavailable"};let N=await L.cardStoreOps.set({body:x});if(N.status!=="success")return N;a.set(I,T);}return {status:"success",data:{count:d.length}}},async del(s){let r=[s.params?.id,...s.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of r){let b=l(d)??u();if(!b)return {status:"fail",error:"Board context is unavailable"};let x=await b.cardStoreOps.del({params:{id:d}});if(x.status!=="success")return x;a.delete(d);}return {status:"success",data:{count:r.length}}},async patch(s){let r=typeof s.params?.id=="string"?s.params.id:void 0,d=typeof s.params?.path=="string"?s.params.path:void 0;if(!r||!d)return {status:"fail",error:"patch requires params.id and params.path"};let b=l(r)??u();return b?b.cardStoreOps.patch(s):{status:"fail",error:"Board context is unavailable"}},async appendFiles(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let d=l(r)??u();return d?d.cardStoreOps.appendFiles(s):{status:"fail",error:"Board context is unavailable"}}}}function A(){return chunkM6STQR5F_cjs.a({board:m(),nonCore:k(),cardStore:v(),chatStore:g,processAccumulated:()=>p(true),sourceFetchDone:({token:s,ref:r})=>o(s,r),sourceFetchFailed:({token:s,reason:r})=>c(s,r),uploadCardFile({cardId:s,fileName:r,contentType:d,bytes:b}){return i(s,r,d,b,{inChat:true})},buildFileDownloadUrl({cardId:s,fileIdx:r,storedName:d}){let b=`${h||""}${y}/cards/${encodeURIComponent(s)}/files/${r}`;return d?`${b}?sn=${encodeURIComponent(d)}`:b},readFetchedSourceJsonByRef({cardId:s,ref:r}){let d=l(s)??u();if(!d||chunkKAWQPLIE_cjs.a(d.boardAdapter))return null;let I=d.boardAdapter.resolveBlob(chunkSFVO2LB2_cjs.b(r)).trim();return I?JSON.parse(I):null}})}return {mcpBoardFacade:m,mcpNonCoreFacade:k,mcpCardStoreFacade:v,createMcpFacade:A}}exports.a=K;exports.b=V;exports.c=z;exports.d=B;exports.e=j;exports.f=D;exports.g=q;exports.h=Q;exports.i=ee;exports.j=re;exports.k=oe;exports.l=se;exports.m=de;exports.n=pe;//# sourceMappingURL=chunk-M3OU6IS5.cjs.map
2
+ //# sourceMappingURL=chunk-M3OU6IS5.cjs.map