@milaboratories/pl-mcp-server 54.0.0 → 55.0.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 (208) hide show
  1. package/README.md +15 -25
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -123
  156. package/src/tools/block-action-context.ts +3 -0
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +135 -25
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +77 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1,4 +1,8 @@
1
1
  import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from "quickjs-emscripten";
2
+ import { isPlainObject } from "@milaboratories/helpers";
3
+
4
+ /** The size of the sandbox's memory, in bytes. */
5
+ const MEMORY_LIMIT = 1024 * 1024 * 16;
2
6
 
3
7
  /** Lazily initialized QuickJS runtime shared across evaluations. */
4
8
  let sharedRuntime: QuickJSRuntime | undefined;
@@ -7,7 +11,7 @@ async function getRuntime(): Promise<QuickJSRuntime> {
7
11
  if (!sharedRuntime) {
8
12
  const quickjs = await getQuickJS();
9
13
  sharedRuntime = quickjs.newRuntime();
10
- sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB
14
+ sharedRuntime.setMemoryLimit(MEMORY_LIMIT);
11
15
  sharedRuntime.setMaxStackSize(1024 * 320);
12
16
  }
13
17
  return sharedRuntime;
@@ -105,14 +109,99 @@ function parseThrown(dumped: unknown): Thrown {
105
109
  return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };
106
110
  }
107
111
 
112
+ /** The longest an expression may run, in milliseconds, whatever the caller asks for. */
113
+ export const MAX_EXPRESSION_TIMEOUT_MS = 10_000;
114
+
115
+ /**
116
+ * The timeout an evaluation runs under: `requested`, at most {@link MAX_EXPRESSION_TIMEOUT_MS}.
117
+ * The sandbox runs on the server's thread, so a long evaluation holds every other call up.
118
+ */
119
+ export function clampExpressionTimeout(requested: number): number {
120
+ if (Number.isNaN(requested)) return MAX_EXPRESSION_TIMEOUT_MS;
121
+ return Math.min(requested, MAX_EXPRESSION_TIMEOUT_MS);
122
+ }
123
+
124
+ /** The words a timeout argument is described with, for every tool that takes one. */
125
+ export function expressionTimeoutText(subject: string, defaultMs: number): string {
126
+ return `Timeout in ms for ${subject} (default ${defaultMs}, at most ${MAX_EXPRESSION_TIMEOUT_MS}).`;
127
+ }
128
+
129
+ const OUT_OF_MEMORY_HINT =
130
+ "The values the expression reads do not fit in the sandbox's 16 MB. Read less: name the " +
131
+ "parts you need, e.g. `outputs.<key>?.value` or `data.<key>`, instead of whole values.";
132
+
133
+ /**
134
+ * Installs the context in the sandbox as globals that read their value from the host on first
135
+ * use, so a variable the expression does not read is never copied in. A plain-object variable is
136
+ * a Proxy that reads one key at a time: `outputs.qc?.value` copies `qc` only, `Object.keys(outputs)`
137
+ * the keys only, a spread or `JSON.stringify(outputs)` all of it. Values are copied as JSON.
138
+ *
139
+ * Writes behave as on a plain object. A value read once is kept, so a change inside it stays. The
140
+ * first change of the record itself (a key set, added or deleted, or the record frozen) copies
141
+ * every key into the Proxy's target, which from then on is the record. A global can be assigned.
142
+ */
143
+ const CONTEXT_SETUP = `(() => {
144
+ const value = globalThis.__plValue, keysOf = globalThis.__plKeys;
145
+ delete globalThis.__plValue;
146
+ delete globalThis.__plKeys;
147
+ const parse = (json) => (json === undefined ? undefined : JSON.parse(json));
148
+ const record = (name) => {
149
+ const cache = new Map();
150
+ let keys;
151
+ // Set by the first change: the target then holds every key and answers for the record.
152
+ let copied = false;
153
+ const keyList = () => (keys ??= JSON.parse(keysOf(name)));
154
+ const own = (k) => !copied && typeof k === "string" && keyList().includes(k);
155
+ const read = (k) => {
156
+ if (!cache.has(k)) cache.set(k, parse(value(name, k)));
157
+ return cache.get(k);
158
+ };
159
+ const copy = (t) => {
160
+ if (copied) return;
161
+ for (const k of keyList())
162
+ Object.defineProperty(t, k, {
163
+ value: read(k), writable: true, enumerable: true, configurable: true,
164
+ });
165
+ copied = true;
166
+ };
167
+ return new Proxy({}, {
168
+ get: (t, k, r) => (own(k) ? read(k) : Reflect.get(t, k, r)),
169
+ has: (t, k) => own(k) || Reflect.has(t, k),
170
+ ownKeys: (t) => (copied ? Reflect.ownKeys(t) : [...keyList()]),
171
+ // An accessor, so that listing the keys (Object.keys) reads no value.
172
+ getOwnPropertyDescriptor: (t, k) =>
173
+ own(k)
174
+ ? { get: () => read(k), enumerable: true, configurable: true }
175
+ : Reflect.getOwnPropertyDescriptor(t, k),
176
+ set: (t, k, v, r) => (copy(t), Reflect.set(t, k, v, r)),
177
+ defineProperty: (t, k, d) => (copy(t), Reflect.defineProperty(t, k, d)),
178
+ deleteProperty: (t, k) => (copy(t), Reflect.deleteProperty(t, k)),
179
+ preventExtensions: (t) => (copy(t), Reflect.preventExtensions(t)),
180
+ });
181
+ };
182
+ for (const [name, isRecord] of JSON.parse(keysOf())) {
183
+ let done = false, v;
184
+ Object.defineProperty(globalThis, name, {
185
+ get: () => {
186
+ if (!done) { v = isRecord ? record(name) : parse(value(name)); done = true; }
187
+ return v;
188
+ },
189
+ set: (next) => { v = next; done = true; },
190
+ });
191
+ }
192
+ })()`;
193
+
108
194
  /**
109
195
  * Evaluate a JS expression in a QuickJS sandbox.
110
- * Variables from `context` are injected as globals.
196
+ * Variables from `context` are globals read from the host when the expression reads them (see
197
+ * {@link CONTEXT_SETUP}), so a large value it does not read costs nothing.
111
198
  * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
112
199
  *
113
200
  * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
114
- * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than
115
- * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.
201
+ * with a hint on writing several statements when the expression does not parse, and one on reading less when the
202
+ * sandbox runs out of memory. An evaluation that runs longer than `timeout` milliseconds (at most
203
+ * {@link MAX_EXPRESSION_TIMEOUT_MS}) throws a {@link SandboxError} saying that it timed out. An expression whose value
204
+ * is `undefined` (or anything else JSON has no form for, such as a function) gives `null`.
116
205
  */
117
206
  export async function safeEval(
118
207
  expression: string,
@@ -120,16 +209,17 @@ export async function safeEval(
120
209
  timeout: number,
121
210
  ): Promise<unknown> {
122
211
  const runtime = await getRuntime();
212
+ const limit = clampExpressionTimeout(timeout);
123
213
 
124
214
  // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,
125
215
  // so the flag is what tells a timeout from an error of the code itself.
126
- const deadline = Date.now() + timeout;
216
+ const deadline = Date.now() + limit;
127
217
  let timedOut = false;
128
218
  runtime.setInterruptHandler(() => {
129
219
  if (Date.now() > deadline) timedOut = true;
130
220
  return timedOut;
131
221
  });
132
- const timeoutMessage = `Evaluation timed out after ${timeout} ms`;
222
+ const timeoutMessage = `Evaluation timed out after ${limit} ms`;
133
223
 
134
224
  const vm = runtime.newContext();
135
225
 
@@ -142,33 +232,53 @@ export async function safeEval(
142
232
  };
143
233
 
144
234
  try {
145
- // Inject context variables via JSON
146
- const contextJson = JSON.stringify(context);
147
- const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});
148
- ${Object.keys(context)
149
- .map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`)
150
- .join("\n")}`;
151
- const setupResult = vm.evalCode(setup, "setup.js", { type: "global" });
235
+ const valueOf = vm.newFunction("__plValue", (nameHandle, keyHandle) => {
236
+ const value = context[vm.getString(nameHandle)];
237
+ const json = JSON.stringify(
238
+ keyHandle === undefined || !isPlainObject(value)
239
+ ? value
240
+ : (Object.getOwnPropertyDescriptor(value, vm.getString(keyHandle))?.value as unknown),
241
+ );
242
+ return json === undefined ? vm.undefined : vm.newString(json);
243
+ });
244
+ const keysOf = vm.newFunction("__plKeys", (nameHandle) => {
245
+ const keys =
246
+ nameHandle === undefined
247
+ ? Object.entries(context).map(([name, value]) => [name, isPlainObject(value)])
248
+ : Object.keys(context[vm.getString(nameHandle)] as object);
249
+ return vm.newString(JSON.stringify(keys));
250
+ });
251
+ vm.setProp(vm.global, "__plValue", valueOf);
252
+ vm.setProp(vm.global, "__plKeys", keysOf);
253
+ valueOf.dispose();
254
+ keysOf.dispose();
255
+ const setupResult = vm.evalCode(CONTEXT_SETUP, "setup.js", { type: "global" });
152
256
  if (setupResult.error) {
153
257
  const thrown = takeThrown(setupResult.error);
154
258
  if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
155
- throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
259
+ throw new SandboxError(
260
+ `Context setup failed: ${thrown.text}${isOutOfMemory(thrown) ? `. ${OUT_OF_MEMORY_HINT}` : ""}`,
261
+ thrown.errorClass,
262
+ );
156
263
  }
157
264
  setupResult.value.dispose();
158
265
 
159
- // Evaluate the expression
160
- const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
266
+ // Evaluate the expression. The line break lets it end in a `//` comment.
267
+ const result = vm.evalCode(`JSON.stringify((${expression}\n))`, EXPRESSION_FILE);
161
268
  if (result.error) {
162
269
  const thrown = takeThrown(result.error);
163
270
  if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
164
271
  throw new SandboxError(
165
272
  thrown.syntaxErrorFile === EXPRESSION_FILE
166
273
  ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`
167
- : thrown.text,
274
+ : isOutOfMemory(thrown)
275
+ ? `${thrown.text}. ${OUT_OF_MEMORY_HINT}`
276
+ : thrown.text,
168
277
  thrown.errorClass,
169
278
  );
170
279
  }
171
- const json = vm.getString(result.value);
280
+ // `JSON.stringify` gives `undefined` for a value JSON has no form for.
281
+ const json = vm.typeof(result.value) === "string" ? vm.getString(result.value) : "null";
172
282
  result.value.dispose();
173
283
  return JSON.parse(json);
174
284
  } finally {
@@ -176,3 +286,7 @@ ${Object.keys(context)
176
286
  vm.dispose();
177
287
  }
178
288
  }
289
+
290
+ function isOutOfMemory(thrown: Thrown): boolean {
291
+ return /out of memory/i.test(thrown.text);
292
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Short declarations of the SDK types kinds use in their params. A kind's `contract.d.ts` imports
3
+ * them from `@platforma-sdk/*` and `@milaboratories/*`, which an agent cannot open; this is what
4
+ * stands for each. `get_block_contract` returns all of them.
5
+ */
6
+ export const SDK_TYPES: Record<string, string> = {
7
+ PlRef:
8
+ "/** Object form of a leaf GlobalPObjectId; copy `ref` from a block's option outputs " +
9
+ "(get_block_outputs) or from list_pool_columns. */\n" +
10
+ "type PlRef = { __isRef: true; blockId: string; name: string; requireEnrichments?: true };",
11
+ PlId: "/** Id made by Platforma: 24 base32 characters. */\ntype PlId = string;",
12
+ ImportFileHandle:
13
+ "/** Handle of a file to import into a block. Copy it from a tool result. */\n" +
14
+ "type ImportFileHandle = `upload://upload/${string}` | `index://index/${string}`;",
15
+ PObjectId:
16
+ "/** A leaf column id only: a block's own column (local) or another block's " +
17
+ "(GlobalPObjectId); never a filtered, discovered or overridden id. */\n" +
18
+ "type PObjectId = string;",
19
+ GlobalPObjectId:
20
+ "/** Canonical JSON of a PlRef without requireEnrichments: the `columnId` list_columns " +
21
+ "and get_block_outputs give a column of another block, and list_pool_columns one with a " +
22
+ "`ref`. */\n" +
23
+ "type GlobalPObjectId = string;",
24
+ SUniversalPColumnId: "/** Same as ColumnUniversalId. */\ntype SUniversalPColumnId = string;",
25
+ ColumnUniversalId:
26
+ "/** Any form of column id, leaf or not. Block workflows resolve leaf ids only today: " +
27
+ "for a block field copy the id the block offers in its option outputs, or a leaf " +
28
+ "`columnId` or `ref`. */\n" +
29
+ "type ColumnUniversalId = string;",
30
+ ColumnValueId:
31
+ "/** One value of one column; copy from `valueIds` of get_column_values (of a pool " +
32
+ "column too); never build it. */\n" +
33
+ "type ColumnValueId = string;",
34
+ AxisId:
35
+ "/** Identity of an axis of a column. */\n" +
36
+ 'type AxisId = { readonly type: "Int" | "Long" | "String"; readonly name: string; ' +
37
+ "readonly domain?: Record<string, string>; readonly contextDomain?: Record<string, string> };",
38
+ PTableColumnId:
39
+ "/** A column of a table: one of its axes or one of its columns. */\n" +
40
+ 'type PTableColumnId = { type: "axis"; id: AxisId } | { type: "column"; id: ColumnUniversalId };',
41
+ PColumnSpec:
42
+ "/** Spec of a column, as tool results show it. */\ntype PColumnSpec = Record<string, unknown>;",
43
+ DatasetSelection:
44
+ "/** A picked dataset: its column, an optional filter, and enrichments attached to it. " +
45
+ "An enrichment is a column the block's dataset option offers with the dataset: copy each " +
46
+ "from `enrichments` of that option in the block's option outputs (get_block_outputs); " +
47
+ "never build one. */\n" +
48
+ 'type DatasetSelection = { readonly __isDatasetSelection: "v1"; readonly primary: ' +
49
+ '{ readonly __isPrimaryRef: "v1"; readonly column: PlRef; readonly filter?: PlRef }; ' +
50
+ "readonly enrichments?: readonly { readonly id: ColumnUniversalId; readonly label: string }[] };",
51
+ CanonicalizedJson:
52
+ "/** JSON text of a value of type T, in canonical form. */\n" +
53
+ "type CanonicalizedJson<T = unknown> = string;",
54
+ };
@@ -0,0 +1,340 @@
1
+ import { asBlockId } from "@milaboratories/pl-model-common";
2
+ import { afterEach, describe, expect, test, vi } from "vitest";
3
+ import { delay } from "@milaboratories/helpers";
4
+ import type { SettleBlockState, SettleOverviewBlock, SettleProject } from "./settle";
5
+ import {
6
+ awaitBlockSettled,
7
+ clampWait,
8
+ pendingOutputKeys,
9
+ progressReporter,
10
+ upstreamOfMarker,
11
+ } from "./settle";
12
+ import type { WaitContext } from "./settle";
13
+
14
+ type Outputs = Record<
15
+ string,
16
+ { ok: true; value: unknown; stable: boolean } | { ok: false; errors: string[] }
17
+ >;
18
+
19
+ /** The block every test waits for. */
20
+ const B = asBlockId("b");
21
+
22
+ const stable = (value: unknown) => ({ ok: true as const, value, stable: true });
23
+ const pending = () => ({ ok: true as const, value: undefined, stable: false });
24
+ const failed = () => ({ ok: false as const, errors: ["boom"] });
25
+
26
+ /**
27
+ * A project whose block `b` has a state that a test changes with `set`, the way a middle-layer
28
+ * computable changes: every change gets a new uTag and wakes the waiters of `awaitChange`.
29
+ */
30
+ function fakeProject(initial: {
31
+ state: SettleBlockState;
32
+ marker?: string;
33
+ blocks?: SettleOverviewBlock[];
34
+ }) {
35
+ let state = initial.state;
36
+ let marker = initial.marker;
37
+ let blocks: SettleOverviewBlock[] = initial.blocks ?? [
38
+ { id: "b", calculationStatus: "NotCalculated", upstreams: [] },
39
+ ];
40
+ let version = 0;
41
+ let waiters: (() => void)[] = [];
42
+ let looks = 0;
43
+
44
+ const project: SettleProject<SettleBlockState> = {
45
+ overview: { getValue: async () => ({ blocks }) },
46
+ getBlockState: () => ({
47
+ getFullValue: async () => {
48
+ looks++;
49
+ return { value: state, uTag: String(version), unstableMarker: marker };
50
+ },
51
+ awaitChange: async (signal, uTag) => {
52
+ if (uTag !== String(version)) return;
53
+ await new Promise<void>((resolve, reject) => {
54
+ const onAbort = () => reject(new DOMException("aborted", "AbortError"));
55
+ signal?.addEventListener("abort", onAbort, { once: true });
56
+ waiters.push(() => {
57
+ signal?.removeEventListener("abort", onAbort);
58
+ resolve();
59
+ });
60
+ });
61
+ },
62
+ }),
63
+ };
64
+
65
+ return {
66
+ project,
67
+ looks: () => looks,
68
+ set(change: { state?: SettleBlockState; marker?: string; blocks?: SettleOverviewBlock[] }) {
69
+ if (change.state !== undefined) state = change.state;
70
+ if ("marker" in change) marker = change.marker;
71
+ if (change.blocks !== undefined) blocks = change.blocks;
72
+ version++;
73
+ const woken = waiters;
74
+ waiters = [];
75
+ for (const w of woken) w();
76
+ },
77
+ };
78
+ }
79
+
80
+ describe("awaitBlockSettled", () => {
81
+ test("settles at once when every output is computed or failed", async () => {
82
+ const { project } = fakeProject({
83
+ state: { outputs: { a: stable(1), b: failed() } },
84
+ });
85
+ const result = await awaitBlockSettled(project, B, {
86
+ timeoutMs: 1000,
87
+ waitForRun: false,
88
+ });
89
+ expect(result).toMatchObject({ settled: true, pendingOutputs: [], runningUpstreams: [] });
90
+ });
91
+
92
+ test.each([["prod_not_locked:up"], ["no_data:up:main"]])(
93
+ "returns early when the outputs wait for a running upstream (%s)",
94
+ async (marker) => {
95
+ const { project } = fakeProject({
96
+ state: { outputs: { a: pending() } },
97
+ marker,
98
+ blocks: [
99
+ { id: "up", calculationStatus: "Running", upstreams: [] },
100
+ { id: "b", calculationStatus: "NotCalculated", upstreams: ["up"] },
101
+ ],
102
+ });
103
+ const started = Date.now();
104
+ const result = await awaitBlockSettled(project, B, {
105
+ timeoutMs: 10_000,
106
+ waitForRun: false,
107
+ });
108
+ expect(Date.now() - started).toBeLessThan(1000);
109
+ expect(result).toMatchObject({
110
+ settled: false,
111
+ stoppedBy: "upstream-running",
112
+ waitingOn: "up",
113
+ pendingOutputs: ["a"],
114
+ runningUpstreams: ["up"],
115
+ });
116
+ },
117
+ );
118
+
119
+ test("does not return early for a marker naming a block that is done", async () => {
120
+ const { project } = fakeProject({
121
+ state: { outputs: { a: pending() } },
122
+ marker: "prod_not_locked:up",
123
+ blocks: [
124
+ { id: "up", calculationStatus: "Done", upstreams: [] },
125
+ { id: "b", calculationStatus: "NotCalculated", upstreams: ["up"] },
126
+ ],
127
+ });
128
+ const result = await awaitBlockSettled(project, B, { timeoutMs: 300, waitForRun: false });
129
+ expect(result).toEqual({
130
+ settled: false,
131
+ stoppedBy: "timeout",
132
+ waitedMs: expect.any(Number),
133
+ calculationStatus: "NotCalculated",
134
+ state: { outputs: { a: pending() } },
135
+ pendingOutputs: ["a"],
136
+ runningUpstreams: [],
137
+ });
138
+ expect(result.waitedMs).toBeGreaterThanOrEqual(250);
139
+ });
140
+
141
+ test.each([
142
+ ["prod_not_locked:up", "NotCalculated"],
143
+ ["no_data:up:main", "NotCalculated"],
144
+ ["prod_not_locked:up", "Limbo"],
145
+ ])(
146
+ "returns early when the outputs wait for an upstream that has not run (%s, %s)",
147
+ async (marker, status) => {
148
+ const { project } = fakeProject({
149
+ state: { outputs: { a: pending() } },
150
+ marker,
151
+ blocks: [
152
+ { id: "up", calculationStatus: status, upstreams: [] },
153
+ { id: "b", calculationStatus: "NotCalculated", upstreams: ["up"] },
154
+ ],
155
+ });
156
+ const started = Date.now();
157
+ const result = await awaitBlockSettled(project, B, {
158
+ timeoutMs: 10_000,
159
+ waitForRun: false,
160
+ });
161
+ expect(Date.now() - started).toBeLessThan(1000);
162
+ expect(result).toMatchObject({
163
+ settled: false,
164
+ stoppedBy: "upstream-not-run",
165
+ waitingOn: "up",
166
+ waitingOnStatus: status,
167
+ pendingOutputs: ["a"],
168
+ runningUpstreams: [],
169
+ });
170
+ },
171
+ );
172
+
173
+ test("stops on the request's abort signal", async () => {
174
+ const { project } = fakeProject({ state: { outputs: { a: pending() } } });
175
+ const controller = new AbortController();
176
+ setTimeout(() => controller.abort(), 100);
177
+ const started = Date.now();
178
+ const result = await awaitBlockSettled(project, B, {
179
+ timeoutMs: 10_000,
180
+ signal: controller.signal,
181
+ waitForRun: false,
182
+ });
183
+ expect(Date.now() - started).toBeLessThan(2000);
184
+ expect(result).toMatchObject({ settled: false, stoppedBy: "aborted" });
185
+ });
186
+
187
+ test("does not spin on a state that never changes", async () => {
188
+ const fake = fakeProject({ state: { outputs: { a: pending() } } });
189
+ await awaitBlockSettled(fake.project, B, { timeoutMs: 300, waitForRun: false });
190
+ expect(fake.looks()).toBeLessThanOrEqual(3);
191
+ });
192
+
193
+ test("with waitForRun, a running block is not settled until its run is over", async () => {
194
+ const fake = fakeProject({
195
+ state: { outputs: { a: stable(1) } },
196
+ blocks: [{ id: "b", calculationStatus: "Running", upstreams: [] }],
197
+ });
198
+ const wait = awaitBlockSettled(fake.project, B, { timeoutMs: 5000, waitForRun: true });
199
+ await delay(150);
200
+ fake.set({ blocks: [{ id: "b", calculationStatus: "Done", upstreams: [] }] });
201
+ const result = await wait;
202
+ expect(result).toMatchObject({ settled: true, calculationStatus: "Done" });
203
+ expect(result.waitedMs).toBeGreaterThanOrEqual(100);
204
+ });
205
+
206
+ test("with waitForRun, a running block waits for its upstream instead of returning early", async () => {
207
+ const { project } = fakeProject({
208
+ state: { outputs: { a: pending() } },
209
+ marker: "prod_not_locked:up",
210
+ blocks: [
211
+ { id: "up", calculationStatus: "Running", upstreams: [] },
212
+ { id: "b", calculationStatus: "Running", upstreams: ["up"] },
213
+ ],
214
+ });
215
+ const result = await awaitBlockSettled(project, B, { timeoutMs: 300, waitForRun: true });
216
+ expect(result).toMatchObject({
217
+ settled: false,
218
+ stoppedBy: "timeout",
219
+ waitingOn: "up",
220
+ runningUpstreams: ["up"],
221
+ });
222
+ });
223
+
224
+ test.each([
225
+ ["NotCalculated", "not-calculated"],
226
+ ["Limbo", "limbo"],
227
+ ])("with waitForRun, a block %s ends the wait", async (status, stoppedBy) => {
228
+ const { project } = fakeProject({
229
+ state: { outputs: {} },
230
+ blocks: [{ id: "b", calculationStatus: status, upstreams: [] }],
231
+ });
232
+ const result = await awaitBlockSettled(project, B, { timeoutMs: 5000, waitForRun: true });
233
+ expect(result).toMatchObject({ settled: false, stoppedBy });
234
+ });
235
+
236
+ test("a block removed while waiting ends the wait", async () => {
237
+ const { project } = fakeProject({ state: { outputs: { a: pending() } }, blocks: [] });
238
+ const result = await awaitBlockSettled(project, B, { timeoutMs: 5000, waitForRun: false });
239
+ expect(result).toMatchObject({ settled: false, stoppedBy: "block-gone" });
240
+ });
241
+
242
+ test("reports progress while it waits", async () => {
243
+ const { project } = fakeProject({ state: { outputs: { a: pending() } } });
244
+ const calls: number[] = [];
245
+ await awaitBlockSettled(project, B, {
246
+ timeoutMs: 300,
247
+ waitForRun: false,
248
+ onProgress: (elapsed) => calls.push(elapsed),
249
+ });
250
+ expect(calls.length).toBeGreaterThan(0);
251
+ });
252
+ });
253
+
254
+ describe("progress of a quiet wait", () => {
255
+ afterEach(() => {
256
+ vi.useRealTimers();
257
+ });
258
+
259
+ test("a 50 s wait on a block that does not change sends progress every 5 s", async () => {
260
+ vi.useFakeTimers();
261
+ const { project } = fakeProject({ state: { outputs: { a: pending() } } });
262
+ const notify = vi.fn(async () => {});
263
+ const ctx: WaitContext = {
264
+ mcpReq: { signal: new AbortController().signal, _meta: { progressToken: "t" }, notify },
265
+ };
266
+ const waiting = awaitBlockSettled(project, B, {
267
+ timeoutMs: 50_000,
268
+ waitForRun: false,
269
+ onProgress: progressReporter(ctx, "Waiting"),
270
+ });
271
+ await vi.advanceTimersByTimeAsync(50_000);
272
+ const result = await waiting;
273
+ expect(result).toMatchObject({ settled: false, stoppedBy: "timeout" });
274
+ // At 5, 10, ..., 45 s; the look at 50 s is the end of the wait.
275
+ expect(notify.mock.calls.length).toBeGreaterThanOrEqual(9);
276
+ expect(notify.mock.calls.length).toBeLessThanOrEqual(10);
277
+ });
278
+ });
279
+
280
+ describe("progressReporter", () => {
281
+ function call(progressToken: string | undefined) {
282
+ const sent: unknown[] = [];
283
+ const ctx: WaitContext = {
284
+ mcpReq: {
285
+ signal: new AbortController().signal,
286
+ _meta: progressToken === undefined ? {} : { progressToken },
287
+ notify: async (n) => {
288
+ sent.push(n);
289
+ },
290
+ },
291
+ };
292
+ return { ctx, sent };
293
+ }
294
+
295
+ test("sends progress at most every 5 s when the request asked for it", () => {
296
+ const { ctx, sent } = call("t1");
297
+ const report = progressReporter(ctx, "Waiting");
298
+ report?.(100, 50_000);
299
+ report?.(5_100, 50_000);
300
+ report?.(6_000, 50_000);
301
+ report?.(10_200, 50_000);
302
+ expect(sent).toEqual([
303
+ {
304
+ method: "notifications/progress",
305
+ params: { progressToken: "t1", progress: 5_100, total: 50_000, message: "Waiting" },
306
+ },
307
+ {
308
+ method: "notifications/progress",
309
+ params: { progressToken: "t1", progress: 10_200, total: 50_000, message: "Waiting" },
310
+ },
311
+ ]);
312
+ });
313
+
314
+ test("sends nothing without a progress token", () => {
315
+ expect(progressReporter(call(undefined).ctx, "Waiting")).toBeUndefined();
316
+ expect(progressReporter(undefined, "Waiting")).toBeUndefined();
317
+ });
318
+ });
319
+
320
+ describe("helpers", () => {
321
+ test("pendingOutputKeys lists computed outputs that are not final", () => {
322
+ const outputs: Outputs = { a: stable(1), b: pending(), c: failed() };
323
+ expect(pendingOutputKeys(outputs)).toEqual(["b"]);
324
+ expect(pendingOutputKeys(undefined)).toEqual([]);
325
+ });
326
+
327
+ test("upstreamOfMarker reads the block of the result pool's markers", () => {
328
+ expect(upstreamOfMarker("prod_not_locked:abc")).toBe("abc");
329
+ expect(upstreamOfMarker("no_data:abc:main")).toBe("abc");
330
+ expect(upstreamOfMarker("staging_not_locked:abc")).toBeUndefined();
331
+ expect(upstreamOfMarker(undefined)).toBeUndefined();
332
+ });
333
+
334
+ test("clampWait", () => {
335
+ expect(clampWait(undefined, 30_000, 1000, 120_000)).toBe(30_000);
336
+ expect(clampWait(10, 30_000, 1000, 120_000)).toBe(1000);
337
+ expect(clampWait(1e9, 30_000, 1000, 120_000)).toBe(120_000);
338
+ expect(clampWait(Number.NaN, 30_000, 1000, 120_000)).toBe(30_000);
339
+ });
340
+ });