@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,86 +1,372 @@
1
1
  const require_types = require("./types.cjs");
2
2
  const require_ids = require("./ids.cjs");
3
+ const require_paging = require("./paging.cjs");
4
+ const require_settle = require("./settle.cjs");
3
5
  const require_tokens = require("./tokens.cjs");
6
+ const require_imports = require("./imports.cjs");
4
7
  const require_sandbox = require("./sandbox.cjs");
8
+ const require_files = require("./files.cjs");
9
+ const require_block_storage = require("./block-storage.cjs");
10
+ const require_readiness = require("./readiness.cjs");
11
+ const require_block_api = require("./block-api.cjs");
12
+ let _milaboratories_helpers = require("@milaboratories/helpers");
13
+ let node_util = require("node:util");
5
14
  let zod = require("zod");
6
- let _milaboratories_pl_errors = require("@milaboratories/pl-errors");
7
- let _platforma_sdk_model = require("@platforma-sdk/model");
8
- // src/tools/block-state.ts
15
+ /** The most characters of an output or exports error the project overview carries per block. */
16
+ const OVERVIEW_ERROR_CHARS = 300;
17
+ /** Default timeout of a `transform` or `update` expression, in milliseconds. */
18
+ const DEFAULT_EXPRESSION_TIMEOUT = 5e3;
19
+ /** The default wait of a write for the block's outputs to settle, in milliseconds. */
20
+ const WRITE_WAIT_DEFAULT_MS = 3e4;
21
+ /** The shortest wait a write may ask for. */
22
+ const WRITE_WAIT_MIN_MS = 1e3;
23
+ /** The longest wait a write may ask for: for clients whose request timeout is longer than the common 60 s. */
24
+ const WRITE_WAIT_MAX_MS = 12e4;
25
+ const setBlockDataInput = zod.z.object({
26
+ projectId: require_ids.projectIdInput.describe("Project ID"),
27
+ blockId: require_ids.blockIdInput.describe("Block ID"),
28
+ pluginId: require_ids.pluginHandleInput.optional().describe("Write the data of this plugin of the block instead of the block's own data: a handle listed under `plugins` by get_block_state."),
29
+ data: zod.z.unknown().optional().describe("The whole new data (the block's, or the plugin's with `pluginId`): the value get_block_state returned, changed. Not a patch: it replaces the stored value whole, so a change made in between by someone else (the user in the application) is overwritten. To change some fields of the current value, send `update` instead. Give `data` or `update`, not both."),
30
+ update: zod.z.string().optional().describe("Instead of `data`: a JS expression evaluated in the server against the current data, available as `data`; its value is the whole new data. Example: `({ ...data, numbers: [1, 2, 3] })`."),
31
+ removeKeys: zod.z.array(zod.z.string()).optional().describe("Top-level keys of the current data the write removes on purpose. A write that leaves out a top-level key not named here is refused."),
32
+ updateTimeout: zod.z.number().optional().describe(require_sandbox.expressionTimeoutText("the `update` expression", DEFAULT_EXPRESSION_TIMEOUT)),
33
+ wait: zod.z.boolean().optional().describe("Wait for the block's outputs to settle on the new data before answering (default true)."),
34
+ timeout: zod.z.number().optional().describe(`The longest wait in ms (default ${WRITE_WAIT_DEFAULT_MS}, at most ${WRITE_WAIT_MAX_MS}).`)
35
+ });
36
+ /**
37
+ * The `set_block_data` tool on one project: {@link writeBlockData}, then the wait for the block's
38
+ * outputs to settle on the new data ({@link settleAfterChange}). Once the value is written the
39
+ * result is `ok`, whatever the wait finds.
40
+ */
41
+ async function writeAndSettle(project, author, input, importHandles, call) {
42
+ const { wait, timeout, ...write } = input;
43
+ const outcome = await writeBlockData(project, author, write, importHandles);
44
+ if (outcome.kind === "refused") return outcome.result;
45
+ return require_types.textResult({
46
+ ok: true,
47
+ ...writeSummary(outcome),
48
+ ...await settleAfterChange(project, input.blockId, {
49
+ wait: wait ?? true,
50
+ timeoutMs: require_settle.clampWait(timeout, WRITE_WAIT_DEFAULT_MS, WRITE_WAIT_MIN_MS, WRITE_WAIT_MAX_MS),
51
+ call,
52
+ notePrerun: true
53
+ })
54
+ });
55
+ }
56
+ /** The `unchanged` and `changes` part of the result of a write. */
57
+ function writeSummary(outcome) {
58
+ return outcome.unchanged ? {
59
+ unchanged: true,
60
+ changes: []
61
+ } : outcome.changes;
62
+ }
63
+ /**
64
+ * Writes a block's data, or one plugin's data, whole (D-004, D-007). The steps:
65
+ *
66
+ * 1. the block must be in the project;
67
+ * 2. the current value is read from the block's storage; a plugin must be one the block registers;
68
+ * 3. the new value is `data`, the value of `update` evaluated against the current one, or the
69
+ * value `computeNext` gives;
70
+ * 4. guards: a plain-object value stays a plain object; no top-level key of the current value is
71
+ * dropped unless it is named in `removeKeys` (not asked of `computeNext`, which decides what
72
+ * its value keeps);
73
+ * 5. with `importHandles`, the import handles of the new value that the current one does not have
74
+ * must check out (see {@link invalidNewImportHandles});
75
+ * 6. a value equal to the current one is not written: `unchanged: true`;
76
+ * 7. one `mutateBlockStorage`: `update-block-data`, or `update-plugin-data` with `pluginId`.
77
+ *
78
+ * Writes of this server to one block run one at a time with the other changes of the block
79
+ * ({@link oneAtATime}), so each reads what the one before it wrote. A write from elsewhere
80
+ * (the application, another server) between the read of step 2 and the write of step 7 is
81
+ * overwritten: the last writer wins.
82
+ *
83
+ * Returns whether the value was written and its changed paths, or the error result of a refusal
84
+ * (nothing is written then).
85
+ */
86
+ async function writeBlockData(project, author, input, importHandles) {
87
+ return await oneAtATime(project, input.blockId, () => writeNow(project, author, input, importHandles));
88
+ }
89
+ /** The changes of this server in progress, per project and block. */
90
+ const blockQueues = /* @__PURE__ */ new WeakMap();
91
+ /**
92
+ * Runs `fn`, a change of one block of the project (its data, its block pack, its removal), after
93
+ * the changes of that block this server started before it (Q-020). Changes of the block list need
94
+ * no queue here: the middle layer runs the project's transactions one at a time.
95
+ */
96
+ async function oneAtATime(project, blockId, fn) {
97
+ let queues = blockQueues.get(project);
98
+ if (queues === void 0) {
99
+ queues = /* @__PURE__ */ new Map();
100
+ blockQueues.set(project, queues);
101
+ }
102
+ const run = (queues.get(blockId) ?? Promise.resolve()).then(fn);
103
+ const tail = run.then(() => {}, () => {});
104
+ queues.set(blockId, tail);
105
+ try {
106
+ return await run;
107
+ } finally {
108
+ if (queues.get(blockId) === tail) queues.delete(blockId);
109
+ }
110
+ }
111
+ async function writeNow(project, author, input, importHandles) {
112
+ const { blockId, pluginId, data, update, computeNext } = input;
113
+ if ([
114
+ data,
115
+ update,
116
+ computeNext
117
+ ].filter((way) => way !== void 0).length !== 1) return refuse(require_types.errorResult("Give either `data` or `update`. Nothing was changed.", "`data` is the whole new value; `update` is an expression computing it from the current one."));
118
+ const overview = await project.overview.getValue();
119
+ if (!overview) return refuse(require_types.errorResult("Project overview not available yet. Nothing was changed."));
120
+ const block = overview.blocks.find((b) => b.id === blockId);
121
+ if (!block) return refuse(require_types.errorResult(`Block ${blockId} not found. Nothing was changed.`, "Use get_project_overview to list the block IDs of the project."));
122
+ const otherApi = require_block_api.blockApiGuardResult(block);
123
+ if (otherApi) return refuse(otherApi);
124
+ const planned = await planWrite((await project.getBlockState(blockId).getValue()).blockStorage, input, importHandles);
125
+ if (planned.kind !== "write") return planned;
126
+ const { current, next } = planned;
127
+ if ((0, node_util.isDeepStrictEqual)(current, next)) return {
128
+ kind: "written",
129
+ unchanged: true,
130
+ changes: { changes: [] }
131
+ };
132
+ const payload = pluginId !== void 0 ? {
133
+ operation: "update-plugin-data",
134
+ pluginId,
135
+ value: next
136
+ } : {
137
+ operation: "update-block-data",
138
+ value: next
139
+ };
140
+ try {
141
+ await project.mutateBlockStorage(blockId, payload, author);
142
+ } catch (e) {
143
+ const unsupported = require_block_api.unsupportedBlockApiResult(e);
144
+ if (unsupported) return refuse(unsupported);
145
+ throw e;
146
+ }
147
+ return {
148
+ kind: "written",
149
+ unchanged: false,
150
+ changes: require_block_storage.diffValues(current, next)
151
+ };
152
+ }
153
+ /** A refused write with `result` as the tool's error result. */
154
+ function refuse(result) {
155
+ return {
156
+ kind: "refused",
157
+ result
158
+ };
159
+ }
160
+ /**
161
+ * Steps 2–5 of {@link writeBlockData} on the block's storage: the current value, the new one and
162
+ * the guards between them, the check of new import handles included.
163
+ */
164
+ async function planWrite(rawStorage, input, importHandles) {
165
+ const { blockId, pluginId, data, update, computeNext, removeKeys, updateTimeout } = input;
166
+ const storage = require_block_storage.readStorageView(rawStorage);
167
+ let current;
168
+ if (pluginId !== void 0) {
169
+ const plugin = require_block_storage.pluginOf(storage, pluginId);
170
+ if (plugin === void 0) {
171
+ const known = Object.keys(storage.plugins);
172
+ return refuse(require_types.errorResult(`Block ${blockId} has no plugin "${pluginId}". Nothing was changed.`, known.length > 0 ? `Its plugins: ${known.join(", ")}.` : "The block has no plugins: omit pluginId to write the block's own data."));
173
+ }
174
+ current = plugin.data;
175
+ } else current = storage.data;
176
+ let next;
177
+ if (computeNext !== void 0) {
178
+ const computed = await computeNext(current, rawStorage);
179
+ if (computed.kind === "refused") return computed;
180
+ next = computed.next;
181
+ } else if (update !== void 0) {
182
+ try {
183
+ next = await require_sandbox.safeEval(update, { data: current }, updateTimeout ?? 5e3);
184
+ } catch (e) {
185
+ return refuse(require_types.transformFailedResult(e, "Nothing was changed. The expression gets the current data as `data` and must return the whole new data, e.g. `({ ...data, key: 1 })`."));
186
+ }
187
+ if (next === void 0 || next === null) return refuse(require_types.errorResult("The `update` expression returned no value. Nothing was changed.", "Return the whole new data, e.g. `({ ...data, key: 1 })`."));
188
+ } else next = data;
189
+ if ((0, _milaboratories_helpers.isPlainObject)(current) && !(0, _milaboratories_helpers.isPlainObject)(next)) return refuse(require_types.errorResult("The current data is an object; the new data must be an object too. Nothing was changed.", "Read the data with get_block_state, change it and write the whole object back."));
190
+ const allowed = new Set(removeKeys ?? []);
191
+ const dropped = computeNext !== void 0 ? [] : require_block_storage.missingTopLevelKeys(current, next).filter((k) => !allowed.has(k));
192
+ if (dropped.length > 0) return refuse(require_types.errorResult(`The new data leaves out top-level keys of the current data: ${dropped.join(", ")}. Nothing was changed.`, "Send the whole object: read it with get_block_state, change it and write all of it back. To remove keys on purpose, name them in `removeKeys`."));
193
+ if (importHandles !== void 0) {
194
+ const invalid = await require_files.invalidNewImportHandles(importHandles, current, next);
195
+ if (invalid.length > 0) return refuse(require_files.invalidHandlesResult(invalid));
196
+ }
197
+ return {
198
+ kind: "write",
199
+ current,
200
+ next
201
+ };
202
+ }
203
+ /**
204
+ * The readiness of a block (see {@link Readiness}): the block's overview entry, those of the blocks
205
+ * above, and what its model makes of its current data. `undefined` when the project has no such
206
+ * block. A model that cannot be run leaves out what only the model says.
207
+ */
208
+ async function readinessOf(project, blockId) {
209
+ const overview = await project.overview.getValue();
210
+ const block = overview?.blocks.find((b) => b.id === blockId);
211
+ if (overview === void 0 || block === void 0) return void 0;
212
+ let model;
213
+ try {
214
+ model = await project.getBlockReadiness(blockId).getValue();
215
+ } catch {
216
+ model = void 0;
217
+ }
218
+ return require_readiness.buildReadiness(block, overview.blocks, model);
219
+ }
220
+ /**
221
+ * What a tool that changed a block adds to its result: whether the block's outputs settled on the
222
+ * change (after waiting up to `timeoutMs`), how long it waited, the readiness and an output
223
+ * summary; unsettled, what the outputs wait for.
224
+ *
225
+ * It never throws: the change is made by then, and an error result would have the agent make it
226
+ * again (a second block, a second write). A failure to read the block afterwards comes back as
227
+ * `settled: false` with `settleError`.
228
+ */
229
+ async function settleAfterChange(project, blockId, options) {
230
+ try {
231
+ return await settleNow(project, blockId, options);
232
+ } catch (e) {
233
+ return {
234
+ settled: false,
235
+ settleError: e instanceof Error ? e.message : String(e),
236
+ note: "The change was made; reading the block afterwards failed. Do not repeat the change: get_block_state shows the block."
237
+ };
238
+ }
239
+ }
240
+ async function settleNow(project, blockId, options) {
241
+ const settle = await require_settle.awaitBlockSettled(project, blockId, {
242
+ timeoutMs: options.wait ? options.timeoutMs : 0,
243
+ signal: options.call?.mcpReq.signal,
244
+ waitForRun: false,
245
+ onProgress: options.wait ? require_settle.progressReporter(options.call, "Waiting for the block's outputs to settle") : void 0
246
+ });
247
+ const readiness = await readinessOf(project, blockId);
248
+ const imports = require_imports.importsOf(settle.state.outputs);
249
+ const notes = [];
250
+ if (options.notePrerun && readiness?.prerun !== void 0 && readiness.prerun !== "staged") notes.push(`The pre-run does not run on this data (prerun: ${readiness.prerun}), so the pre-run outputs still show the previous configuration.`);
251
+ if (!settle.settled && settle.stoppedBy === "upstream-not-run" && settle.waitingOn !== void 0) notes.push(`The outputs wait for block ${settle.waitingOn} above, which has not run; they compute after it runs: run_block on this block starts it with the other stale blocks above.`);
252
+ else if (!settle.settled && settle.waitingOn !== void 0) notes.push(`The outputs wait for block ${settle.waitingOn} above, which is running; await_block_done on it waits for it.`);
253
+ else if (!settle.settled && options.wait) notes.push("The outputs are still computing; get_block_state shows them when they settle.");
254
+ return {
255
+ settled: settle.settled,
256
+ waitedMs: settle.waitedMs,
257
+ ...settle.settled ? {} : {
258
+ pendingOutputs: settle.pendingOutputs,
259
+ ...settle.waitingOn !== void 0 ? {
260
+ waitingOn: settle.waitingOn,
261
+ waitingOnStatus: settle.waitingOnStatus
262
+ } : {},
263
+ runningUpstreams: settle.runningUpstreams
264
+ },
265
+ readiness,
266
+ ...require_tokens.outputsView(settle.state.outputs),
267
+ ...imports !== void 0 ? { imports } : {},
268
+ ...notes.length > 0 ? { note: notes.join(" ") } : {}
269
+ };
270
+ }
9
271
  function registerBlockStateTools(server, ctx) {
10
272
  server.registerTool("get_project_overview", {
11
273
  title: "Get Project Overview",
12
274
  annotations: require_types.hints.read,
13
- description: "Get project overview with all blocks and their statuses (calculationStatus, canRun, stale, errors, upstreams/downstreams)",
14
- inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID (must be opened)") })
15
- }, async ({ projectId }) => {
16
- const overview = await (await ctx.getOpenedProject(projectId)).overview.getValue();
17
- if (!overview) return require_types.errorResult("Project overview not available yet.");
18
- return require_types.textResult({
19
- label: overview.meta.label,
20
- blocks: overview.blocks.map((b) => ({
21
- id: b.id,
22
- title: b.title ?? b.label,
23
- calculationStatus: b.calculationStatus,
24
- canRun: b.canRun,
25
- stale: b.stale,
26
- inputsValid: b.inputsValid,
27
- outputErrors: b.outputErrors,
28
- upstreams: b.upstreams,
29
- downstreams: b.downstreams
30
- }))
275
+ description: `Get the project's blocks in order, each with its status and what it depends on. \`status\`: running, limbo (results from before an upstream changed: it failed, was stopped or ran again), failed (the last run ended with errors in its outputs; \`outputsError\` holds the error, get_block_state reads each output's), up-to-date, ready (can run), blocked (cannot run: invalid inputs, an invalid upstream or a missing reference; get_block_state says why). Built from stored state; no block model is run.
276
+
277
+ Result: \`{ label, blocks, totalBlocks, offset, hasMore, notFound? }\`: at most 50 blocks unless \`limit\` says otherwise; page with \`offset\`, or ask for some blocks by id with \`blockIds\`.`,
278
+ inputSchema: zod.z.object({
279
+ projectId: require_ids.projectIdInput.describe("Project ID"),
280
+ blockIds: zod.z.array(require_ids.blockIdInput).optional().describe("Only these blocks, in project order; `notFound` lists the ids the project lacks."),
281
+ ...require_paging.pagingArgs("blocks", 50, 200)
282
+ })
283
+ }, async ({ projectId, blockIds, limit, offset }) => {
284
+ return await ctx.withProject(projectId, async (project) => {
285
+ const overview = await project.overview.getValue();
286
+ if (!overview) return require_types.errorResult("Project overview not available yet.");
287
+ const wanted = blockIds === void 0 ? void 0 : new Set(blockIds);
288
+ const selected = wanted === void 0 ? overview.blocks : overview.blocks.filter((b) => wanted.has(b.id));
289
+ const known = new Set(overview.blocks.map((b) => b.id));
290
+ const notFound = (blockIds ?? []).filter((id) => !known.has(id));
291
+ const { items, total, ...paging } = require_paging.page(selected, offset, limit ?? 50);
292
+ return require_types.textResult({
293
+ label: overview.meta.label,
294
+ totalBlocks: total,
295
+ ...paging,
296
+ ...notFound.length > 0 ? { notFound } : {},
297
+ blocks: items.map((b) => ({
298
+ id: b.id,
299
+ title: b.title ?? b.label,
300
+ subtitle: b.subtitle,
301
+ status: require_readiness.blockStatus(b),
302
+ calculationStatus: b.calculationStatus,
303
+ canRun: b.canRun,
304
+ stale: b.stale,
305
+ inputsValid: b.inputsValid,
306
+ missingReference: b.missingReference,
307
+ outputErrors: b.outputErrors,
308
+ outputsError: b.outputsError === void 0 ? void 0 : require_tokens.clip(b.outputsError, OVERVIEW_ERROR_CHARS),
309
+ exportsError: b.exportsError === void 0 ? void 0 : require_tokens.clip(b.exportsError, OVERVIEW_ERROR_CHARS),
310
+ upstreams: b.upstreams,
311
+ downstreams: b.downstreams
312
+ }))
313
+ }, { hint: "Ask for fewer blocks: a smaller `limit` with `offset` to page, or `blockIds` for the blocks you need." });
31
314
  });
32
315
  });
33
316
  server.registerTool("get_block_state", {
34
317
  title: "Get Block State",
35
318
  annotations: require_types.hints.read,
36
- description: "Get block state. Returns block args (data) and a concise output summary with token estimates by default. Use `transform` to extract specific data server-side without loading full outputs into context.\n\nDefault: returns `{ data, outputs: [{ key, ok, hasValue, tokensEstimate }] }`\n\nTransform examples:\n- `outputs.logs?.value` — get one specific output value\n- `data` — get only block args\n- `({ preset: outputs.preset?.value, qc: outputs.qc?.value })` — get specific outputs",
319
+ description: "Get one block: its data (the configuration set_block_data writes), the data of its plugins, and a summary of its outputs.\n\nDefault result: `{ dataVersion, data, plugins?, outputs: [{ key, status, hasValue, tokensEstimate? }], outputsNote?, outputsSettled, readiness }`. Output `status` is ok, pending (no final value yet) or error; `outputsNote` says how to read an error. `outputsSettled` is true when no output is pending. `readiness`: `{ status, blockers: [{ kind, message, blockId? }], warnings, prerun, prerunReason? }`, why the block can or cannot run, in the words of the block's own model (kind args), or a missing reference or a block above that cannot run; `prerun` says whether the pre-run outputs follow the current data (staged) or still show an earlier one. The options a block offers for results of blocks above appear only once those results exist, and some blocks publish results only from their run: if an option is missing and the block above has not run, run it first (run_block, await_block_done).\n\nTransform examples:\n- `outputs.logs?.value` — one output value\n- `data.settings` — one part of the data\n- `plugins[\"counter\"]` — one plugin's data\n- `({ preset: outputs.preset?.value, qc: outputs.qc?.value })` — several outputs",
37
320
  inputSchema: zod.z.object({
38
321
  projectId: require_ids.projectIdInput.describe("Project ID"),
39
322
  blockId: require_ids.blockIdInput.describe("Block ID"),
40
- transform: zod.z.string().optional().describe("JS expression evaluated server-side against full block state. Available variables: `data` (block args), `outputs` (raw outputs object). Omit for default concise summary."),
41
- transformTimeout: zod.z.number().optional().default(5e3).describe("Timeout in ms for transform evaluation (default 5000).")
323
+ transform: zod.z.string().optional().describe("JS expression evaluated server-side against the block. Available variables: `data` (block data), `plugins` (plugin handle → plugin data), `outputs` (raw outputs object). Omit for the default view."),
324
+ transformTimeout: zod.z.number().optional().default(DEFAULT_EXPRESSION_TIMEOUT).describe(require_sandbox.expressionTimeoutText("transform evaluation", DEFAULT_EXPRESSION_TIMEOUT))
42
325
  })
43
326
  }, async ({ projectId, blockId, transform, transformTimeout }) => {
44
- const state = await (await ctx.getOpenedProject(projectId)).getBlockState(blockId).getValue();
45
- const data = (0, _platforma_sdk_model.deriveDataFromStorage)(state.blockStorage);
46
- if (transform) try {
47
- const result = await require_sandbox.safeEval(transform, {
48
- data,
49
- outputs: state.outputs
50
- }, transformTimeout);
51
- return require_types.textResult(result);
52
- } catch (e) {
53
- return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, outputs.");
54
- }
55
- return require_types.textResult({
56
- data,
57
- outputs: require_tokens.summarizeOutputs(state.outputs)
327
+ return await ctx.withProject(projectId, async (project) => {
328
+ const { error } = await require_readiness.findBlock(project, projectId, blockId);
329
+ if (error) return error;
330
+ const state = await project.getBlockState(blockId).getValue();
331
+ if (transform) {
332
+ const storage = require_block_storage.readStorageView(state.blockStorage);
333
+ try {
334
+ const result = await require_sandbox.safeEval(transform, {
335
+ data: storage.data,
336
+ plugins: Object.fromEntries(Object.entries(storage.plugins).map(([handle, p]) => [handle, p.data])),
337
+ outputs: state.outputs
338
+ }, transformTimeout);
339
+ return require_types.textResult(result);
340
+ } catch (e) {
341
+ return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, plugins, outputs.");
342
+ }
343
+ }
344
+ return require_types.textResult({
345
+ ...require_block_storage.blockView(state),
346
+ outputsSettled: require_settle.pendingOutputKeys(state.outputs).length === 0,
347
+ readiness: await readinessOf(project, blockId)
348
+ });
58
349
  });
59
350
  });
60
351
  server.registerTool("set_block_data", {
61
352
  title: "Set Block Data",
62
353
  annotations: require_types.hints.destructive,
63
- description: "Set the user-facing data of a block (triggers args derivation and staging)",
64
- inputSchema: zod.z.object({
65
- projectId: require_ids.projectIdInput.describe("Project ID"),
66
- blockId: require_ids.blockIdInput.describe("Block ID"),
67
- data: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Block data object")
68
- })
69
- }, async ({ projectId, blockId, data }) => {
70
- const project = await ctx.getOpenedProject(projectId);
71
- const value = data.args ?? data;
72
- try {
73
- await project.mutateBlockStorage(blockId, {
74
- operation: "update-block-data",
75
- value
76
- }, ctx.getAuthorMarker());
77
- } catch (e) {
78
- if (e instanceof _milaboratories_pl_errors.ModelAPIVersionMismatchError) await project.setBlockArgs(blockId, value, ctx.getAuthorMarker());
79
- else throw e;
80
- }
81
- return require_types.textResult({ ok: true });
354
+ description: "Write the whole data of a block (its configuration), or of one of its plugins with `pluginId`. For what a block's kind params describe, set_block_params is the way; set_block_data is for what params do not cover: table filters, plot settings, plugin data, blocks whose params are `{}` or that give none. Read the data with get_block_state, change it, and send the whole object back as `data` (it replaces the stored value, edits made since your read included); or send `update`, an expression the server evaluates against the current data, which is the way to edit some fields. Not a patch: a write that leaves out a top-level key of the current data is refused unless the key is named in `removeKeys`. A write equal to the current data is skipped (`unchanged: true`). Binary data reads as `{bytes: N}`, and a write stores that stub as it is: change such data with `update`, which runs on the stored value. The write re-derives the block's args; the block's results, and those of blocks below it, become stale until they run again. Only blocks on the current block API can be written.\n\nBy default the call then waits (up to `timeout`) for the block's outputs to settle on the new data: the pre-run outputs (option lists, previews) recompute without run_block. A wait that runs out is not an error: the write was made, and `settled: false` says what is still pending.\n\nResult: `{ ok, unchanged?, changes: [{ path, op, from?, to? }], moreChanges?, settled, waitedMs, readiness, outputs, outputsNote?, note? }`: at most 50 changed paths; `settled` false comes with `pendingOutputs`, `waitingOn` (a block above that is running or has not run) and `runningUpstreams`, or with `settleError` when the block could not be read after the write (the write was made: do not repeat it); `readiness` as get_block_state gives it, the block's own messages on what keeps it from running; `note` says when the pre-run outputs still show the previous configuration.\n\nFiles are given to a block as import handles from get_file_handles, written where the block's data takes a file. A handle the current data does not hold yet must check out (a local file that exists unchanged since the handle was made), or the write is refused; `imports` in the result and in get_block_state shows the upload progress.",
355
+ inputSchema: setBlockDataInput
356
+ }, async ({ projectId, ...input }, call) => {
357
+ return await ctx.withProject(projectId, (project) => writeAndSettle(project, ctx.getAuthorMarker(), input, ctx.requireMl().internalDriverKit.lsDriver, call));
82
358
  });
83
359
  }
360
+ exports.DEFAULT_EXPRESSION_TIMEOUT = DEFAULT_EXPRESSION_TIMEOUT;
361
+ exports.WRITE_WAIT_DEFAULT_MS = WRITE_WAIT_DEFAULT_MS;
362
+ exports.WRITE_WAIT_MAX_MS = WRITE_WAIT_MAX_MS;
363
+ exports.WRITE_WAIT_MIN_MS = WRITE_WAIT_MIN_MS;
364
+ exports.oneAtATime = oneAtATime;
365
+ exports.readinessOf = readinessOf;
366
+ exports.refuse = refuse;
84
367
  exports.registerBlockStateTools = registerBlockStateTools;
368
+ exports.settleAfterChange = settleAfterChange;
369
+ exports.writeAndSettle = writeAndSettle;
370
+ exports.writeBlockData = writeBlockData;
85
371
 
86
372
  //# sourceMappingURL=block-state.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"block-state.cjs","names":["hints","z","projectIdInput","errorResult","textResult","blockIdInput","deriveDataFromStorage","safeEval","transformFailedResult","summarizeOutputs","ModelAPIVersionMismatchError"],"sources":["../../src/tools/block-state.ts"],"sourcesContent":["import { deriveDataFromStorage } from \"@platforma-sdk/model\";\nimport { ModelAPIVersionMismatchError } from \"@milaboratories/pl-errors\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { summarizeOutputs } from \"./tokens\";\nimport { safeEval } from \"./sandbox\";\nimport { errorResult, hints, textResult, transformFailedResult } from \"./types\";\n\nexport function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_project_overview\",\n {\n title: \"Get Project Overview\",\n annotations: hints.read,\n description:\n \"Get project overview with all blocks and their statuses (calculationStatus, canRun, stale, errors, upstreams/downstreams)\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID (must be opened)\"),\n }),\n },\n async ({ projectId }) => {\n const project = await ctx.getOpenedProject(projectId);\n const overview = await project.overview.getValue();\n if (!overview) return errorResult(\"Project overview not available yet.\");\n return textResult({\n label: overview.meta.label,\n blocks: overview.blocks.map((b) => ({\n id: b.id,\n title: b.title ?? b.label,\n calculationStatus: b.calculationStatus,\n canRun: b.canRun,\n stale: b.stale,\n inputsValid: b.inputsValid,\n outputErrors: b.outputErrors,\n upstreams: b.upstreams,\n downstreams: b.downstreams,\n })),\n });\n },\n );\n\n server.registerTool(\n \"get_block_state\",\n {\n title: \"Get Block State\",\n annotations: hints.read,\n description:\n \"Get block state. Returns block args (data) and a concise output summary with token estimates by default. \" +\n \"Use `transform` to extract specific data server-side without loading full outputs into context.\\n\\n\" +\n \"Default: returns `{ data, outputs: [{ key, ok, hasValue, tokensEstimate }] }`\\n\\n\" +\n \"Transform examples:\\n\" +\n \"- `outputs.logs?.value` — get one specific output value\\n\" +\n \"- `data` — get only block args\\n\" +\n \"- `({ preset: outputs.preset?.value, qc: outputs.qc?.value })` — get specific outputs\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against full block state. \" +\n \"Available variables: `data` (block args), `outputs` (raw outputs object). \" +\n \"Omit for default concise summary.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(5000)\n .describe(\"Timeout in ms for transform evaluation (default 5000).\"),\n }),\n },\n async ({ projectId, blockId, transform, transformTimeout }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n const data = deriveDataFromStorage(state.blockStorage);\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n { data, outputs: state.outputs },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: data, outputs.\",\n );\n }\n }\n return textResult({\n data,\n outputs: summarizeOutputs(state.outputs as Record<string, unknown> | undefined),\n });\n },\n );\n\n server.registerTool(\n \"set_block_data\",\n {\n title: \"Set Block Data\",\n annotations: hints.destructive,\n description: \"Set the user-facing data of a block (triggers args derivation and staging)\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n data: z.record(z.string(), z.unknown()).describe(\"Block data object\"),\n }),\n },\n async ({ projectId, blockId, data }) => {\n const project = await ctx.getOpenedProject(projectId);\n\n // V1 state shape: { args, uiState } — callers may pass either the full state\n // or just the args object. Unwrap once for both V2 and V1 paths.\n const value = data.args ?? data;\n\n // Try V2 (BlockModelV3 storage facade) first, fall back to V1 (legacy setBlockArgs).\n try {\n await project.mutateBlockStorage(\n blockId,\n { operation: \"update-block-data\", value },\n ctx.getAuthorMarker(),\n );\n } catch (e: unknown) {\n if (e instanceof ModelAPIVersionMismatchError) {\n await project.setBlockArgs(blockId, value, ctx.getAuthorMarker());\n } else {\n throw e;\n }\n }\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,wBAAwB,QAAuB,KAAwB;CACrF,OAAO,aACL,wBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;EACF,aAAaC,IAAAA,EAAE,OAAO,EACpB,WAAWC,YAAAA,eAAe,SAAS,6BAA6B,EAClE,CAAC;CACH,GACA,OAAO,EAAE,gBAAgB;EAEvB,MAAM,WAAW,OAAM,MADD,IAAI,iBAAiB,SAAS,EAAA,CACrB,SAAS,SAAS;EACjD,IAAI,CAAC,UAAU,OAAOC,cAAAA,YAAY,qCAAqC;EACvE,OAAOC,cAAAA,WAAW;GAChB,OAAO,SAAS,KAAK;GACrB,QAAQ,SAAS,OAAO,KAAK,OAAO;IAClC,IAAI,EAAE;IACN,OAAO,EAAE,SAAS,EAAE;IACpB,mBAAmB,EAAE;IACrB,QAAQ,EAAE;IACV,OAAO,EAAE;IACT,aAAa,EAAE;IACf,cAAc,EAAE;IAChB,WAAW,EAAE;IACb,aAAa,EAAE;GACjB,EAAE;EACJ,CAAC;CACH,CACF;CAEA,OAAO,aACL,mBACA;EACE,OAAO;EACP,aAAaJ,cAAAA,MAAM;EACnB,aACE;EAOF,aAAaC,IAAAA,EAAE,OAAO;GACpB,WAAWC,YAAAA,eAAe,SAAS,YAAY;GAC/C,SAASG,YAAAA,aAAa,SAAS,UAAU;GACzC,WAAWJ,IAAAA,EACR,OAAO,CAAC,CACR,SAAS,CAAC,CACV,S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BAAgB,CAAC;QAEhE,MAAM;EAEV;EACA,OAAON,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
1
+ {"version":3,"file":"block-state.cjs","names":["z","projectIdInput","blockIdInput","pluginHandleInput","expressionTimeoutText","textResult","clampWait","errorResult","blockApiGuardResult","isDeepStrictEqual","unsupportedBlockApiResult","diffValues","readStorageView","pluginOf","safeEval","transformFailedResult","isPlainObject","missingTopLevelKeys","invalidNewImportHandles","invalidHandlesResult","buildReadiness","awaitBlockSettled","progressReporter","importsOf","outputsView","hints","pagingArgs","page","blockStatus","clip","findBlock","blockView","pendingOutputKeys"],"sources":["../../src/tools/block-state.ts"],"sourcesContent":["import { isDeepStrictEqual } from \"node:util\";\nimport type { BlockCodeFeatureFlags, BlockId } from \"@milaboratories/pl-model-common\";\nimport type { BlockReadiness } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\nimport { projectIdInput, blockIdInput, pluginHandleInput } from \"./ids\";\nimport type { AuthorMarker, ToolContext, ToolRegistrar } from \"./types\";\nimport {\n blockView,\n diffValues,\n missingTopLevelKeys,\n pluginOf,\n readStorageView,\n} from \"./block-storage\";\nimport { clip, outputsView } from \"./tokens\";\nimport {\n blockStatus,\n buildReadiness,\n findBlock,\n type Readiness,\n type ReadinessOverviewBlock,\n} from \"./readiness\";\nimport {\n awaitBlockSettled,\n clampWait,\n pendingOutputKeys,\n progressReporter,\n type SettleBlockState,\n type SettleProject,\n type WaitContext,\n} from \"./settle\";\nimport { importsOf } from \"./imports\";\nimport { expressionTimeoutText, safeEval } from \"./sandbox\";\nimport { invalidHandlesResult, invalidNewImportHandles, type FileLsDriver } from \"./files\";\nimport { page, pagingArgs } from \"./paging\";\nimport { blockApiGuardResult, unsupportedBlockApiResult } from \"./block-api\";\nimport { errorResult, hints, textResult, transformFailedResult } from \"./types\";\n\nexport { blockStatus, type BlockStatus } from \"./readiness\";\n\n/** How many blocks get_project_overview returns when the caller does not say. */\nexport const OVERVIEW_DEFAULT_LIMIT = 50;\n/** The most blocks one get_project_overview call returns. */\nexport const OVERVIEW_MAX_LIMIT = 200;\n\n/** The most characters of an output or exports error the project overview carries per block. */\nconst OVERVIEW_ERROR_CHARS = 300;\n\n/** Default timeout of a `transform` or `update` expression, in milliseconds. */\nexport const DEFAULT_EXPRESSION_TIMEOUT = 5000;\n\n/** The default wait of a write for the block's outputs to settle, in milliseconds. */\nexport const WRITE_WAIT_DEFAULT_MS = 30_000;\n/** The shortest wait a write may ask for. */\nexport const WRITE_WAIT_MIN_MS = 1_000;\n/** The longest wait a write may ask for: for clients whose request timeout is longer than the common 60 s. */\nexport const WRITE_WAIT_MAX_MS = 120_000;\n\n/** What {@link writeBlockData} needs of a project; a `Project` of the middle layer has it. */\nexport type BlockDataProject = {\n overview: {\n getValue(): Promise<\n | {\n blocks: { id: string; featureFlags: BlockCodeFeatureFlags | undefined }[];\n }\n | undefined\n >;\n };\n getBlockState(blockId: BlockId): { getValue(): Promise<{ blockStorage: unknown }> };\n mutateBlockStorage(\n blockId: BlockId,\n payload: { operation: string; value: unknown },\n author?: AuthorMarker,\n ): Promise<void>;\n};\n\nconst setBlockDataInput = z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n pluginId: pluginHandleInput\n .optional()\n .describe(\n \"Write the data of this plugin of the block instead of the block's own data: a handle \" +\n \"listed under `plugins` by get_block_state.\",\n ),\n data: z\n .unknown()\n .optional()\n .describe(\n \"The whole new data (the block's, or the plugin's with `pluginId`): the value \" +\n \"get_block_state returned, changed. Not a patch: it replaces the stored value whole, \" +\n \"so a change made in between by someone else (the user in the application) is \" +\n \"overwritten. To change some fields of the current value, send `update` instead. \" +\n \"Give `data` or `update`, not both.\",\n ),\n update: z\n .string()\n .optional()\n .describe(\n \"Instead of `data`: a JS expression evaluated in the server against the current data, \" +\n \"available as `data`; its value is the whole new data. \" +\n \"Example: `({ ...data, numbers: [1, 2, 3] })`.\",\n ),\n removeKeys: z\n .array(z.string())\n .optional()\n .describe(\n \"Top-level keys of the current data the write removes on purpose. A write that leaves out \" +\n \"a top-level key not named here is refused.\",\n ),\n updateTimeout: z\n .number()\n .optional()\n .describe(expressionTimeoutText(\"the `update` expression\", DEFAULT_EXPRESSION_TIMEOUT)),\n wait: z\n .boolean()\n .optional()\n .describe(\n \"Wait for the block's outputs to settle on the new data before answering (default true).\",\n ),\n timeout: z\n .number()\n .optional()\n .describe(\n `The longest wait in ms (default ${WRITE_WAIT_DEFAULT_MS}, at most ${WRITE_WAIT_MAX_MS}).`,\n ),\n});\n\n/** What checks the import handles a write adds: the middle layer's ls driver. */\nexport type ImportHandleChecker = Pick<FileLsDriver, \"getLocalFileSize\">;\n\n/** Input of the `set_block_data` tool. */\nexport type SetBlockDataInput = z.infer<typeof setBlockDataInput>;\n\n/**\n * The third way to give the new value of a write, next to `data` and `update`: a function of the\n * current value and the raw storage it was read from. It refuses, or gives the new value.\n */\nexport type ComputeNext = (\n current: unknown,\n rawStorage: unknown,\n) => Promise<WriteRefused | { kind: \"next\"; next: unknown }>;\n\n/** What {@link writeBlockData} writes: the tool's input, or a {@link ComputeNext} in place of `data`. */\nexport type WriteInput = Omit<SetBlockDataInput, \"projectId\" | \"wait\" | \"timeout\"> & {\n computeNext?: ComputeNext;\n};\n\n/** What {@link writeBlockData} did. */\nexport type WriteOutcome =\n | WriteRefused\n | { kind: \"written\"; unchanged: boolean; changes: ReturnType<typeof diffValues> };\n\n/** A write that was refused: nothing was written; `result` is the tool's error result. */\nexport type WriteRefused = { kind: \"refused\"; result: ReturnType<typeof errorResult> };\n\n/**\n * The `set_block_data` tool on one project: {@link writeBlockData}, then the wait for the block's\n * outputs to settle on the new data ({@link settleAfterChange}). Once the value is written the\n * result is `ok`, whatever the wait finds.\n */\nexport async function writeAndSettle(\n project: BlockDataProject & ChangeProject,\n author: AuthorMarker,\n input: Omit<SetBlockDataInput, \"projectId\">,\n importHandles?: ImportHandleChecker,\n call?: WaitContext,\n) {\n const { wait, timeout, ...write } = input;\n const outcome = await writeBlockData(project, author, write, importHandles);\n if (outcome.kind === \"refused\") return outcome.result;\n return textResult({\n ok: true,\n ...writeSummary(outcome),\n ...(await settleAfterChange(project, input.blockId, {\n wait: wait ?? true,\n timeoutMs: clampWait(timeout, WRITE_WAIT_DEFAULT_MS, WRITE_WAIT_MIN_MS, WRITE_WAIT_MAX_MS),\n call,\n notePrerun: true,\n })),\n });\n}\n\n/** The `unchanged` and `changes` part of the result of a write. */\nfunction writeSummary(outcome: Extract<WriteOutcome, { kind: \"written\" }>) {\n return outcome.unchanged ? { unchanged: true, changes: [] } : outcome.changes;\n}\n\n/**\n * Writes a block's data, or one plugin's data, whole (D-004, D-007). The steps:\n *\n * 1. the block must be in the project;\n * 2. the current value is read from the block's storage; a plugin must be one the block registers;\n * 3. the new value is `data`, the value of `update` evaluated against the current one, or the\n * value `computeNext` gives;\n * 4. guards: a plain-object value stays a plain object; no top-level key of the current value is\n * dropped unless it is named in `removeKeys` (not asked of `computeNext`, which decides what\n * its value keeps);\n * 5. with `importHandles`, the import handles of the new value that the current one does not have\n * must check out (see {@link invalidNewImportHandles});\n * 6. a value equal to the current one is not written: `unchanged: true`;\n * 7. one `mutateBlockStorage`: `update-block-data`, or `update-plugin-data` with `pluginId`.\n *\n * Writes of this server to one block run one at a time with the other changes of the block\n * ({@link oneAtATime}), so each reads what the one before it wrote. A write from elsewhere\n * (the application, another server) between the read of step 2 and the write of step 7 is\n * overwritten: the last writer wins.\n *\n * Returns whether the value was written and its changed paths, or the error result of a refusal\n * (nothing is written then).\n */\nexport async function writeBlockData(\n project: BlockDataProject,\n author: AuthorMarker,\n input: WriteInput,\n importHandles?: ImportHandleChecker,\n): Promise<WriteOutcome> {\n return await oneAtATime(project, input.blockId, () =>\n writeNow(project, author, input, importHandles),\n );\n}\n\n/** The changes of this server in progress, per project and block. */\nconst blockQueues = new WeakMap<object, Map<BlockId, Promise<void>>>();\n\n/**\n * Runs `fn`, a change of one block of the project (its data, its block pack, its removal), after\n * the changes of that block this server started before it (Q-020). Changes of the block list need\n * no queue here: the middle layer runs the project's transactions one at a time.\n */\nexport async function oneAtATime<T>(\n project: object,\n blockId: BlockId,\n fn: () => Promise<T>,\n): Promise<T> {\n let queues = blockQueues.get(project);\n if (queues === undefined) {\n queues = new Map();\n blockQueues.set(project, queues);\n }\n const run = (queues.get(blockId) ?? Promise.resolve()).then(fn);\n const tail = run.then(\n () => {},\n () => {},\n );\n queues.set(blockId, tail);\n try {\n return await run;\n } finally {\n if (queues.get(blockId) === tail) queues.delete(blockId);\n }\n}\n\nasync function writeNow(\n project: BlockDataProject,\n author: AuthorMarker,\n input: WriteInput,\n importHandles: ImportHandleChecker | undefined,\n): Promise<WriteOutcome> {\n const { blockId, pluginId, data, update, computeNext } = input;\n const ways = [data, update, computeNext].filter((way) => way !== undefined).length;\n if (ways !== 1)\n return refuse(\n errorResult(\n \"Give either `data` or `update`. Nothing was changed.\",\n \"`data` is the whole new value; `update` is an expression computing it from the current \" +\n \"one.\",\n ),\n );\n\n const overview = await project.overview.getValue();\n if (!overview)\n return refuse(errorResult(\"Project overview not available yet. Nothing was changed.\"));\n const block = overview.blocks.find((b) => b.id === blockId);\n if (!block)\n return refuse(\n errorResult(\n `Block ${blockId} not found. Nothing was changed.`,\n \"Use get_project_overview to list the block IDs of the project.\",\n ),\n );\n // Before the write is planned: a block on block API 1 keeps its data in another shape, and a\n // guard of the plan would refuse it for that first (Q-042).\n const otherApi = blockApiGuardResult(block);\n if (otherApi) return refuse(otherApi);\n\n const state = await project.getBlockState(blockId).getValue();\n const planned = await planWrite(state.blockStorage, input, importHandles);\n if (planned.kind !== \"write\") return planned;\n const { current, next } = planned;\n if (isDeepStrictEqual(current, next))\n return { kind: \"written\", unchanged: true, changes: { changes: [] } };\n\n const payload =\n pluginId !== undefined\n ? { operation: \"update-plugin-data\", pluginId, value: next }\n : { operation: \"update-block-data\", value: next };\n try {\n await project.mutateBlockStorage(blockId, payload, author);\n } catch (e: unknown) {\n const unsupported = unsupportedBlockApiResult(e);\n if (unsupported) return refuse(unsupported);\n throw e;\n }\n return { kind: \"written\", unchanged: false, changes: diffValues(current, next) };\n}\n\n/** A refused write with `result` as the tool's error result. */\nexport function refuse(result: ReturnType<typeof errorResult>): WriteRefused {\n return { kind: \"refused\", result };\n}\n\n/**\n * Steps 2–5 of {@link writeBlockData} on the block's storage: the current value, the new one and\n * the guards between them, the check of new import handles included.\n */\nasync function planWrite(\n rawStorage: unknown,\n input: WriteInput,\n importHandles: ImportHandleChecker | undefined,\n): Promise<WriteRefused | { kind: \"write\"; current: unknown; next: unknown }> {\n const { blockId, pluginId, data, update, computeNext, removeKeys, updateTimeout } = input;\n const storage = readStorageView(rawStorage);\n let current: unknown;\n if (pluginId !== undefined) {\n const plugin = pluginOf(storage, pluginId);\n if (plugin === undefined) {\n const known = Object.keys(storage.plugins);\n return refuse(\n errorResult(\n `Block ${blockId} has no plugin \"${pluginId}\". Nothing was changed.`,\n known.length > 0\n ? `Its plugins: ${known.join(\", \")}.`\n : \"The block has no plugins: omit pluginId to write the block's own data.\",\n ),\n );\n }\n current = plugin.data;\n } else {\n current = storage.data;\n }\n\n let next: unknown;\n if (computeNext !== undefined) {\n const computed = await computeNext(current, rawStorage);\n if (computed.kind === \"refused\") return computed;\n next = computed.next;\n } else if (update !== undefined) {\n try {\n next = await safeEval(update, { data: current }, updateTimeout ?? DEFAULT_EXPRESSION_TIMEOUT);\n } catch (e: unknown) {\n return refuse(\n transformFailedResult(\n e,\n \"Nothing was changed. The expression gets the current data as `data` and must return \" +\n \"the whole new data, e.g. `({ ...data, key: 1 })`.\",\n ),\n );\n }\n if (next === undefined || next === null)\n return refuse(\n errorResult(\n \"The `update` expression returned no value. Nothing was changed.\",\n \"Return the whole new data, e.g. `({ ...data, key: 1 })`.\",\n ),\n );\n } else {\n next = data;\n }\n\n if (isPlainObject(current) && !isPlainObject(next))\n return refuse(\n errorResult(\n \"The current data is an object; the new data must be an object too. Nothing was changed.\",\n \"Read the data with get_block_state, change it and write the whole object back.\",\n ),\n );\n\n const allowed = new Set(removeKeys ?? []);\n const dropped =\n computeNext !== undefined\n ? []\n : missingTopLevelKeys(current, next).filter((k) => !allowed.has(k));\n if (dropped.length > 0)\n return refuse(\n errorResult(\n `The new data leaves out top-level keys of the current data: ${dropped.join(\", \")}. ` +\n \"Nothing was changed.\",\n \"Send the whole object: read it with get_block_state, change it and write all of it \" +\n \"back. To remove keys on purpose, name them in `removeKeys`.\",\n ),\n );\n\n // A value equal to the current one has no new handles: nothing is checked.\n if (importHandles !== undefined) {\n const invalid = await invalidNewImportHandles(importHandles, current, next);\n if (invalid.length > 0) return refuse(invalidHandlesResult(invalid));\n }\n\n return { kind: \"write\", current, next };\n}\n\n/** What {@link readinessOf} reads of a project; a middle-layer `Project` has it. */\nexport type ReadinessProject = {\n overview: { getValue(): Promise<{ blocks: ReadinessOverviewBlock[] } | undefined> };\n getBlockReadiness(blockId: BlockId): { getValue(): Promise<BlockReadiness | undefined> };\n};\n\n/**\n * The readiness of a block (see {@link Readiness}): the block's overview entry, those of the blocks\n * above, and what its model makes of its current data. `undefined` when the project has no such\n * block. A model that cannot be run leaves out what only the model says.\n */\nexport async function readinessOf(\n project: ReadinessProject,\n blockId: BlockId,\n): Promise<Readiness | undefined> {\n const overview = await project.overview.getValue();\n const block = overview?.blocks.find((b) => b.id === blockId);\n if (overview === undefined || block === undefined) return undefined;\n let model;\n try {\n model = await project.getBlockReadiness(blockId).getValue();\n } catch {\n model = undefined;\n }\n return buildReadiness(block, overview.blocks, model);\n}\n\n/** Options of {@link settleAfterChange}. */\nexport type SettleAfterChangeOptions = {\n /** Wait for the outputs to settle; otherwise look once. */\n wait: boolean;\n timeoutMs: number;\n /** The tool call: its abort signal ends the wait, its progress token asks for progress. */\n call?: WaitContext;\n /** Say when the pre-run outputs show an earlier configuration (after a write, D-008). */\n notePrerun: boolean;\n};\n\n/** What {@link settleAfterChange} reads of a project; a middle-layer `Project` has it. */\nexport type ChangeProject = SettleProject<SettleBlockState> & ReadinessProject;\n\n/**\n * What a tool that changed a block adds to its result: whether the block's outputs settled on the\n * change (after waiting up to `timeoutMs`), how long it waited, the readiness and an output\n * summary; unsettled, what the outputs wait for.\n *\n * It never throws: the change is made by then, and an error result would have the agent make it\n * again (a second block, a second write). A failure to read the block afterwards comes back as\n * `settled: false` with `settleError`.\n */\nexport async function settleAfterChange(\n project: ChangeProject,\n blockId: BlockId,\n options: SettleAfterChangeOptions,\n): Promise<\n Awaited<ReturnType<typeof settleNow>> | { settled: false; settleError: string; note: string }\n> {\n try {\n return await settleNow(project, blockId, options);\n } catch (e: unknown) {\n return {\n settled: false,\n settleError: e instanceof Error ? e.message : String(e),\n note:\n \"The change was made; reading the block afterwards failed. Do not repeat the change: \" +\n \"get_block_state shows the block.\",\n };\n }\n}\n\nasync function settleNow(\n project: ChangeProject,\n blockId: BlockId,\n options: SettleAfterChangeOptions,\n) {\n const settle = await awaitBlockSettled(project, blockId, {\n timeoutMs: options.wait ? options.timeoutMs : 0,\n signal: options.call?.mcpReq.signal,\n waitForRun: false,\n onProgress: options.wait\n ? progressReporter(options.call, \"Waiting for the block's outputs to settle\")\n : undefined,\n });\n const readiness = await readinessOf(project, blockId);\n const imports = importsOf(settle.state.outputs);\n const notes: string[] = [];\n if (options.notePrerun && readiness?.prerun !== undefined && readiness.prerun !== \"staged\")\n notes.push(\n `The pre-run does not run on this data (prerun: ${readiness.prerun}), so the pre-run ` +\n \"outputs still show the previous configuration.\",\n );\n if (!settle.settled && settle.stoppedBy === \"upstream-not-run\" && settle.waitingOn !== undefined)\n notes.push(\n `The outputs wait for block ${settle.waitingOn} above, which has not run; they compute ` +\n \"after it runs: run_block on this block starts it with the other stale blocks above.\",\n );\n else if (!settle.settled && settle.waitingOn !== undefined)\n notes.push(\n `The outputs wait for block ${settle.waitingOn} above, which is running; ` +\n \"await_block_done on it waits for it.\",\n );\n else if (!settle.settled && options.wait)\n notes.push(\"The outputs are still computing; get_block_state shows them when they settle.\");\n return {\n settled: settle.settled,\n waitedMs: settle.waitedMs,\n ...(settle.settled\n ? {}\n : {\n pendingOutputs: settle.pendingOutputs,\n ...(settle.waitingOn !== undefined\n ? { waitingOn: settle.waitingOn, waitingOnStatus: settle.waitingOnStatus }\n : {}),\n runningUpstreams: settle.runningUpstreams,\n }),\n readiness,\n ...outputsView(settle.state.outputs),\n ...(imports !== undefined ? { imports } : {}),\n ...(notes.length > 0 ? { note: notes.join(\" \") } : {}),\n };\n}\n\nexport function registerBlockStateTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_project_overview\",\n {\n title: \"Get Project Overview\",\n annotations: hints.read,\n description:\n \"Get the project's blocks in order, each with its status and what it depends on. \" +\n \"`status`: running, limbo (results from before an upstream changed: it failed, was \" +\n \"stopped or ran again), failed (the last run ended with errors in its outputs; \" +\n \"`outputsError` holds the error, get_block_state reads each output's), up-to-date, \" +\n \"ready (can run), blocked (cannot run: invalid inputs, an invalid upstream or a \" +\n \"missing reference; get_block_state says why). \" +\n \"Built from stored state; no block model is run.\\n\\n\" +\n `Result: \\`{ label, blocks, totalBlocks, offset, hasMore, notFound? }\\`: at most ` +\n `${OVERVIEW_DEFAULT_LIMIT} blocks unless \\`limit\\` says otherwise; page with \\`offset\\`, ` +\n \"or ask for some blocks by id with `blockIds`.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockIds: z\n .array(blockIdInput)\n .optional()\n .describe(\n \"Only these blocks, in project order; `notFound` lists the ids the project lacks.\",\n ),\n ...pagingArgs(\"blocks\", OVERVIEW_DEFAULT_LIMIT, OVERVIEW_MAX_LIMIT),\n }),\n },\n async ({ projectId, blockIds, limit, offset }) => {\n return await ctx.withProject(projectId, async (project) => {\n const overview = await project.overview.getValue();\n if (!overview) return errorResult(\"Project overview not available yet.\");\n const wanted = blockIds === undefined ? undefined : new Set<string>(blockIds);\n const selected =\n wanted === undefined ? overview.blocks : overview.blocks.filter((b) => wanted.has(b.id));\n const known = new Set(overview.blocks.map((b) => b.id));\n const notFound = (blockIds ?? []).filter((id) => !known.has(id));\n const { items, total, ...paging } = page(selected, offset, limit ?? OVERVIEW_DEFAULT_LIMIT);\n return textResult(\n {\n label: overview.meta.label,\n totalBlocks: total,\n ...paging,\n ...(notFound.length > 0 ? { notFound } : {}),\n blocks: items.map((b) => ({\n id: b.id,\n title: b.title ?? b.label,\n subtitle: b.subtitle,\n status: blockStatus(b),\n calculationStatus: b.calculationStatus,\n canRun: b.canRun,\n stale: b.stale,\n inputsValid: b.inputsValid,\n missingReference: b.missingReference,\n outputErrors: b.outputErrors,\n outputsError:\n b.outputsError === undefined\n ? undefined\n : clip(b.outputsError, OVERVIEW_ERROR_CHARS),\n exportsError:\n b.exportsError === undefined\n ? undefined\n : clip(b.exportsError, OVERVIEW_ERROR_CHARS),\n upstreams: b.upstreams,\n downstreams: b.downstreams,\n })),\n },\n {\n hint:\n \"Ask for fewer blocks: a smaller `limit` with `offset` to page, or `blockIds` for \" +\n \"the blocks you need.\",\n },\n );\n });\n },\n );\n\n server.registerTool(\n \"get_block_state\",\n {\n title: \"Get Block State\",\n annotations: hints.read,\n description:\n \"Get one block: its data (the configuration set_block_data writes), the data of its \" +\n \"plugins, and a summary of its outputs.\\n\\n\" +\n \"Default result: `{ dataVersion, data, plugins?, outputs: [{ key, \" +\n \"status, hasValue, tokensEstimate? }], outputsNote?, outputsSettled, readiness }`. \" +\n \"Output `status` is ok, pending (no final value yet) or error; `outputsNote` says how \" +\n \"to read an error. \" +\n \"`outputsSettled` is true when no output is pending. `readiness`: `{ status, blockers: \" +\n \"[{ kind, message, blockId? }], warnings, prerun, prerunReason? }`, why the block can or \" +\n \"cannot run, in the words of the block's own model (kind args), or a missing reference \" +\n \"or a block above that cannot run; `prerun` says whether the pre-run outputs follow the \" +\n \"current data (staged) or still show an earlier one. The options a block offers for \" +\n \"results of blocks above appear only once those results exist, and some blocks publish \" +\n \"results only from their run: if an option is missing and the block above has not run, \" +\n \"run it first (run_block, await_block_done).\\n\\n\" +\n \"Transform examples:\\n\" +\n \"- `outputs.logs?.value` — one output value\\n\" +\n \"- `data.settings` — one part of the data\\n\" +\n '- `plugins[\"counter\"]` — one plugin\\'s data\\n' +\n \"- `({ preset: outputs.preset?.value, qc: outputs.qc?.value })` — several outputs\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against the block. \" +\n \"Available variables: `data` (block data), `plugins` (plugin handle → plugin \" +\n \"data), `outputs` (raw outputs object). Omit for the default view.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(DEFAULT_EXPRESSION_TIMEOUT)\n .describe(expressionTimeoutText(\"transform evaluation\", DEFAULT_EXPRESSION_TIMEOUT)),\n }),\n },\n async ({ projectId, blockId, transform, transformTimeout }) => {\n return await ctx.withProject(projectId, async (project) => {\n const { error } = await findBlock(project, projectId, blockId);\n if (error) return error;\n const state = await project.getBlockState(blockId).getValue();\n if (transform) {\n const storage = readStorageView(state.blockStorage);\n try {\n const result = await safeEval(\n transform,\n {\n data: storage.data,\n plugins: Object.fromEntries(\n Object.entries(storage.plugins).map(([handle, p]) => [handle, p.data]),\n ),\n outputs: state.outputs,\n },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: data, plugins, outputs.\",\n );\n }\n }\n return textResult({\n ...blockView(state),\n outputsSettled: pendingOutputKeys(state.outputs).length === 0,\n readiness: await readinessOf(project, blockId),\n });\n });\n },\n );\n\n server.registerTool(\n \"set_block_data\",\n {\n title: \"Set Block Data\",\n annotations: hints.destructive,\n description:\n \"Write the whole data of a block (its configuration), or of one of its plugins with \" +\n \"`pluginId`. For what a block's kind params describe, set_block_params is the way; \" +\n \"set_block_data is for what params do not cover: table filters, plot settings, plugin \" +\n \"data, blocks whose params are `{}` or that give none. \" +\n \"Read the data with get_block_state, change it, and send the whole object \" +\n \"back as `data` (it replaces the stored value, edits made since your read included); \" +\n \"or send `update`, an expression the server evaluates against the current data, \" +\n \"which is the way to edit some fields. Not a patch: a write that leaves out a top-level key of the current data \" +\n \"is refused unless the key is named in `removeKeys`. A write equal to the current data \" +\n \"is skipped (`unchanged: true`). Binary data reads as `{bytes: N}`, and a write stores \" +\n \"that stub as it is: change such data with `update`, which runs on the stored value. \" +\n \"The write re-derives the block's args; the block's results, and those of blocks \" +\n \"below it, become stale until they run again. Only blocks on the current block API can \" +\n \"be written.\\n\\n\" +\n \"By default the call then waits (up to `timeout`) for the block's outputs to settle on \" +\n \"the new data: the pre-run outputs (option lists, previews) recompute without run_block. \" +\n \"A wait that runs out is not an error: the write was made, and `settled: false` says \" +\n \"what is still pending.\\n\\n\" +\n \"Result: `{ ok, unchanged?, changes: [{ path, op, from?, to? }], moreChanges?, settled, \" +\n \"waitedMs, readiness, outputs, outputsNote?, note? }`: at most 50 changed paths; \" +\n \"`settled` false comes with `pendingOutputs`, `waitingOn` (a block above that is running \" +\n \"or has not run) and `runningUpstreams`, or with `settleError` when the block could not \" +\n \"be read after the write (the write was made: do not repeat it); `readiness` as \" +\n \"get_block_state gives it, the block's own messages \" +\n \"on what keeps it from running; `note` says when the pre-run outputs still show the \" +\n \"previous configuration.\\n\\n\" +\n \"Files are given to a block as import handles from get_file_handles, written where the \" +\n \"block's data takes a file. A handle the current data does not hold yet must check out \" +\n \"(a local file that exists unchanged since the handle was made), or the write is \" +\n \"refused; `imports` in the result and in get_block_state shows the upload progress.\",\n inputSchema: setBlockDataInput,\n },\n async ({ projectId, ...input }, call) => {\n return await ctx.withProject(projectId, (project) =>\n writeAndSettle(\n project,\n ctx.getAuthorMarker(),\n input,\n ctx.requireMl().internalDriverKit.lsDriver,\n call,\n ),\n );\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8CA,MAAM,uBAAu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