@milaboratories/pl-mcp-server 53.1.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 +30 -37
  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 +16 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +16 -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 +122 -0
  14. package/dist/project-holds.cjs.map +1 -0
  15. package/dist/project-holds.js +122 -0
  16. package/dist/project-holds.js.map +1 -0
  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 +48 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +48 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +71 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +37 -24
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +71 -19
  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 -72
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -74
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +14 -9
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +14 -9
  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 +275 -6
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +273 -8
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +343 -57
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +337 -61
  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 +199 -76
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +193 -76
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +470 -101
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +465 -106
  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 +72 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +63 -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 +111 -30
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +108 -31
  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 +68 -38
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +69 -40
  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 +16 -12
  143. package/src/project-holds.test.ts +362 -0
  144. package/src/project-holds.ts +207 -0
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +71 -6
  148. package/src/server-log.ts +58 -27
  149. package/src/server.logging.test.ts +46 -51
  150. package/src/server.test.ts +166 -22
  151. package/src/server.ts +97 -37
  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 -122
  156. package/src/tools/block-action-context.ts +17 -13
  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 +626 -10
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +678 -83
  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 +354 -113
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +839 -145
  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 +89 -1
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +154 -44
  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 +136 -48
  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 +84 -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,7 +1,509 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { BlockId } from "@milaboratories/pl-model-common";
3
+ import type {
4
+ BlockPackSpecAny,
5
+ BlockParamsModel,
6
+ DescribedBlockPack,
7
+ VersionedBlockData,
8
+ } from "@milaboratories/pl-middle-layer";
9
+ import { BlockKindRef, KindContractFileName } from "@milaboratories/pl-middle-layer";
10
+ import type { BlockKindReference } from "@platforma-sdk/model";
1
11
  import { z } from "zod";
12
+ import { blockSpecInput, centralBlockRegistryUrl } from "./blocks";
13
+ import { SDK_TYPES } from "./sdk-types";
2
14
  import { projectIdInput, blockIdInput } from "./ids";
3
- import type { ToolContext, ToolRegistrar } from "./types";
4
- import { hints, textResult } from "./types";
15
+ import { expressionTimeoutText, safeEval } from "./sandbox";
16
+ import type { AuthorMarker, ToolContext, ToolRegistrar } from "./types";
17
+ import { errorResult, hints, textResult, transformFailedResult } from "./types";
18
+ import { findBlock } from "./readiness";
19
+ import {
20
+ type BlockDataProject,
21
+ type ComputeNext,
22
+ DEFAULT_EXPRESSION_TIMEOUT,
23
+ refuse,
24
+ settleAfterChange,
25
+ type WriteOutcome,
26
+ type WriteRefused,
27
+ WRITE_WAIT_DEFAULT_MS,
28
+ WRITE_WAIT_MAX_MS,
29
+ WRITE_WAIT_MIN_MS,
30
+ writeBlockData,
31
+ } from "./block-state";
32
+ import { type DataVersion, diffValues, readStorageView } from "./block-storage";
33
+ import { clampWait } from "./settle";
34
+ import { unsupportedBlockApiResult } from "./block-api";
35
+ import { mergeThreeWay } from "./params-merge";
36
+
37
+ /** The most conflicting or differing paths a refusal of set_block_params names. */
38
+ const MAX_NAMED_PATHS = 20;
39
+
40
+ /** Where a refusal of set_block_params sends the agent. */
41
+ const USE_SET_BLOCK_DATA =
42
+ "Write the block's data with set_block_data instead: read it with get_block_state, change it " +
43
+ "and write it back.";
44
+
45
+ /** What {@link writeBlockParams} needs of a project; a `Project` of the middle layer has it. */
46
+ export type BlockParamsProject = BlockDataProject & {
47
+ getBlockParamsModel(blockId: BlockId): Promise<BlockParamsModel>;
48
+ };
49
+
50
+ const setBlockParamsInput = z.object({
51
+ projectId: projectIdInput.describe("Project ID"),
52
+ blockId: blockIdInput.describe("Block ID"),
53
+ params: z
54
+ .unknown()
55
+ .optional()
56
+ .describe(
57
+ "The whole new params of the block's kind: the value get_block_params returned, changed. " +
58
+ "Not a patch. Give `params` or `update`, not both.",
59
+ ),
60
+ update: z
61
+ .string()
62
+ .optional()
63
+ .describe(
64
+ "Instead of `params`: a JS expression evaluated in the server against the current params, " +
65
+ "available as `params`; its value is the whole new params. " +
66
+ "Example: `({ ...params, threshold: 2 })`.",
67
+ ),
68
+ updateTimeout: z
69
+ .number()
70
+ .optional()
71
+ .describe(expressionTimeoutText("the `update` expression", DEFAULT_EXPRESSION_TIMEOUT)),
72
+ wait: z
73
+ .boolean()
74
+ .optional()
75
+ .describe(
76
+ "Wait for the block's outputs to settle on the new data before answering (default true).",
77
+ ),
78
+ timeout: z
79
+ .number()
80
+ .optional()
81
+ .describe(
82
+ `The longest wait in ms (default ${WRITE_WAIT_DEFAULT_MS}, at most ${WRITE_WAIT_MAX_MS}).`,
83
+ ),
84
+ });
85
+
86
+ /** Input of the `set_block_params` tool. */
87
+ export type SetBlockParamsInput = z.infer<typeof setBlockParamsInput>;
88
+
89
+ /**
90
+ * Writes a block's configuration as its kind's params (D-040, Q-047, D-045). A block whose model
91
+ * declares `applyParams` puts the new params `p1` onto its current data itself. For any other
92
+ * block the new data is a three-way merge ({@link mergeThreeWay}): base `init(p0)` from the current
93
+ * params `p0 = templateParams(data)`, theirs `init(p1)` from the new params, ours the current data.
94
+ * Refused, with nothing written, when the block gives no params, its data waits for a migration,
95
+ * the kind rejects `p1`, the merge conflicts, or the new data does not give back the params of
96
+ * `init(p1)`.
97
+ *
98
+ * The write is {@link writeBlockData}'s: one at a time per block.
99
+ */
100
+ export async function writeBlockParams(
101
+ project: BlockParamsProject,
102
+ author: AuthorMarker,
103
+ input: Omit<SetBlockParamsInput, "projectId" | "wait" | "timeout">,
104
+ ): Promise<WriteOutcome> {
105
+ const { blockId, params, update, updateTimeout } = input;
106
+ if ((params === undefined) === (update === undefined))
107
+ return refuse(
108
+ errorResult(
109
+ "Give either `params` or `update`. Nothing was changed.",
110
+ "`params` is the whole new params; `update` is an expression computing them from the " +
111
+ "current ones.",
112
+ ),
113
+ );
114
+
115
+ const computeNext: ComputeNext = async (current, rawStorage) => {
116
+ let found: BlockParamsModel;
117
+ try {
118
+ found = await project.getBlockParamsModel(blockId);
119
+ } catch (e: unknown) {
120
+ const unsupported = unsupportedBlockApiResult(e);
121
+ if (unsupported) return refuse(unsupported);
122
+ throw e;
123
+ }
124
+ return await mergeParams(found, blockId, current, readStorageView(rawStorage).dataVersion, {
125
+ params,
126
+ update,
127
+ updateTimeout,
128
+ });
129
+ };
130
+ return await writeBlockData(project, author, { blockId, computeNext });
131
+ }
132
+
133
+ /** The data set_block_params writes over `current` (at `dataVersion`), or why it writes none. */
134
+ async function mergeParams(
135
+ model: BlockParamsModel,
136
+ blockId: BlockId,
137
+ current: unknown,
138
+ dataVersion: DataVersion,
139
+ input: Pick<SetBlockParamsInput, "params" | "update" | "updateTimeout">,
140
+ ): Promise<WriteRefused | { kind: "next"; next: unknown }> {
141
+ if (!model.givesParams)
142
+ return refuse(
143
+ errorResult(
144
+ `Block ${blockId} gives no params: this version of the block was built before blocks ` +
145
+ "had them. Nothing was changed.",
146
+ USE_SET_BLOCK_DATA,
147
+ ),
148
+ );
149
+ if (dataVersion === undefined)
150
+ return refuse(
151
+ errorResult(
152
+ `Block ${blockId} keeps no versioned data yet, so its params cannot be merged into it. ` +
153
+ "Nothing was changed.",
154
+ USE_SET_BLOCK_DATA,
155
+ ),
156
+ );
157
+ if (typeof dataVersion !== "string")
158
+ return refuse(
159
+ errorResult(
160
+ `Block ${blockId} keeps its data in the format of an early SDK release, so its params ` +
161
+ "cannot be merged into it. Nothing was changed.",
162
+ USE_SET_BLOCK_DATA,
163
+ ),
164
+ );
165
+
166
+ const p0 = model.paramsOf({ dataVersion, data: current });
167
+ if (p0.error !== undefined)
168
+ return refuse(
169
+ errorResult(
170
+ `The block's model could not derive its params from its data: ${p0.error.message}. ` +
171
+ "Nothing was changed.",
172
+ USE_SET_BLOCK_DATA,
173
+ ),
174
+ );
175
+
176
+ const p1 = await newParams(p0.value, input);
177
+ if (p1.kind === "refused") return p1;
178
+
179
+ if (model.appliesParams) return appliedParams(model, current, dataVersion, p1.params);
180
+
181
+ const base = model.dataOf(p0.value);
182
+ if (base.error !== undefined)
183
+ return refuse(
184
+ errorResult(
185
+ "The block's model cannot build its data from its own current params: " +
186
+ `${base.error.message}. Nothing was changed.`,
187
+ USE_SET_BLOCK_DATA,
188
+ ),
189
+ );
190
+ if (base.value.dataVersion !== dataVersion)
191
+ return refuse(
192
+ errorResult(
193
+ `The block's data is at version ${dataVersion}; its model builds version ` +
194
+ `${base.value.dataVersion}, so the data waits for a migration. Nothing was changed.`,
195
+ USE_SET_BLOCK_DATA,
196
+ ),
197
+ );
198
+
199
+ const theirs = model.dataOf(p1.params);
200
+ if (theirs.error !== undefined)
201
+ return refuse(
202
+ errorResult(
203
+ `The block does not accept these params: ${theirs.error.message}. Nothing was changed.`,
204
+ "get_block_params gives the current params; change them and send them whole.",
205
+ ),
206
+ );
207
+
208
+ const { merged, conflicts } = mergeThreeWay(base.value.data, theirs.value.data, current);
209
+ if (conflicts.length > 0)
210
+ return refuse(
211
+ errorResult(
212
+ "The new params change parts of the block's data that also hold changes the params do " +
213
+ `not describe: ${named(conflicts)}. Nothing was changed.`,
214
+ USE_SET_BLOCK_DATA,
215
+ ),
216
+ );
217
+
218
+ // The merged data must give back what the new params alone give: otherwise the merge kept
219
+ // something of the current data that overrides the new params.
220
+ const refused = givesParamsBack(model, theirs.value, { dataVersion, data: merged }, (paths) =>
221
+ errorResult(
222
+ "The block's data merged with the new params would not give these params back; they " +
223
+ `differ at ${paths}. Nothing was changed.`,
224
+ USE_SET_BLOCK_DATA,
225
+ ),
226
+ );
227
+ if (refused !== undefined) return refused;
228
+
229
+ return { kind: "next", next: merged };
230
+ }
231
+
232
+ /**
233
+ * The data a block that declares `applyParams` writes: `applyParams(current, p1)`, by the block's
234
+ * own model (D-045), which refuses params the kind rejects and data waiting for a migration.
235
+ * Refused too when the new data does not give back the params `init(p1)` gives.
236
+ */
237
+ function appliedParams(
238
+ model: BlockParamsModel,
239
+ current: unknown,
240
+ dataVersion: string,
241
+ p1: unknown,
242
+ ): WriteRefused | { kind: "next"; next: unknown } {
243
+ const next = model.applyParams({ dataVersion, data: current }, p1);
244
+ if (next.error !== undefined)
245
+ return refuse(
246
+ errorResult(
247
+ `The block's applyParams could not put these params onto its data: ${next.error.message}. ` +
248
+ "Nothing was changed.",
249
+ USE_SET_BLOCK_DATA,
250
+ ),
251
+ );
252
+
253
+ // The law the server keeps checking: params put onto any data project back as they do onto
254
+ // the defaults. A block that breaks it would write data that does not say what was asked.
255
+ const theirs = model.dataOf(p1);
256
+ if (theirs.error !== undefined)
257
+ return refuse(
258
+ errorResult(
259
+ `The block's model cannot build its data from these params: ${theirs.error.message}. ` +
260
+ "Nothing was changed.",
261
+ USE_SET_BLOCK_DATA,
262
+ ),
263
+ );
264
+ const refused = givesParamsBack(model, theirs.value, next.value, (paths) =>
265
+ errorResult(
266
+ "The block's applyParams does not give its params back: the data it builds from the " +
267
+ `current data and these params gives other params than these, at ${paths}. Nothing was ` +
268
+ "changed.",
269
+ USE_SET_BLOCK_DATA,
270
+ ),
271
+ );
272
+ if (refused !== undefined) return refused;
273
+
274
+ return { kind: "next", next: next.value.data };
275
+ }
276
+
277
+ /**
278
+ * Nothing when `next` gives back the params `theirs` (the data of the new params alone) gives;
279
+ * otherwise the refusal `differ` makes of the named paths where they differ, or one naming why
280
+ * params could not be derived.
281
+ */
282
+ function givesParamsBack(
283
+ model: BlockParamsModel,
284
+ theirs: VersionedBlockData,
285
+ next: VersionedBlockData,
286
+ differ: (paths: string) => ReturnType<typeof errorResult>,
287
+ ): WriteRefused | undefined {
288
+ const wanted = model.paramsOf(theirs);
289
+ const got = model.paramsOf(next);
290
+ if (wanted.error !== undefined || got.error !== undefined)
291
+ return refuse(
292
+ errorResult(
293
+ "The block's model could not derive params from the new data: " +
294
+ `${(wanted.error ?? got.error)?.message}. Nothing was changed.`,
295
+ USE_SET_BLOCK_DATA,
296
+ ),
297
+ );
298
+ if (!isDeepStrictEqual(wanted.value, got.value))
299
+ return refuse(
300
+ differ(
301
+ named(diffValues(wanted.value, got.value, MAX_NAMED_PATHS).changes.map((c) => c.path)),
302
+ ),
303
+ );
304
+ return undefined;
305
+ }
306
+
307
+ /** The new params: `params`, or the value of `update` over the current params `p0`. */
308
+ async function newParams(
309
+ p0: unknown,
310
+ input: Pick<SetBlockParamsInput, "params" | "update" | "updateTimeout">,
311
+ ): Promise<WriteRefused | { kind: "params"; params: unknown }> {
312
+ if (input.update === undefined) return { kind: "params", params: input.params };
313
+ let value: unknown;
314
+ try {
315
+ value = await safeEval(
316
+ input.update,
317
+ { params: p0 },
318
+ input.updateTimeout ?? DEFAULT_EXPRESSION_TIMEOUT,
319
+ );
320
+ } catch (e: unknown) {
321
+ return refuse(
322
+ transformFailedResult(
323
+ e,
324
+ "Nothing was changed. The expression gets the current params as `params` and must " +
325
+ "return the whole new params, e.g. `({ ...params, key: 1 })`.",
326
+ ),
327
+ );
328
+ }
329
+ if (value === undefined || value === null)
330
+ return refuse(
331
+ errorResult(
332
+ "The `update` expression returned no value. Nothing was changed.",
333
+ "Return the whole new params, e.g. `({ ...params, key: 1 })`.",
334
+ ),
335
+ );
336
+ return { kind: "params", params: value };
337
+ }
338
+
339
+ /** The first {@link MAX_NAMED_PATHS} of `paths`, and how many more there are. */
340
+ function named(paths: string[]): string {
341
+ const shown = paths.slice(0, MAX_NAMED_PATHS).join(", ");
342
+ return paths.length > MAX_NAMED_PATHS
343
+ ? `${shown} and ${paths.length - MAX_NAMED_PATHS} more`
344
+ : shown;
345
+ }
346
+
347
+ const getBlockContractInput = z.object({
348
+ spec: blockSpecInput.describe("The block, named as for add_block"),
349
+ });
350
+
351
+ /** Input of the `get_block_contract` tool. */
352
+ export type GetBlockContractInput = z.infer<typeof getBlockContractInput>;
353
+
354
+ /** What `get_block_contract` needs from the application. */
355
+ export type GetBlockContractDeps = {
356
+ /** Resolves a kind reference to the block implementing it; throws when there is none. */
357
+ resolveKind: (
358
+ kind: BlockKindReference,
359
+ registryUrl: string | undefined,
360
+ allowUnstable: boolean,
361
+ ) => Promise<BlockPackSpecAny>;
362
+ describeBlockPack: (spec: BlockPackSpecAny) => Promise<DescribedBlockPack>;
363
+ };
364
+
365
+ function errorMessage(e: unknown): string {
366
+ return e instanceof Error ? e.message : String(e);
367
+ }
368
+
369
+ /** Thrown by the block registry reader when the registry answered, but not with the file. */
370
+ function isRegistryReadError(e: unknown): boolean {
371
+ return e instanceof Error && e.name === "RegistryReadError";
372
+ }
373
+
374
+ /** The size over which `get_block_contract` returns where the declaration is, not its text. */
375
+ export const DECLARATION_CAP_BYTES = 16 * 1024;
376
+
377
+ const REGISTRY_HINT =
378
+ "The registry could not be read; this says nothing about the kind. Try again.";
379
+
380
+ /**
381
+ * Returns the declaration of the kind the block in `input` implements, whose type argument of
382
+ * `kind` is what `params` of add_block accepts. A kind built before kinds carried a declaration
383
+ * agents read gets a note and where to look instead.
384
+ */
385
+ export async function getBlockContract(deps: GetBlockContractDeps, input: GetBlockContractInput) {
386
+ const { spec } = input;
387
+
388
+ let blockPackSpec: BlockPackSpecAny;
389
+ if (spec.type === "kind") {
390
+ try {
391
+ blockPackSpec = await deps.resolveKind(
392
+ BlockKindRef.parse(spec.kind),
393
+ spec.registryUrl,
394
+ spec.allowUnstable ?? false,
395
+ );
396
+ } catch (e: unknown) {
397
+ return isRegistryReadError(e)
398
+ ? errorResult(`Kind "${spec.kind}" was not resolved: ${errorMessage(e)}`, REGISTRY_HINT)
399
+ : errorResult(
400
+ `Kind "${spec.kind}" was not resolved to a block: ${errorMessage(e)}`,
401
+ "Check the kind name and version. Pass allowUnstable: true if the block is not " +
402
+ "published to the stable channel, or registryUrl if it lives in another registry.",
403
+ );
404
+ }
405
+ } else {
406
+ blockPackSpec = spec;
407
+ }
408
+
409
+ let described: DescribedBlockPack;
410
+ try {
411
+ described = await deps.describeBlockPack(blockPackSpec);
412
+ } catch (e: unknown) {
413
+ return errorResult(
414
+ `The block was not read: ${errorMessage(e)}`,
415
+ isRegistryReadError(e) ? REGISTRY_HINT : undefined,
416
+ );
417
+ }
418
+
419
+ if (described.kind === undefined)
420
+ return textResult({
421
+ notes: ["This block declares no kind, so add_block takes no params for it."],
422
+ });
423
+ const declaredKind = described.declaredKind;
424
+ const identity = {
425
+ kind: described.kind,
426
+ ...(declaredKind !== undefined && declaredKind !== described.kind ? { declaredKind } : {}),
427
+ };
428
+ const declaration = described.declaration;
429
+ if (declaration === undefined) {
430
+ if (declaredKind === undefined)
431
+ return textResult({
432
+ ...identity,
433
+ notes: ["Kind declarations are read only for registry and dev blocks."],
434
+ });
435
+ const { legacyDeclarationUrl: url, homepage } = described;
436
+ return textResult({
437
+ ...identity,
438
+ ...(url !== undefined ? { declarationUrl: url } : {}),
439
+ ...(homepage !== undefined ? { homepage } : {}),
440
+ notes: [
441
+ `Kind ${declaredKind} has no ${KindContractFileName}: it was built before kinds carried ` +
442
+ "a declaration agents can read. " +
443
+ (spec.type === "dev-v2"
444
+ ? "Rebuilding the kind package with a current @milaboratories/ts-builder adds one."
445
+ : "One comes with the next release of the block.") +
446
+ (url !== undefined
447
+ ? " `declarationUrl` is its kind.d.ts, with every dependency inlined (tens of KB); " +
448
+ "the params are the type argument of `kind`."
449
+ : "") +
450
+ (homepage !== undefined ? " The block's homepage is `homepage`." : ""),
451
+ ],
452
+ });
453
+ }
454
+
455
+ const bytes = Buffer.byteLength(declaration.text, "utf8");
456
+ if (bytes > DECLARATION_CAP_BYTES)
457
+ return textResult({
458
+ ...identity,
459
+ source: KindContractFileName,
460
+ declarationBytes: bytes,
461
+ declarationUrl: declaration.url,
462
+ notes: [
463
+ `The declaration is ${bytes} bytes, over the ${DECLARATION_CAP_BYTES} this tool ` +
464
+ "returns. Read it at `declarationUrl`.",
465
+ ],
466
+ });
467
+
468
+ return textResult({
469
+ ...identity,
470
+ source: KindContractFileName,
471
+ declaration: declaration.text,
472
+ sdkTypes: SDK_TYPES,
473
+ });
474
+ }
475
+
476
+ /** Default timeout of a `transform` of `get_block_params`, in milliseconds. */
477
+ const DEFAULT_TRANSFORM_TIMEOUT = 5000;
478
+
479
+ /**
480
+ * The answer of `get_block_params`: the block's kind and params, or, with `transform`, the value
481
+ * of that expression evaluated in the sandbox against them (variables `kind` and `params`).
482
+ */
483
+ export async function blockParamsResult(
484
+ initialization: { kind: BlockKindReference | undefined; params: unknown },
485
+ transform: string | undefined,
486
+ transformTimeout: number,
487
+ ) {
488
+ if (!transform)
489
+ return textResult(initialization, {
490
+ hint: "Read part of the params with `transform`, e.g. `params.<key>`.",
491
+ });
492
+ try {
493
+ return textResult(
494
+ await safeEval(
495
+ transform,
496
+ { kind: initialization.kind, params: initialization.params },
497
+ transformTimeout,
498
+ ),
499
+ );
500
+ } catch (e: unknown) {
501
+ return transformFailedResult(
502
+ e,
503
+ "Check your JS expression syntax. Available variables: kind, params.",
504
+ );
505
+ }
506
+ }
5
507
 
6
508
  export function registerBlockParamsTools(server: ToolRegistrar, ctx: ToolContext): void {
7
509
  server.registerTool(
@@ -12,18 +514,132 @@ export function registerBlockParamsTools(server: ToolRegistrar, ctx: ToolContext
12
514
  description:
13
515
  "Get a block's configuration as the initialization params of its kind: what a project " +
14
516
  "template stores for this block. The block's own model derives them from its current data. " +
15
- "Pass the result as `params` of add_block, with a block of the same kind, to create a " +
16
- "block configured the same way. Read-only: params usually leave out view state, so to " +
17
- "change an existing block use get_block_state and set_block_data.\n\n" +
18
- "Returns `{ kind, params }`. `kind` is absent for a block that declares none.",
517
+ "Change them with set_block_params. Pass the result as `params` of add_block, with a " +
518
+ "block of the same kind, to create a block configured the same way. Params leave out " +
519
+ "view state (table filters, plot settings) and values that do not travel in a template, " +
520
+ "such as file handles and per-sample values. The kind may still accept them: " +
521
+ "set_block_params writes them, get_block_state shows them.\n\n" +
522
+ "Returns `{ kind, params }`. `kind` is absent for a block that declares none. Read " +
523
+ "part of large params with `transform`, e.g. `params.settings`.",
19
524
  inputSchema: z.object({
20
- projectId: projectIdInput.describe("Project ID (must be opened)"),
525
+ projectId: projectIdInput.describe("Project ID"),
21
526
  blockId: blockIdInput.describe("Block ID"),
527
+ transform: z
528
+ .string()
529
+ .optional()
530
+ .describe(
531
+ "JS expression evaluated server-side against the params. Available variables: " +
532
+ "`kind` (the block's kind), `params` (its params). Omit for `{ kind, params }`.",
533
+ ),
534
+ transformTimeout: z
535
+ .number()
536
+ .optional()
537
+ .default(DEFAULT_TRANSFORM_TIMEOUT)
538
+ .describe(expressionTimeoutText("transform evaluation", DEFAULT_TRANSFORM_TIMEOUT)),
22
539
  }),
23
540
  },
24
- async ({ projectId, blockId }) => {
25
- const project = await ctx.getOpenedProject(projectId);
26
- return textResult(await project.getBlockInitializationParams(blockId));
541
+ async ({ projectId, blockId, transform, transformTimeout }) => {
542
+ return await ctx.withProject(projectId, async (project) => {
543
+ const { error } = await findBlock(project, projectId, blockId);
544
+ if (error) return error;
545
+ return await blockParamsResult(
546
+ await project.getBlockInitializationParams(blockId),
547
+ transform,
548
+ transformTimeout,
549
+ );
550
+ });
551
+ },
552
+ );
553
+
554
+ server.registerTool(
555
+ "get_block_contract",
556
+ {
557
+ title: "Get Block Contract",
558
+ annotations: hints.read,
559
+ description:
560
+ "Get the params a block kind accepts at creation: the kind's TypeScript declaration " +
561
+ `(\`${KindContractFileName}\`), ` +
562
+ "where `params` of add_block is the type argument of the exported `kind` " +
563
+ "(usually `BlockParams`). `spec` names the block as add_block does. This describes " +
564
+ "creation params only; the data of an existing block is read with get_block_state.\n\n" +
565
+ "Returns `{ kind, source, declaration, sdkTypes, notes? }`. `declaration` is the whole " +
566
+ "file: the kind's own types, with the SDK types they use imported; `sdkTypes` declares " +
567
+ "the SDK types kinds use in short form. For a column or value id it names the form (PlRef object, " +
568
+ "GlobalPObjectId string, leaf PObjectId, any ColumnUniversalId, ColumnValueId) and the " +
569
+ "tool that gives it; ids go into params as written, the server never narrows one to its " +
570
+ "leaf. Over 16 KB, `declaration` is replaced by `declarationBytes` and `declarationUrl`. " +
571
+ "A kind published before kinds carried this declaration returns no `declaration`: a " +
572
+ "note says so, with `declarationUrl` of its published file and the block's `homepage` " +
573
+ "when it names one.",
574
+ inputSchema: getBlockContractInput,
575
+ },
576
+ async (input) => {
577
+ const ml = ctx.requireMl();
578
+ return await getBlockContract(
579
+ {
580
+ resolveKind: (kind, registryUrl, allowUnstable) =>
581
+ ml.blockRegistryProvider
582
+ .getRegistry(registryUrl ?? centralBlockRegistryUrl())
583
+ .resolveKind(kind, { allowUnstable }),
584
+ describeBlockPack: (spec) => ml.describeBlockPack(spec),
585
+ },
586
+ input,
587
+ );
588
+ },
589
+ );
590
+
591
+ server.registerTool(
592
+ "set_block_params",
593
+ {
594
+ title: "Set Block Params",
595
+ annotations: hints.destructive,
596
+ description:
597
+ "Configure a block through its kind's params, the values get_block_params returns. " +
598
+ "Send the whole new `params`, or `update`, an expression the server evaluates against " +
599
+ "the current params. A block that puts params onto its data itself does so; for any " +
600
+ "other, its model builds data from the new params and the server merges it into the " +
601
+ "current data. Either way what the params changed is written, the rest " +
602
+ "(view state such as table filters and plot settings) is kept. Elements of lists that " +
603
+ "carry an `id` follow their id in the merge. A write equal to the current data is skipped " +
604
+ "(`unchanged: true`). The write re-derives the block's args; the block's results, and " +
605
+ "those of blocks below it, become stale until they run again.\n\n" +
606
+ "Refused, with nothing changed, when the block is not on the current block API, gives no " +
607
+ "params, its data waits for a " +
608
+ "migration, the block rejects the params, the new params change a part of the data that " +
609
+ "also holds other changes, or the new data would not give the params back; the error " +
610
+ "names the paths. set_block_data writes the data directly then. Keys the kind accepts " +
611
+ "but its params leave out are written too and do not show in get_block_params " +
612
+ "afterwards: file handles (from get_file_handles), per-sample values, resource " +
613
+ "settings. Give files here when the kind accepts them; set_block_data only when it " +
614
+ "does not.\n\n" +
615
+ "By default the call then waits (up to `timeout`) for the block's outputs to settle on " +
616
+ "the new data, as set_block_data does; a wait that runs out is not an error.\n\n" +
617
+ "Result: `{ ok, unchanged?, settled, waitedMs, readiness, outputs, outputsNote?, " +
618
+ "note? }`, " +
619
+ "as set_block_data gives them, without the changed paths.",
620
+ inputSchema: setBlockParamsInput,
621
+ },
622
+ async ({ projectId, wait, timeout, ...input }, call) => {
623
+ return await ctx.withProject(projectId, async (project) => {
624
+ const author = ctx.getAuthorMarker();
625
+ const outcome = await writeBlockParams(project, author, input);
626
+ if (outcome.kind === "refused") return outcome.result;
627
+ return textResult({
628
+ ok: true,
629
+ ...(outcome.unchanged ? { unchanged: true } : {}),
630
+ ...(await settleAfterChange(project, input.blockId, {
631
+ wait: wait ?? true,
632
+ timeoutMs: clampWait(
633
+ timeout,
634
+ WRITE_WAIT_DEFAULT_MS,
635
+ WRITE_WAIT_MIN_MS,
636
+ WRITE_WAIT_MAX_MS,
637
+ ),
638
+ call,
639
+ notePrerun: true,
640
+ })),
641
+ });
642
+ });
27
643
  },
28
644
  );
29
645
  }