@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
@@ -0,0 +1,483 @@
1
+ import type {
2
+ BlockStateOverview,
3
+ PoolColumn,
4
+ PoolColumns,
5
+ PoolColumnsQuery,
6
+ } from "@milaboratories/pl-middle-layer";
7
+ import {
8
+ Annotation,
9
+ isPlRef,
10
+ isPObjectId,
11
+ readAnnotation,
12
+ ValueType,
13
+ type AnchorEntry,
14
+ type AxisSpec,
15
+ type BlockId,
16
+ type ColumnSelector,
17
+ type ColumnUniversalId,
18
+ type MatchingMode,
19
+ type ProjectId,
20
+ type RelaxedAxisSelector,
21
+ type RelaxedColumnSelector,
22
+ type StringMatcher,
23
+ } from "@milaboratories/pl-model-common";
24
+ import { z } from "zod";
25
+ import { blockIdInput, columnIdFromAgent, columnIdInput, plRefObject, projectIdInput } from "./ids";
26
+ import { pagingArgs } from "./paging";
27
+ import { findBlock, type BlockLookupProject } from "./readiness";
28
+ import { expressionTimeoutText, safeEval } from "./sandbox";
29
+ import type { ToolContext, ToolRegistrar } from "./types";
30
+ import { errorResult, hints, textResult, transformFailedResult } from "./types";
31
+
32
+ /** Default page of {@link listPoolColumnsResult}. */
33
+ export const POOL_COLUMNS_DEFAULT = 50;
34
+ /** Largest page of {@link listPoolColumnsResult}. */
35
+ export const POOL_COLUMNS_MAX = 200;
36
+
37
+ // Selectors, in the forms block models pass them. Typed against the SDK's types, so a schema that
38
+ // drifts from them does not compile.
39
+ //
40
+ // The schemas used more than once carry an `id`: the JSON Schema a client is sent then defines each
41
+ // once under `$defs` and refers to it, instead of repeating it at every use (40 kB of arguments for
42
+ // list_pool_columns otherwise). The id is the name of the SDK type the schema stands for.
43
+
44
+ /** A regular expression the pattern of a selector must compile to. */
45
+ export function regexText(what: string) {
46
+ return z.string().superRefine((value, ctx) => {
47
+ try {
48
+ new RegExp(value);
49
+ } catch (err) {
50
+ ctx.addIssue({
51
+ code: "custom",
52
+ message: `${what} is not a valid regular expression: ${err instanceof Error ? err.message : String(err)}`,
53
+ });
54
+ }
55
+ });
56
+ }
57
+
58
+ const stringMatcher: z.ZodType<StringMatcher> = z
59
+ .union([
60
+ z.strictObject({ type: z.literal("exact"), value: z.string() }),
61
+ z.strictObject({ type: z.literal("regex"), value: regexText("A `regex` matcher") }),
62
+ ])
63
+ .meta({ id: "StringMatcher" });
64
+
65
+ /** A plain string is a regular expression, as in the SDK. */
66
+ const relaxedMatchers = z
67
+ .union([
68
+ regexText("A plain-string matcher"),
69
+ stringMatcher,
70
+ z.array(z.union([regexText("A plain-string matcher"), stringMatcher])),
71
+ ])
72
+ .meta({ id: "RelaxedStringMatchers" });
73
+
74
+ const relaxedRecord = z.record(z.string(), relaxedMatchers);
75
+ const valueType = z.enum(ValueType).meta({ id: "ValueType" });
76
+ const axisValueType = z.enum(["Int", "Long", "String"]);
77
+
78
+ const relaxedAxisSelector: z.ZodType<RelaxedAxisSelector> = z
79
+ .strictObject({
80
+ name: relaxedMatchers.optional(),
81
+ type: z.union([axisValueType, z.array(axisValueType)]).optional(),
82
+ domain: relaxedRecord.optional(),
83
+ contextDomain: relaxedRecord.optional(),
84
+ annotations: relaxedRecord.optional(),
85
+ })
86
+ .meta({ id: "RelaxedAxisSelector" });
87
+
88
+ const relaxedColumnSelector: z.ZodType<RelaxedColumnSelector> = z
89
+ .strictObject({
90
+ name: relaxedMatchers.optional(),
91
+ type: z.union([valueType, z.array(valueType)]).optional(),
92
+ domain: relaxedRecord.optional(),
93
+ contextDomain: relaxedRecord.optional(),
94
+ annotations: relaxedRecord.optional(),
95
+ axes: z.array(relaxedAxisSelector).optional(),
96
+ partialAxesMatch: z.boolean().optional(),
97
+ })
98
+ .meta({ id: "RelaxedColumnSelector" });
99
+
100
+ /** `ColumnSelector`: one selector or several, any of which may match. */
101
+ export const columnSelectorInput: z.ZodType<ColumnSelector> = z
102
+ .union([relaxedColumnSelector, z.array(relaxedColumnSelector)])
103
+ .meta({ id: "ColumnSelector" });
104
+
105
+ /**
106
+ * An anchor of `ColumnsCollection.discover`: the id of a column of the pool (its `columnId` as
107
+ * list_pool_columns lists it without anchors, or its PlRef object), or a selector that matches one
108
+ * column.
109
+ */
110
+ export const poolAnchorInput = z
111
+ .union([z.string(), plRefObject, relaxedColumnSelector])
112
+ .transform((raw, ctx): AnchorEntry => {
113
+ if (typeof raw !== "string" && !isPlRef(raw)) return raw;
114
+ const id = columnIdFromAgent(raw);
115
+ if (id !== undefined && isPObjectId(id)) return id;
116
+ ctx.addIssue({
117
+ code: "custom",
118
+ message:
119
+ "an anchor is a `columnId` that list_pool_columns gives without anchors, its `ref`, " +
120
+ "or a selector",
121
+ });
122
+ return z.NEVER;
123
+ });
124
+
125
+ /** The `include` / `exclude` pair of `ColumnsCollection.filter`. */
126
+ export const poolSelectorInput = z.strictObject({
127
+ include: columnSelectorInput.optional(),
128
+ exclude: columnSelectorInput.optional(),
129
+ });
130
+
131
+ // Results
132
+
133
+ /** What the pool tools need of a project: its overview (block titles) and its pool columns. */
134
+ export type PoolProject = BlockLookupProject<Pick<BlockStateOverview, "id" | "title">> & {
135
+ getPoolColumns(query: PoolColumnsQuery): { getValue(): Promise<PoolColumns> };
136
+ getPoolColumnsById(
137
+ ids: readonly ColumnUniversalId[],
138
+ viewAs?: BlockId,
139
+ ): { getValue(): Promise<(PoolColumn | undefined)[]> };
140
+ };
141
+
142
+ /** Which part of the pool a tool reads, and how it is filtered. */
143
+ export type PoolListInput = {
144
+ blockId?: BlockId;
145
+ selector?: { include?: ColumnSelector; exclude?: ColumnSelector };
146
+ /** Columns to discover from: the pool lists what is reachable from them, with discovered ids. */
147
+ anchors?: Record<string, AnchorEntry>;
148
+ mode?: MatchingMode;
149
+ maxHops?: number;
150
+ detail?: "summary" | "full";
151
+ limit?: number;
152
+ offset?: number;
153
+ };
154
+
155
+ const POOL_NOT_COMPLETE_NOTE =
156
+ "Some blocks in view are still being calculated: more columns may appear when they finish.";
157
+
158
+ /** The titles of the project's blocks by id, or the error result to return. */
159
+ async function blockTitles(
160
+ project: PoolProject,
161
+ projectId: ProjectId,
162
+ blockId: BlockId | undefined,
163
+ ): Promise<
164
+ | { titles: Map<string, string>; error?: undefined }
165
+ | { titles?: undefined; error: ReturnType<typeof errorResult> }
166
+ > {
167
+ const overview = await project.overview.getValue();
168
+ if (overview === undefined)
169
+ return { error: errorResult("Project overview not available yet. Try again.") };
170
+ if (blockId !== undefined) {
171
+ const { error } = await findBlock(project, projectId, blockId);
172
+ if (error) return { error };
173
+ }
174
+ const titles = new Map<string, string>();
175
+ for (const b of overview.blocks) if (b.title !== undefined) titles.set(b.id, b.title);
176
+ return { titles };
177
+ }
178
+
179
+ /** Reads the pool columns, or the error result to return. */
180
+ async function readPool(
181
+ project: PoolProject,
182
+ projectId: ProjectId,
183
+ input: Pick<PoolListInput, "blockId" | "selector" | "anchors" | "mode" | "maxHops">,
184
+ ): Promise<
185
+ | { pool: PoolColumns; titles: Map<string, string>; error?: undefined }
186
+ | { error: ReturnType<typeof errorResult> }
187
+ > {
188
+ const { titles, error } = await blockTitles(project, projectId, input.blockId);
189
+ if (error !== undefined) return { error };
190
+ try {
191
+ const pool = await project
192
+ .getPoolColumns({
193
+ viewAs: input.blockId,
194
+ include: input.selector?.include,
195
+ exclude: input.selector?.exclude,
196
+ anchors: input.anchors,
197
+ mode: input.mode,
198
+ maxHops: input.maxHops,
199
+ })
200
+ .getValue();
201
+ return { pool, titles };
202
+ } catch (err) {
203
+ const message = err instanceof Error ? err.message : String(err);
204
+ return {
205
+ error:
206
+ input.anchors !== undefined
207
+ ? errorResult(
208
+ `The anchors or the selector were not accepted: ${message}`,
209
+ "An anchor selector must match exactly one column, and two anchors not the same one.",
210
+ )
211
+ : input.selector !== undefined
212
+ ? errorResult(
213
+ `The selector was not accepted: ${message}`,
214
+ "Check the selector against the ColumnSelector type of the SDK; a plain string is a regular expression.",
215
+ )
216
+ : errorResult(`Reading the result pool failed: ${message}`),
217
+ };
218
+ }
219
+ }
220
+
221
+ function axisEntry(a: AxisSpec, full: boolean) {
222
+ return {
223
+ name: a.name,
224
+ type: a.type,
225
+ ...(a.domain !== undefined && Object.keys(a.domain).length > 0 ? { domain: a.domain } : {}),
226
+ ...(readAnnotation(a, Annotation.Label) !== undefined
227
+ ? { label: readAnnotation(a, Annotation.Label) }
228
+ : {}),
229
+ ...(full && a.annotations !== undefined ? { annotations: a.annotations } : {}),
230
+ };
231
+ }
232
+
233
+ function nonEmpty(r: Record<string, string> | undefined): Record<string, string> | undefined {
234
+ return r !== undefined && Object.keys(r).length > 0 ? r : undefined;
235
+ }
236
+
237
+ /** One column as the pool tools show it. */
238
+ export function poolColumnEntry(c: PoolColumn, titles: Map<string, string>, full: boolean) {
239
+ const spec = c.spec;
240
+ const label = readAnnotation(spec, Annotation.Label);
241
+ const title = titles.get(c.producedBy);
242
+ const domain = nonEmpty(spec.domain);
243
+ const contextDomain = nonEmpty(spec.contextDomain);
244
+ return {
245
+ columnId: c.columnId,
246
+ ...(c.ref !== undefined ? { ref: c.ref } : {}),
247
+ ...(c.path !== undefined ? { path: c.path } : {}),
248
+ exportName: c.exportName,
249
+ producedBy: { blockId: c.producedBy, ...(title !== undefined ? { label: title } : {}) },
250
+ name: spec.name,
251
+ ...(label !== undefined ? { label } : {}),
252
+ valueType: spec.valueType,
253
+ axes: spec.axesSpec.map((a) => axisEntry(a, full)),
254
+ ...(domain !== undefined ? { domain } : {}),
255
+ ...(contextDomain !== undefined ? { contextDomain } : {}),
256
+ ...(full && spec.annotations !== undefined ? { annotations: spec.annotations } : {}),
257
+ };
258
+ }
259
+
260
+ /** The result-pool columns of a project, filtered and paged (`list_pool_columns`). */
261
+ export async function listPoolColumnsResult(
262
+ project: PoolProject,
263
+ projectId: ProjectId,
264
+ input: PoolListInput,
265
+ ) {
266
+ const read = await readPool(project, projectId, input);
267
+ if (read.error) return read.error;
268
+ const { pool, titles } = read;
269
+ const matching = pool.columns;
270
+ const offset = input.offset ?? 0;
271
+ const limit = input.limit ?? POOL_COLUMNS_DEFAULT;
272
+ const pageItems = matching.slice(offset, offset + limit);
273
+ const end = offset + pageItems.length;
274
+ const full = input.detail === "full";
275
+ return textResult(
276
+ {
277
+ total: matching.length,
278
+ offset,
279
+ hasMore: end < matching.length,
280
+ ...(end < matching.length ? { nextOffset: end } : {}),
281
+ ...(pool.isComplete ? {} : { isComplete: false, note: POOL_NOT_COMPLETE_NOTE }),
282
+ columns: pageItems.map((c) => poolColumnEntry(c, titles, full)),
283
+ },
284
+ {
285
+ hint: 'Ask for fewer columns: a smaller `limit`, `detail: "summary"` or a `selector`.',
286
+ },
287
+ );
288
+ }
289
+
290
+ /** Default timeout of a `transform` of `get_pool_column`, in milliseconds. */
291
+ const DEFAULT_TRANSFORM_TIMEOUT = 5000;
292
+
293
+ const POOL_COLUMN_TRANSFORM_VARIABLES =
294
+ "`spec`, `columnId`, `ref`, `path`, `exportName`, `producedBy`";
295
+
296
+ /**
297
+ * One column of the result pool with its whole spec (`get_pool_column`), or, with `transform`, the
298
+ * value of that expression evaluated in the sandbox against it (variables `spec`, `columnId`, `ref`,
299
+ * `path`, `exportName` and `producedBy`).
300
+ */
301
+ export async function poolColumnResult(
302
+ project: PoolProject,
303
+ projectId: ProjectId,
304
+ input: {
305
+ columnId: ColumnUniversalId;
306
+ blockId?: BlockId;
307
+ transform?: string;
308
+ transformTimeout?: number;
309
+ },
310
+ ) {
311
+ const { titles, error } = await blockTitles(project, projectId, input.blockId);
312
+ if (error !== undefined) return error;
313
+ const [column] = await project.getPoolColumnsById([input.columnId], input.blockId).getValue();
314
+ if (column === undefined)
315
+ return errorResult(
316
+ `Column ${input.columnId} is not in the result pool of project ${projectId}` +
317
+ (input.blockId !== undefined ? ` as block ${input.blockId} sees it.` : "."),
318
+ "list_pool_columns lists the column ids of the pool" +
319
+ (input.blockId !== undefined
320
+ ? "; a block sees only its own columns and those of the blocks above it"
321
+ : "") +
322
+ "; ids follow current specs: list_pool_columns again.",
323
+ );
324
+ const title = titles.get(column.producedBy);
325
+ const producedBy = {
326
+ blockId: column.producedBy,
327
+ ...(title !== undefined ? { label: title } : {}),
328
+ };
329
+ if (input.transform) {
330
+ try {
331
+ return textResult(
332
+ await safeEval(
333
+ input.transform,
334
+ {
335
+ spec: column.spec,
336
+ columnId: column.columnId,
337
+ ref: column.ref,
338
+ path: column.path,
339
+ exportName: column.exportName,
340
+ producedBy,
341
+ },
342
+ input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT,
343
+ ),
344
+ );
345
+ } catch (e: unknown) {
346
+ return transformFailedResult(
347
+ e,
348
+ `Check your JS expression syntax. Available variables: ${POOL_COLUMN_TRANSFORM_VARIABLES}.`,
349
+ );
350
+ }
351
+ }
352
+ return textResult(
353
+ {
354
+ columnId: column.columnId,
355
+ ...(column.ref !== undefined ? { ref: column.ref } : {}),
356
+ ...(column.path !== undefined ? { path: column.path } : {}),
357
+ exportName: column.exportName,
358
+ producedBy,
359
+ spec: column.spec,
360
+ },
361
+ {
362
+ hint:
363
+ "Read part of the spec with `transform`, e.g. `spec.annotations`, `spec.domain` or " +
364
+ "`spec.axesSpec[0]`.",
365
+ },
366
+ );
367
+ }
368
+
369
+ // Tools
370
+
371
+ export const WHAT_THE_POOL_IS =
372
+ "The result pool is the set of columns that blocks export for blocks below them: a block sees " +
373
+ "the columns of the blocks above it and its own.";
374
+
375
+ export function registerResultPoolTools(server: ToolRegistrar, ctx: ToolContext): void {
376
+ server.registerTool(
377
+ "list_pool_columns",
378
+ {
379
+ title: "List Result Pool Columns",
380
+ annotations: hints.read,
381
+ description:
382
+ `${WHAT_THE_POOL_IS} List those columns with their specs, a page at a time: \`{ total, ` +
383
+ "offset, hasMore, nextOffset?, isComplete?, columns: [{ columnId, ref?, path?, " +
384
+ "exportName, producedBy: { blockId, label? }, name, label?, valueType, axes: [{ name, " +
385
+ "type, domain?, label? }], " +
386
+ 'domain?, contextDomain?, annotations? }] }` (annotations with `detail: "full"`). ' +
387
+ "With `blockId`, the pool as that block sees it; without, every block's columns. " +
388
+ "Use it to see what data a project has, and to write or check the column selector of a " +
389
+ "block's model: `selector` takes `{ include?, exclude? }` exactly as a model passes them " +
390
+ 'to `ColumnsCollection(["result_pool"]).filter(…)`; the result is what the ' +
391
+ "selector matches here. `anchors` lists the columns reachable from those columns, through " +
392
+ "linker columns too, with discovered ids and the linker ids in `path`; `ref` is the " +
393
+ "object form of a leaf's `columnId`; `exportName` is the name its block exports the " +
394
+ "column under. Specs only, no values. A block's choices are in its own option outputs " +
395
+ "(get_block_outputs); a column's `ref`, or its `columnId` when it has a `ref`, fits a " +
396
+ "block field of that form (get_block_contract).",
397
+ inputSchema: z.object({
398
+ projectId: projectIdInput.describe("Project ID"),
399
+ blockId: blockIdInput
400
+ .optional()
401
+ .describe("See the pool as this block does: its own columns and those of blocks above."),
402
+ selector: poolSelectorInput
403
+ .optional()
404
+ .describe(
405
+ "`{ include?, exclude? }` of `ColumnsCollection.filter`: a `ColumnSelector` each " +
406
+ "(one selector or an array, any of which may match). A selector has `name`, " +
407
+ "`type`, `domain`, `contextDomain`, `annotations`, `axes`, `partialAxesMatch`; a " +
408
+ 'matcher is `{ type: "exact" | "regex", value }`; a plain string is a regex found ' +
409
+ "anywhere in the value, case-sensitive (`^…$` for all of it). E.g. by label " +
410
+ '`{ include: { annotations: { "pl7.app/label": "Score" } } }`; by type and axis ' +
411
+ '`{ include: { type: "Double", axes: [{ name: "pl7.app/sampleId" }] } }`.',
412
+ ),
413
+ anchors: z
414
+ .record(z.string(), poolAnchorInput)
415
+ .optional()
416
+ .describe(
417
+ "Name → anchor column: its `columnId` (as listed without anchors), its `ref`, or a " +
418
+ "selector matching one column. Lists what `ColumnsCollection.discover({ anchors })` " +
419
+ "finds from them; `selector` narrows it.",
420
+ ),
421
+ mode: z
422
+ .enum(["enrichment", "related", "exact"])
423
+ .optional()
424
+ .describe(
425
+ "With `anchors`, how axes may match theirs: `enrichment` (default), `related` " +
426
+ "(widest) or `exact`.",
427
+ ),
428
+ maxHops: z
429
+ .number()
430
+ .int()
431
+ .min(0)
432
+ .max(8)
433
+ .optional()
434
+ .describe("With `anchors`, the most linker columns on the way (default 4)."),
435
+ detail: z
436
+ .enum(["summary", "full"])
437
+ .optional()
438
+ .describe("`summary` (default): no annotations; `full`: column and axis annotations."),
439
+ ...pagingArgs("columns", POOL_COLUMNS_DEFAULT, POOL_COLUMNS_MAX),
440
+ }),
441
+ },
442
+ async ({ projectId, ...input }) =>
443
+ await ctx.withProject(projectId, (project) =>
444
+ listPoolColumnsResult(project, projectId, input),
445
+ ),
446
+ );
447
+
448
+ server.registerTool(
449
+ "get_pool_column",
450
+ {
451
+ title: "Get Result Pool Column",
452
+ annotations: hints.read,
453
+ description:
454
+ "Get one column of the result pool with its whole spec: `{ columnId, ref?, path?, " +
455
+ "exportName, producedBy: { blockId, label? }, spec }`, the spec with every " +
456
+ "domain and annotation of the column and its axes. Column ids come from " +
457
+ "list_pool_columns. Specs only, no values: get_column_values reads them. " +
458
+ "Read part of a large spec with `transform`, e.g. `spec.annotations`.",
459
+ inputSchema: z.object({
460
+ projectId: projectIdInput.describe("Project ID"),
461
+ columnId: columnIdInput.describe("Column id from list_pool_columns, or a PlRef object."),
462
+ blockId: blockIdInput
463
+ .optional()
464
+ .describe("Look the column up as this block sees the pool (default: every block's)."),
465
+ transform: z
466
+ .string()
467
+ .optional()
468
+ .describe(
469
+ "JS expression evaluated server-side against the column. Available variables: " +
470
+ `${POOL_COLUMN_TRANSFORM_VARIABLES} (\`{ blockId, label? }\`). Omit for the whole ` +
471
+ "answer.",
472
+ ),
473
+ transformTimeout: z
474
+ .number()
475
+ .optional()
476
+ .default(DEFAULT_TRANSFORM_TIMEOUT)
477
+ .describe(expressionTimeoutText("transform evaluation", DEFAULT_TRANSFORM_TIMEOUT)),
478
+ }),
479
+ },
480
+ async ({ projectId, ...input }) =>
481
+ await ctx.withProject(projectId, (project) => poolColumnResult(project, projectId, input)),
482
+ );
483
+ }
@@ -1,5 +1,5 @@
1
- import { describe, expect, it } from "vitest";
2
- import { safeEval, SandboxError } from "./sandbox";
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { MAX_EXPRESSION_TIMEOUT_MS, safeEval, SandboxError } from "./sandbox";
3
3
 
4
4
  const TIMEOUT = 5000;
5
5
 
@@ -112,12 +112,6 @@ describe("safeEval", () => {
112
112
  expect(await safeEval("rows.length + 1", ROWS, TIMEOUT)).toBe(3);
113
113
  });
114
114
 
115
- it("reports a failed context setup with the real error", async () => {
116
- const message = await failureMessage("1", { "not-an-identifier": 1 });
117
- expect(message).toMatch(/^Context setup failed: SyntaxError: /);
118
- expect(message).not.toContain("single expression");
119
- });
120
-
121
115
  it("says that the setup step timed out", async () => {
122
116
  // QuickJS calls the interrupt handler once when an evaluation starts, so a deadline already in the past
123
117
  // stops the setup step.
@@ -152,7 +146,6 @@ describe("safeEval", () => {
152
146
  "Error",
153
147
  );
154
148
  expect(await failureClass(ENDLESS_LOOP, {}, 50)).toBe("timeout");
155
- expect(await failureClass("1", { "not-an-identifier": 1 })).toBe("SyntaxError");
156
149
  });
157
150
 
158
151
  it.each([
@@ -165,7 +158,6 @@ describe("safeEval", () => {
165
158
  ["thrown function", "(() => { throw function f() {}; })()", {}, TIMEOUT],
166
159
  ["value JSON cannot hold", "10n", {}, TIMEOUT],
167
160
  ["endless loop", ENDLESS_LOOP, {}, 50],
168
- ["context setup", "1", { "not-an-identifier": 1 }, TIMEOUT],
169
161
  [
170
162
  "error without name or message",
171
163
  '(() => { const e = new Error(""); e.name = ""; throw e; })()',
@@ -180,4 +172,130 @@ describe("safeEval", () => {
180
172
  expect(message).not.toContain("[object Object]");
181
173
  },
182
174
  );
175
+
176
+ it("clamps a timeout over the limit to it", async () => {
177
+ // Every look at the clock is a second later, so the loop runs out of time at once.
178
+ let now = Date.now();
179
+ const clock = vi.spyOn(Date, "now").mockImplementation(() => (now += 1000));
180
+ try {
181
+ expect(await failureMessage(ENDLESS_LOOP, {}, 600_000)).toBe(
182
+ `Evaluation timed out after ${MAX_EXPRESSION_TIMEOUT_MS} ms`,
183
+ );
184
+ } finally {
185
+ clock.mockRestore();
186
+ }
187
+ });
188
+
189
+ it("gives null for an expression whose value is undefined, not a host error", async () => {
190
+ expect(await safeEval("outputs.missing?.value", { outputs: {} }, TIMEOUT)).toBeNull();
191
+ expect(await safeEval("undefined", {}, TIMEOUT)).toBeNull();
192
+ expect(await safeEval("() => 1", {}, TIMEOUT)).toBeNull();
193
+ });
194
+
195
+ it("takes an expression that ends in a line comment", async () => {
196
+ expect(await safeEval("rows.length // how many", ROWS, TIMEOUT)).toBe(2);
197
+ });
198
+
199
+ it("gives the expression only the variables it names", async () => {
200
+ // `big` would not fit in the sandbox; an expression that does not name it never pays for it.
201
+ const big = "x".repeat(20 * 1024 * 1024);
202
+ expect(await safeEval("rows.length", { ...ROWS, big }, TIMEOUT)).toBe(2);
203
+ expect(await failureMessage("missing", { rows: [] })).toMatch(/ReferenceError/);
204
+ });
205
+
206
+ it("gives only the outputs the expression reads by name", async () => {
207
+ const big = "x".repeat(20 * 1024 * 1024);
208
+ const outputs = { qc: { ok: true, value: 7 }, table: { ok: true, value: big } };
209
+ expect(await safeEval("outputs.qc?.value", { outputs }, TIMEOUT)).toBe(7);
210
+ expect(await safeEval('outputs["qc"].value + 1', { outputs }, TIMEOUT)).toBe(8);
211
+ // A key computed at run time is read alone too.
212
+ expect(await safeEval('outputs["q" + "c"].value', { outputs }, TIMEOUT)).toBe(7);
213
+ expect(await safeEval("Object.keys(outputs)", { outputs }, TIMEOUT)).toEqual(["qc", "table"]);
214
+ });
215
+
216
+ it("reads a record as a plain object: keys, `in`, spread, JSON", async () => {
217
+ const data = JSON.parse('{"a": 1, "__proto__": {"b": 2}}') as Record<string, unknown>;
218
+ expect(await safeEval('"a" in data && !("z" in data)', { data }, TIMEOUT)).toBe(true);
219
+ expect(await safeEval("({ ...data, c: 3 })", { data }, TIMEOUT)).toEqual(
220
+ JSON.parse('{"a": 1, "__proto__": {"b": 2}, "c": 3}'),
221
+ );
222
+ expect(await safeEval("JSON.stringify(data)", { data }, TIMEOUT)).toBe(JSON.stringify(data));
223
+ expect(await safeEval("data.hasOwnProperty('a')", { data }, TIMEOUT)).toBe(true);
224
+ });
225
+
226
+ describe("keeps the writes of an expression, as on a plain object", () => {
227
+ const current = () => ({ x: 1, nested: { y: 1 }, list: [1], gone: true });
228
+ /** Runs the statements `body` and returns `variable` after them. */
229
+ const after = (variable: string, body: string) =>
230
+ safeEval(`(() => { ${body}; return ${variable}; })()`, { [variable]: current() }, TIMEOUT);
231
+
232
+ // `outputs` as a read transform names it, `data` as an update of the block's data does.
233
+ describe.each(["outputs", "data"])("of %s", (v) => {
234
+ it("an assignment", async () => {
235
+ expect(await after(v, `${v}.x = 2`)).toEqual({ ...current(), x: 2 });
236
+ });
237
+
238
+ it("a nested assignment, before and after a change of the record itself", async () => {
239
+ expect(await after(v, `${v}.nested.y = 2`)).toEqual({ ...current(), nested: { y: 2 } });
240
+ expect(await after(v, `${v}.nested.y = 2; ${v}.x = 2; ${v}.nested.z = 3`)).toEqual({
241
+ ...current(),
242
+ x: 2,
243
+ nested: { y: 2, z: 3 },
244
+ });
245
+ });
246
+
247
+ it("a delete", async () => {
248
+ const { gone: _, ...rest } = current();
249
+ expect(await after(v, `delete ${v}.gone`)).toEqual(rest);
250
+ expect(
251
+ await safeEval(`delete ${v}.gone && "gone" in ${v}`, { [v]: current() }, TIMEOUT),
252
+ ).toBe(false);
253
+ });
254
+
255
+ it("an added key", async () => {
256
+ expect(await after(v, `${v}.added = 3`)).toEqual({ ...current(), added: 3 });
257
+ });
258
+
259
+ it("a push to an array", async () => {
260
+ expect(await after(v, `${v}.list.push(2)`)).toEqual({ ...current(), list: [1, 2] });
261
+ });
262
+
263
+ it("the keys and a spread after writes", async () => {
264
+ const writes = `${v}.x = 2; delete ${v}.gone; ${v}.added = 3`;
265
+ expect(await after(v, writes)).toEqual({
266
+ x: 2,
267
+ nested: { y: 1 },
268
+ list: [1],
269
+ added: 3,
270
+ });
271
+ expect(
272
+ await safeEval(
273
+ `(() => { ${writes}; return Object.keys(${v}); })()`,
274
+ { [v]: current() },
275
+ TIMEOUT,
276
+ ),
277
+ ).toEqual(["x", "nested", "list", "added"]);
278
+ expect(
279
+ await safeEval(
280
+ `(() => { ${writes}; return { ...${v} }; })()`,
281
+ { [v]: current() },
282
+ TIMEOUT,
283
+ ),
284
+ ).toEqual({ x: 2, nested: { y: 1 }, list: [1], added: 3 });
285
+ });
286
+
287
+ it("a frozen record and an assigned variable", async () => {
288
+ expect(await after(v, `${v}.x = 2; Object.freeze(${v})`)).toEqual({ ...current(), x: 2 });
289
+ expect(await after(v, `${v} = { ...${v}, x: 2 }`)).toEqual({ ...current(), x: 2 });
290
+ });
291
+ });
292
+ });
293
+
294
+ it("says how to read less when the values do not fit in the sandbox", async () => {
295
+ const big = "x".repeat(20 * 1024 * 1024);
296
+ const outputs = { qc: { ok: true, value: 7 }, table: { ok: true, value: big } };
297
+ const message = await failureMessage("Object.values(outputs)", { outputs });
298
+ expect(message).toMatch(/out of memory/i);
299
+ expect(message).toContain("outputs.<key>?.value");
300
+ });
183
301
  });