@milaboratories/pl-mcp-server 54.0.0 → 55.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +15 -25
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -123
  156. package/src/tools/block-action-context.ts +3 -0
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +135 -25
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +77 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1,91 +1,234 @@
1
1
  const require_types = require("./types.cjs");
2
2
  const require_ids = require("./ids.cjs");
3
- const require_tokens = require("./tokens.cjs");
3
+ const require_settle = require("./settle.cjs");
4
+ const require_imports = require("./imports.cjs");
4
5
  const require_sandbox = require("./sandbox.cjs");
5
- let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
6
+ const require_block_storage = require("./block-storage.cjs");
7
+ const require_readiness = require("./readiness.cjs");
8
+ const require_block_state = require("./block-state.cjs");
6
9
  let zod = require("zod");
7
- let _platforma_sdk_model = require("@platforma-sdk/model");
8
10
  // src/tools/await.ts
11
+ /**
12
+ * The default wait of `await_block_done`, in milliseconds: under the 60 s after which common MCP
13
+ * clients give up on a request (D-018).
14
+ */
15
+ const AWAIT_DEFAULT_MS = 5e4;
16
+ /** The shortest wait `await_block_done` takes. */
17
+ const AWAIT_MIN_MS = 1e3;
18
+ /** The longest wait `await_block_done` takes, for clients whose request timeout is that long. */
19
+ const AWAIT_MAX_MS = 6e5;
20
+ /** Default timeout of a `transform` of `await_block_done`, in milliseconds. */
21
+ const DEFAULT_TRANSFORM_TIMEOUT = 5e3;
22
+ /** What a block in limbo means, and what brings it back. */
23
+ const LIMBO_NOTE = "The block is in limbo: its results are from before a block above it changed. That happens when a block above failed or was stopped, and also when a block above was run again: a run of an upstream block moves the settled blocks below it to limbo. run_block on this block runs it again, together with the stale blocks above it.";
24
+ /** What a block that is not calculated means. */
25
+ const NOT_CALCULATED_NOTE = "The block has not been run, or its run was reset before it finished. There is nothing to wait for: run_block starts it, then call await_block_done again.";
26
+ /** The block's overview fields every answer of `await_block_done` carries. */
27
+ function blockInfo(block) {
28
+ return {
29
+ id: block.id,
30
+ title: block.title ?? block.label,
31
+ calculationStatus: block.calculationStatus,
32
+ canRun: block.canRun,
33
+ stale: block.stale,
34
+ outputErrors: block.outputErrors
35
+ };
36
+ }
37
+ /** The answer for a block whose status ends the wait without results: not calculated, in limbo. */
38
+ async function stoppedAnswer(project, projectId, blockId, status, waitedMs, upstreamHalt) {
39
+ const { block, error } = await require_readiness.findBlock(project, projectId, blockId);
40
+ if (error) return error;
41
+ const state = await project.getBlockState(blockId).getValue();
42
+ const pendingOutputs = require_settle.pendingOutputKeys(state.outputs);
43
+ const notes = [status === "Limbo" ? LIMBO_NOTE : NOT_CALCULATED_NOTE];
44
+ if (upstreamHalt !== void 0 && pendingOutputs.length > 0) notes.push(`Some outputs wait for block ${upstreamHalt.waitingOn} above, which ` + (upstreamHalt.running ? "is running: await_block_done on it, then on this block." : "has not run: run_block on this block runs it with the stale blocks above."));
45
+ return require_types.textResult({
46
+ status,
47
+ note: notes.join(" "),
48
+ block: blockInfo(block),
49
+ waitedMs,
50
+ readiness: await require_block_state.readinessOf(project, blockId),
51
+ ...require_block_storage.blockView(state),
52
+ outputsSettled: pendingOutputs.length === 0,
53
+ ...upstreamHalt !== void 0 && pendingOutputs.length > 0 ? {
54
+ pendingOutputs,
55
+ waitingOn: upstreamHalt.waitingOn,
56
+ waitingOnStatus: upstreamHalt.waitingOnStatus
57
+ } : {}
58
+ });
59
+ }
60
+ /**
61
+ * Waits for a block's run to finish and its outputs to settle, and with `waitForImports` for its
62
+ * files to upload; returns the result of `await_block_done`. One clock and one progress reporter
63
+ * run across both waits, so the progress a client sees only grows. A block that was never run or
64
+ * is in limbo has no run to wait for, but its imports are still waited for when asked: its
65
+ * pre-run may be uploading files. Its outputs are waited for first, within the same deadline: an
66
+ * output still computing may be the one that names the files, so no imports count as done only
67
+ * once the outputs settled (or wait for a block above that is running or has not run). A block
68
+ * somebody runs while that wait goes on is answered as such (not finished, call again), so the
69
+ * answer never says a running block has not run.
70
+ */
71
+ async function awaitBlockDone(project, input, options = {}) {
72
+ const { projectId, blockId, transform, waitForImports } = input;
73
+ const { call } = options;
74
+ const found = await require_readiness.findBlock(project, projectId, blockId);
75
+ if (found.error) return found.error;
76
+ const timeoutMs = require_settle.clampWait(input.timeout, AWAIT_DEFAULT_MS, AWAIT_MIN_MS, AWAIT_MAX_MS);
77
+ const start = Date.now();
78
+ const report = require_settle.progressReporter(call, "Waiting for the block to finish");
79
+ const progress = (message) => report === void 0 ? void 0 : () => report(Date.now() - start, timeoutMs, message);
80
+ const signal = call?.mcpReq.signal;
81
+ const timeLeft = () => Math.max(0, timeoutMs - (Date.now() - start));
82
+ /** The block's calculation status now; `undefined` when it cannot be read. */
83
+ const statusNow = async () => {
84
+ return (await require_readiness.findBlock(project, projectId, blockId)).block?.calculationStatus;
85
+ };
86
+ /** Waits for the block's imports with what is left of the time; `undefined` when they are in. */
87
+ const importsLeft = async (status) => {
88
+ const imports = await require_imports.awaitImportsDone(project.getBlockState(blockId), {
89
+ timeoutMs: timeLeft(),
90
+ signal,
91
+ onProgress: progress("Waiting for the block's imports")
92
+ });
93
+ if (imports.done) return { state: imports.state };
94
+ const now = await statusNow() ?? status;
95
+ return { result: require_types.timedOutResult({
96
+ status: now,
97
+ settled: now === "Done",
98
+ waitedMs: Date.now() - start,
99
+ imports: imports.imports,
100
+ hint: (now === "Done" ? "The block's run is over but some of its files " : now === "Running" ? "The block is running; some of its files " : "The block has not run; some of the files its data names ") + "are still uploading or being indexed. Call await_block_done with waitForImports again."
101
+ }) };
102
+ };
103
+ const stopped = async (status) => {
104
+ if (waitForImports !== true) return await stoppedAnswer(project, projectId, blockId, status, Date.now() - start);
105
+ const outputs = await require_settle.awaitBlockSettled(project, blockId, {
106
+ timeoutMs: timeLeft(),
107
+ signal,
108
+ waitForRun: false,
109
+ onProgress: progress("Waiting for the block's outputs to settle")
110
+ });
111
+ if (outputs.stoppedBy === "block-gone") return blockGone();
112
+ if (outputs.stoppedBy === "timeout" || outputs.stoppedBy === "aborted") return require_types.timedOutResult({
113
+ status,
114
+ settled: false,
115
+ waitedMs: Date.now() - start,
116
+ pendingOutputs: outputs.pendingOutputs,
117
+ hint: "The block has not run; some of its outputs are still computing, and they may name files to upload. Call await_block_done with waitForImports again."
118
+ });
119
+ const afterOutputs = await stillStopped(status);
120
+ if (afterOutputs.result !== void 0) return afterOutputs.result;
121
+ const left = await importsLeft(afterOutputs.status);
122
+ if (left.result !== void 0) return left.result;
123
+ const halt = outputs.waitingOn === void 0 ? void 0 : {
124
+ waitingOn: outputs.waitingOn,
125
+ waitingOnStatus: outputs.waitingOnStatus,
126
+ running: outputs.stoppedBy === "upstream-running"
127
+ };
128
+ const afterImports = await stillStopped(afterOutputs.status);
129
+ if (afterImports.result !== void 0) return afterImports.result;
130
+ return await stoppedAnswer(project, projectId, blockId, afterImports.status, Date.now() - start, halt);
131
+ };
132
+ /**
133
+ * After a wait on a block that had not run, its status now: still not calculated or in limbo,
134
+ * or, when somebody ran it meanwhile, an answer saying so, for the agent to wait for the run.
135
+ */
136
+ const stillStopped = async (status) => {
137
+ const now = await require_readiness.findBlock(project, projectId, blockId);
138
+ if (now.error) return { result: now.error };
139
+ const current = now.block.calculationStatus;
140
+ if (current === "NotCalculated" || current === "Limbo") return { status: current };
141
+ if (current === void 0) return { status };
142
+ return { result: require_types.timedOutResult({
143
+ status: current,
144
+ settled: false,
145
+ waitedMs: Date.now() - start,
146
+ hint: "The block was run while waiting. Call await_block_done again to wait for the run."
147
+ }) };
148
+ };
149
+ const blockGone = () => require_types.errorResult(`Block ${blockId} was removed from project ${projectId} while waiting.`, "Use get_project_overview to list the block ids of the project.");
150
+ /** Waits for the block's run with what is left of the time, then answers. */
151
+ const awaitRun = async () => {
152
+ const settle = await require_settle.awaitBlockSettled(project, blockId, {
153
+ timeoutMs: timeLeft(),
154
+ signal,
155
+ waitForRun: true,
156
+ onProgress: progress("Waiting for the block to finish")
157
+ });
158
+ if (settle.stoppedBy === "block-gone") return blockGone();
159
+ if (settle.stoppedBy === "not-calculated") return await stopped("NotCalculated");
160
+ if (settle.stoppedBy === "limbo") return await stopped("Limbo");
161
+ if (!settle.settled) return require_types.timedOutResult({
162
+ status: settle.calculationStatus ?? "Unknown",
163
+ settled: false,
164
+ waitedMs: Date.now() - start,
165
+ pendingOutputs: settle.pendingOutputs,
166
+ ...settle.waitingOn !== void 0 ? { waitingOn: settle.waitingOn } : {},
167
+ runningUpstreams: settle.runningUpstreams,
168
+ hint: settle.stoppedBy === "upstream-running" && settle.waitingOn !== void 0 ? `The outputs wait for block ${settle.waitingOn} above, which is running: await_block_done on it, then on this block.` : settle.calculationStatus === "Running" ? "Not finished: the block is still running. Call await_block_done again." : "Not finished: some outputs are still computing. Call await_block_done again."
169
+ });
170
+ let state = settle.state;
171
+ if (waitForImports === true) {
172
+ const left = await importsLeft("Done");
173
+ if (left.result !== void 0) return left.result;
174
+ state = left.state;
175
+ }
176
+ const { block, error } = await require_readiness.findBlock(project, projectId, blockId);
177
+ if (error) return error;
178
+ const info = blockInfo(block);
179
+ if (transform) try {
180
+ const result = await require_sandbox.safeEval(transform, {
181
+ data: require_block_storage.readStorageView(state.blockStorage).data,
182
+ outputs: state.outputs,
183
+ block: info
184
+ }, input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT);
185
+ return require_types.textResult({
186
+ status: "Done",
187
+ block: info,
188
+ ...require_readiness.staleResults(block),
189
+ result
190
+ });
191
+ } catch (e) {
192
+ return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, outputs, block.");
193
+ }
194
+ return require_types.textResult({
195
+ status: "Done",
196
+ ...require_readiness.staleResults(block),
197
+ block: info,
198
+ waitedMs: Date.now() - start,
199
+ readiness: await require_block_state.readinessOf(project, blockId),
200
+ ...require_block_storage.blockView(state)
201
+ });
202
+ };
203
+ const initial = found.block.calculationStatus;
204
+ if (initial === "NotCalculated" || initial === "Limbo") return await stopped(initial);
205
+ return await awaitRun();
206
+ }
9
207
  function registerAwaitTools(server, ctx) {
10
208
  server.registerTool("await_block_done", {
11
209
  title: "Wait for Block",
12
210
  annotations: require_types.hints.read,
13
- description: "Wait for a block to finish computation and outputs to stabilize. Returns block status, data, and concise output summary with token estimates. Use `transform` to extract specific data server-side on completion.",
211
+ description: `Wait for a block's run to finish and its outputs to settle. Returns the block status and the block view of get_block_state (data, plugins, output summary, readiness); large data comes as an outline, as there. Use \`transform\` to extract specific data server-side on completion.
212
+
213
+ Waits up to \`timeout\` (default ${AWAIT_DEFAULT_MS} ms, under the 60 s after which most clients give up; raise it only when your client waits longer). A wait that runs out is not an error: \`{ timedOut: true, status, pendingOutputs, waitingOn?, runningUpstreams }\`, the block is not finished: call again. A block that was never run (status NotCalculated) or is in limbo (results from before a block above changed: it failed, was stopped, or ran again) returns with a \`note\`; run_block starts it. A block whose results are from an earlier configuration (its data, or the data of a block above, changed after the run) is Done with \`stale: true\` and a \`note\`. \`waitForImports\` also waits for the files the block imports (its \`imports\` summary), for a block that has not run too, once its pre-run outputs settle: its pre-run uploads the files its data names.`,
14
214
  inputSchema: zod.z.object({
15
215
  projectId: require_ids.projectIdInput.describe("Project ID"),
16
216
  blockId: require_ids.blockIdInput.describe("Block ID to wait for"),
17
- timeout: zod.z.number().optional().default(12e4).describe("Timeout in ms (default 120000)"),
18
- transform: zod.z.string().optional().describe("JS expression evaluated server-side when block completes. Available variables: `data` (block args), `outputs` (raw outputs), `block` (status info). Omit for default concise summary."),
19
- transformTimeout: zod.z.number().optional().default(5e3).describe("Timeout in ms for transform evaluation (default 5000).")
217
+ timeout: zod.z.number().optional().default(AWAIT_DEFAULT_MS).describe(`The longest wait in ms (default ${AWAIT_DEFAULT_MS}, from ${AWAIT_MIN_MS} to ${AWAIT_MAX_MS}).`),
218
+ transform: zod.z.string().optional().describe("JS expression evaluated server-side when block completes. Available variables: `data` (block data), `outputs` (raw outputs), `block` (status info). Omit for default concise summary."),
219
+ transformTimeout: zod.z.number().optional().default(DEFAULT_TRANSFORM_TIMEOUT).describe(require_sandbox.expressionTimeoutText("transform evaluation", DEFAULT_TRANSFORM_TIMEOUT)),
220
+ waitForImports: zod.z.boolean().optional().describe("Also wait until the files the block imports are uploaded or indexed (its `imports` summary has nothing left to finish), within the same `timeout` (default false).")
20
221
  })
21
- }, async ({ projectId, blockId, timeout, transform, transformTimeout }) => {
22
- return await ctx.withProject(projectId, async (project) => {
23
- const deadline = Date.now() + timeout;
24
- while (Date.now() < deadline) {
25
- const overview = await project.overview.getValue();
26
- if (!overview) continue;
27
- const block = overview.blocks.find((b) => b.id === blockId);
28
- if (!block) return require_types.errorResult(`Block ${blockId} not found in project ${projectId}.`, "Use get_project_overview to list all block IDs in this project.");
29
- if (block.calculationStatus === "Limbo") return require_types.errorResult("Block entered Limbo state (upstream failed or was stopped).", "Check upstream blocks with get_project_overview. Fix or re-run the failed upstream, then retry.");
30
- if (block.calculationStatus === "NotCalculated") return require_types.errorResult("Block has not been started.", "Use run_block to start it first, then call await_block_done.");
31
- if (block.calculationStatus === "Done") {
32
- const remaining = Math.max(deadline - Date.now(), 1e3);
33
- let state;
34
- try {
35
- state = await project.getBlockState(blockId).awaitStableValue(AbortSignal.timeout(remaining));
36
- } catch (e) {
37
- if ((0, _milaboratories_pl_middle_layer.isTimeoutError)(e)) return require_types.timedOutResult({
38
- status: "Done",
39
- note: "Computation done but outputs did not stabilize in time. Retry with a longer timeout."
40
- });
41
- return require_types.errorResult(`Failed to get block state: ${e instanceof Error ? e.message : String(e)}`);
42
- }
43
- const data = (0, _platforma_sdk_model.deriveDataFromStorage)(state.blockStorage);
44
- const blockInfo = {
45
- id: block.id,
46
- title: block.title ?? block.label,
47
- calculationStatus: block.calculationStatus,
48
- canRun: block.canRun,
49
- stale: block.stale,
50
- outputErrors: block.outputErrors
51
- };
52
- if (transform) try {
53
- const result = await require_sandbox.safeEval(transform, {
54
- data,
55
- outputs: state.outputs,
56
- block: blockInfo
57
- }, transformTimeout);
58
- return require_types.textResult({
59
- status: "Done",
60
- block: blockInfo,
61
- result
62
- });
63
- } catch (e) {
64
- return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, outputs, block.");
65
- }
66
- return require_types.textResult({
67
- status: "Done",
68
- block: blockInfo,
69
- data,
70
- outputs: require_tokens.summarizeOutputs(state.outputs)
71
- });
72
- }
73
- const pollStart = Date.now();
74
- try {
75
- const result = await project.overview.getFullValue();
76
- await project.overview.awaitChange(AbortSignal.timeout(5e3), result.uTag);
77
- } catch {}
78
- const elapsed = Date.now() - pollStart;
79
- if (elapsed < 500) await new Promise((r) => setTimeout(r, 500 - elapsed));
80
- }
81
- const block = (await project.overview.getValue())?.blocks.find((b) => b.id === blockId);
82
- return require_types.timedOutResult({
83
- status: block?.calculationStatus ?? "Unknown",
84
- hint: "The block is still running. Call await_block_done again with a longer timeout."
85
- });
86
- });
222
+ }, async (input, call) => {
223
+ return await ctx.withProject(input.projectId, (project) => awaitBlockDone(project, input, { call }));
87
224
  });
88
225
  }
226
+ exports.AWAIT_DEFAULT_MS = AWAIT_DEFAULT_MS;
227
+ exports.AWAIT_MAX_MS = AWAIT_MAX_MS;
228
+ exports.AWAIT_MIN_MS = AWAIT_MIN_MS;
229
+ exports.LIMBO_NOTE = LIMBO_NOTE;
230
+ exports.NOT_CALCULATED_NOTE = NOT_CALCULATED_NOTE;
231
+ exports.awaitBlockDone = awaitBlockDone;
89
232
  exports.registerAwaitTools = registerAwaitTools;
90
233
 
91
234
  //# sourceMappingURL=await.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"await.cjs","names":["hints","z","projectIdInput","blockIdInput","errorResult","isTimeoutError","timedOutResult","deriveDataFromStorage","safeEval","textResult","transformFailedResult","summarizeOutputs"],"sources":["../../src/tools/await.ts"],"sourcesContent":["import { isTimeoutError } from \"@milaboratories/pl-middle-layer\";\nimport { deriveDataFromStorage } from \"@platforma-sdk/model\";\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, timedOutResult, transformFailedResult } from \"./types\";\n\nexport function registerAwaitTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"await_block_done\",\n {\n title: \"Wait for Block\",\n annotations: hints.read,\n description:\n \"Wait for a block to finish computation and outputs to stabilize. \" +\n \"Returns block status, data, and concise output summary with token estimates. \" +\n \"Use `transform` to extract specific data server-side on completion.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID to wait for\"),\n timeout: z.number().optional().default(120000).describe(\"Timeout in ms (default 120000)\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side when block completes. \" +\n \"Available variables: `data` (block args), `outputs` (raw outputs), `block` (status info). \" +\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, timeout, transform, transformTimeout }) => {\n return await ctx.withProject(projectId, async (project) => {\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const overview = await project.overview.getValue();\n if (!overview) continue;\n const block = overview.blocks.find((b) => b.id === blockId);\n if (!block)\n return errorResult(\n `Block ${blockId} not found in project ${projectId}.`,\n \"Use get_project_overview to list all block IDs in this project.\",\n );\n\n // Terminal error states — return immediately\n if (block.calculationStatus === \"Limbo\") {\n return errorResult(\n \"Block entered Limbo state (upstream failed or was stopped).\",\n \"Check upstream blocks with get_project_overview. Fix or re-run the failed upstream, then retry.\",\n );\n }\n\n if (block.calculationStatus === \"NotCalculated\") {\n return errorResult(\n \"Block has not been started.\",\n \"Use run_block to start it first, then call await_block_done.\",\n );\n }\n\n if (block.calculationStatus === \"Done\") {\n // Await stable block state with remaining time budget\n const remaining = Math.max(deadline - Date.now(), 1000);\n let state;\n try {\n state = await project\n .getBlockState(blockId)\n .awaitStableValue(AbortSignal.timeout(remaining));\n } catch (e: unknown) {\n if (isTimeoutError(e)) {\n return timedOutResult({\n status: \"Done\",\n note: \"Computation done but outputs did not stabilize in time. Retry with a longer timeout.\",\n });\n }\n return errorResult(\n `Failed to get block state: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n\n const data = deriveDataFromStorage(state.blockStorage);\n\n const blockInfo = {\n id: block.id,\n title: block.title ?? block.label,\n calculationStatus: block.calculationStatus,\n canRun: block.canRun,\n stale: block.stale,\n outputErrors: block.outputErrors,\n };\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n data,\n outputs: state.outputs,\n block: blockInfo,\n },\n transformTimeout,\n );\n return textResult({ status: \"Done\", block: blockInfo, result });\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: data, outputs, block.\",\n );\n }\n }\n\n return textResult({\n status: \"Done\",\n block: blockInfo,\n data,\n outputs: summarizeOutputs(state.outputs as Record<string, unknown> | undefined),\n });\n }\n\n // Still running — wait up to 5s for overview to change, then re-poll.\n // Minimum 500ms delay to avoid busy-looping if awaitChange resolves immediately.\n const pollStart = Date.now();\n try {\n const result = await project.overview.getFullValue();\n await project.overview.awaitChange(AbortSignal.timeout(5000), result.uTag);\n } catch {\n // timeout or abort — just re-poll\n }\n const elapsed = Date.now() - pollStart;\n if (elapsed < 500) {\n await new Promise((r) => setTimeout(r, 500 - elapsed));\n }\n }\n\n // Timed out while running\n const overview = await project.overview.getValue();\n const block = overview?.blocks.find((b) => b.id === blockId);\n return timedOutResult({\n status: block?.calculationStatus ?? \"Unknown\",\n hint: \"The block is still running. Call await_block_done again with a longer timeout.\",\n });\n });\n },\n );\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,mBAAmB,QAAuB,KAAwB;CAChF,OAAO,aACL,oBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;EAGF,aAAaC,IAAAA,EAAE,OAAO;GACpB,WAAWC,YAAAA,eAAe,SAAS,YAAY;GAC/C,SAASC,YAAAA,aAAa,SAAS,sBAAsB;GACrD,SAASF,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,IAAM,CAAC,CAAC,SAAS,gCAAgC;GACxF,WAAWA,IAAAA,EACR,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,uLAGF;GACF,kBAAkBA,IAAAA,EACf,OAAO,CAAC,CACR,SAAS,CAAC,CACV,QAAQ,GAAI,CAAC,CACb,SAAS,wDAAwD;EACtE,CAAC;CACH,GACA,OAAO,EAAE,WAAW,SAAS,SAAS,WAAW,uBAAuB;EACtE,OAAO,MAAM,IAAI,YAAY,WAAW,OAAO,YAAY;GACzD,MAAM,WAAW,K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A,sBACL,GACA,6EACF;KACF;KAGF,OAAOD,cAAAA,WAAW;MAChB,QAAQ;MACR,OAAO;MACP;MACA,SAASE,eAAAA,iBAAiB,MAAM,OAA8C;KAChF,CAAC;IACH;IAIA,MAAM,YAAY,KAAK,IAAI;IAC3B,IAAI;KACF,MAAM,SAAS,MAAM,QAAQ,SAAS,aAAa;KACnD,MAAM,QAAQ,SAAS,YAAY,YAAY,QAAQ,GAAI,GAAG,OAAO,IAAI;IAC3E,QAAQ,CAER;IACA,MAAM,UAAU,KAAK,IAAI,IAAI;IAC7B,IAAI,UAAU,KACZ,MAAM,IAAI,SAAS,MAAM,WAAW,GAAG,MAAM,OAAO,CAAC;GAEzD;GAIA,MAAM,SAAQ,MADS,QAAQ,SAAS,SAAS,EAAA,EACzB,OAAO,MAAM,MAAM,EAAE,OAAO,OAAO;GAC3D,OAAOL,cAAAA,eAAe;IACpB,QAAQ,OAAO,qBAAqB;IACpC,MAAM;GACR,CAAC;EACH,CAAC;CACH,CACF;AACF"}
1
+ {"version":3,"file":"await.cjs","names":["findBlock","pendingOutputKeys","textResult","readinessOf","blockView","clampWait","progressReporter","awaitImportsDone","timedOutResult","awaitBlockSettled","errorResult","safeEval","readStorageView","staleResults","transformFailedResult","hints","z","projectIdInput","blockIdInput","expressionTimeoutText"],"sources":["../../src/tools/await.ts"],"sourcesContent":["import type { BlockId, ProjectId } from \"@milaboratories/pl-model-common\";\nimport type { BlockReadiness, BlockStateOverview } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { blockIdInput, projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { blockView, readStorageView } from \"./block-storage\";\nimport { readinessOf } from \"./block-state\";\nimport { awaitImportsDone } from \"./imports\";\nimport { findBlock, staleResults } from \"./readiness\";\nimport { expressionTimeoutText, safeEval } from \"./sandbox\";\nimport {\n awaitBlockSettled,\n clampWait,\n pendingOutputKeys,\n progressReporter,\n type SettleStateComputable,\n type WaitContext,\n} from \"./settle\";\nimport { errorResult, hints, textResult, timedOutResult, transformFailedResult } from \"./types\";\n\n/**\n * The default wait of `await_block_done`, in milliseconds: under the 60 s after which common MCP\n * clients give up on a request (D-018).\n */\nexport const AWAIT_DEFAULT_MS = 50_000;\n/** The shortest wait `await_block_done` takes. */\nexport const AWAIT_MIN_MS = 1_000;\n/** The longest wait `await_block_done` takes, for clients whose request timeout is that long. */\nexport const AWAIT_MAX_MS = 600_000;\n\n/** Default timeout of a `transform` of `await_block_done`, in milliseconds. */\nconst DEFAULT_TRANSFORM_TIMEOUT = 5000;\n\n/** What a block in limbo means, and what brings it back. */\nexport const LIMBO_NOTE =\n \"The block is in limbo: its results are from before a block above it changed. That happens \" +\n \"when a block above failed or was stopped, and also when a block above was run again: a run \" +\n \"of an upstream block moves the settled blocks below it to limbo. run_block on this block \" +\n \"runs it again, together with the stale blocks above it.\";\n\n/** What a block that is not calculated means. */\nexport const NOT_CALCULATED_NOTE =\n \"The block has not been run, or its run was reset before it finished. There is nothing to \" +\n \"wait for: run_block starts it, then call await_block_done again.\";\n\n/** What `await_block_done` reads of a block of the project overview. */\nexport type AwaitOverviewBlock = Pick<\n BlockStateOverview,\n | \"id\"\n | \"title\"\n | \"label\"\n | \"calculationStatus\"\n | \"canRun\"\n | \"stale\"\n | \"outputErrors\"\n | \"missingReference\"\n | \"upstreams\"\n>;\n\n/** What `await_block_done` reads of a block state. */\nexport type AwaitBlockState = {\n outputs?: Record<string, unknown> | undefined;\n blockStorage: unknown;\n};\n\n/** What `await_block_done` needs of a project; a middle-layer `Project` has it. */\nexport type AwaitProject = {\n overview: { getValue(): Promise<{ blocks: AwaitOverviewBlock[] } | undefined> };\n getBlockState(blockId: BlockId): SettleStateComputable<AwaitBlockState> & {\n getValue(): Promise<AwaitBlockState>;\n };\n getBlockReadiness(blockId: BlockId): { getValue(): Promise<BlockReadiness | undefined> };\n};\n\n/** What {@link awaitBlockDone} returns: the result of `await_block_done`. */\ntype AwaitResult = ReturnType<typeof textResult> | ReturnType<typeof errorResult>;\n\n/** Input of {@link awaitBlockDone}: the arguments of `await_block_done`. */\nexport type AwaitInput = {\n projectId: ProjectId;\n blockId: BlockId;\n timeout?: number;\n transform?: string;\n transformTimeout?: number;\n waitForImports?: boolean;\n};\n\n/** The block's overview fields every answer of `await_block_done` carries. */\nfunction blockInfo(block: AwaitOverviewBlock) {\n return {\n id: block.id,\n title: block.title ?? block.label,\n calculationStatus: block.calculationStatus,\n canRun: block.canRun,\n stale: block.stale,\n outputErrors: block.outputErrors,\n };\n}\n\n/** The answer for a block whose status ends the wait without results: not calculated, in limbo. */\nasync function stoppedAnswer(\n project: AwaitProject,\n projectId: ProjectId,\n blockId: BlockId,\n status: \"NotCalculated\" | \"Limbo\",\n waitedMs: number,\n upstreamHalt?: { waitingOn: BlockId; waitingOnStatus: string | undefined; running: boolean },\n) {\n const { block, error } = await findBlock(project, projectId, blockId);\n if (error) return error;\n const state = await project.getBlockState(blockId).getValue();\n const pendingOutputs = pendingOutputKeys(state.outputs);\n const notes = [status === \"Limbo\" ? LIMBO_NOTE : NOT_CALCULATED_NOTE];\n if (upstreamHalt !== undefined && pendingOutputs.length > 0)\n notes.push(\n `Some outputs wait for block ${upstreamHalt.waitingOn} above, which ` +\n (upstreamHalt.running\n ? \"is running: await_block_done on it, then on this block.\"\n : \"has not run: run_block on this block runs it with the stale blocks above.\"),\n );\n return textResult({\n status,\n note: notes.join(\" \"),\n block: blockInfo(block),\n waitedMs,\n readiness: await readinessOf(project, blockId),\n ...blockView(state),\n outputsSettled: pendingOutputs.length === 0,\n ...(upstreamHalt !== undefined && pendingOutputs.length > 0\n ? {\n pendingOutputs,\n waitingOn: upstreamHalt.waitingOn,\n waitingOnStatus: upstreamHalt.waitingOnStatus,\n }\n : {}),\n });\n}\n\n/**\n * Waits for a block's run to finish and its outputs to settle, and with `waitForImports` for its\n * files to upload; returns the result of `await_block_done`. One clock and one progress reporter\n * run across both waits, so the progress a client sees only grows. A block that was never run or\n * is in limbo has no run to wait for, but its imports are still waited for when asked: its\n * pre-run may be uploading files. Its outputs are waited for first, within the same deadline: an\n * output still computing may be the one that names the files, so no imports count as done only\n * once the outputs settled (or wait for a block above that is running or has not run). A block\n * somebody runs while that wait goes on is answered as such (not finished, call again), so the\n * answer never says a running block has not run.\n */\nexport async function awaitBlockDone(\n project: AwaitProject,\n input: AwaitInput,\n options: { call?: WaitContext } = {},\n): Promise<AwaitResult> {\n const { projectId, blockId, transform, waitForImports } = input;\n const { call } = options;\n const found = await findBlock(project, projectId, blockId);\n if (found.error) return found.error;\n\n const timeoutMs = clampWait(input.timeout, AWAIT_DEFAULT_MS, AWAIT_MIN_MS, AWAIT_MAX_MS);\n const start = Date.now();\n const report = progressReporter(call, \"Waiting for the block to finish\");\n const progress = (message: string) =>\n report === undefined ? undefined : () => report(Date.now() - start, timeoutMs, message);\n const signal = call?.mcpReq.signal;\n\n const timeLeft = () => Math.max(0, timeoutMs - (Date.now() - start));\n\n /** The block's calculation status now; `undefined` when it cannot be read. */\n const statusNow = async () => {\n const now = await findBlock(project, projectId, blockId);\n return now.block?.calculationStatus;\n };\n\n /** Waits for the block's imports with what is left of the time; `undefined` when they are in. */\n const importsLeft = async (status: string) => {\n const imports = await awaitImportsDone(project.getBlockState(blockId), {\n timeoutMs: timeLeft(),\n signal,\n onProgress: progress(\"Waiting for the block's imports\"),\n });\n if (imports.done) return { state: imports.state };\n // The status may have changed while the imports were waited for: somebody ran the block.\n const now = (await statusNow()) ?? status;\n return {\n result: timedOutResult({\n status: now,\n settled: now === \"Done\",\n waitedMs: Date.now() - start,\n imports: imports.imports,\n hint:\n (now === \"Done\"\n ? \"The block's run is over but some of its files \"\n : now === \"Running\"\n ? \"The block is running; some of its files \"\n : \"The block has not run; some of the files its data names \") +\n \"are still uploading or being indexed. Call await_block_done with waitForImports again.\",\n }),\n };\n };\n\n const stopped = async (status: \"NotCalculated\" | \"Limbo\"): Promise<AwaitResult> => {\n if (waitForImports !== true)\n return await stoppedAnswer(project, projectId, blockId, status, Date.now() - start);\n\n // The pre-run outputs first: until they settle, an empty progress map may only mean the\n // output that names the files has not computed yet.\n const outputs = await awaitBlockSettled(project, blockId, {\n timeoutMs: timeLeft(),\n signal,\n waitForRun: false,\n onProgress: progress(\"Waiting for the block's outputs to settle\"),\n });\n if (outputs.stoppedBy === \"block-gone\") return blockGone();\n if (outputs.stoppedBy === \"timeout\" || outputs.stoppedBy === \"aborted\")\n return timedOutResult({\n status,\n settled: false,\n waitedMs: Date.now() - start,\n pendingOutputs: outputs.pendingOutputs,\n hint:\n \"The block has not run; some of its outputs are still computing, and they may name \" +\n \"files to upload. Call await_block_done with waitForImports again.\",\n });\n\n // Somebody may have run the block while its outputs were waited for.\n const afterOutputs = await stillStopped(status);\n if (afterOutputs.result !== undefined) return afterOutputs.result;\n\n const left = await importsLeft(afterOutputs.status);\n if (left.result !== undefined) return left.result;\n const halt =\n outputs.waitingOn === undefined\n ? undefined\n : {\n waitingOn: outputs.waitingOn,\n waitingOnStatus: outputs.waitingOnStatus,\n running: outputs.stoppedBy === \"upstream-running\",\n };\n\n // ... or while its imports were.\n const afterImports = await stillStopped(afterOutputs.status);\n if (afterImports.result !== undefined) return afterImports.result;\n return await stoppedAnswer(\n project,\n projectId,\n blockId,\n afterImports.status,\n Date.now() - start,\n halt,\n );\n };\n\n /**\n * After a wait on a block that had not run, its status now: still not calculated or in limbo,\n * or, when somebody ran it meanwhile, an answer saying so, for the agent to wait for the run.\n */\n const stillStopped = async (\n status: \"NotCalculated\" | \"Limbo\",\n ): Promise<\n | { status: \"NotCalculated\" | \"Limbo\"; result?: undefined }\n | { status?: undefined; result: AwaitResult }\n > => {\n const now = await findBlock(project, projectId, blockId);\n if (now.error) return { result: now.error };\n const current = now.block.calculationStatus;\n if (current === \"NotCalculated\" || current === \"Limbo\") return { status: current };\n if (current === undefined) return { status };\n return {\n result: timedOutResult({\n status: current,\n settled: false,\n waitedMs: Date.now() - start,\n hint: \"The block was run while waiting. Call await_block_done again to wait for the run.\",\n }),\n };\n };\n\n const blockGone = () =>\n errorResult(\n `Block ${blockId} was removed from project ${projectId} while waiting.`,\n \"Use get_project_overview to list the block ids of the project.\",\n );\n\n /** Waits for the block's run with what is left of the time, then answers. */\n const awaitRun = async (): Promise<AwaitResult> => {\n const settle = await awaitBlockSettled(project, blockId, {\n timeoutMs: timeLeft(),\n signal,\n waitForRun: true,\n onProgress: progress(\"Waiting for the block to finish\"),\n });\n\n if (settle.stoppedBy === \"block-gone\") return blockGone();\n if (settle.stoppedBy === \"not-calculated\") return await stopped(\"NotCalculated\");\n if (settle.stoppedBy === \"limbo\") return await stopped(\"Limbo\");\n\n if (!settle.settled)\n return timedOutResult({\n status: settle.calculationStatus ?? \"Unknown\",\n settled: false,\n waitedMs: Date.now() - start,\n pendingOutputs: settle.pendingOutputs,\n ...(settle.waitingOn !== undefined ? { waitingOn: settle.waitingOn } : {}),\n runningUpstreams: settle.runningUpstreams,\n hint:\n settle.stoppedBy === \"upstream-running\" && settle.waitingOn !== undefined\n ? `The outputs wait for block ${settle.waitingOn} above, which is running: ` +\n \"await_block_done on it, then on this block.\"\n : settle.calculationStatus === \"Running\"\n ? \"Not finished: the block is still running. Call await_block_done again.\"\n : \"Not finished: some outputs are still computing. Call await_block_done again.\",\n });\n\n let state = settle.state;\n if (waitForImports === true) {\n const left = await importsLeft(\"Done\");\n if (left.result !== undefined) return left.result;\n state = left.state;\n }\n\n const { block, error } = await findBlock(project, projectId, blockId);\n if (error) return error;\n const info = blockInfo(block);\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n data: readStorageView(state.blockStorage).data,\n outputs: state.outputs,\n block: info,\n },\n input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT,\n );\n return textResult({ status: \"Done\", block: info, ...staleResults(block), result });\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: data, outputs, block.\",\n );\n }\n }\n\n return textResult({\n status: \"Done\",\n ...staleResults(block),\n block: info,\n waitedMs: Date.now() - start,\n readiness: await readinessOf(project, blockId),\n ...blockView(state),\n });\n };\n\n const initial = found.block.calculationStatus;\n if (initial === \"NotCalculated\" || initial === \"Limbo\") return await stopped(initial);\n return await awaitRun();\n}\n\nexport function registerAwaitTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"await_block_done\",\n {\n title: \"Wait for Block\",\n annotations: hints.read,\n description:\n \"Wait for a block's run to finish and its outputs to settle. Returns the block status \" +\n \"and the block view of get_block_state (data, plugins, output summary, readiness); large \" +\n \"data comes as an outline, as there. Use `transform` to extract specific data \" +\n \"server-side on completion.\\n\\n\" +\n `Waits up to \\`timeout\\` (default ${AWAIT_DEFAULT_MS} ms, under the 60 s after which ` +\n \"most clients give up; raise it only when your client waits longer). A wait that runs \" +\n \"out is not an error: `{ timedOut: true, status, pendingOutputs, waitingOn?, \" +\n \"runningUpstreams }`, the block is not finished: call again. A block that was never run \" +\n \"(status NotCalculated) or is in limbo (results from before a block above changed: it \" +\n \"failed, was stopped, or ran again) returns with a `note`; run_block starts it. A \" +\n \"block whose results are from an earlier configuration (its data, or the data of a \" +\n \"block above, changed after the run) is Done with `stale: true` and a `note`. \" +\n \"`waitForImports` also waits for the files the block imports (its `imports` summary), \" +\n \"for a block that has not run too, once its pre-run outputs settle: its pre-run \" +\n \"uploads the files its data names.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID to wait for\"),\n timeout: z\n .number()\n .optional()\n .default(AWAIT_DEFAULT_MS)\n .describe(\n `The longest wait in ms (default ${AWAIT_DEFAULT_MS}, from ${AWAIT_MIN_MS} to ` +\n `${AWAIT_MAX_MS}).`,\n ),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side when block completes. \" +\n \"Available variables: `data` (block data), `outputs` (raw outputs), `block` (status info). \" +\n \"Omit for default concise summary.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(DEFAULT_TRANSFORM_TIMEOUT)\n .describe(expressionTimeoutText(\"transform evaluation\", DEFAULT_TRANSFORM_TIMEOUT)),\n waitForImports: z\n .boolean()\n .optional()\n .describe(\n \"Also wait until the files the block imports are uploaded or indexed (its `imports` \" +\n \"summary has nothing left to finish), within the same `timeout` (default false).\",\n ),\n }),\n },\n async (input, call) => {\n return await ctx.withProject(input.projectId, (project) =>\n awaitBlockDone(project, input, { call }),\n );\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,MAAa,mBAAmB;;AAEhC,MAAa,eAAe;;AAE5B,MAAa,eAAe;;AAG5B,MAAM,4BAA4B;;AAGlC,MAAa,aACX;;AAMF,MAAa,sBACX;;AA8CF,SAAS,UAAU,OAA2B;CAC5C,OAAO;EACL,IAAI,MAAM;EACV,OAAO,MAAM,SAAS,MAAM;EAC5B,mBAAmB,MAAM;EACzB,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,cAAc,MAAM;CACtB;AACF;;AAGA,eAAe,cACb,SACA,WACA,SACA,QACA,UACA,cACA;CACA,MAAM,EAAE,OAAO,UAAU,MAAMA,kBAAAA,UAAU,SAAS,WAAW,OAAO;CACpE,IAAI,OAAO,OAAO;CAClB,MAAM,QAAQ,MAAM,QAAQ,cAAc,OAAO,CAAC,CAAC,SAAS;CAC5D,MAAM,iBAAiBC,eAAAA,kBAAkB,MAAM,OAAO;CACtD,MAAM,QAAQ,CAAC,WAAW,UAAU,aAAa,mBAAmB;CACpE,IAAI,iBAAiB,KAAA,KAAa,eAAe,SAAS,GACxD,MAAM,KACJ,+BAA+B,aAAa,UAAU,mBACnD,aAAa,UACV,4DACA,4EACR;CACF,OAAOC,cAAAA,WAAW;EAChB;EACA,MAAM,MAAM,KAAK,GAAG;EACpB,OAAO,UAAU,KAAK;EACtB;EACA,WAAW,MAAMC,oBAAAA,YAAY,SAAS,OAAO;EAC7C,GAAGC,sBAAAA,UAAU,KAAK;EAClB,gBAAgB,eAAe,WAAW;EAC1C,GAAI,iBAAi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