yaml-flow 8.8.7 → 8.9.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 (155) hide show
  1. package/browser/adapters/firestore-storage.js +2 -2
  2. package/browser/adapters/localstorage-storage.js +3 -3
  3. package/browser/asset-integrity.json +7 -7
  4. package/browser/server-runtime-controlface.js +5 -5
  5. package/examples/board/test/server-http-test-browser.ts +2394 -0
  6. package/examples/board/test/server-http-test.js +44 -35
  7. package/lib/{artifacts-store-lib-C6qBpMfU.d.cts → artifacts-store-lib-CqkJEgbx.d.cts} +1 -1
  8. package/lib/{artifacts-store-lib-D4qf7Q-7.d.ts → artifacts-store-lib-D6Bo4yFN.d.ts} +1 -1
  9. package/lib/artifacts-store-public.d.cts +5 -3
  10. package/lib/artifacts-store-public.d.ts +5 -3
  11. package/lib/board-callback-transport-Bekq8Gp-.d.ts +71 -0
  12. package/lib/board-callback-transport-kP0K6UMq.d.cts +71 -0
  13. package/lib/board-live-cards-lib-DVh3t9NT.d.cts +222 -0
  14. package/lib/board-live-cards-lib-iU8xOwNp.d.ts +222 -0
  15. package/lib/board-live-cards-mcp.cjs +1 -1
  16. package/lib/board-live-cards-mcp.d.cts +4 -8
  17. package/lib/board-live-cards-mcp.d.ts +4 -8
  18. package/lib/board-live-cards-mcp.js +1 -1
  19. package/lib/board-live-cards-node.cjs +7 -7
  20. package/lib/board-live-cards-node.d.cts +15 -11
  21. package/lib/board-live-cards-node.d.ts +15 -11
  22. package/lib/board-live-cards-node.js +7 -7
  23. package/lib/{board-live-cards-public-async-CYjr4mgX.d.cts → board-live-cards-public-async-Cl0M3j5P.d.cts} +6 -4
  24. package/lib/{board-live-cards-public-async-DlyC3PgC.d.ts → board-live-cards-public-async-U98IXUBx.d.ts} +6 -4
  25. package/lib/board-live-cards-public.cjs +1 -1
  26. package/lib/board-live-cards-public.d.cts +325 -3
  27. package/lib/board-live-cards-public.d.ts +325 -3
  28. package/lib/board-live-cards-public.js +1 -1
  29. package/lib/board-live-cards-server-runtime.cjs +1 -1
  30. package/lib/board-live-cards-server-runtime.d.cts +8 -6
  31. package/lib/board-live-cards-server-runtime.d.ts +8 -6
  32. package/lib/board-live-cards-server-runtime.js +1 -1
  33. package/lib/{board-platform-adapter-async-JP9V-U5E.d.ts → board-platform-adapter-async-ByBRFn1G.d.ts} +4 -3
  34. package/lib/{board-platform-adapter-async-BZIftm36.d.cts → board-platform-adapter-async-DjBwE0m9.d.cts} +4 -3
  35. package/lib/board-state-reducer.cjs +2 -0
  36. package/lib/board-state-reducer.d.cts +53 -0
  37. package/lib/board-state-reducer.d.ts +53 -0
  38. package/lib/board-state-reducer.js +2 -0
  39. package/lib/card-store-public.cjs +1 -1
  40. package/lib/card-store-public.d.cts +11 -4
  41. package/lib/card-store-public.d.ts +11 -4
  42. package/lib/card-store-public.js +1 -1
  43. package/lib/chat-store-public.cjs +1 -1
  44. package/lib/chat-store-public.d.cts +15 -4
  45. package/lib/chat-store-public.d.ts +15 -4
  46. package/lib/chat-store-public.js +1 -1
  47. package/lib/chunk-2RIHC5TZ.cjs +2 -0
  48. package/lib/chunk-37FDOKDK.js +3 -0
  49. package/lib/chunk-3S7LV2HZ.cjs +2 -0
  50. package/lib/chunk-3T5TMAWG.cjs +3 -0
  51. package/lib/chunk-5XLFPPTY.cjs +2 -0
  52. package/lib/{chunk-R44X3RQB.cjs → chunk-6EJRZHFP.cjs} +2 -2
  53. package/lib/{chunk-NNSBBO5R.js → chunk-6MD6FVE3.js} +2 -2
  54. package/lib/chunk-7QNEV5S3.js +2 -0
  55. package/lib/{chunk-6OPXQPSC.js → chunk-7UJQMFVS.js} +2 -2
  56. package/lib/chunk-BJGK5FNL.js +2 -0
  57. package/lib/{chunk-ETW3BXHD.cjs → chunk-BQJVCCFU.cjs} +2 -2
  58. package/lib/chunk-DQPBAB5Z.cjs +2 -0
  59. package/lib/chunk-JB4Q2W7I.js +7 -0
  60. package/lib/chunk-JYVYAAXT.js +3 -0
  61. package/lib/chunk-LFVMX23W.cjs +7 -0
  62. package/lib/chunk-NIBLKYXN.js +2 -0
  63. package/lib/chunk-OF4FPYNI.cjs +2 -0
  64. package/lib/chunk-P3R6TXII.js +3 -0
  65. package/lib/{chunk-7BTZCOT5.js → chunk-QLB6PKOT.js} +2 -2
  66. package/lib/chunk-R4YASXSJ.js +2 -0
  67. package/lib/chunk-RZRIXQ6A.cjs +3 -0
  68. package/lib/chunk-SDJ3747Q.cjs +2 -0
  69. package/lib/chunk-SJANU3PL.cjs +3 -0
  70. package/lib/chunk-UGB7PC4P.js +2 -0
  71. package/lib/chunk-VBYNMTWC.js +2 -0
  72. package/lib/{chunk-37HDEW26.cjs → chunk-WRMOGPRG.cjs} +2 -2
  73. package/lib/cloud-storage.cjs +1 -1
  74. package/lib/cloud-storage.d.cts +44 -8
  75. package/lib/cloud-storage.d.ts +44 -8
  76. package/lib/cloud-storage.js +1 -1
  77. package/lib/firebase-storage/index.d.cts +2 -2
  78. package/lib/firebase-storage/index.d.ts +2 -2
  79. package/lib/firestore-storage/index.cjs +2 -2
  80. package/lib/firestore-storage/index.d.cts +6 -5
  81. package/lib/firestore-storage/index.d.ts +6 -5
  82. package/lib/firestore-storage/index.js +2 -2
  83. package/lib/index.cjs +2 -2
  84. package/lib/index.d.cts +1 -1
  85. package/lib/index.d.ts +1 -1
  86. package/lib/index.js +1 -1
  87. package/lib/localstorage-storage/index.cjs +1 -1
  88. package/lib/localstorage-storage/index.d.cts +6 -5
  89. package/lib/localstorage-storage/index.d.ts +6 -5
  90. package/lib/localstorage-storage/index.js +1 -1
  91. package/lib/notification-consumer/index.cjs +2 -0
  92. package/lib/notification-consumer/index.d.cts +17 -0
  93. package/lib/notification-consumer/index.d.ts +17 -0
  94. package/lib/notification-consumer/index.js +2 -0
  95. package/lib/queue-storage-public.cjs +2 -0
  96. package/lib/queue-storage-public.d.cts +13 -0
  97. package/lib/queue-storage-public.d.ts +13 -0
  98. package/lib/queue-storage-public.js +2 -0
  99. package/lib/server-jobs-queue-runner/index.cjs +1 -1
  100. package/lib/server-jobs-queue-runner/index.d.cts +9 -7
  101. package/lib/server-jobs-queue-runner/index.d.ts +9 -7
  102. package/lib/server-jobs-queue-runner/index.js +1 -1
  103. package/lib/server-runtime/index.cjs +1 -1
  104. package/lib/server-runtime/index.d.cts +9 -7
  105. package/lib/server-runtime/index.d.ts +9 -7
  106. package/lib/server-runtime/index.js +1 -1
  107. package/lib/server-runtime-agentface/index.d.cts +8 -6
  108. package/lib/server-runtime-agentface/index.d.ts +8 -6
  109. package/lib/server-runtime-controlface/index.cjs +1 -1
  110. package/lib/server-runtime-controlface/index.d.cts +8 -6
  111. package/lib/server-runtime-controlface/index.d.ts +8 -6
  112. package/lib/server-runtime-controlface/index.js +1 -1
  113. package/lib/server-runtime-core/index.cjs +1 -1
  114. package/lib/server-runtime-core/index.d.cts +16 -37
  115. package/lib/server-runtime-core/index.d.ts +16 -37
  116. package/lib/server-runtime-core/index.js +1 -1
  117. package/lib/server-runtime-watchers/index.cjs +1 -1
  118. package/lib/server-runtime-watchers/index.d.cts +11 -8
  119. package/lib/server-runtime-watchers/index.d.ts +11 -8
  120. package/lib/server-runtime-watchers/index.js +1 -1
  121. package/lib/server-runtime-webhooks/index.d.cts +8 -6
  122. package/lib/server-runtime-webhooks/index.d.ts +8 -6
  123. package/lib/{sse-hub-DM8bw-dO.d.ts → sse-hub-BRBvymHR.d.cts} +18 -15
  124. package/lib/{sse-hub-BDjWI7JR.d.cts → sse-hub-D_94fV87.d.ts} +18 -15
  125. package/lib/step-machine-public/index.d.cts +1 -1
  126. package/lib/step-machine-public/index.d.ts +1 -1
  127. package/lib/{storage-async-interface-CyO-zwVQ.d.cts → storage-async-interface-CLOXiqwC.d.cts} +2 -2
  128. package/lib/{storage-async-interface-CG0bMqvE.d.ts → storage-async-interface-Cb-SULrI.d.ts} +2 -2
  129. package/lib/{storage-interface-D-iEiTJA.d.cts → storage-interface-DogVPooM.d.cts} +1 -1
  130. package/lib/{storage-interface-D-iEiTJA.d.ts → storage-interface-DogVPooM.d.ts} +1 -1
  131. package/lib/stores/index.d.cts +1 -1
  132. package/lib/stores/index.d.ts +1 -1
  133. package/lib/stores/kv.d.cts +1 -1
  134. package/lib/stores/kv.d.ts +1 -1
  135. package/lib/{types-BsfXZyI3.d.ts → types-BsqzUZNl.d.ts} +6 -4
  136. package/lib/{types-CPnYv7RC.d.cts → types-DxhB6Toz.d.cts} +6 -4
  137. package/package.json +16 -1
  138. package/lib/board-live-cards-public-BT5HrgqZ.d.cts +0 -529
  139. package/lib/board-live-cards-public-DSRamFm8.d.ts +0 -529
  140. package/lib/chunk-35N7ONTH.js +0 -2
  141. package/lib/chunk-36QUKFL7.cjs +0 -3
  142. package/lib/chunk-3MMTBEAO.js +0 -2
  143. package/lib/chunk-7QQFDYBM.js +0 -3
  144. package/lib/chunk-7QZ267XP.cjs +0 -2
  145. package/lib/chunk-ABAVFLDP.js +0 -7
  146. package/lib/chunk-EPCJYP4N.js +0 -3
  147. package/lib/chunk-H22NK6KH.cjs +0 -7
  148. package/lib/chunk-KBELAKIY.js +0 -2
  149. package/lib/chunk-OJ2CAQ4C.cjs +0 -2
  150. package/lib/chunk-Q3OTUDIE.js +0 -2
  151. package/lib/chunk-QG6ERLZQ.cjs +0 -3
  152. package/lib/chunk-UB54HZA4.cjs +0 -2
  153. package/lib/chunk-YMEIPKLW.cjs +0 -2
  154. package/lib/chunk-ZENTBLLA.cjs +0 -3
  155. package/lib/chunk-ZWVT24YW.js +0 -3
@@ -1,529 +0,0 @@
1
- import { g as JournalStorage, K as KVStorage, B as BlobStorage, S as ScratchStorage, A as ArchiveFactory, f as QueueStorage, h as AtomicRelayLock, a as KindValueRef } from './storage-interface-D-iEiTJA.js';
2
- import { ExecutionRef } from './execution-refs.js';
3
- import { f as GraphEvent, G as GraphConfig } from './types-BBhqYGhE.js';
4
-
5
- /**
6
- * board-live-cards-lib — Pure logic library for the board-live-cards CLI.
7
- *
8
- * Merged from:
9
- * board-live-cards-all-stores.ts
10
- * board-live-cards-lib-types.ts
11
- * board-live-cards-lib-board-status.ts
12
- * board-live-cards-lib-card-handler.ts
13
- * board-live-cards-cli-board-commands.ts
14
- * board-live-cards-cli-card-commands.ts
15
- * board-live-cards-cli-callbacks.ts
16
- *
17
- * Zero platform imports. All storage is injected via adapter interfaces.
18
- * Safe for Node, browser, and neutral (V8/PyMiniRacer) bundles.
19
- */
20
-
21
- interface LiveCard {
22
- id: string;
23
- [key: string]: unknown;
24
- }
25
- interface CardIndexEntry {
26
- /** Storage-specific address (file path, Cosmos doc id, localStorage key). */
27
- key: string;
28
- /** Checksum of card content — computed by the adapter at write time. */
29
- checksum: string;
30
- updatedAt: string;
31
- }
32
- type CardIndex = Record<string, CardIndexEntry>;
33
- type CardChecksumIndex = Record<string, string>;
34
- interface CardStorageAdapter {
35
- readIndex(): CardIndex | null;
36
- writeIndex(index: CardIndex): void;
37
- readCard(key: string): LiveCard | null;
38
- /** Write card content; returns checksum of what was written. */
39
- writeCard(key: string, card: LiveCard): string;
40
- removeCard(key: string): void;
41
- cardExists(key: string): boolean;
42
- defaultCardKey(cardId: string): string;
43
- }
44
- interface CardStore {
45
- readCard(id: string): LiveCard | null;
46
- readCardKey(id: string): string | null;
47
- readAllCards(): LiveCard[];
48
- readChecksumIndex(): CardChecksumIndex;
49
- changedSince(snapshotChecksumIndex: CardChecksumIndex): string[];
50
- }
51
- interface CardUpsertValidation {
52
- ok: boolean;
53
- error?: string;
54
- }
55
- interface CardAdminStore extends CardStore {
56
- validateUpsert(id: string, cardKey: string): CardUpsertValidation;
57
- writeCard(id: string, card: LiveCard, cardKey?: string): void;
58
- patchCard(id: string, jsonPath: string, value: unknown): void;
59
- removeCard(id: string): void;
60
- readIndex(): CardIndex;
61
- }
62
- declare function createCardStore(adapter: CardStorageAdapter, onWarn?: (msg: string) => void): CardAdminStore;
63
- interface JournalEntry {
64
- id: string;
65
- event: GraphEvent;
66
- }
67
- interface JournalStorageAdapter {
68
- readAllEntries(): JournalEntry[];
69
- appendEntry(entry: JournalEntry): void;
70
- generateId(): string;
71
- }
72
- declare const SNAPSHOT_SCHEMA_VERSION_V1 = "v1";
73
- declare const BOARD_GRAPH_KEY = "board/graph";
74
- interface StateSnapshotReadView {
75
- version: string | null;
76
- values: Record<string, unknown>;
77
- }
78
- type OutputStoreEvent = {
79
- kind: 'computed_values';
80
- cardId: string;
81
- values: Record<string, unknown>;
82
- } | {
83
- kind: 'data_object';
84
- key: string;
85
- payload: unknown;
86
- } | {
87
- kind: 'status';
88
- status: unknown;
89
- };
90
- interface BoardStatusCard {
91
- name: string;
92
- status: string;
93
- error?: {
94
- message: string;
95
- code?: string;
96
- at?: string;
97
- source?: 'task-runtime' | 'source-fetch' | 'timeout' | 'unknown';
98
- };
99
- requires: string[];
100
- requires_satisfied: string[];
101
- requires_missing: string[];
102
- provides_declared: string[];
103
- provides_runtime: string[];
104
- blocked_by: string[];
105
- unblocks: string[];
106
- runtime: {
107
- attempt_count: number;
108
- restart_count: number;
109
- in_progress_since: string | null;
110
- last_transition_at: string | null;
111
- last_completed_at: string | null;
112
- last_restarted_at: string | null;
113
- status_age_ms: number | null;
114
- };
115
- }
116
- interface BoardStatusObject {
117
- schema_version: 'v1';
118
- meta: {
119
- board: {
120
- path: string;
121
- };
122
- };
123
- summary: {
124
- card_count: number;
125
- completed: number;
126
- eligible: number;
127
- pending: number;
128
- blocked: number;
129
- unresolved: number;
130
- failed?: number;
131
- in_progress?: number;
132
- orphan_cards?: number;
133
- topology?: {
134
- edge_count: number;
135
- max_fan_out_card: string | null;
136
- max_fan_out: number;
137
- };
138
- };
139
- cards: BoardStatusCard[];
140
- }
141
- declare const EMPTY_CONFIG: GraphConfig;
142
-
143
- /**
144
- * chat-storage-lib.ts
145
- *
146
- * ChatStorage interface + factories backed by JournalStorage (history) and
147
- * KVStorage (processing state and config).
148
- *
149
- * Platform-free — no node:fs or node:crypto imports.
150
- */
151
-
152
- type Awaitable<T> = T | Promise<T>;
153
- interface ChatRecord {
154
- /** Journal entry id — also used as SSE cursor. */
155
- id: string;
156
- role: string;
157
- text: string;
158
- files: unknown[];
159
- turn: string;
160
- updated_at: string;
161
- }
162
- interface ChatConfig {
163
- systemPrompt?: string;
164
- }
165
- interface ChatReadAfterResult {
166
- records: ChatRecord[];
167
- /** Pass as cursor on the next call. Null when the journal is empty. */
168
- cursor: string | null;
169
- }
170
- interface ChatStorage {
171
- /** Append a message; returns the new entry id (usable as a cursor). */
172
- append(cardId: string, role: string, text: string, files?: unknown[], turn?: string): Awaitable<string>;
173
- /** Read all messages in insertion order. */
174
- readAll(cardId: string): Awaitable<ChatRecord[]>;
175
- /**
176
- * Read messages appended after cursor.
177
- * Pass null to read from the beginning.
178
- */
179
- readAfter(cardId: string, cursor: string | null): Awaitable<ChatReadAfterResult>;
180
- /** Remove all messages for this card. */
181
- clear(cardId: string): Awaitable<void>;
182
- setProcessing(cardId: string, active: boolean): Awaitable<void>;
183
- isProcessing(cardId: string): Awaitable<boolean>;
184
- getConfig(cardId: string): Awaitable<ChatConfig>;
185
- setConfig(cardId: string, patch: Partial<ChatConfig>): Awaitable<void>;
186
- }
187
- /**
188
- * Create a ChatStorage backed by:
189
- * - journalFactory(cardId) → JournalStorage (one per-card journal for history)
190
- * - kv → KVStorage (shared processing flags + config)
191
- */
192
- declare function createChatStorage(journalFactory: (cardId: string) => JournalStorage, kv: KVStorage): ChatStorage;
193
- declare function createInMemoryChatStorage(): ChatStorage;
194
-
195
- interface BoardTaskCallback {
196
- token: string;
197
- via: ExecutionRef;
198
- }
199
- interface BoardCallbackTransport {
200
- createCallback(token: string): BoardTaskCallback;
201
- }
202
- declare function createHttpBoardCallbackTransport(baseUrl: string): BoardCallbackTransport;
203
- declare function createInProcessBoardCallbackTransport(handlerKey: string): BoardCallbackTransport;
204
- declare function createLocalNodeBoardCallbackTransport(opts?: string | {
205
- notifyChannel?: string;
206
- boardRuntimeStoreRef?: string;
207
- queueStoreRef?: string;
208
- }): BoardCallbackTransport;
209
-
210
- /**
211
- * board-live-cards-public.ts
212
- *
213
- * Platform-free public API layer for the board-live-cards system.
214
- *
215
- * ─────────────────────────────────────────────────────────────────────────────
216
- * LAYER DIAGRAM
217
- * ─────────────────────────────────────────────────────────────────────────────
218
- *
219
- * board-live-cards-cli.ts (THIN — arg parse → call public → print JSON)
220
- * ↓ calls
221
- * board-live-cards-public.ts (THIS FILE — facade, all logic, no platform code)
222
- * ↓ depends on injected
223
- * board-live-cards-lib.ts (pure domain — stores, graph, codecs)
224
- *
225
- * ─────────────────────────────────────────────────────────────────────────────
226
- * PLATFORM ADAPTERS (injected into BoardPlatformAdapter)
227
- * ─────────────────────────────────────────────────────────────────────────────
228
- *
229
- * Node/FS createFsBoardPlatformAdapter(baseRef, cliDir)
230
- * Azure Functions createAzureBoardPlatformAdapter(baseRef, containerClient, …)
231
- * Firebase Fn createFirebaseBoardPlatformAdapter(baseRef, firestoreDb, …)
232
- * In-memory/test createInMemoryBoardPlatformAdapter(baseRef)
233
- *
234
- * ─────────────────────────────────────────────────────────────────────────────
235
- * USAGE
236
- * ─────────────────────────────────────────────────────────────────────────────
237
- *
238
- * const board = createBoardLiveCardsPublic(baseRef, adapter);
239
- * const status = board.status();
240
- */
241
-
242
- type CommandInput = {
243
- params?: Record<string, string | number | boolean>;
244
- body?: unknown;
245
- };
246
- type CommandResult<T = undefined> = (T extends undefined ? {
247
- status: 'success';
248
- } : {
249
- status: 'success';
250
- data: T;
251
- }) | {
252
- status: 'fail';
253
- error: string;
254
- } | {
255
- status: 'error';
256
- error: string;
257
- };
258
- interface BoardPlatformAdapter {
259
- /**
260
- * KV storage factory — scoped by namespace.
261
- * Namespaces used by the public layer:
262
- * 'state-snapshot' — board graph snapshot (StateSnapshotStorageAdapter, built internally)
263
- * 'config' — board configuration (.task-executor, .chat-handler, .chat-handler-flow, .card-store-ref)
264
- * 'card-upsert' — card upsert dedup index
265
- * 'execution-requests' — queued execution requests (keyed by journalId)
266
- * 'card-runtime' — card runtime state snapshots
267
- * 'output' — published board status + card computed outputs
268
- */
269
- kvStorage(namespace: string): KVStorage;
270
- /**
271
- * Build a KVStorage rooted at the given ref.
272
- * Used by the public layer for both card store and outputs store routing.
273
- * FS: createFsKvStorage(parseRef(ref).value)
274
- * localStorage: createLocalStorageKvStorage(parseRef(ref).value)
275
- */
276
- kvStorageForRef(ref: string): KVStorage;
277
- /**
278
- * Blob storage factory — scoped by namespace.
279
- * Namespaces used by the public layer:
280
- * '' — root-scoped blob access (for resolving arbitrary KindValueRef blobs)
281
- */
282
- blobStorage(namespace: string): BlobStorage;
283
- blobStorageForRef(ref: string): BlobStorage;
284
- chatStorageForRef(ref: string): ChatStorage;
285
- /**
286
- * Ephemeral scratch store for transient I/O staging (probe in/out/err,
287
- * dispatchExecution argv/out/err). Default scope is board-local; if the
288
- * config has a 'scratch-store-ref' set, scratchStorageForRef(ref) is used
289
- * instead.
290
- */
291
- scratchStorage(): ScratchStorage;
292
- scratchStorageForRef(ref: string): ScratchStorage;
293
- /**
294
- * Archive factory — long-lived tracking / audit store. Default scope is
295
- * board-local; if the config has an 'archive-store-ref' set,
296
- * archiveFactoryForRef(ref) is used instead so archives can live on a
297
- * different backend / path than the main board runtime.
298
- */
299
- archiveFactory(): ArchiveFactory;
300
- archiveFactoryForRef(ref: string): ArchiveFactory;
301
- /**
302
- * Journal storage adapter (append-only log).
303
- * Uses the lib's JournalStorageAdapter interface.
304
- * One journal per board — no namespace parameter needed.
305
- */
306
- journalAdapter(): JournalStorageAdapter;
307
- journalAdapterForRef(ref: string): JournalStorageAdapter;
308
- /**
309
- * Queue storage lane resolved from an explicit queue store ref.
310
- * The adapter chooses the backend from the ref; lane chooses the internal queue.
311
- */
312
- queueStorageForRef(ref: string, lane: string): QueueStorage;
313
- /**
314
- * AtomicRelayLock — non-blocking try-acquire with relay-on-busy semantics.
315
- * Guards processAccumulatedEvents drain cycle.
316
- * FS: proper-lockfile (createFsAtomicRelayLock)
317
- * Azure: blob lease
318
- * Firestore: Firestore transaction + sentinel document
319
- */
320
- lock: AtomicRelayLock;
321
- /**
322
- * Adapter-owned callback transport used to build worker callback payloads.
323
- * The board core treats callback delivery as a platform concern.
324
- */
325
- callbackTransport?: BoardCallbackTransport;
326
- /**
327
- * Generic execution dispatch — platform adapts ExecutionRef → actual transport.
328
- * Public layer constructs fully-formed semantic args (source def, base_ref,
329
- * callback token with selfRef baked in). Platform handles transport:
330
- * Node host adapter: may write args to temp file and may spawn a detached process
331
- * Azure: HTTP POST args as JSON body
332
- * Firebase: publishes args as pubsub message
333
- */
334
- dispatchExecution(ref: ExecutionRef, args: Record<string, unknown>): Promise<{
335
- dispatched: boolean;
336
- error?: string;
337
- }>;
338
- /**
339
- * Whether dispatchExecution can accept a board-owned staged source output ref
340
- * for this executor. When false/absent, the adapter keeps its legacy staging
341
- * protocol such as scratch in/out refs for local process launch.
342
- */
343
- supportsDirectSourceOutput?(ref: ExecutionRef): boolean;
344
- /**
345
- * Resolve a blob ref to its string contents.
346
- * The adapter handles the platform-specific lookup (e.g. absolute FS path vs board-relative key).
347
- * Throws if the blob does not exist.
348
- */
349
- resolveBlob(ref: KindValueRef): string;
350
- /**
351
- * Compute a stable, deterministic content hash for any JSON-serializable value.
352
- * Used for dedup indexes and snapshot versioning.
353
- * Node/FS: computeStableJsonHash (storage-fs-adapters)
354
- * Browser: Web Crypto subtle.digest or equivalent
355
- */
356
- hashFn(value: unknown): string;
357
- /**
358
- * Generate a random short ID (32 hex chars).
359
- * Used for commit IDs and delivery tokens.
360
- * Node/FS: getHash(`${Date.now()}-${Math.random()}`).slice(0, 32)
361
- * Browser: crypto.randomUUID().replace(/-/g, '')
362
- */
363
- genId(): string;
364
- /**
365
- * Request an additional drain pass asynchronously (e.g. spawn a background process).
366
- * Called as the relay continuation after each drain cycle so that events written
367
- * during the cycle (e.g. task-completed appended by the card handler) are eventually
368
- * processed even when the current process exits immediately after returning.
369
- * Optional — if absent, no continuation is scheduled.
370
- */
371
- requestProcessAccumulated?(): void;
372
- /**
373
- * Optional cross-process board change notification publisher (named pipe, webhook, pubsub, etc.).
374
- * Called once per drain cycle with the complete batch of notifications produced in that cycle.
375
- */
376
- publishBoardChangeNotifications?(notifications: BoardChangeNotification[]): void | Promise<void>;
377
- /** Optional warn sink — defaults to no-op. */
378
- onWarn?(msg: string): void;
379
- }
380
- interface BoardLiveCardsPublic {
381
- init(input: CommandInput): CommandResult;
382
- status(input: CommandInput): CommandResult<BoardStatusObject>;
383
- getBoardRuntimeStoreRef(input: CommandInput): CommandResult<{
384
- storeRef: string | null;
385
- }>;
386
- getCardStoreRef(input: CommandInput): CommandResult<{
387
- storeRef: string;
388
- }>;
389
- getOutputsStoreRef(input: CommandInput): CommandResult<{
390
- storeRef: string;
391
- }>;
392
- getScratchStoreRef(input: CommandInput): CommandResult<{
393
- storeRef: string | null;
394
- }>;
395
- getChatStoreRef(input: CommandInput): CommandResult<{
396
- storeRef: string | null;
397
- }>;
398
- getArtifactsStoreRef(input: CommandInput): CommandResult<{
399
- storeRef: string | null;
400
- }>;
401
- getFetchedSourcesStoreRef(input: CommandInput): CommandResult<{
402
- storeRef: string | null;
403
- }>;
404
- getConfig(input: CommandInput): CommandResult<{
405
- value: unknown;
406
- }>;
407
- getOutputsDataObject(input: CommandInput): CommandResult;
408
- getAllOutputsDataObjects(input: CommandInput): CommandResult<Record<string, unknown>>;
409
- getOutputsComputedValues(input: CommandInput): CommandResult;
410
- getAllOutputsComputedValues(input: CommandInput): CommandResult<Record<string, unknown>>;
411
- getOutputsFetchedSources(input: CommandInput): CommandResult<Record<string, string>>;
412
- getAllOutputsFetchedSources(input: CommandInput): CommandResult<Record<string, Record<string, string>>>;
413
- removeCard(input: CommandInput): CommandResult;
414
- addCardFiles(input: CommandInput): CommandResult<{
415
- cardId: string;
416
- files_added: Array<{
417
- idx: number;
418
- entry: unknown;
419
- }>;
420
- notified: true;
421
- }>;
422
- cardRefreshedNotify(input: CommandInput): CommandResult;
423
- retrigger(input: CommandInput): CommandResult;
424
- processAccumulatedEvents(input: CommandInput): Promise<CommandResult>;
425
- upsertCard(input: CommandInput): CommandResult;
426
- taskFailed(input: CommandInput): CommandResult;
427
- taskProgress(input: CommandInput): CommandResult;
428
- sourceDataFetched(input: CommandInput): CommandResult;
429
- sourceDataFetchFailure(input: CommandInput): CommandResult;
430
- }
431
- type BoardChangeNotification = OutputStoreEvent | {
432
- kind: 'card_refreshed';
433
- cardId: string;
434
- card: LiveCard;
435
- } | {
436
- kind: 'card_removed';
437
- cardId: string;
438
- };
439
- interface BoardLiveCardsPublicOptions {
440
- boardRuntimeStoreRef?: string;
441
- scratchStoreRef?: string;
442
- taskExecutorRef?: ExecutionRef;
443
- chatHandlerFlow?: unknown;
444
- }
445
- declare function createBoardLiveCardsPublic(baseRef: KindValueRef, adapter: BoardPlatformAdapter, options?: BoardLiveCardsPublicOptions): BoardLiveCardsPublic;
446
- interface BoardNonCorePlatformAdapter extends BoardPlatformAdapter {
447
- /**
448
- * Invoke a task executor subcommand and return stdout.
449
- * Throws on transport failure, non-zero exit, or timeout.
450
- */
451
- invokeExecutor(ref: ExecutionRef, subcommand: string, opts?: {
452
- timeout?: number;
453
- input?: string;
454
- }): Promise<string>;
455
- /** Schema-only card validator (no executor invocation). */
456
- validateSchema(card: Record<string, unknown>): {
457
- ok: boolean;
458
- errors: string[];
459
- };
460
- /** Absolute-path blob I/O for resolving arbitrary KindValueRef blobs. */
461
- absoluteBlob: BlobStorage;
462
- /**
463
- * Default timeouts (ms) for executor request/response calls.
464
- * Each field can also be overridden per-source via source_def.timeout.
465
- *
466
- * validationMs — validate-source-def, validate-card-preflight (structural, fast). Default: 10_000.
467
- * preflightMs — source preflight executor hooks (probe-source-preflight). Default: 60_000.
468
- * probeMs — run-source-fetch in probe/simulation paths. Default: 60_000.
469
- * describeMs — describe-capabilities introspection. Default: 10_000.
470
- */
471
- executorTimeouts?: {
472
- validationMs?: number;
473
- preflightMs?: number;
474
- probeMs?: number;
475
- describeMs?: number;
476
- };
477
- }
478
- interface BoardLiveCardsNonCorePublic {
479
- /** body: { "card-content": <card> } — card JSON arrives via stdin; validates schema + JSONata + provides refs + source_defs (executor, if configured) */
480
- validateCardPreflight(input: CommandInput): Promise<CommandResult<{
481
- cardId: string;
482
- isValid: boolean;
483
- issues: string[];
484
- }>>;
485
- /** body: { "card-content": <card>, "mock-projections"?: {} }; params: sourceIdx, outRef? — card JSON arrives via stdin; no board state needed */
486
- probeSourcePreflight(input: CommandInput): Promise<CommandResult>;
487
- /** body: { "card-content": <card>, "mock-projections"?: {} }; params: sourceIdx, outRef? — runs the real source fetch flow as a preflight */
488
- runSourcePreflight(input: CommandInput): Promise<CommandResult<{
489
- bindTo: string;
490
- ok: boolean;
491
- result: unknown;
492
- issues: string[];
493
- }>>;
494
- /** body: { "card-content": <card>, "mock-fetched-sources"?: {}, "mock-requires"?: {} } — evaluates compute expressions with supplied data; no board state needed */
495
- evalCardCompute(input: CommandInput): CommandResult<{
496
- cardId: string;
497
- ok: boolean;
498
- computed_values: Record<string, unknown>;
499
- errors: Array<{
500
- bindTo: string;
501
- error: string;
502
- }>;
503
- }>;
504
- /** body: { "card-content": <card>, "mock-fetched-sources"?: {}, "mock-requires"?: {} } — full cycle: validate → resolve projections → probe sources → compute */
505
- simulateCardCycle(input: CommandInput): Promise<CommandResult>;
506
- /** no params needed */
507
- describeTaskExecutorCapabilities(input: CommandInput): Promise<CommandResult>;
508
- /**
509
- * Write/update cards in the configured card store.
510
- * body: { ops: Array<{ op: 'update', id: string, 'card-content': LiveCard }> }
511
- */
512
- updatesInCardStore(input: CommandInput): CommandResult;
513
- /**
514
- * Read cards from the configured card store by id.
515
- * body: { ids: string[] }
516
- */
517
- readFromCardStore(input: CommandInput): CommandResult<{
518
- cards: Array<{
519
- id: string;
520
- 'card-content': LiveCard | null;
521
- }>;
522
- }>;
523
- }
524
- declare function createBoardLiveCardsNonCorePublic(baseRef: KindValueRef, adapter: BoardNonCorePlatformAdapter, opts?: {
525
- boardRuntimeStoreRef?: string;
526
- taskExecutorRef?: ExecutionRef;
527
- }): BoardLiveCardsNonCorePublic;
528
-
529
- export { type BoardChangeNotification as B, type CommandInput as C, EMPTY_CONFIG as E, type LiveCard as L, type StateSnapshotReadView as S, type CommandResult as a, type CardAdminStore as b, type BoardLiveCardsPublic as c, type BoardNonCorePlatformAdapter as d, type BoardPlatformAdapter as e, type ChatStorage as f, type ChatRecord as g, type ChatReadAfterResult as h, type ChatConfig as i, type BoardStatusObject as j, type BoardCallbackTransport as k, type BoardLiveCardsNonCorePublic as l, type CardChecksumIndex as m, type CardUpsertValidation as n, type CardIndex as o, BOARD_GRAPH_KEY as p, SNAPSHOT_SCHEMA_VERSION_V1 as q, createBoardLiveCardsNonCorePublic as r, createBoardLiveCardsPublic as s, createCardStore as t, createChatStorage as u, createHttpBoardCallbackTransport as v, createInMemoryChatStorage as w, createInProcessBoardCallbackTransport as x, createLocalNodeBoardCallbackTransport as y, type BoardLiveCardsPublicOptions as z };
@@ -1,2 +0,0 @@
1
- import {a as a$1}from'./chunk-JMDHDY6M.js';function v(s,i){if(s?.status==="success")return Object.prototype.hasOwnProperty.call(s,"data")?s.data:void 0;throw s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function H(s,i){if(s?.status==="success"&&Object.prototype.hasOwnProperty.call(s,"data"))return s.data;throw s?.status==="success"?new Error(`${i} returned success without data`):s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function a(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function b(s){return Array.isArray(s)?s:[]}function z(s,i){if(typeof i!="string"||i.length===0)return;let c=s,u=i;u.startsWith("fetched_sources.")&&(c=a(s).fetched_sources,u=u.slice(16));for(let f of u.split(".")){if(c==null||typeof c!="object")return;c=c[f];}return c}function V(s,i){let c=a(s.view),u=b(c.elements);return {layout:c.layout,features:c.features,elements:u.map((f,_)=>{let I=a(f),k=a(I.data),R=typeof I.visible=="string"?!!z(i,I.visible):true,M=typeof k.bind=="string"?k.bind:void 0,P=typeof k.maxRows=="number"?k.maxRows:void 0,B=M?z(i,M):void 0,F={id:typeof I.id=="string"&&I.id?I.id:`element-${_}`,kind:I.kind,label:I.label,visible:R};return B!==void 0&&(F.resolved=Array.isArray(B)&&typeof P=="number"?B.slice(0,P):B),F})}}function G(s,i){let c=typeof s.id=="string"&&s.id?s.id:"card",u=b(s.provides),f=u.length>0?u:[{bindTo:c,ref:"card_data"}],_={};for(let I of f){let k=a(I),R=typeof k.bindTo=="string"?k.bindTo:"",M=typeof k.ref=="string"?k.ref:"";if(!R||!M)continue;let P=z(i,M);P!==void 0&&(_[R]=P);}return _}function he(s){if(typeof s!="string"||!s.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(s.trim());if(!i)return null;let c=Number.parseInt(i[2],10);return !Number.isInteger(c)||c<0?null:c}function ke(s){return {"card-content":s}}function E(s){let i={...s};return delete i.__private,i}function D(s,i){return Object.prototype.hasOwnProperty.call(s,i)}function Re(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function ve(s,i){let c=Re(s);if(!i||Object.keys(i).length===0)return c;function u(f,_,I){let k=String(_||"").split(".").filter(Boolean);if(!k.length)return;let R=f;for(let M=0;M<k.length-1;M+=1){let P=k[M];(!R[P]||typeof R[P]!="object")&&(R[P]={}),R=R[P];}R[k[k.length-1]]=I;}if(i.fieldValues!==void 0&&i.fieldValues!==null){let f=null,_=a(c.view),I=b(_.elements);for(let k of I){let R=a(a(k).data);if(typeof R.writeTo=="string"&&R.writeTo){f=R.writeTo;break}}return f?u(c,f,i.fieldValues):typeof i.fieldValues=="object"&&!Array.isArray(i.fieldValues)&&(c.card_data={...a(c.card_data),...i.fieldValues}),c}if(Array.isArray(i._stagedFiles)&&i._stagedFiles.length>0)return c;for(let[f,_]of Object.entries(i))f!=="_stagedFiles"&&(_!==null&&typeof _=="object"&&!Array.isArray(_)&&c[f]!==null&&typeof c[f]=="object"&&!Array.isArray(c[f])?c[f]={...c[f],..._}:c[f]=_);return c}function Q(s){return a(s.__private).visible_controlplane_only===true}async function T(s,i){let c=await U(s.get({params:{id:i}}),"cardStore.get"),u=Array.isArray(c?.cards)?c.cards:[];if(u.length===0)throw new Error(`Card "${i}" not found`);return u[0]}function Ae(s){let{board:i,nonCore:c,cardStore:u,chatStore:f,processAccumulated:_,sourceFetchDone:I,sourceFetchFailed:k,uploadCardFile:R,buildFileDownloadUrl:M,readFetchedSourceJsonByRef:P}=s;function B(e,r){if(typeof e=="function")return e;throw new Error(`${r} is not configured for this MCP facade`)}async function F(){let e=await U(u.get({}),"cardStore.get");return Array.isArray(e.cards)?e.cards.map(r=>a(r)):[]}function X(e){if(Array.isArray(e.bytes))return new Uint8Array(e.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof e.text=="string")return new TextEncoder().encode(e.text);if(typeof e.base64=="string"){let r=String(e.base64).replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function Y(){let e=a(await U(c.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:e.version,commonSourceFields:a(e.commonSourceDefFields),sourceKinds:a(e.sourceKinds)}}async function Z(){let e=a(await U(i.status({}),"status")),r=a(e.summary),t=b(e.cards);return {meta:a(e.meta),summary:{card_count:typeof r.card_count=="number"?r.card_count:0,completed:typeof r.completed=="number"?r.completed:0,eligible:typeof r.eligible=="number"?r.eligible:0,pending:typeof r.pending=="number"?r.pending:0,blocked:typeof r.blocked=="number"?r.blocked:0,in_progress:typeof r.in_progress=="number"?r.in_progress:0,failed:typeof r.failed=="number"?r.failed:0,unresolved:typeof r.unresolved=="number"?r.unresolved:0},cards:t.map(n=>{let o=a(n);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:b(o.requires),requires_satisfied:b(o.requires_satisfied),requires_missing:b(o.requires_missing),provides_declared:b(o.provides_declared),provides_runtime:b(o.provides_runtime)}})}}async function ee(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let t=a(await U(i.status({}),"status")),o=b(t.cards).map(a).find(p=>p.name===r);if(!o)throw new Error(`card "${r}" not found in board status`);let d=a(await T(u,r));if(Q(d))throw Object.assign(new Error(`card "${r}" not found`),{statusCode:404});let m=E(d),g=b(o.requires_satisfied).filter(p=>typeof p=="string"&&!!p),w=b(o.provides_runtime).filter(p=>typeof p=="string"&&!!p),h=Object.fromEntries(await Promise.all(g.map(async p=>[p,await U(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),A=Object.fromEntries(await Promise.all(w.map(async p=>[p,await U(i.getOutputsDataObject({params:{key:p}}),`getOutputsDataObject(${p})`)]))),C=a(await U(i.getOutputsComputedValues({params:{key:r}}),"getOutputsComputedValues")),l=await U(i.getOutputsFetchedSources({params:{key:r}}),"getOutputsFetchedSources"),S=b(d.source_defs).map(a),y={};for(let p of S)typeof p.bindTo=="string"&&typeof p.outputFile=="string"&&(y[p.outputFile]=p.bindTo);let x={};for(let[p,O]of Object.entries(l)){let q=y[p]??p;if(!P||typeof O!="string"){x[q]=null;continue}try{x[q]=P({cardId:r,ref:O});}catch{x[q]=null;}}let L={card_data:a(d.card_data),requires:h,fetched_sources:x,computed_values:C};return {cardId:r,card_status_in_board:o,card_definition_and_static_data:m,refs_for_fetched_source_files:l,runtime_data:{requires:h,provides:A,computed_values:C,rendered_view:V(d,L)}}}async function re(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectChatMessagesOnCards requires cardId");let t=typeof e.turnId=="string"?e.turnId:"",n=e.allTurns===true,o=typeof e.tailTurnsBeforeId=="string"?e.tailTurnsBeforeId:"",d=n?void 0:e.lastUserTurns??(t?void 0:1),m=e.tail,g={...d===void 0?{}:{tailTurns:d},...t?{turnId:t}:{},...n?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},w=Object.keys(g).length>0?{params:{cardId:r},body:g}:{params:{cardId:r}},h=v(await f.readAll(w),"chatStore.readAll"),A=a(await T(u,r)),C=b(a(A.card_data).files).map((y,x)=>({idx:x,stored_name:a(y).stored_name})).filter(y=>typeof y.stored_name=="string"&&y.stored_name.length>0),S=(Array.isArray(h.records)?h.records:[]).map(y=>{let L=a(y.payload),p={...y},O=typeof y?.role=="string"?y.role:typeof L.role=="string"?String(L.role):"",q=typeof y?.text=="string"?y.text:typeof L.text=="string"?String(L.text):"";if(O==="system"){let N=he(q);if(N!==null&&C.some(j=>j.idx===N)){let j=`Retrieve using inspect-file-contents --card-id ${r} --file-idx ${N}`;p.retrieval_hint=j,Object.keys(L).length>0&&typeof y.role!="string"&&(p.payload={...L,retrieval_hint:j});}}return p});return {cardId:r,messages:typeof m=="number"&&m>=0?S.slice(-m):S}}async function te(e){let r=String(e.cardId||"").trim(),t=Number(e.fileIdx);if(!r)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(t)||t<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let n=a(await T(u,r)),o=b(a(n.card_data).files).map(a);if(t>=o.length)throw new Error(`attachment index ${t} is out of range for card "${r}"`);let d=o[t],m=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:r,fileIdx:t,downloadUrl:M({cardId:r,fileIdx:t,storedName:m}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function $(e){return await c.validateCardPreflight({body:ke(e.candidateCardContent)})}function ne(e){if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!e.mockFetchedSources||typeof e.mockFetchedSources!="object"||Array.isArray(e.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let r=c.evalCardCompute({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires,"mock-fetched-sources":e.mockFetchedSources}});if(r.status!=="success")return r;let t=a(H(r,"evalCardCompute")),n=a(e.candidateCardContent),o={card_data:a(n.card_data),requires:a(e.mockRequires),fetched_sources:a(e.mockFetchedSources),computed_values:a(t.computed_values)};return {status:"success",data:{cardId:typeof t.cardId=="string"?t.cardId:typeof n.id=="string"?n.id:"(unknown)",ok:t.ok===true,computed_values:a(t.computed_values),errors:b(t.errors).map(d=>{let m=a(d);return {bindTo:typeof m.bindTo=="string"?m.bindTo:"",error:typeof m.error=="string"?m.error:""}}),provides_outputs:G(n,o),rendered_view:V(n,o)}}}async function ae(e){return await c.probeSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function oe(e){return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function se(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let t=a(await T(u,r)),n=b(t.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),o={};if(e.sourceIdx>=0&&e.sourceIdx<n.length){let d=n[e.sourceIdx],m=a$1.enrichSourcesSync([d],{card_data:a(t.card_data),requires:e.mockRequires});Array.isArray(m)&&m.length>0&&(o=a(m[0]._projections));}return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":t,"mock-requires":e.mockRequires,"mock-projections":o}})}async function ie(e){let r=a(await U(c.simulateCardCycle({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires}}),"simulateCardCycle")),t=a(e.candidateCardContent),n=a(r.validation),o=b(r.source_probes),d=b(r.projection_errors),m=a(r.fetched_sources),g=b(r.compute_errors),w=a(r.computed_values),h={card_data:a(t.card_data),requires:e.mockRequires,fetched_sources:m,computed_values:w},A=[];for(let C of b(n.issues))typeof C=="string"&&C&&A.push(C);for(let C of o){let l=a(C),S=typeof l.bindTo=="string"?l.bindTo:"source",y=typeof l.error=="string"?l.error:"";y&&A.push(`${S}: ${y}`);}for(let C of d){let l=a(C),S=typeof l.bindTo=="string"?l.bindTo:"source",y=typeof l.key=="string"?l.key:"projection",x=typeof l.error=="string"?l.error:"projection failed";A.push(`${S}.${y}: ${x}`);}for(let C of g){let l=a(C),S=typeof l.bindTo=="string"?l.bindTo:"compute",y=typeof l.error=="string"?l.error:"compute failed";A.push(`${S}: ${y}`);}return {status:"success",data:{cardId:typeof r.cardId=="string"?r.cardId:"(unknown)",ok:r.ok===true,issues:A,provides_outputs:G(t,h),rendered_view:V(t,h)}}}async function K(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageReadCard requires cardId");let t=await U(u.get({params:{id:r}}),"cardStore.get"),n=Array.isArray(t.cards)?t.cards.map(a):[];if(n.some(Q))throw Object.assign(new Error(`Card "${r}" not found`),{statusCode:404});return n.map(o=>E(o))}async function W(e){let r=await Promise.all(b(e.files).map(async t=>{let n=a(t),o=String(n.file_name??n.fileName??n.name??"").trim(),d=String(n.content_type??n.contentType??"application/octet-stream");if(!o)throw new Error("file entry requires file_name");return await R({cardId:e.cardId,fileName:o,contentType:d,bytes:X(n),suppressChatRecordWrite:true})}));for(let[t,n]of r.entries()){let o=a(n.file),d=typeof n.file_idx=="number"&&Number.isInteger(n.file_idx)&&n.file_idx>=0?n.file_idx:t,m=e.role==="assistant"?`AI generated: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`:`file uploaded: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`;v(await f.append({params:{cardId:e.cardId},body:{role:"system",text:m,files:[],turn:e.turn}}),"chatStore.append(system attachment message)");}return r.map(t=>t.file)}async function de(e){let r=String(e.cardId||"").trim(),t=String(e.role||"user").trim()||"user",n=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatAttachment requires cardId");let o=await W({cardId:r,role:t,turn:n,files:e.files});return {status:"success",data:{cardId:r,turn:n,files:o}}}async function ce(e){let r=String(e.cardId||"").trim(),t=String(e.role||"").trim(),n=typeof e.text=="string"?e.text:"",o=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!t)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(t==="assistant"&&o){let g=v(await f.readAll({params:{cardId:r},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),w=Array.isArray(g.records)?g.records.find(h=>h.role==="assistant"&&String(h.turn||"")===o):void 0;if(w)return {status:"success",data:{cardId:r,id:String(w.id),role:t,turn:o,files:Array.isArray(w.files)?w.files:[]}}}let d=await W({cardId:r,role:t,turn:o,files:e.files}),m=v(await f.append({params:{cardId:r},body:{role:t,text:n,files:d,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:r,id:String(m.id),role:t,turn:o,files:d}}}async function ue(e){let r=String(e.cardId||"").trim(),t=a(e.patch);if(!r)throw new Error("managePatchCard requires cardId");let n=await K({cardId:r}),o=a(n[0]),m={...ve(o,t),...D(o,"meta")?{meta:o.meta}:{},...D(o,"__private")?{__private:o.__private}:{}},g=await u.set({body:m});v(g,"cardStore.set");let w;try{w=await i.upsertCard({params:{cardId:r,restart:!0}}),v(w,"upsertCard");}catch(A){try{await u.set({body:o});}catch{}throw A}let h=null;try{h=await i.cardRefreshedNotify({params:{cardId:r}}),v(h,"cardRefreshedNotify");}catch{h=null;}return {status:"success",data:{validation:null,card_saved:null,board_result:w,refresh_notify:h}}}async function le(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("manageUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await $({candidateCardContent:n}),d=a(o),m=a(d.data);if(d.status!=="success"||m.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let w=g?a(g):null,h={...n,...w&&D(w,"meta")?{meta:w.meta}:{},...w&&D(w,"__private")?{__private:w.__private}:{}},A=await u.set({body:h});v(A,"cardStore.set");let C;try{C=await i.upsertCard({params:{cardId:r,restart:!0}}),v(C,"upsertCard");}catch(S){try{g&&await u.set({body:g});}catch{}throw S}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:r}}),v(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:C,refresh_notify:l}}}async function me(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageRemoveCard requires cardId");let t=await i.removeCard({params:{id:r}});v(t,"removeCard");let n=await u.del({params:{id:r}});return v(n,"cardStore.del"),{status:"success",data:{board_result:t,store_result:n}}}async function pe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("adminReadCard requires cardId");let t=await U(u.get({params:{id:r}}),"cardStore.get");return Array.isArray(t.cards)?t.cards.map(n=>a(n)):[]}async function fe(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("adminUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await $({candidateCardContent:n}),d=a(o),m=a(d.data);if(d.status!=="success"||m.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let w=g?a(a(g).__private):{},h={...n,__private:{...w,visible_controlplane_only:true}},A=await u.set({body:h});v(A,"cardStore.set");let C;try{C=await i.upsertCard({params:{cardId:r,restart:!0}}),v(C,"upsertCard");}catch(S){try{g&&await u.set({body:g});}catch{}throw S}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:r}}),v(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:C,refresh_notify:l}}}async function ge(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("getChatProcessing requires cardId");let t=H(await f.isProcessing({params:{cardId:r}}),"chatStore.isProcessing");return {cardId:r,active:!!t.active}}async function we(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("setChatProcessing requires cardId");if(typeof e.active!="boolean")throw new Error("setChatProcessing requires boolean active");return v(await f.setProcessing({params:{cardId:r},body:{active:e.active}}),"chatStore.setProcessing"),{cardId:r,active:e.active}}async function Ce(){let e=await B(_,"webhook.process-accumulated")();return e?.status==="fail"||e?.status==="error"?e:{status:"success",data:{runtime_result:Object.prototype.hasOwnProperty.call(e??{},"data")?e.data??null:null}}}async function ye(e){let r=String(e.token||"").trim(),t=String(e.ref||"").trim();if(!r)throw new Error("webhookSourceFetchDone requires token");if(!t)throw new Error("webhookSourceFetchDone requires ref");let n=await B(I,"webhook.source-fetch-done")({token:r,ref:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,ref:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}async function be(e){let r=String(e.token||"").trim(),t=String(e.reason||"").trim();if(!r)throw new Error("webhookSourceFetchFailed requires token");if(!t)throw new Error("webhookSourceFetchFailed requires reason");let n=await B(k,"webhook.source-fetch-failed")({token:r,reason:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,reason:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}return {listRuntimeCards:F,discoverSourceKinds:Y,inspectBoardRuntimeStatus:Z,inspectCardDefinitionAndRuntime:ee,inspectChatMessagesOnCards:re,inspectFileContents:te,preflightValidateCandidateCardDefinition:$,preflightMaterializeCandidateCard:ne,preflightProbeSingleSourceInCandidateCard:ae,preflightRunSingleSourceInCandidateCard:oe,preflightRunSingleSourceInLiveCard:se,preflightRunOneCycleWithCandidateCard:ie,manageReadCard:K,manageAddChatAttachment:de,manageAddChatEntryAndAnyAttachments:ce,managePatchCard:ue,manageUpsertCard:le,manageRemoveCard:me,adminReadCard:pe,adminUpsertCard:fe,getChatProcessing:ge,setChatProcessing:we,webhookProcessAccumulated:Ce,webhookSourceFetchDone:ye,webhookSourceFetchFailed:be}}async function U(s,i){return v(await s,i)}export{Ae as a};//# sourceMappingURL=chunk-35N7ONTH.js.map
2
- //# sourceMappingURL=chunk-35N7ONTH.js.map
@@ -1,3 +0,0 @@
1
- 'use strict';var chunk37HDEW26_cjs=require('./chunk-37HDEW26.cjs'),chunkZENTBLLA_cjs=require('./chunk-ZENTBLLA.cjs'),chunkVQCIOKJV_cjs=require('./chunk-VQCIOKJV.cjs'),chunkG4XXRHL2_cjs=require('./chunk-G4XXRHL2.cjs'),chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');async function Ye(t,o,n){let s=await t.tryAcquire();if(!s)return false;try{await o();}finally{await s();}return await n?.(),true}function ct(t){return typeof t=="object"&&t!==null&&"then"in t&&typeof t.then=="function"}function ge(t,o){return ct(t)?t.then(o):o(t)}function Xe(t,o){let n={...t};for(let[s,d]of Object.entries(o))d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[s]!==null&&typeof n[s]=="object"&&!Array.isArray(n[s])?n[s]=Xe(n[s],d):n[s]=d;return n}function pe(t,o,n){if(o.length===0)return t;let[s,...d]=o;if(d.length===0)return {...t,[s]:n};let g=t[s]!==null&&typeof t[s]=="object"&&!Array.isArray(t[s])?t[s]:{};return {...t,[s]:pe(g,d,n)}}function Ze(t){return {read:n=>t.read(n),get(n,s){return ge(t.read(n),d=>{if(d===null)return null;let g=d;for(let c of s.split(".").filter(Boolean)){if(g===null||typeof g!="object"||Array.isArray(g))return null;g=g[c]??null;}return g??null})},write:(n,s)=>t.write(n,s),delete:n=>t.delete(n),listKeys:n=>t.listKeys(n),shallowMerge(n,s){return ge(t.read(n),d=>t.write(n,{...d??{},...s}))},deepMerge(n,s){return ge(t.read(n),d=>t.write(n,Xe(d??{},s)))},patch(n,s,d){return ge(t.read(n),g=>{let c=s.split(".").filter(Boolean);return t.write(n,pe(g??{},c,d))})}}}function et(t){return Ze(t)}function tt(t,o){return {async readIndex(){return await t.read("_index")},writeIndex(n){return t.write("_index",n)},async readCard(n){return await t.read(n)},async writeCard(n,s){return await t.write(n,s),o(s)},removeCard(n){return t.delete(n)},async cardExists(n){return await t.read(n)!==null},defaultCardKey(n){return n}}}function rt(t,o){async function n(){return await t.readIndex()??{}}return {async readCard(s){let d=(await n())[s];return !d||!await t.cardExists(d.key)?null:await t.readCard(d.key)},async readCardKey(s){return (await n())[s]?.key??null},async readAllCards(){let s=[];for(let[d,g]of Object.entries(await n())){if(!await t.cardExists(g.key))continue;let c=await t.readCard(g.key);c?s.push(c):o?.(`[card-store] could not read card "${d}" at key "${g.key}"`);}return s},async readChecksumIndex(){let s={};for(let[d,g]of Object.entries(await n()))s[d]=g.checksum;return s},async changedSince(s){let d=await n(),g=[];for(let[c,w]of Object.entries(d))s[c]!==w.checksum&&g.push(c);for(let c of Object.keys(s))d[c]||g.push(c);return g},async validateUpsert(s,d){let g=await n(),c=g[s],w=Object.entries(g).find(([,v])=>v.key===d);return c&&c.key!==d?{ok:false,error:`Card id "${s}" is already mapped to key "${c.key}", cannot remap to "${d}"`}:w&&w[0]!==s?{ok:false,error:`Key "${d}" is already mapped to card id "${w[0]}", cannot remap to "${s}"`}:{ok:true}},async writeCard(s,d,g){let c=await n(),w=g??c[s]?.key??t.defaultCardKey(s),v=await t.writeCard(w,d);c[s]={key:w,checksum:v,updatedAt:new Date().toISOString()},await t.writeIndex(c);},async patchCard(s,d,g){let c=await n(),w=c[s];if(!w||!await t.cardExists(w.key))throw new Error(`card "${s}" not found`);let v=await t.readCard(w.key);if(!v||typeof v!="object"||Array.isArray(v))throw new Error(`card "${s}" is not patchable`);let B=String(d||"").split(".").filter(Boolean),te=pe(v,B,g),O=await t.writeCard(w.key,te);c[s]={key:w.key,checksum:O,updatedAt:new Date().toISOString()},await t.writeIndex(c);},async removeCard(s){let d=await n(),g=d[s];g&&(await t.removeCard(g.key),delete d[s],await t.writeIndex(d));},readIndex(){return n()}}}function Ct(t,o){return chunkZENTBLLA_cjs.a(t,o)}function ht(t,o,n){return {blob:t,kv:o,journal:n}}function h(t){return t!==void 0?{status:"success",data:t}:{status:"success"}}function p(t){return {status:"fail",error:t}}function P(t){return {status:"error",error:t instanceof Error?t.message:String(t)}}function x(){return new Date().toISOString()}function lt(t){let o=new TextEncoder().encode(t),n=Array.from(o,s=>String.fromCharCode(s)).join("");return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function st(t){let o=t.replace(/-/g,"+").replace(/_/g,"/"),n=o+"=".repeat((4-o.length%4)%4),s=atob(n),d=Uint8Array.from(s,g=>g.charCodeAt(0));return new TextDecoder().decode(d)}function ye(t){try{let o=JSON.parse(st(t));return typeof o?.t=="string"?{taskName:o.t}:null}catch{return null}}function nt(t){return lt(JSON.stringify(t))}function ot(t){try{let o=JSON.parse(st(t));return typeof o?.cbk=="string"&&typeof o?.cid=="string"&&typeof o?.b=="string"&&typeof o?.d=="string"?o:null}catch{return null}}function mt(t){return chunkZENTBLLA_cjs.j(t,chunkZENTBLLA_cjs.o,()=>({_sources:{}}))}function ft(t,o){return chunkZENTBLLA_cjs.h(t,o)}function gt(t){return chunkZENTBLLA_cjs.k(t)}function pt(t,o){return chunkZENTBLLA_cjs.i(t,o)}function yt(t,o,n,s,d,g){return async c=>{let w=[],v=await n.cardStore.readCard(c.nodeId);if(!v)return "task-initiate-failure";let B=v.id,te=v.card_data??{},O=v.source_defs??[],re=O.filter(m=>m.optionalForCompletionGating!==true),b=await n.cardRuntimeStore.readRuntime(B),_=false,$=async()=>{_&&(await n.cardRuntimeStore.writeRuntime(B,b),_=false);},T=m=>chunkZENTBLLA_cjs.p(b._sources[m]),D=(m,f)=>{b._sources[m]=chunkZENTBLLA_cjs.p(f),_=true;},se=c.taskState?.executionCount??0;if(b._lastExecutionCount!==se&&(b._sources={},b._lastExecutionCount=se,_=true),c.update){let m=c.update.outputFile;if(m){let f=T(m);if(c.update.failure){let R=c.update.rqt??f.lastRequestedToken??f.queueRequestedToken;R&&D(m,chunkZENTBLLA_cjs.s(f,R));}else {let R=c.update.rqt;if(!f.lastCompletedToken||R>f.lastCompletedToken){let r=typeof c.update.deliveryToken=="string"?c.update.deliveryToken:void 0,e=r?await n.fetchedSourcesStore.commitSourceData(B,m,r):false;D(m,e?chunkZENTBLLA_cjs.r(f,R):chunkZENTBLLA_cjs.s(f,R));}}await $();}}let J={};for(let m of O){if(!m.outputFile)continue;let f=await n.fetchedSourcesStore.readSourceData(B,m.outputFile);f!==null&&(J[m.bindTo]=f);}let H={};for(let[m,f]of Object.entries(c.state??{}))if(f!==null&&typeof f=="object"&&!Array.isArray(f)){let R=f[m];H[m]=R!==void 0?R:f;}else H[m]=f;let L={id:B,card_data:{...te},requires:H,source_defs:O,compute:v.compute};L._sourcesData=J,v.compute&&chunkIXZG74EW_cjs.a.runSync(L,{sourcesData:J}),(d??(()=>{}))(B,L.computed_values??{});let ne=chunkIXZG74EW_cjs.a.enrichSourcesSync(Array.isArray(v.source_defs)?v.source_defs:void 0,{card_data:v.card_data,requires:H}),F={...v,source_defs:Array.isArray(ne)?ne.map(m=>({...m,boardDir:typeof m.boardDir=="string"&&m.boardDir?m.boardDir:t.value})):ne},M=x(),G=c.update?void 0:M,W=re.filter(m=>{let f=m.outputFile;if(typeof f!="string"||!f)return true;let R=T(f);G&&(R={...R,queueRequestedToken:G},D(f,R));let r=R.queueRequestedToken??R.lastRequestedToken??M;return chunkZENTBLLA_cjs.q(R,r)==="dispatch"});if(await $(),W.length>0){let m=false,f=M;for(let R of W){let r=R.outputFile;if(typeof r!="string"||!r)continue;let e=T(r),u=e.queueRequestedToken??M;D(r,{...e,lastRequestedToken:u}),f=u,m=true;}return m&&await $(),m&&(w.push({taskKind:"source-fetch",payload:{boardRef:chunkVQCIOKJV_cjs.a(t),enrichedCard:F,callbackToken:c.callbackToken,rqt:f}}),await n.executionRequestStore.appendEntries(o,w)),"task-initiated"}if(re.some(m=>{let f=m.outputFile;if(typeof f!="string"||!f)return false;let R=T(f),r=R.queueRequestedToken??R.lastRequestedToken??M;return chunkZENTBLLA_cjs.q(R,r)==="in-flight"}))return "task-initiated";let Re=v.provides??[],oe={};for(let{bindTo:m,ref:f}of Re)oe[m]=chunkIXZG74EW_cjs.a.resolve(L,f);return (g??(()=>{}))(oe),O.filter(m=>{if(m.optionalForCompletionGating!==true)return false;let f=T(m.outputFile);return !f.lastRequestedToken||!f.lastCompletedToken?true:f.lastCompletedToken<=f.lastRequestedToken}).length>0&&w.push({taskKind:"source-fetch",payload:{boardRef:chunkVQCIOKJV_cjs.a(t),enrichedCard:F,callbackToken:c.callbackToken,rqt:M}}),s(c.nodeId,oe),w.length>0&&await n.executionRequestStore.appendEntries(o,w),"task-initiated"}}function _t(t,o,n={}){chunkZENTBLLA_cjs.d(o.callbackTransport,"createAsyncBoardLiveCardsPublic");let s=o.callbackTransport,d=o.warn??(()=>{}),g=chunkVQCIOKJV_cjs.a(t),c=null,w=n.boardRuntimeStoreRef,v=n.scratchStoreRef,B=n.taskExecutorRef,te=n.chatHandlerFlow;function O(){if(!w)throw new Error(`Board at ${t.value} has no board runtime store configured. Pass boardRuntimeStoreRef at construction or init.`);return w}function re(r){if(r.length!==0)try{return Promise.resolve(o.publishBoardChangeNotifications?.(r)).catch(e=>{d(`[async-board-live-cards-public] publishBoardChangeNotifications failed: ${e instanceof Error?e.message:String(e)}`);})}catch(e){d(`[async-board-live-cards-public] publishBoardChangeNotifications failed: ${e instanceof Error?e.message:String(e)}`);return}}let b=()=>chunk37HDEW26_cjs.b(o.kvStorageForRef(O())),_=t.value,$=()=>chunkZENTBLLA_cjs.b(chunkZENTBLLA_cjs.a(()=>o.kvStorageForRef(O()),o.hashFn),"v1"),T=async()=>{let r=await b().readOutputsStoreRef();if(!r)throw new Error(`Board at ${t.value} has no outputs store configured.`);return gt(o.kvStorageForRef(r))},D=async()=>{let r=await b().readCardStoreRef();if(!r)throw new Error(`Board at ${t.value} has no card store configured.`);let e=o.kvStorageForRef(r);return rt(tt(et(e),o.hashFn),d)};async function se(){return !!(await $().readSnapshot(_)).values[chunkZENTBLLA_cjs.n]}async function J(){let r=await $().readSnapshot(_);if(!r.values[chunkZENTBLLA_cjs.n])throw new Error(`Board not initialized at ${t.value}`);return chunkZENTBLLA_cjs.w(r.values)}async function H(r,e){let u=await $().commitSnapshot(_,{schemaVersion:"v1",expectedVersion:e,deleteKeys:[],shallowMerge:chunkZENTBLLA_cjs.v(r)});if(!u.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${e??"null"} current=${u.currentVersion??"null"}`)}let L=()=>chunkZENTBLLA_cjs.c(o.journalStorageForRef(O()));async function ne(){return B??await b().readTaskExecutorRef()}async function F(r){await L().appendEvent(r);}async function M(){let r=await b().readFetchedSourcesStoreRef();if(!r)throw new Error(`Board at ${t.value} has no fetched sources store configured. Run: init --fetched-sources-store-ref <b64-ref>`);return r}async function G(){return o.blobStorageForRef(await M())}async function W(){return ft(await G(),r=>o.resolveBlob(r))}async function ke(r){let e=(await G()).keyRef?.(r);if(!e)throw new Error("configured fetched-sources store does not support keyRef");let u=await Promise.resolve(e);return chunkVQCIOKJV_cjs.a(u)}async function Re(){let r=pt(o.kvStorageForRef(O()),async(i,l)=>{let S=i.payload,I=(S.enrichedCard??{}).id??S.cardId??"unknown";await F({type:"task-failed",taskName:I,error:l,timestamp:x()});}),e=mt(o.kvStorageForRef(O())),u=await G(),a=await W(),k=await D(),C=await T(),A=new Map,y=new Map,z=[],Q=[],V=[],U=new Map,Y=new Set,Se={async readRuntime(i){return A.get(i)??await e.readRuntime(i)},async writeRuntime(i,l){A.set(i,l),Ce[i]=l;}},at={async readSourceData(i,l){let S=`${i}/${l}`;return y.has(S)?y.get(S):await a.readSourceData(i,l)},ingestSourceDataStaged(i,l,S,E){return a.ingestSourceDataStaged(i,l,S,E)},async commitSourceData(i,l,S){let E=`${i}/.staged/${S}/${l}`,I=await u.read(E);if(I==null){let j=await Promise.resolve(u.keyRef?.(E));j&&(I=await o.resolveBlob(j));}if(I==null)return false;let K=`${i}/${l}`,Z=I.trim();try{y.set(K,JSON.parse(Z));}catch{y.set(K,Z);}return z.push({cardId:i,outputFile:l,deliveryToken:S}),true},async hasSource(i,l){let S=`${i}/${l}`;return y.has(S)||await a.hasSource(i,l)},async listSources(i){let l=await a.listSources(i),S=[...y.keys()].filter(E=>E.startsWith(`${i}/`)).map(E=>E.slice(`${i}/`.length));return [...new Set([...l,...S])]}},we=await J(),it=chunkG4XXRHL2_cjs.q(we.graph),Ce={...we.runtimeByCardId},{events:ut,newCursor:he}=await L().readEntriesAfterCursor(we.lastDrainedJournalId),ae=ut,ie=chunkG4XXRHL2_cjs.u(it,{handlers:{"card-handler":yt(t,he,{cardStore:k,cardRuntimeStore:Se,fetchedSourcesStore:at,executionRequestStore:r},(i,l)=>{ae.push({type:"task-completed",taskName:i,data:l,timestamp:x()});},(i,l)=>{Q.push({cardId:i,values:l});},i=>{V.push(i);})},onNodeRemoved:i=>{U.delete(i),A.delete(i),delete Ce[i],Y.add(i);}});for(;ae.length>0;){let i=ae;ae=[];for(let l of i)if(l.type==="task-restart"){let S=await k.readCard(l.taskName);S&&U.set(l.taskName,S);}ie.pushAll(i),await ie.waitForHandlers();}let Fe=ie.getState();await ie.dispose({wait:true}),await H({lastDrainedJournalId:he,graph:chunkG4XXRHL2_cjs.p(Fe),runtimeByCardId:Ce},(await $().readSnapshot(_)).version);for(let{cardId:i,values:l}of Q)await C.writeComputedValues(i,l);for(let i of V)await C.writeDataObjects(i);for(let[i,l]of A)await e.writeRuntime(i,l);for(let i of z)await a.commitSourceData(i.cardId,i.outputFile,i.deliveryToken);let qe=chunkZENTBLLA_cjs.t(g,Fe);await C.writeStatusSnapshot(qe);let ee=[];for(let{cardId:i,values:l}of Q)ee.push({kind:"computed_values",cardId:i,values:l});for(let i of V)for(let[l,S]of Object.entries(i))ee.push({kind:"data_object",key:l,payload:S});for(let[i,l]of U)ee.push({kind:"card_refreshed",cardId:i,card:l});for(let i of Y)ee.push({kind:"card_removed",cardId:i});ee.push({kind:"status",status:qe}),await re(ee);let X=await ne();if(!X)return;let Te=o.supportsDirectSourceOutput?.(X)===true;await r.dispatchEntriesForJournalId(he,async i=>{if(i.taskKind!=="source-fetch"){d(`[async-process-accumulated-events] unknown taskKind "${i.taskKind}" \u2014 skipping`);return}let l=i.payload,S=l.enrichedCard?.id??"unknown",E=l.enrichedCard?.source_defs??[];if(X.howToRun==="queue-storage"&&Te){try{let I=await b().readQueueStoreRef();if(!I)throw new Error(`Board at ${t.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);let K=o.queueStorageForRef(I,"task-executor"),Z=typeof X.extra?.boardId=="string"?X.extra.boardId:void 0,j=[];for(let N of E){if(!N.outputFile)continue;let ue=o.genId(),de=`${S}/.staged/${ue}/${N.outputFile}`,Oe=await Promise.resolve(u.keyRef?.(de));if(!Oe)continue;let Ee={ref:chunkVQCIOKJV_cjs.a(Oe),deliveryToken:ue,outputFile:N.outputFile,cardId:S},dt=nt({cbk:l.callbackToken,rg:t.value,br:chunkVQCIOKJV_cjs.a(t),cid:S,b:N.bindTo,d:N.outputFile,cs:void 0,rqt:l.rqt,dt:Ee.deliveryToken});j.push({...Z?{boardId:Z}:{},ref:X,args:{source_def:N,base_ref:chunkVQCIOKJV_cjs.a(t),callback:s.createCallback(dt),output:Ee}});}j.length>0&&await K.enqueueMany(j);}catch(I){await F({type:"task-failed",taskName:S,error:I instanceof Error?I.message:String(I),timestamp:x()});}return}for(let I of E){if(!I.outputFile)continue;let K;if(Te){let N=o.genId(),ue=`${S}/.staged/${N}/${I.outputFile}`,de=await Promise.resolve(u.keyRef?.(ue));de&&(K={ref:chunkVQCIOKJV_cjs.a(de),deliveryToken:N,outputFile:I.outputFile,cardId:S});}let Z=nt({cbk:l.callbackToken,rg:t.value,br:chunkVQCIOKJV_cjs.a(t),cid:S,b:I.bindTo,d:I.outputFile,cs:void 0,rqt:l.rqt,...K?{dt:K.deliveryToken}:{}}),j=await o.dispatchExecution(X,{source_def:I,base_ref:chunkVQCIOKJV_cjs.a(t),callback:s.createCallback(Z),...K?{output:K}:{}});j.dispatched||await F({type:"task-failed",taskName:S,error:j.error??"dispatch failed",timestamp:x()});}});}async function oe(){try{let r=async()=>{let u=await J(),{events:a}=await L().readEntriesAfterCursor(u.lastDrainedJournalId);a.length>0&&await m();},e=await Ye(o.lock,Re,r);return h({ran:e!==!1})}catch(r){return P(r)}}async function xe(){return c||(c=oe().finally(()=>{c=null;}),c)}async function m(){let r=await b().readQueueStoreRef();if(!r)throw new Error(`Board at ${t.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);let e=o.queueStorageForRef(r,"process-accumulated");e.enqueueIfAbsent?await e.enqueueIfAbsent({boardRef:chunkVQCIOKJV_cjs.a(t)},`process-accumulated:${chunkVQCIOKJV_cjs.a(t)}`):await e.enqueue({boardRef:chunkVQCIOKJV_cjs.a(t)}),await o.requestProcessAccumulated?.();}async function f(){let r=await b().readQueueStoreRef();if(!r)throw new Error(`Board at ${t.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);let e=o.queueStorageForRef(r,"process-accumulated");for(;;){let u=await e.lease({max:64,visibilityMs:1e3});if(u.length<=0)return;for(let a of u)await e.ack(a.id,a.leaseToken);if(u.length<64)return}}function R(){m();}return {async init(r){try{let e=r.params?.cardStoreRef;if(!e)return p("init requires params.cardStoreRef");if(w=r.params?.boardRuntimeStoreRef,!w)return p("init requires params.boardRuntimeStoreRef");let u=r.params?.outputsStoreRef;if(!u)return p("init requires params.outputsStoreRef");let a=r.params?.queueStoreRef;if(!a)return p("init requires params.queueStoreRef");let k=r.params?.fetchedSourcesStoreRef;if(!k)return p("init requires params.fetchedSourcesStoreRef");if(v=r.params?.scratchStoreRef,!v)return p("init requires params.scratchStoreRef");let C=r.params?.chatStoreRef;if(!C)return p("init requires params.chatStoreRef");let A=r.params?.artifactsStoreRef;if(!A)return p("init requires params.artifactsStoreRef");await se()||await H({lastDrainedJournalId:"",graph:chunkG4XXRHL2_cjs.p(chunkG4XXRHL2_cjs.a(chunkZENTBLLA_cjs.u)),runtimeByCardId:{}},null);let y=b();return await y.writeBoardRuntimeStoreRef(w),await y.writeCardStoreRef(e),await y.writeOutputsStoreRef(u),await y.writeQueueStoreRef(a),await y.writeFetchedSourcesStoreRef(k),await y.writeChatStoreRef(C),await y.writeArtifactsStoreRef(A),await(await T()).writeStatusSnapshot(chunkZENTBLLA_cjs.t(g,chunkG4XXRHL2_cjs.q((await J()).graph))),h()}catch(e){return P(e)}},async status(r){try{let e=await T(),u=await e.readStatusSnapshot();return u||(u=chunkZENTBLLA_cjs.t(g,chunkG4XXRHL2_cjs.q((await J()).graph)),await e.writeStatusSnapshot(u)),h(u)}catch(e){return P(e)}},async getCardStoreRef(r){try{let e=await b().readCardStoreRef();return e?h({storeRef:e}):p(`Board at ${t.value} has no card store configured`)}catch(e){return P(e)}},async getBoardRuntimeStoreRef(r){try{return h({storeRef:w??null})}catch(e){return P(e)}},async getOutputsStoreRef(r){try{let e=await b().readOutputsStoreRef();return e?h({storeRef:e}):p(`Board at ${t.value} has no outputs store configured`)}catch(e){return P(e)}},async getScratchStoreRef(r){try{return h({storeRef:v??null})}catch(e){return P(e)}},async getChatStoreRef(r){try{return h({storeRef:await b().readChatStoreRef()})}catch(e){return P(e)}},async getArtifactsStoreRef(r){try{return h({storeRef:await b().readArtifactsStoreRef()})}catch(e){return P(e)}},async getFetchedSourcesStoreRef(r){try{return h({storeRef:await b().readFetchedSourcesStoreRef()})}catch(e){return P(e)}},async getConfig(r){try{let e=r.params?.key;if(!e)return p("getConfig requires params.key");let u=b(),a;switch(e){case "task-executor":a=B??null;break;case "chat-handler-flow":a=te??null;break;case "board-runtime-store-ref":a=await u.readBoardRuntimeStoreRef();break;case "card-store-ref":a=await u.readCardStoreRef();break;case "outputs-store-ref":a=await u.readOutputsStoreRef();break;case "scratch-store-ref":a=v??null;break;case "chat-store-ref":a=await u.readChatStoreRef();break;case "artifacts-store-ref":a=await u.readArtifactsStoreRef();break;case "fetched-sources-store-ref":a=await u.readFetchedSourcesStoreRef();break;default:return p(`getConfig: unknown key "${e}"`)}return h({value:a})}catch(e){return P(e)}},async getOutputsDataObject(r){try{let e=r.params?.key;return e?h(await(await T()).readDataObject(e)):p("getOutputsDataObject requires params.key")}catch(e){return P(e)}},async getAllOutputsDataObjects(r){try{return h(await(await T()).readAllDataObjects())}catch(e){return P(e)}},async getOutputsComputedValues(r){try{let e=r.params?.key;return e?h(await(await T()).readComputedValues(e)):p("getOutputsComputedValues requires params.key")}catch(e){return P(e)}},async getAllOutputsComputedValues(r){try{return h(await(await T()).readAllComputedValues())}catch(e){return P(e)}},async getOutputsFetchedSources(r){try{let e=r.params?.key;if(!e)return p("getOutputsFetchedSources requires params.key");let u=await(await W()).listSources(e),a={};for(let k of u)a[k]=await ke(`${e}/${k}`);return h(a)}catch(e){return P(e)}},async getAllOutputsFetchedSources(r){try{let e=await W(),u=await(await G()).listKeys(),a=new Set;for(let C of u){let A=C.indexOf("/");A>0&&!C.includes("/.staged/")&&a.add(C.slice(0,A));}let k={};for(let C of a){let A=await e.listSources(C);if(A.length!==0){k[C]={};for(let y of A)k[C][y]=await ke(`${C}/${y}`);}}return h(k)}catch(e){return P(e)}},async addCardFiles(r){try{let e=r.params?.cardId;if(!e)return p("addCardFiles requires params.cardId");let u=await D(),a=await u.readCard(e);if(!a)return p(`card "${e}" not found`);let k=r.body,C=Array.isArray(k)?k:k&&typeof k=="object"&&Array.isArray(k.files)?k.files:k!=null?[k]:null;if(!C||C.length===0)return p("addCardFiles requires a file metadata object, array, or body.files array");let A=a.card_data&&typeof a.card_data=="object"&&!Array.isArray(a.card_data)?a.card_data:{},y=Array.isArray(A.files)?A.files:[],z=[...y,...C],Q=C.map((U,Y)=>({idx:y.length+Y,entry:U}));await u.writeCard(e,{...a,card_data:{...A,files:z}});let V=await this.cardRefreshedNotify({params:{cardId:e}});return V.status!=="success"?V:h({cardId:e,files_added:Q,notified:!0})}catch(e){return P(e)}},async cardRefreshedNotify(r){try{let e=r.params?.cardId;if(!e)return p("cardRefreshedNotify requires params.cardId");let u=await(await D()).readCard(e);return u?(await re([{kind:"card_refreshed",cardId:e,card:u}]),h({cardId:e,notified:!0})):p(`Card "${e}" not found in board at ${t.value}`)}catch(e){return P(e)}},async removeCard(r){try{let e=r.params?.id;if(!e)return p("removeCard requires params.id");try{await o.kvStorage("card-upsert").delete(e);}catch{}return await F({type:"task-removal",taskName:e,timestamp:x()}),R(),h()}catch(e){return P(e)}},async retrigger(r){try{let e=r.params?.id;return e?(await F({type:"task-restart",taskName:e,timestamp:x()}),R(),h()):p("retrigger requires params.id")}catch(e){return P(e)}},async processAccumulatedEvents(r){return await f(),xe()},async upsertCard(r){try{let e=r.params?.cardId,u=r.params?.all,a=!!r.params?.restart;if(!e&&!u)return p("upsertCard requires --card-id <id> or --all");let k=await D(),C=u?(await k.readAllCards()).map(y=>y.id):[e];for(let y of C)if(!await k.readCard(y))return p(`Card "${y}" not found in board at ${t.value}`);let A=o.kvStorage("card-upsert");for(let y of C){let z=await k.readCard(y);if(!z)continue;let Q=chunkZENTBLLA_cjs.x(z),V=o.hashFn(Q),U=await A.read(y),Y=U?.taskConfigHash!==V;if(!(!Y&&!a)){if(Y){let Se=U?.blobRef??await k.readCardKey(y)??y;await F({type:"task-upsert",taskName:y,taskConfig:Q,timestamp:x()}),await A.write(y,{blobRef:Se,taskConfigHash:V,updatedAt:x()});}a&&await F({type:"task-restart",taskName:y,timestamp:x()});}}return R(),h()}catch(e){return P(e)}},async taskFailed(r){try{let e=r.params?.token;if(!e)return p("taskFailed requires params.token");let u=r.params?.error??"unknown error",a=ye(e);return a?(await F({type:"task-failed",taskName:a.taskName,error:u,timestamp:x()}),R(),h()):p("Invalid callback token")}catch(e){return P(e)}},async taskProgress(r){try{let e=r.params?.token;if(!e)return p("taskProgress requires params.token");let u=(r.body??{}).update??{},a=ye(e);return a?(await F({type:"task-progress",taskName:a.taskName,update:u,timestamp:x()}),R(),h()):p("Invalid callback token")}catch(e){return P(e)}},async sourceDataFetched(r){try{let e=r.params?.token,u=r.params?.ref;if(!e)return p("sourceDataFetched requires params.token");if(!u)return p("sourceDataFetched requires params.ref");let a=ot(e);if(!a)return p("Invalid source token");let k=await W(),C=a.dt||o.genId();a.dt||await k.ingestSourceDataStaged(a.cid,a.d,chunkVQCIOKJV_cjs.b(u),C);let A=ye(a.cbk);return A?(await F({type:"task-progress",taskName:A.taskName,update:{bindTo:a.b,outputFile:a.d,fetchedAt:x(),deliveryToken:C,sourceChecksum:a.cs,rqt:a.rqt},timestamp:x()}),R(),h()):p("Invalid callback token embedded in source token")}catch(e){return P(e)}},async sourceDataFetchFailure(r){try{let e=r.params?.token,u=r.params?.reason??"unknown";if(!e)return p("sourceDataFetchFailure requires params.token");let a=ot(e);if(!a)return p("Invalid source token");let k=ye(a.cbk);return k?(await F({type:"task-progress",taskName:k.taskName,update:{bindTo:a.b,outputFile:a.d,failure:!0,reason:u,sourceChecksum:a.cs,rqt:a.rqt},timestamp:x()}),R(),h()):p("Invalid callback token embedded in source token")}catch(e){return P(e)}}}}
2
- exports.a=Ye;exports.b=et;exports.c=tt;exports.d=rt;exports.e=Ct;exports.f=ht;exports.g=_t;//# sourceMappingURL=chunk-36QUKFL7.cjs.map
3
- //# sourceMappingURL=chunk-36QUKFL7.cjs.map