@milaboratories/pl-mcp-server 54.0.0 → 55.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +15 -25
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -123
  156. package/src/tools/block-action-context.ts +3 -0
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +135 -25
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +77 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -0,0 +1,643 @@
1
+ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
2
+ const require_types = require("./types.cjs");
3
+ const require_ids = require("./ids.cjs");
4
+ const require_imports = require("./imports.cjs");
5
+ const require_sandbox = require("./sandbox.cjs");
6
+ let _milaboratories_helpers = require("@milaboratories/helpers");
7
+ let zod = require("zod");
8
+ let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
9
+ let node_fs_promises = require("node:fs/promises");
10
+ node_fs_promises = require_runtime.__toESM(node_fs_promises, 1);
11
+ let node_path = require("node:path");
12
+ node_path = require_runtime.__toESM(node_path, 1);
13
+ /** Bytes `read_file` reads by default. */
14
+ const READ_DEFAULT_BYTES = 16384;
15
+ /** The most bytes `read_file` returns. */
16
+ const READ_MAX_BYTES = 65536;
17
+ /** The most bytes `read_file` reads for a `transform`. */
18
+ const READ_MAX_TRANSFORM_BYTES = 4194304;
19
+ /** Default timeout of a `transform`, in milliseconds. */
20
+ const DEFAULT_TRANSFORM_TIMEOUT = 5e3;
21
+ const LOCAL_BLOB_RE = /^blob\+local:\/\/download\/.*#.*$/;
22
+ const REMOTE_BLOB_RE = /^blob\+remote:\/\/download\/.+\/(\d+)#.*$/;
23
+ /** Parses a block-output blob handle (`blob+local://` or `blob+remote://`); else `undefined`. */
24
+ function parseBlobHandle(s) {
25
+ if (LOCAL_BLOB_RE.test(s)) return {
26
+ kind: "local",
27
+ handle: s
28
+ };
29
+ const remote = REMOTE_BLOB_RE.exec(s);
30
+ if (remote !== null) return {
31
+ kind: "remote",
32
+ handle: s,
33
+ size: Number(remote[1])
34
+ };
35
+ }
36
+ /** Whether a storage is on this computer (`local://` handle) or a remote data library. */
37
+ function storageKind(entry) {
38
+ return entry.handle.startsWith("local://") ? "local" : "remote";
39
+ }
40
+ /** The root folder of a local storage, from its handle (`local://<id>/<encoded root>`). */
41
+ function localStorageRoot(entry) {
42
+ return decodeURIComponent(entry.handle.slice(entry.handle.lastIndexOf("/") + 1));
43
+ }
44
+ /** Finds a storage by its id, then by its name. */
45
+ function findStorage(storages, ref) {
46
+ return storages.find((s) => s.id === ref) ?? storages.find((s) => s.name === ref);
47
+ }
48
+ function unknownStorage(ref, storages) {
49
+ return require_types.errorResult(`No storage "${ref}".`, `Storages: ${storages.map((s) => s.id).join(", ") || "none"}. list_files with no arguments lists them.`);
50
+ }
51
+ /** A path of a local storage made absolute: a relative one is under the storage's root. */
52
+ function localPath(entry, p) {
53
+ if (node_path.isAbsolute(p)) return p;
54
+ return node_path.join(entry === void 0 ? "/" : localStorageRoot(entry), p);
55
+ }
56
+ /** A `pattern` of `list_files` that does not parse, or takes too long to match. */
57
+ var PatternError = class extends Error {
58
+ hint;
59
+ constructor(message, hint) {
60
+ super(message);
61
+ this.hint = hint;
62
+ this.name = "PatternError";
63
+ }
64
+ };
65
+ /**
66
+ * The indices of the names `pattern` matches. The caller's regular expression runs in the
67
+ * sandbox, all names in one evaluation under `budgetMs`: a pattern that backtracks
68
+ * catastrophically is stopped there instead of blocking the server. Throws a
69
+ * {@link PatternError} when the pattern does not parse or runs out of time.
70
+ */
71
+ async function matchNames(pattern, names, budgetMs = 500) {
72
+ try {
73
+ return await require_sandbox.safeEval("(() => { const re = new RegExp(pattern); const hits = []; for (let i = 0; i < names.length; i++) if (re.test(names[i])) hits.push(i); return hits; })()", {
74
+ pattern,
75
+ names
76
+ }, budgetMs);
77
+ } catch (e) {
78
+ if (e instanceof require_sandbox.SandboxError && e.errorClass === "timeout") throw new PatternError(`\`pattern\` took longer than ${budgetMs} ms to match ${names.length} ${names.length === 1 ? "name" : "names"}.`, "Simplify it: avoid nested repetition such as `(a+)+`, or anchor it with ^…$.");
79
+ if (e instanceof require_sandbox.SandboxError && e.errorClass === "SyntaxError") throw new PatternError(`\`pattern\` is not a valid regular expression: ${e.message}`, "Give a JavaScript regular expression, e.g. `^S\\d+_R[12]\\.fastq\\.gz$`.");
80
+ throw e;
81
+ }
82
+ }
83
+ /**
84
+ * Filters entries by `type` and `pattern` (tested against the name), sorts them by name and
85
+ * returns the page `[offset, offset + limit)`.
86
+ */
87
+ async function pageEntries(entries, options) {
88
+ let matching = entries.filter((e) => options.type === void 0 || e.type === options.type);
89
+ if (options.pattern !== void 0) {
90
+ const candidates = matching;
91
+ matching = (await matchNames(options.pattern, candidates.map((e) => e.name))).map((i) => candidates[i]);
92
+ }
93
+ matching.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
94
+ const page = matching.slice(options.offset, options.offset + options.limit);
95
+ const end = options.offset + page.length;
96
+ const hasMore = end < matching.length;
97
+ return {
98
+ total: matching.length,
99
+ page,
100
+ hasMore,
101
+ ...hasMore ? { nextOffset: end } : {}
102
+ };
103
+ }
104
+ /** The page size asked for, clamped to `[1, LIST_MAX_LIMIT]`. */
105
+ function clampLimit(limit, fallback, max) {
106
+ if (limit === void 0 || !Number.isFinite(limit)) return fallback;
107
+ return (0, _milaboratories_helpers.clamp)(Math.floor(limit), 1, max);
108
+ }
109
+ /**
110
+ * Lists a local folder. Every entry's type comes from the folder listing (a symbolic link from a
111
+ * `stat` of its target); sizes are read with one `stat` per file of the returned page only, so a
112
+ * large folder costs one listing, not one `stat` per entry.
113
+ */
114
+ async function listLocalFolder(dir, options) {
115
+ const dirents = await node_fs_promises.readdir(dir, { withFileTypes: true });
116
+ const entries = [];
117
+ for (const d of dirents) {
118
+ const full = node_path.join(dir, d.name);
119
+ let type;
120
+ if (d.isFile()) type = "file";
121
+ else if (d.isDirectory()) type = "dir";
122
+ else if (d.isSymbolicLink()) try {
123
+ const st = await node_fs_promises.stat(full);
124
+ type = st.isFile() ? "file" : st.isDirectory() ? "dir" : void 0;
125
+ } catch {
126
+ type = void 0;
127
+ }
128
+ if (type !== void 0) entries.push({
129
+ name: d.name,
130
+ type,
131
+ path: full
132
+ });
133
+ }
134
+ const { total, page, hasMore, nextOffset } = await pageEntries(entries, options);
135
+ const withSizes = await Promise.all(page.map(async (e) => {
136
+ if (e.type !== "file") return e;
137
+ try {
138
+ return {
139
+ ...e,
140
+ size: (await node_fs_promises.stat(e.path)).size
141
+ };
142
+ } catch {
143
+ return e;
144
+ }
145
+ }));
146
+ return {
147
+ total,
148
+ offset: options.offset,
149
+ entries: withSizes,
150
+ hasMore,
151
+ ...nextOffset !== void 0 ? { nextOffset } : {}
152
+ };
153
+ }
154
+ /** Lists a folder of a remote storage; the listing gives sizes. */
155
+ async function listRemoteFolder(ls, storage, dir, options) {
156
+ const { total, page, hasMore, nextOffset } = await pageEntries((await ls.listRemoteFilesWithFileStats(storage.handle, dir)).entries.map((e) => ({
157
+ name: e.name,
158
+ type: e.type,
159
+ path: e.fullPath,
160
+ ...e.type === "file" ? { size: e.size } : {}
161
+ })), options);
162
+ return {
163
+ total,
164
+ offset: options.offset,
165
+ entries: page,
166
+ hasMore,
167
+ ...nextOffset !== void 0 ? { nextOffset } : {}
168
+ };
169
+ }
170
+ /** Makes the import handle of a local file; a folder or a relative path gets an error. */
171
+ async function localFileHandle(ls, p) {
172
+ if (!node_path.isAbsolute(p)) return {
173
+ path: p,
174
+ error: "Not an absolute path."
175
+ };
176
+ try {
177
+ const st = await node_fs_promises.stat(p);
178
+ if (!st.isFile()) return {
179
+ path: p,
180
+ error: "Not a file."
181
+ };
182
+ return {
183
+ path: p,
184
+ handle: await ls.getLocalFileHandle(p),
185
+ size: st.size
186
+ };
187
+ } catch (e) {
188
+ return {
189
+ path: p,
190
+ error: errorText(e)
191
+ };
192
+ }
193
+ }
194
+ /**
195
+ * The `index://` handles of files of a remote storage. A handle carries what the storage's
196
+ * listing gives, so the folder of each file is listed (once per folder) and the file looked up in
197
+ * it by its full path.
198
+ */
199
+ async function remoteFileHandles(ls, storage, paths) {
200
+ const folderOf = (p) => {
201
+ const trimmed = (0, _milaboratories_helpers.trimChars)(p, ["/"]);
202
+ const slash = trimmed.lastIndexOf("/");
203
+ return slash < 0 ? "" : trimmed.slice(0, slash);
204
+ };
205
+ const listings = /* @__PURE__ */ new Map();
206
+ return await Promise.all(paths.map(async (p) => {
207
+ const folder = folderOf(p);
208
+ let listing = listings.get(folder);
209
+ if (listing === void 0) {
210
+ listing = ls.listRemoteFilesWithFileStats(storage.handle, folder);
211
+ listings.set(folder, listing);
212
+ }
213
+ try {
214
+ const { entries } = await listing;
215
+ const entry = entries.find((e) => e.fullPath === p || (0, _milaboratories_helpers.trimChars)(e.fullPath, ["/"]) === (0, _milaboratories_helpers.trimChars)(p, ["/"]));
216
+ if (entry === void 0) return {
217
+ path: p,
218
+ error: "No such file in the storage."
219
+ };
220
+ if (entry.type !== "file") return {
221
+ path: p,
222
+ error: "Not a file."
223
+ };
224
+ return {
225
+ path: p,
226
+ handle: entry.handle,
227
+ size: entry.size
228
+ };
229
+ } catch (e) {
230
+ return {
231
+ path: p,
232
+ error: errorText(e)
233
+ };
234
+ }
235
+ }));
236
+ }
237
+ /** A range clamped to a size: `[from, to)`, empty at or past the end. */
238
+ function clampRange(offset, length, size) {
239
+ const from = (0, _milaboratories_helpers.clamp)(offset, 0, size);
240
+ return {
241
+ from,
242
+ to: (0, _milaboratories_helpers.clamp)(from + length, from, size)
243
+ };
244
+ }
245
+ function isUtf8Continuation(b) {
246
+ return (b & 192) === 128;
247
+ }
248
+ /**
249
+ * Decodes `bytes`, a range of a file, as text of whole characters:
250
+ * - `skipLead` (the range does not start the file): up to 3 leading continuation bytes, the tail
251
+ * of a character begun before the range, are skipped (`skippedBytes`);
252
+ * - unless `atEnd` (the range ends the file), an incomplete character at the end is left for the
253
+ * next read: `usedBytes` stops before it.
254
+ *
255
+ * Content that is not UTF-8, or holds NUL bytes, is binary: all the bytes, none skipped.
256
+ */
257
+ function decodeContent(bytes, options = {}) {
258
+ let start = 0;
259
+ if (options.skipLead === true) while (start < 3 && start < bytes.length && isUtf8Continuation(bytes[start])) start++;
260
+ const part = bytes.subarray(start);
261
+ if (part.includes(0)) return {
262
+ encoding: "binary",
263
+ usedBytes: bytes.length
264
+ };
265
+ try {
266
+ const text = new TextDecoder("utf-8", {
267
+ fatal: true,
268
+ ignoreBOM: true
269
+ }).decode(part, { stream: options.atEnd !== true });
270
+ return {
271
+ encoding: "utf-8",
272
+ text,
273
+ skippedBytes: start,
274
+ usedBytes: Buffer.byteLength(text, "utf8")
275
+ };
276
+ } catch {
277
+ return {
278
+ encoding: "binary",
279
+ usedBytes: bytes.length
280
+ };
281
+ }
282
+ }
283
+ /** Characters of a `read_file` result the content may take; the rest is for the other fields. */
284
+ const READ_CONTENT_CHARS = require_types.RESULT_CHAR_LIMIT - 1e3;
285
+ /**
286
+ * Cuts decoded content so that the result stays under the result size limit: text to the
287
+ * characters whose JSON fits in {@link READ_CONTENT_CHARS}, base64 to the bytes whose encoding
288
+ * fits. `usedBytes` then counts the bytes kept, so `nextOffset` continues after them.
289
+ */
290
+ function fitToResult(decoded, base64) {
291
+ if (decoded.encoding === "binary") {
292
+ if (!base64) return decoded;
293
+ const maxBytes = Math.floor(READ_CONTENT_CHARS / 4) * 3;
294
+ return decoded.usedBytes <= maxBytes ? decoded : {
295
+ encoding: "binary",
296
+ usedBytes: maxBytes
297
+ };
298
+ }
299
+ if (JSON.stringify(decoded.text).length <= READ_CONTENT_CHARS) return decoded;
300
+ let lo = 0;
301
+ let hi = decoded.text.length;
302
+ while (lo < hi) {
303
+ const mid = Math.ceil((lo + hi) / 2);
304
+ if (JSON.stringify(decoded.text.slice(0, mid)).length <= READ_CONTENT_CHARS) lo = mid;
305
+ else hi = mid - 1;
306
+ }
307
+ let cut = lo;
308
+ const code = decoded.text.charCodeAt(cut - 1);
309
+ if (cut > 0 && code >= 55296 && code <= 56319) cut--;
310
+ const text = decoded.text.slice(0, cut);
311
+ return {
312
+ ...decoded,
313
+ text,
314
+ usedBytes: Buffer.byteLength(text, "utf8")
315
+ };
316
+ }
317
+ /**
318
+ * Reads ranges of a local file through the ls driver, by its import handle. The driver takes no
319
+ * signal, so the wait for a read ends when `signal` aborts; the read itself goes on and closes its
320
+ * file.
321
+ */
322
+ function localSource(ls, kind, handle, size, signal) {
323
+ return {
324
+ kind,
325
+ size,
326
+ read: (range) => raceAbort(() => ls.getLocalFileContent(handle, {
327
+ offset: range.from,
328
+ length: range.to - range.from
329
+ }), signal)
330
+ };
331
+ }
332
+ /**
333
+ * The result of `start()`, or a rejection with the reason of `signal` when it aborts first. An
334
+ * aborted signal does not start the work; a work that fails after the abort fails unobserved.
335
+ */
336
+ function raceAbort(start, signal) {
337
+ if (signal.aborted) return Promise.reject(signal.reason);
338
+ const work = start();
339
+ work.catch(() => {});
340
+ return new Promise((resolve, reject) => {
341
+ const onAbort = () => reject(signal.reason);
342
+ signal.addEventListener("abort", onAbort, { once: true });
343
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
344
+ });
345
+ }
346
+ /** The error a `read_file` of an `index://` handle gets. */
347
+ const INDEX_HANDLE_ERROR = "An index:// handle names a file in a remote data library; MCP cannot read it from here.";
348
+ const INDEX_HANDLE_HINT = "Give the handle to the block (set_block_data) and read what the block makes of it: blocks that read such a file in their pre-run give its content, or a part of it, as an output blob (a blob+remote:// or blob+local:// handle in get_block_state outputs); read_file reads that handle.";
349
+ /** Resolves what `read_file` was given to a source; an error result when it cannot be read. */
350
+ async function resolveSource(ls, blob, input, signal) {
351
+ if (input.path !== void 0) {
352
+ const p = input.path;
353
+ if (!node_path.isAbsolute(p)) return require_types.errorResult(`Not an absolute path: ${p}`);
354
+ const st = await node_fs_promises.stat(p);
355
+ if (!st.isFile()) return require_types.errorResult(`Not a file: ${p}`);
356
+ return localSource(ls, "local", await ls.getLocalFileHandle(p), st.size, signal);
357
+ }
358
+ const handle = input.handle ?? "";
359
+ if (require_imports.isImportHandle(handle)) {
360
+ if ((0, _milaboratories_pl_model_common.isImportFileHandleIndex)(handle)) return require_types.errorResult(INDEX_HANDLE_ERROR, INDEX_HANDLE_HINT);
361
+ const upload = handle;
362
+ return localSource(ls, "upload", upload, await ls.getLocalFileSize(upload), signal);
363
+ }
364
+ const parsed = parseBlobHandle(handle);
365
+ if (parsed !== void 0) return {
366
+ kind: "blob",
367
+ size: parsed.kind === "remote" ? parsed.size : (await node_fs_promises.stat(blob.getLocalPath(parsed.handle))).size,
368
+ read: (range) => blob.getContent(parsed.handle, {
369
+ range,
370
+ signal
371
+ })
372
+ };
373
+ return require_types.errorResult("Not a handle read_file reads.", "Give `path` (an absolute local path), an upload:// import handle (get_file_handles), or a blob+local:// / blob+remote:// handle from a block's outputs.");
374
+ }
375
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
376
+ /** Every import handle in `value`, with its path (`a.b[2]`, `(root)` for the value itself). */
377
+ function importHandlesIn(value) {
378
+ const found = [];
379
+ const walk = (v, p) => {
380
+ if (require_imports.isImportHandle(v)) found.push({
381
+ path: p || "(root)",
382
+ handle: v
383
+ });
384
+ else if (Array.isArray(v)) v.forEach((item, i) => walk(item, `${p}[${i}]`));
385
+ else if ((0, _milaboratories_helpers.isPlainObject)(v)) for (const [k, item] of Object.entries(v)) walk(item, IDENTIFIER.test(k) ? p === "" ? k : `${p}.${k}` : `${p}[${JSON.stringify(k)}]`);
386
+ };
387
+ walk(value, "");
388
+ return found;
389
+ }
390
+ /**
391
+ * Checks the import handles `next` carries that `current` does not: an `upload://` handle must be
392
+ * signed by this computer and name a file that exists unchanged since the handle was made; an
393
+ * `index://` handle must parse. Handles already stored are not checked: their file may have
394
+ * changed since, and that must not keep the rest of the data from being written.
395
+ */
396
+ async function invalidNewImportHandles(ls, current, next) {
397
+ const stored = new Set(importHandlesIn(current).map((h) => h.handle));
398
+ const fresh = importHandlesIn(next).filter((h) => !stored.has(h.handle));
399
+ const unique = [...new Set(fresh.map((h) => h.handle))];
400
+ const problems = new Map(await Promise.all(unique.map(async (h) => [h, await handleProblem(ls, h)])));
401
+ return fresh.flatMap(({ path: p, handle }) => {
402
+ const error = problems.get(handle);
403
+ return error === void 0 ? [] : [{
404
+ path: p,
405
+ error
406
+ }];
407
+ });
408
+ }
409
+ /** What is wrong with an import handle a write would store; `undefined` when it checks out. */
410
+ async function handleProblem(ls, handle) {
411
+ if ((0, _milaboratories_pl_model_common.isImportFileHandleUpload)(handle)) try {
412
+ await ls.getLocalFileSize(handle);
413
+ return;
414
+ } catch (e) {
415
+ return errorText(e);
416
+ }
417
+ try {
418
+ (0, _milaboratories_pl_model_common.getFilePathFromHandle)(handle);
419
+ return;
420
+ } catch {
421
+ return "The index:// handle does not parse.";
422
+ }
423
+ }
424
+ /** The most invalid handles a refusal names. */
425
+ const MAX_INVALID_NAMED = 10;
426
+ /** The refusal of a write that carries invalid new import handles. */
427
+ function invalidHandlesResult(invalid) {
428
+ const named = invalid.slice(0, MAX_INVALID_NAMED).map((h) => `${h.path}: ${h.error}`).join("; ");
429
+ const more = invalid.length > MAX_INVALID_NAMED ? ` (and ${invalid.length - MAX_INVALID_NAMED} more)` : "";
430
+ return require_types.errorResult(`The new data has ${invalid.length} import handle(s) that do not check out: ${named}${more}. Nothing was changed.`, "Make the handles with get_file_handles and copy them as they are. A handle of a local file stops checking out when the file is changed, moved or deleted: make a new one.");
431
+ }
432
+ function errorText(e) {
433
+ return e instanceof Error ? e.message : String(e);
434
+ }
435
+ /** The storages, or a page of a folder's entries (`list_files`). */
436
+ async function listFilesResult(ls, input) {
437
+ const { storage, path: dir, pattern, type, offset, limit } = input;
438
+ const storages = await ls.getStorageList();
439
+ if (storage === void 0 && dir === void 0) return require_types.textResult({ storages: storages.map((s) => ({
440
+ id: s.id,
441
+ name: s.name,
442
+ kind: storageKind(s),
443
+ initialPath: s.initialFullPath
444
+ })) });
445
+ const options = {
446
+ pattern: pattern === void 0 || pattern === "" ? void 0 : pattern,
447
+ type,
448
+ offset: Math.max(0, Math.floor(offset ?? 0)),
449
+ limit: clampLimit(limit, 100, 500)
450
+ };
451
+ const entry = storage === void 0 ? void 0 : findStorage(storages, storage);
452
+ if (storage !== void 0 && entry === void 0) return unknownStorage(storage, storages);
453
+ try {
454
+ if (entry !== void 0 && storageKind(entry) === "remote") {
455
+ const folder = dir ?? "";
456
+ return require_types.textResult({
457
+ storage: entry.id,
458
+ path: folder,
459
+ ...await listRemoteFolder(ls, entry, folder, options)
460
+ });
461
+ }
462
+ const folder = localPath(entry, dir ?? entry?.initialFullPath ?? "/");
463
+ return require_types.textResult({
464
+ ...entry !== void 0 ? { storage: entry.id } : {},
465
+ path: folder,
466
+ ...await listLocalFolder(folder, options)
467
+ });
468
+ } catch (e) {
469
+ if (e instanceof PatternError) return require_types.errorResult(e.message, e.hint);
470
+ return require_types.errorResult(`Cannot list ${dir ?? "the folder"}: ${errorText(e)}`, "Check the path with list_files on its parent folder.");
471
+ }
472
+ }
473
+ /** Import handles for files (`get_file_handles`). */
474
+ async function fileHandlesResult(ls, input) {
475
+ const { paths, storage } = input;
476
+ if (paths.length === 0) return require_types.errorResult("`paths` is empty.");
477
+ if (paths.length > 200) return require_types.errorResult(`${paths.length} paths; at most 200 per call.`, "Split the paths over several calls.");
478
+ let results;
479
+ if (storage === void 0) results = await Promise.all(paths.map((p) => localFileHandle(ls, p)));
480
+ else {
481
+ const storages = await ls.getStorageList();
482
+ const entry = findStorage(storages, storage);
483
+ if (entry === void 0) return unknownStorage(storage, storages);
484
+ results = storageKind(entry) === "remote" ? await remoteFileHandles(ls, entry, paths) : await Promise.all(paths.map((p) => localFileHandle(ls, localPath(entry, p))));
485
+ }
486
+ const handles = results.filter((r) => "handle" in r);
487
+ const errors = results.filter((r) => "error" in r);
488
+ return require_types.textResult({
489
+ handles,
490
+ ...errors.length > 0 ? { errors } : {}
491
+ });
492
+ }
493
+ /**
494
+ * A bounded read of a file (`read_file`). A blob handle is read inside `holdProject` on the
495
+ * project that gave it: while that project is held, it is not unloaded, so the block's downloaded
496
+ * file keeps its owner and is not deleted from the cache between two pages of a read.
497
+ */
498
+ async function readFileResult(ls, blob, input, signal, holdProject) {
499
+ if (input.path === void 0 === (input.handle === void 0)) return require_types.errorResult("Give either `path` or `handle`.");
500
+ if (input.handle !== void 0 && parseBlobHandle(input.handle) !== void 0 && holdProject !== void 0) {
501
+ if (input.projectId === void 0) return require_types.errorResult("A blob handle is read with `projectId`: the project whose block outputs gave it.");
502
+ return await holdProject(input.projectId, () => readFileResult(ls, blob, input, signal));
503
+ }
504
+ let source;
505
+ try {
506
+ source = await resolveSource(ls, blob, input, signal);
507
+ } catch (e) {
508
+ return require_types.errorResult(`Cannot read ${input.path ?? "the handle"}: ${errorText(e)}`, input.path === void 0 ? "A handle of a local file stops working when the file changes; make a new one with get_file_handles. A blob handle comes from get_block_state outputs." : void 0);
509
+ }
510
+ if ("isError" in source) return source;
511
+ const max = input.transform !== void 0 ? READ_MAX_TRANSFORM_BYTES : READ_MAX_BYTES;
512
+ const min = input.base64 === true ? 1 : 4;
513
+ const length = (0, _milaboratories_helpers.clamp)(Math.floor(input.length ?? 16384), min, max);
514
+ const range = clampRange(Math.floor(input.offset ?? 0), length, source.size);
515
+ let bytes;
516
+ try {
517
+ bytes = range.to > range.from ? await source.read(range) : /* @__PURE__ */ new Uint8Array(0);
518
+ } catch (e) {
519
+ return require_types.errorResult(`Read failed: ${errorText(e)}`, signal.aborted ? "The read took too long or was cancelled: try again, or read a smaller range." : void 0);
520
+ }
521
+ let decoded = input.base64 === true ? decodeContent(bytes, { atEnd: true }) : decodeContent(bytes, {
522
+ skipLead: range.from > 0,
523
+ atEnd: range.to >= source.size
524
+ });
525
+ if (input.transform === void 0) decoded = fitToResult(decoded, input.base64 === true);
526
+ const skipped = decoded.encoding === "utf-8" ? decoded.skippedBytes : 0;
527
+ const used = decoded.usedBytes;
528
+ bytes = bytes.subarray(skipped, skipped + used);
529
+ const start = range.from + skipped;
530
+ const end = start + used;
531
+ const meta = {
532
+ source: source.kind,
533
+ size: source.size,
534
+ offset: start,
535
+ bytesRead: used,
536
+ eof: end >= source.size,
537
+ ...end < source.size ? { nextOffset: end } : {},
538
+ encoding: decoded.encoding
539
+ };
540
+ const base64 = decoded.encoding === "binary" ? Buffer.from(bytes).toString("base64") : void 0;
541
+ if (input.transform !== void 0) try {
542
+ const result = await require_sandbox.safeEval(input.transform, {
543
+ text: decoded.encoding === "utf-8" ? decoded.text : void 0,
544
+ base64,
545
+ size: meta.size,
546
+ offset: meta.offset,
547
+ bytesRead: meta.bytesRead,
548
+ eof: meta.eof
549
+ }, input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT);
550
+ return require_types.textResult({
551
+ ...meta,
552
+ result
553
+ });
554
+ } catch (e) {
555
+ return require_types.transformFailedResult(e, "Check the expression. Available variables: text, base64, size, offset, bytesRead, eof.");
556
+ }
557
+ if (decoded.encoding === "utf-8") return require_types.textResult({
558
+ ...meta,
559
+ text: decoded.text
560
+ });
561
+ return require_types.textResult(input.base64 === true ? {
562
+ ...meta,
563
+ base64
564
+ } : meta);
565
+ }
566
+ function registerFileTools(server, ctx) {
567
+ const drivers = () => {
568
+ const kit = ctx.requireMl().internalDriverKit;
569
+ return {
570
+ ls: kit.lsDriver,
571
+ blob: kit.blobDriver
572
+ };
573
+ };
574
+ server.registerTool("list_files", {
575
+ title: "List Files",
576
+ annotations: require_types.hints.read,
577
+ description: "List the storages files can be taken from, or the entries of a folder in one. With no arguments: the storages, `[{ id, name, kind: local|remote, initialPath }]` (local: this computer; remote: data libraries of the server). With `storage` (an id) and `path`: the folder's entries `{ name, type: file|dir, path, size? }`, sorted by name, a page at a time (`total`, `hasMore`, `nextOffset`). `path` alone lists a folder of this computer. Listing gives no handles: get_file_handles makes them for the files you pick, and that is how files are given to a block.",
578
+ inputSchema: zod.z.object({
579
+ storage: zod.z.string().optional().describe("Storage id (or name) from the storage list. Omit for this computer."),
580
+ path: zod.z.string().optional().describe("Folder to list. Local: absolute, or relative to the storage's root; omitted, the storage's initial folder. Remote: the folder's path in the storage, '' for its top."),
581
+ pattern: zod.z.string().optional().describe(`JavaScript regular expression the entry name must match (tested anywhere in the name: anchor it with ^…\$ for the whole name), e.g. \`^S\\d+_R[12]\\.fastq\\.gz\$\`. Matching one folder may take at most 500 ms.`),
582
+ type: zod.z.enum(["file", "dir"]).optional().describe("Only files, or only folders."),
583
+ offset: zod.z.number().optional().describe("Entries to skip (default 0)."),
584
+ limit: zod.z.number().optional().describe(`Entries per page (default 100, at most 500).`)
585
+ })
586
+ }, async (input) => listFilesResult(drivers().ls, input));
587
+ server.registerTool("get_file_handles", {
588
+ title: "Get File Handles",
589
+ annotations: require_types.hints.read,
590
+ description: `Make import handles for files: this is how files are given to a block. Put a handle into the block's data where the block takes a file (set_block_data). When the block uses the file (its pre-run, which follows every change of the data, or its run), a file of this computer is uploaded to the server, a file of a data library is used where it is. get_block_state shows the progress under \`imports\`; await_block_done with waitForImports waits for it.
591
+
592
+ \`paths\`: absolute paths of files of this computer, or with \`storage\`, paths in that storage (as list_files gives them). Result: \`{ handles: [{ path, handle, size? }], errors?: [{ path, error }] }\`, in the order asked. At most 200 files per call. Copy handles as they are; a local file's handle stops working when the file changes.`,
593
+ inputSchema: zod.z.object({
594
+ paths: zod.z.array(zod.z.string()).describe("File paths."),
595
+ storage: zod.z.string().optional().describe("Storage id (or name) the paths are in. Omit for this computer.")
596
+ })
597
+ }, async (input) => fileHandlesResult(drivers().ls, input));
598
+ server.registerTool("read_file", {
599
+ title: "Read File",
600
+ annotations: require_types.hints.read,
601
+ description: `Read a part of a file: a local file (\`path\`), an upload:// import handle, or a blob handle from a block's outputs (blob+local://, blob+remote://). Reads \`length\` bytes from \`offset\` (default ${READ_DEFAULT_BYTES}, at most ${READ_MAX_BYTES}); a range past the end is cut to it. Result: \`{ size, offset, bytesRead, eof, nextOffset?, encoding: utf-8|binary, text? , base64? }\`: text when the bytes are UTF-8, otherwise only their count (base64 with \`base64: true\`). Text keeps whole characters: a range that starts inside one starts after it (\`offset\` says where) and one that ends inside one stops before it (\`nextOffset\`). With \`base64: true\` the range is returned as it is. With \`transform\` the server reads up to 4 MiB and returns only the expression's value. index:// handles (files of a data library) cannot be read here: read the block's output blob instead.`,
602
+ inputSchema: zod.z.object({
603
+ path: zod.z.string().optional().describe("Absolute path of a local file."),
604
+ handle: zod.z.string().optional().describe("An upload:// import handle, or a blob handle from a block's outputs."),
605
+ projectId: require_ids.projectIdInput.optional().describe("With a blob handle (required): the project whose block outputs gave it."),
606
+ offset: zod.z.number().optional().describe("Byte to start at (default 0)."),
607
+ length: zod.z.number().optional().describe(`Bytes to read (default ${READ_DEFAULT_BYTES}; at most ${READ_MAX_BYTES}, or ${READ_MAX_TRANSFORM_BYTES} with \`transform\`).`),
608
+ base64: zod.z.boolean().optional().describe("Return binary content as base64 (default false: its byte count only)."),
609
+ transform: zod.z.string().optional().describe("JS expression evaluated in the server against the content: `text` (UTF-8 content, or undefined), `base64` (binary content, or undefined), `size`, `offset`, `bytesRead`, `eof`. Example: `text.split('\\n').slice(0, 3)` for the first lines."),
610
+ transformTimeout: zod.z.number().optional().describe(require_sandbox.expressionTimeoutText("the transform", DEFAULT_TRANSFORM_TIMEOUT))
611
+ })
612
+ }, async (input, call) => readFileResult(drivers().ls, drivers().blob, input, require_types.readSignal(call?.mcpReq.signal), (projectId, read) => ctx.withProject(projectId, () => read())));
613
+ }
614
+ exports.INDEX_HANDLE_ERROR = INDEX_HANDLE_ERROR;
615
+ exports.INDEX_HANDLE_HINT = INDEX_HANDLE_HINT;
616
+ exports.PatternError = PatternError;
617
+ exports.READ_CONTENT_CHARS = READ_CONTENT_CHARS;
618
+ exports.READ_DEFAULT_BYTES = READ_DEFAULT_BYTES;
619
+ exports.READ_MAX_BYTES = READ_MAX_BYTES;
620
+ exports.READ_MAX_TRANSFORM_BYTES = READ_MAX_TRANSFORM_BYTES;
621
+ exports.clampLimit = clampLimit;
622
+ exports.clampRange = clampRange;
623
+ exports.decodeContent = decodeContent;
624
+ exports.fileHandlesResult = fileHandlesResult;
625
+ exports.findStorage = findStorage;
626
+ exports.fitToResult = fitToResult;
627
+ exports.importHandlesIn = importHandlesIn;
628
+ exports.invalidHandlesResult = invalidHandlesResult;
629
+ exports.invalidNewImportHandles = invalidNewImportHandles;
630
+ exports.listFilesResult = listFilesResult;
631
+ exports.listLocalFolder = listLocalFolder;
632
+ exports.listRemoteFolder = listRemoteFolder;
633
+ exports.localFileHandle = localFileHandle;
634
+ exports.localStorageRoot = localStorageRoot;
635
+ exports.matchNames = matchNames;
636
+ exports.pageEntries = pageEntries;
637
+ exports.parseBlobHandle = parseBlobHandle;
638
+ exports.readFileResult = readFileResult;
639
+ exports.registerFileTools = registerFileTools;
640
+ exports.remoteFileHandles = remoteFileHandles;
641
+ exports.storageKind = storageKind;
642
+
643
+ //# sourceMappingURL=files.cjs.map