@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 @@
1
+ {"version":3,"file":"files.js","names":[],"sources":["../../src/tools/files.ts"],"sourcesContent":["import type {\n ImportFileHandle,\n LocalBlobHandle,\n LocalImportFileHandle,\n ProjectId,\n RemoteBlobHandle,\n StorageEntry,\n StorageHandle,\n TableRange,\n} from \"@milaboratories/pl-model-common\";\nimport {\n getFilePathFromHandle,\n isImportFileHandleIndex,\n isImportFileHandleUpload,\n} from \"@milaboratories/pl-model-common\";\nimport * as fsp from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { z } from \"zod\";\nimport { clamp, isPlainObject, trimChars } from \"@milaboratories/helpers\";\nimport { projectIdInput } from \"./ids\";\nimport { isImportHandle } from \"./imports\";\nimport { expressionTimeoutText, safeEval, SandboxError, TIMEOUT } from \"./sandbox\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport {\n errorResult,\n hints,\n readSignal,\n RESULT_CHAR_LIMIT,\n textResult,\n transformFailedResult,\n} from \"./types\";\n\n/** Entries `list_files` gives by default. */\nexport const LIST_DEFAULT_LIMIT = 100;\n/** The most entries one `list_files` page has. */\nexport const LIST_MAX_LIMIT = 500;\n/** The most files one `get_file_handles` call makes handles for. */\nexport const MAX_HANDLES = 200;\n/** Bytes `read_file` reads by default. */\nexport const READ_DEFAULT_BYTES = 16_384;\n/** The most bytes `read_file` returns. */\nexport const READ_MAX_BYTES = 65_536;\n/** The most bytes `read_file` reads for a `transform`. */\nexport const READ_MAX_TRANSFORM_BYTES = 4 * 1024 * 1024;\n/** How long matching `pattern` against the names of one folder may take, in milliseconds. */\nexport const PATTERN_TIME_BUDGET_MS = 500;\n/** Default timeout of a `transform`, in milliseconds. */\nconst DEFAULT_TRANSFORM_TIMEOUT = 5000;\n\n/** What the file tools use of the middle layer's ls driver (`InternalLsDriver`). */\nexport type FileLsDriver = {\n getStorageList(): Promise<StorageEntry[]>;\n getLocalFileHandle(localPath: string): Promise<LocalImportFileHandle>;\n getLocalFileSize(file: LocalImportFileHandle): Promise<number>;\n getLocalFileContent(file: LocalImportFileHandle, range?: TableRange): Promise<Uint8Array>;\n listRemoteFilesWithFileStats(\n storage: StorageHandle,\n fullPath: string,\n ): Promise<{\n entries: (\n | { type: \"dir\"; name: string; fullPath: string; size: number }\n | { type: \"file\"; name: string; fullPath: string; handle: ImportFileHandle; size: number }\n )[];\n }>;\n};\n\n/** What `read_file` uses of the middle layer's blob driver (`DownloadDriver`). */\nexport type FileBlobDriver = {\n getLocalPath(handle: LocalBlobHandle): string;\n getContent(\n handle: LocalBlobHandle | RemoteBlobHandle,\n options: { range?: { from: number; to: number }; signal?: AbortSignal },\n ): Promise<Uint8Array>;\n};\n\n// ---------------------------------------------------------------------------------------------\n// Handles parsed from strings: the only place their brands are put on.\n// ---------------------------------------------------------------------------------------------\n\nconst LOCAL_BLOB_RE = /^blob\\+local:\\/\\/download\\/.*#.*$/;\nconst REMOTE_BLOB_RE = /^blob\\+remote:\\/\\/download\\/.+\\/(\\d+)#.*$/;\n\n/** A blob handle of a block output, with the size a remote one carries. */\nexport type ParsedBlobHandle =\n | { kind: \"local\"; handle: LocalBlobHandle }\n | { kind: \"remote\"; handle: RemoteBlobHandle; size: number };\n\n/** Parses a block-output blob handle (`blob+local://` or `blob+remote://`); else `undefined`. */\nexport function parseBlobHandle(s: string): ParsedBlobHandle | undefined {\n if (LOCAL_BLOB_RE.test(s)) return { kind: \"local\", handle: s as LocalBlobHandle };\n const remote = REMOTE_BLOB_RE.exec(s);\n if (remote !== null)\n return { kind: \"remote\", handle: s as RemoteBlobHandle, size: Number(remote[1]) };\n return undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Storages\n// ---------------------------------------------------------------------------------------------\n\n/** Whether a storage is on this computer (`local://` handle) or a remote data library. */\nexport function storageKind(entry: StorageEntry): \"local\" | \"remote\" {\n return entry.handle.startsWith(\"local://\") ? \"local\" : \"remote\";\n}\n\n/** The root folder of a local storage, from its handle (`local://<id>/<encoded root>`). */\nexport function localStorageRoot(entry: StorageEntry): string {\n return decodeURIComponent(entry.handle.slice(entry.handle.lastIndexOf(\"/\") + 1));\n}\n\n/** Finds a storage by its id, then by its name. */\nexport function findStorage(storages: StorageEntry[], ref: string): StorageEntry | undefined {\n return storages.find((s) => s.id === ref) ?? storages.find((s) => s.name === ref);\n}\n\nfunction unknownStorage(ref: string, storages: StorageEntry[]) {\n return errorResult(\n `No storage \"${ref}\".`,\n `Storages: ${storages.map((s) => s.id).join(\", \") || \"none\"}. list_files with no arguments lists them.`,\n );\n}\n\n/** A path of a local storage made absolute: a relative one is under the storage's root. */\nfunction localPath(entry: StorageEntry | undefined, p: string): string {\n if (path.isAbsolute(p)) return p;\n return path.join(entry === undefined ? \"/\" : localStorageRoot(entry), p);\n}\n\n// ---------------------------------------------------------------------------------------------\n// list_files\n// ---------------------------------------------------------------------------------------------\n\n/** One entry of a folder. */\nexport type ListedEntry = { name: string; type: \"file\" | \"dir\"; path: string; size?: number };\n\n/** A page of a folder's entries. */\nexport type ListPage = {\n total: number;\n offset: number;\n entries: ListedEntry[];\n hasMore: boolean;\n nextOffset?: number;\n};\n\n/** Options of {@link pageEntries}. */\nexport type PageOptions = {\n /** A regular expression the name must match, tested in the sandbox ({@link matchNames}). */\n pattern?: string;\n type?: \"file\" | \"dir\";\n offset: number;\n limit: number;\n};\n\n/** A `pattern` of `list_files` that does not parse, or takes too long to match. */\nexport class PatternError extends Error {\n constructor(\n message: string,\n readonly hint: string,\n ) {\n super(message);\n this.name = \"PatternError\";\n }\n}\n\n/**\n * The indices of the names `pattern` matches. The caller's regular expression runs in the\n * sandbox, all names in one evaluation under `budgetMs`: a pattern that backtracks\n * catastrophically is stopped there instead of blocking the server. Throws a\n * {@link PatternError} when the pattern does not parse or runs out of time.\n */\nexport async function matchNames(\n pattern: string,\n names: string[],\n budgetMs: number = PATTERN_TIME_BUDGET_MS,\n): Promise<number[]> {\n try {\n const hits = await safeEval(\n \"(() => { const re = new RegExp(pattern); const hits = []; \" +\n \"for (let i = 0; i < names.length; i++) if (re.test(names[i])) hits.push(i); \" +\n \"return hits; })()\",\n { pattern, names },\n budgetMs,\n );\n return hits as number[];\n } catch (e: unknown) {\n if (e instanceof SandboxError && e.errorClass === TIMEOUT)\n throw new PatternError(\n `\\`pattern\\` took longer than ${budgetMs} ms to match ${names.length} ` +\n `${names.length === 1 ? \"name\" : \"names\"}.`,\n \"Simplify it: avoid nested repetition such as `(a+)+`, or anchor it with ^…$.\",\n );\n if (e instanceof SandboxError && e.errorClass === \"SyntaxError\")\n throw new PatternError(\n `\\`pattern\\` is not a valid regular expression: ${e.message}`,\n \"Give a JavaScript regular expression, e.g. `^S\\\\d+_R[12]\\\\.fastq\\\\.gz$`.\",\n );\n throw e;\n }\n}\n\n/**\n * Filters entries by `type` and `pattern` (tested against the name), sorts them by name and\n * returns the page `[offset, offset + limit)`.\n */\nexport async function pageEntries<E extends { name: string; type: \"file\" | \"dir\" }>(\n entries: E[],\n options: PageOptions,\n): Promise<{ total: number; page: E[]; hasMore: boolean; nextOffset?: number }> {\n let matching = entries.filter((e) => options.type === undefined || e.type === options.type);\n if (options.pattern !== undefined) {\n const candidates = matching;\n const hits = await matchNames(\n options.pattern,\n candidates.map((e) => e.name),\n );\n matching = hits.map((i) => candidates[i]);\n }\n matching.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n const page = matching.slice(options.offset, options.offset + options.limit);\n const end = options.offset + page.length;\n const hasMore = end < matching.length;\n return { total: matching.length, page, hasMore, ...(hasMore ? { nextOffset: end } : {}) };\n}\n\n/** The page size asked for, clamped to `[1, LIST_MAX_LIMIT]`. */\nexport function clampLimit(limit: number | undefined, fallback: number, max: number): number {\n if (limit === undefined || !Number.isFinite(limit)) return fallback;\n return clamp(Math.floor(limit), 1, max);\n}\n\n/**\n * Lists a local folder. Every entry's type comes from the folder listing (a symbolic link from a\n * `stat` of its target); sizes are read with one `stat` per file of the returned page only, so a\n * large folder costs one listing, not one `stat` per entry.\n */\nexport async function listLocalFolder(dir: string, options: PageOptions): Promise<ListPage> {\n const dirents = await fsp.readdir(dir, { withFileTypes: true });\n const entries: ListedEntry[] = [];\n for (const d of dirents) {\n const full = path.join(dir, d.name);\n let type: \"file\" | \"dir\" | undefined;\n if (d.isFile()) type = \"file\";\n else if (d.isDirectory()) type = \"dir\";\n else if (d.isSymbolicLink()) {\n try {\n const st = await fsp.stat(full);\n type = st.isFile() ? \"file\" : st.isDirectory() ? \"dir\" : undefined;\n } catch {\n type = undefined; // a dangling link\n }\n }\n if (type !== undefined) entries.push({ name: d.name, type, path: full });\n }\n const { total, page, hasMore, nextOffset } = await pageEntries(entries, options);\n const withSizes = await Promise.all(\n page.map(async (e): Promise<ListedEntry> => {\n if (e.type !== \"file\") return e;\n try {\n return { ...e, size: (await fsp.stat(e.path)).size };\n } catch {\n return e;\n }\n }),\n );\n return {\n total,\n offset: options.offset,\n entries: withSizes,\n hasMore,\n ...(nextOffset !== undefined ? { nextOffset } : {}),\n };\n}\n\n/** Lists a folder of a remote storage; the listing gives sizes. */\nexport async function listRemoteFolder(\n ls: FileLsDriver,\n storage: StorageEntry,\n dir: string,\n options: PageOptions,\n): Promise<ListPage> {\n const listing = await ls.listRemoteFilesWithFileStats(storage.handle, dir);\n const entries = listing.entries.map((e): ListedEntry => ({\n name: e.name,\n type: e.type,\n path: e.fullPath,\n ...(e.type === \"file\" ? { size: e.size } : {}),\n }));\n const { total, page, hasMore, nextOffset } = await pageEntries(entries, options);\n return {\n total,\n offset: options.offset,\n entries: page,\n hasMore,\n ...(nextOffset !== undefined ? { nextOffset } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------------------------\n// get_file_handles\n// ---------------------------------------------------------------------------------------------\n\n/** The handle of one file, or why there is none. */\nexport type HandleResult =\n | { path: string; handle: ImportFileHandle; size?: number }\n | { path: string; error: string };\n\n/** Makes the import handle of a local file; a folder or a relative path gets an error. */\nexport async function localFileHandle(ls: FileLsDriver, p: string): Promise<HandleResult> {\n if (!path.isAbsolute(p)) return { path: p, error: \"Not an absolute path.\" };\n try {\n const st = await fsp.stat(p);\n if (!st.isFile()) return { path: p, error: \"Not a file.\" };\n return { path: p, handle: await ls.getLocalFileHandle(p), size: st.size };\n } catch (e: unknown) {\n return { path: p, error: errorText(e) };\n }\n}\n\n/**\n * The `index://` handles of files of a remote storage. A handle carries what the storage's\n * listing gives, so the folder of each file is listed (once per folder) and the file looked up in\n * it by its full path.\n */\nexport async function remoteFileHandles(\n ls: FileLsDriver,\n storage: StorageEntry,\n paths: string[],\n): Promise<HandleResult[]> {\n const folderOf = (p: string) => {\n const trimmed = trimChars(p, [\"/\"]);\n const slash = trimmed.lastIndexOf(\"/\");\n return slash < 0 ? \"\" : trimmed.slice(0, slash);\n };\n const listings = new Map<\n string,\n Promise<Awaited<ReturnType<FileLsDriver[\"listRemoteFilesWithFileStats\"]>>>\n >();\n return await Promise.all(\n paths.map(async (p): Promise<HandleResult> => {\n const folder = folderOf(p);\n let listing = listings.get(folder);\n if (listing === undefined) {\n listing = ls.listRemoteFilesWithFileStats(storage.handle, folder);\n listings.set(folder, listing);\n }\n try {\n const { entries } = await listing;\n const entry = entries.find(\n (e) => e.fullPath === p || trimChars(e.fullPath, [\"/\"]) === trimChars(p, [\"/\"]),\n );\n if (entry === undefined) return { path: p, error: \"No such file in the storage.\" };\n if (entry.type !== \"file\") return { path: p, error: \"Not a file.\" };\n return { path: p, handle: entry.handle, size: entry.size };\n } catch (e: unknown) {\n return { path: p, error: errorText(e) };\n }\n }),\n );\n}\n\n// ---------------------------------------------------------------------------------------------\n// read_file\n// ---------------------------------------------------------------------------------------------\n\n/** A range clamped to a size: `[from, to)`, empty at or past the end. */\nexport function clampRange(\n offset: number,\n length: number,\n size: number,\n): { from: number; to: number } {\n const from = clamp(offset, 0, size);\n return { from, to: clamp(from + length, from, size) };\n}\n\n/** The most bytes of one UTF-8 character: the shortest read, so that text always advances. */\nexport const UTF8_MAX_BYTES = 4;\n\nfunction isUtf8Continuation(b: number): boolean {\n return (b & 0xc0) === 0x80;\n}\n\n/** Decoded content: text when it is UTF-8 without NUL bytes, otherwise binary. */\nexport type Decoded =\n | { encoding: \"utf-8\"; text: string; skippedBytes: number; usedBytes: number }\n | { encoding: \"binary\"; usedBytes: number };\n\n/**\n * Decodes `bytes`, a range of a file, as text of whole characters:\n * - `skipLead` (the range does not start the file): up to 3 leading continuation bytes, the tail\n * of a character begun before the range, are skipped (`skippedBytes`);\n * - unless `atEnd` (the range ends the file), an incomplete character at the end is left for the\n * next read: `usedBytes` stops before it.\n *\n * Content that is not UTF-8, or holds NUL bytes, is binary: all the bytes, none skipped.\n */\nexport function decodeContent(\n bytes: Uint8Array,\n options: { skipLead?: boolean; atEnd?: boolean } = {},\n): Decoded {\n let start = 0;\n if (options.skipLead === true)\n while (start < UTF8_MAX_BYTES - 1 && start < bytes.length && isUtf8Continuation(bytes[start]))\n start++;\n const part = bytes.subarray(start);\n if (part.includes(0)) return { encoding: \"binary\", usedBytes: bytes.length };\n try {\n const text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(part, {\n stream: options.atEnd !== true,\n });\n return {\n encoding: \"utf-8\",\n text,\n skippedBytes: start,\n usedBytes: Buffer.byteLength(text, \"utf8\"),\n };\n } catch {\n return { encoding: \"binary\", usedBytes: bytes.length };\n }\n}\n\n/** Characters of a `read_file` result the content may take; the rest is for the other fields. */\nexport const READ_CONTENT_CHARS = RESULT_CHAR_LIMIT - 1000;\n\n/**\n * Cuts decoded content so that the result stays under the result size limit: text to the\n * characters whose JSON fits in {@link READ_CONTENT_CHARS}, base64 to the bytes whose encoding\n * fits. `usedBytes` then counts the bytes kept, so `nextOffset` continues after them.\n */\nexport function fitToResult(decoded: Decoded, base64: boolean): Decoded {\n if (decoded.encoding === \"binary\") {\n if (!base64) return decoded;\n const maxBytes = Math.floor(READ_CONTENT_CHARS / 4) * 3;\n return decoded.usedBytes <= maxBytes ? decoded : { encoding: \"binary\", usedBytes: maxBytes };\n }\n if (JSON.stringify(decoded.text).length <= READ_CONTENT_CHARS) return decoded;\n // The longest prefix whose JSON fits; a cut never splits a surrogate pair.\n let lo = 0;\n let hi = decoded.text.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (JSON.stringify(decoded.text.slice(0, mid)).length <= READ_CONTENT_CHARS) lo = mid;\n else hi = mid - 1;\n }\n let cut = lo;\n const code = decoded.text.charCodeAt(cut - 1);\n if (cut > 0 && code >= 0xd800 && code <= 0xdbff) cut--;\n const text = decoded.text.slice(0, cut);\n return { ...decoded, text, usedBytes: Buffer.byteLength(text, \"utf8\") };\n}\n\n/** What a source of `read_file` reads: its size, and a range of its bytes. */\ntype ReadSource = {\n kind: \"local\" | \"upload\" | \"blob\";\n size: number;\n read(range: { from: number; to: number }): Promise<Uint8Array>;\n};\n\n/**\n * Reads ranges of a local file through the ls driver, by its import handle. The driver takes no\n * signal, so the wait for a read ends when `signal` aborts; the read itself goes on and closes its\n * file.\n */\nfunction localSource(\n ls: FileLsDriver,\n kind: \"local\" | \"upload\",\n handle: LocalImportFileHandle,\n size: number,\n signal: AbortSignal,\n): ReadSource {\n return {\n kind,\n size,\n read: (range) =>\n raceAbort(\n () => ls.getLocalFileContent(handle, { offset: range.from, length: range.to - range.from }),\n signal,\n ),\n };\n}\n\n/**\n * The result of `start()`, or a rejection with the reason of `signal` when it aborts first. An\n * aborted signal does not start the work; a work that fails after the abort fails unobserved.\n */\nfunction raceAbort<T>(start: () => Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason);\n const work = start();\n work.catch(() => {});\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n work.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n/** The error a `read_file` of an `index://` handle gets. */\nexport const INDEX_HANDLE_ERROR =\n \"An index:// handle names a file in a remote data library; MCP cannot read it from here.\";\nexport const INDEX_HANDLE_HINT =\n \"Give the handle to the block (set_block_data) and read what the block makes of it: blocks \" +\n \"that read such a file in their pre-run give its content, or a part of it, as an output blob \" +\n \"(a blob+remote:// or blob+local:// handle in get_block_state outputs); read_file reads that \" +\n \"handle.\";\n\n/** Resolves what `read_file` was given to a source; an error result when it cannot be read. */\nasync function resolveSource(\n ls: FileLsDriver,\n blob: FileBlobDriver,\n input: { path?: string; handle?: string },\n signal: AbortSignal,\n): Promise<ReadSource | ReturnType<typeof errorResult>> {\n if (input.path !== undefined) {\n const p = input.path;\n if (!path.isAbsolute(p)) return errorResult(`Not an absolute path: ${p}`);\n const st = await fsp.stat(p);\n if (!st.isFile()) return errorResult(`Not a file: ${p}`);\n return localSource(ls, \"local\", await ls.getLocalFileHandle(p), st.size, signal);\n }\n const handle = input.handle ?? \"\";\n if (isImportHandle(handle)) {\n if (isImportFileHandleIndex(handle)) return errorResult(INDEX_HANDLE_ERROR, INDEX_HANDLE_HINT);\n const upload = handle as LocalImportFileHandle;\n return localSource(ls, \"upload\", upload, await ls.getLocalFileSize(upload), signal);\n }\n const parsed = parseBlobHandle(handle);\n if (parsed !== undefined) {\n const size =\n parsed.kind === \"remote\"\n ? parsed.size\n : (await fsp.stat(blob.getLocalPath(parsed.handle))).size;\n return {\n kind: \"blob\",\n size,\n read: (range) => blob.getContent(parsed.handle, { range, signal }),\n };\n }\n return errorResult(\n \"Not a handle read_file reads.\",\n \"Give `path` (an absolute local path), an upload:// import handle (get_file_handles), or a \" +\n \"blob+local:// / blob+remote:// handle from a block's outputs.\",\n );\n}\n\n// ---------------------------------------------------------------------------------------------\n// Import handles written into block data\n// ---------------------------------------------------------------------------------------------\n\n/** One import handle in a value, with its JSON path. */\nexport type FoundHandle = { path: string; handle: ImportFileHandle };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Every import handle in `value`, with its path (`a.b[2]`, `(root)` for the value itself). */\nexport function importHandlesIn(value: unknown): FoundHandle[] {\n const found: FoundHandle[] = [];\n const walk = (v: unknown, p: string) => {\n if (isImportHandle(v)) found.push({ path: p || \"(root)\", handle: v });\n else if (Array.isArray(v)) v.forEach((item, i) => walk(item, `${p}[${i}]`));\n else if (isPlainObject(v))\n for (const [k, item] of Object.entries(v))\n walk(\n item,\n IDENTIFIER.test(k) ? (p === \"\" ? k : `${p}.${k}`) : `${p}[${JSON.stringify(k)}]`,\n );\n };\n walk(value, \"\");\n return found;\n}\n\n/** A handle a write would store that does not check out. */\nexport type InvalidHandle = { path: string; error: string };\n\n/**\n * Checks the import handles `next` carries that `current` does not: an `upload://` handle must be\n * signed by this computer and name a file that exists unchanged since the handle was made; an\n * `index://` handle must parse. Handles already stored are not checked: their file may have\n * changed since, and that must not keep the rest of the data from being written.\n */\nexport async function invalidNewImportHandles(\n ls: Pick<FileLsDriver, \"getLocalFileSize\">,\n current: unknown,\n next: unknown,\n): Promise<InvalidHandle[]> {\n const stored = new Set(importHandlesIn(current).map((h) => h.handle));\n const fresh = importHandlesIn(next).filter((h) => !stored.has(h.handle));\n const unique = [...new Set(fresh.map((h) => h.handle))];\n const problems = new Map(\n await Promise.all(unique.map(async (h) => [h, await handleProblem(ls, h)] as const)),\n );\n return fresh.flatMap(({ path: p, handle }) => {\n const error = problems.get(handle);\n return error === undefined ? [] : [{ path: p, error }];\n });\n}\n\n/** What is wrong with an import handle a write would store; `undefined` when it checks out. */\nasync function handleProblem(\n ls: Pick<FileLsDriver, \"getLocalFileSize\">,\n handle: ImportFileHandle,\n): Promise<string | undefined> {\n if (isImportFileHandleUpload(handle)) {\n try {\n await ls.getLocalFileSize(handle as LocalImportFileHandle);\n return undefined;\n } catch (e: unknown) {\n return errorText(e);\n }\n }\n try {\n getFilePathFromHandle(handle);\n return undefined;\n } catch {\n return \"The index:// handle does not parse.\";\n }\n}\n\n/** The most invalid handles a refusal names. */\nconst MAX_INVALID_NAMED = 10;\n\n/** The refusal of a write that carries invalid new import handles. */\nexport function invalidHandlesResult(invalid: InvalidHandle[]) {\n const named = invalid\n .slice(0, MAX_INVALID_NAMED)\n .map((h) => `${h.path}: ${h.error}`)\n .join(\"; \");\n const more =\n invalid.length > MAX_INVALID_NAMED ? ` (and ${invalid.length - MAX_INVALID_NAMED} more)` : \"\";\n return errorResult(\n `The new data has ${invalid.length} import handle(s) that do not check out: ${named}${more}. ` +\n \"Nothing was changed.\",\n \"Make the handles with get_file_handles and copy them as they are. A handle of a local file \" +\n \"stops checking out when the file is changed, moved or deleted: make a new one.\",\n );\n}\n\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Tools\n// ---------------------------------------------------------------------------------------------\n\n/** Input of `list_files`. */\nexport type ListFilesInput = {\n storage?: string;\n path?: string;\n pattern?: string;\n type?: \"file\" | \"dir\";\n offset?: number;\n limit?: number;\n};\n\n/** The storages, or a page of a folder's entries (`list_files`). */\nexport async function listFilesResult(ls: FileLsDriver, input: ListFilesInput) {\n const { storage, path: dir, pattern, type, offset, limit } = input;\n const storages = await ls.getStorageList();\n if (storage === undefined && dir === undefined)\n return textResult({\n storages: storages.map((s) => ({\n id: s.id,\n name: s.name,\n kind: storageKind(s),\n initialPath: s.initialFullPath,\n })),\n });\n\n const options: PageOptions = {\n pattern: pattern === undefined || pattern === \"\" ? undefined : pattern,\n type,\n offset: Math.max(0, Math.floor(offset ?? 0)),\n limit: clampLimit(limit, LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT),\n };\n\n const entry = storage === undefined ? undefined : findStorage(storages, storage);\n if (storage !== undefined && entry === undefined) return unknownStorage(storage, storages);\n try {\n if (entry !== undefined && storageKind(entry) === \"remote\") {\n const folder = dir ?? \"\";\n return textResult({\n storage: entry.id,\n path: folder,\n ...(await listRemoteFolder(ls, entry, folder, options)),\n });\n }\n const folder = localPath(entry, dir ?? entry?.initialFullPath ?? \"/\");\n return textResult({\n ...(entry !== undefined ? { storage: entry.id } : {}),\n path: folder,\n ...(await listLocalFolder(folder, options)),\n });\n } catch (e: unknown) {\n if (e instanceof PatternError) return errorResult(e.message, e.hint);\n return errorResult(\n `Cannot list ${dir ?? \"the folder\"}: ${errorText(e)}`,\n \"Check the path with list_files on its parent folder.\",\n );\n }\n}\n\n/** Import handles for files (`get_file_handles`). */\nexport async function fileHandlesResult(\n ls: FileLsDriver,\n input: { paths: string[]; storage?: string },\n) {\n const { paths, storage } = input;\n if (paths.length === 0) return errorResult(\"`paths` is empty.\");\n if (paths.length > MAX_HANDLES)\n return errorResult(\n `${paths.length} paths; at most ${MAX_HANDLES} per call.`,\n \"Split the paths over several calls.\",\n );\n let results: HandleResult[];\n if (storage === undefined) {\n results = await Promise.all(paths.map((p) => localFileHandle(ls, p)));\n } else {\n const storages = await ls.getStorageList();\n const entry = findStorage(storages, storage);\n if (entry === undefined) return unknownStorage(storage, storages);\n results =\n storageKind(entry) === \"remote\"\n ? await remoteFileHandles(ls, entry, paths)\n : await Promise.all(paths.map((p) => localFileHandle(ls, localPath(entry, p))));\n }\n const handles = results.filter((r) => \"handle\" in r);\n const errors = results.filter((r) => \"error\" in r);\n return textResult({ handles, ...(errors.length > 0 ? { errors } : {}) });\n}\n\n/** Input of `read_file`. */\nexport type ReadFileInput = {\n path?: string;\n handle?: string;\n /** The project whose block outputs gave a blob `handle`. */\n projectId?: ProjectId;\n offset?: number;\n length?: number;\n base64?: boolean;\n transform?: string;\n transformTimeout?: number;\n};\n\n/** Runs `read` holding the project `projectId` (the server's `withProject`). */\nexport type ProjectHold = <T>(projectId: ProjectId, read: () => Promise<T>) => Promise<T>;\n\n/**\n * A bounded read of a file (`read_file`). A blob handle is read inside `holdProject` on the\n * project that gave it: while that project is held, it is not unloaded, so the block's downloaded\n * file keeps its owner and is not deleted from the cache between two pages of a read.\n */\nexport async function readFileResult(\n ls: FileLsDriver,\n blob: FileBlobDriver,\n input: ReadFileInput,\n signal: AbortSignal,\n holdProject?: ProjectHold,\n): Promise<ReturnType<typeof textResult> | ReturnType<typeof errorResult>> {\n if ((input.path === undefined) === (input.handle === undefined))\n return errorResult(\"Give either `path` or `handle`.\");\n const isBlob = input.handle !== undefined && parseBlobHandle(input.handle) !== undefined;\n if (isBlob && holdProject !== undefined) {\n if (input.projectId === undefined)\n return errorResult(\n \"A blob handle is read with `projectId`: the project whose block outputs gave it.\",\n );\n return await holdProject(input.projectId, () => readFileResult(ls, blob, input, signal));\n }\n\n let source: ReadSource | ReturnType<typeof errorResult>;\n try {\n source = await resolveSource(ls, blob, input, signal);\n } catch (e: unknown) {\n return errorResult(\n `Cannot read ${input.path ?? \"the handle\"}: ${errorText(e)}`,\n input.path === undefined\n ? \"A handle of a local file stops working when the file changes; make a new one \" +\n \"with get_file_handles. A blob handle comes from get_block_state outputs.\"\n : undefined,\n );\n }\n if (\"isError\" in source) return source;\n\n const max = input.transform !== undefined ? READ_MAX_TRANSFORM_BYTES : READ_MAX_BYTES;\n // A text read takes at least one whole character; a base64 read returns bytes as they are.\n const min = input.base64 === true ? 1 : UTF8_MAX_BYTES;\n const length = clamp(Math.floor(input.length ?? READ_DEFAULT_BYTES), min, max);\n const range = clampRange(Math.floor(input.offset ?? 0), length, source.size);\n let bytes: Uint8Array;\n try {\n bytes = range.to > range.from ? await source.read(range) : new Uint8Array(0);\n } catch (e: unknown) {\n return errorResult(\n `Read failed: ${errorText(e)}`,\n signal.aborted\n ? \"The read took too long or was cancelled: try again, or read a smaller range.\"\n : undefined,\n );\n }\n // A base64 read returns the bytes of the range as they are: text only when they are whole\n // characters.\n let decoded =\n input.base64 === true\n ? decodeContent(bytes, { atEnd: true })\n : decodeContent(bytes, { skipLead: range.from > 0, atEnd: range.to >= source.size });\n if (input.transform === undefined) decoded = fitToResult(decoded, input.base64 === true);\n const skipped = decoded.encoding === \"utf-8\" ? decoded.skippedBytes : 0;\n const used = decoded.usedBytes;\n bytes = bytes.subarray(skipped, skipped + used);\n const start = range.from + skipped;\n const end = start + used;\n const meta = {\n source: source.kind,\n size: source.size,\n offset: start,\n bytesRead: used,\n eof: end >= source.size,\n ...(end < source.size ? { nextOffset: end } : {}),\n encoding: decoded.encoding,\n };\n const base64 = decoded.encoding === \"binary\" ? Buffer.from(bytes).toString(\"base64\") : undefined;\n\n if (input.transform !== undefined) {\n try {\n const result = await safeEval(\n input.transform,\n {\n text: decoded.encoding === \"utf-8\" ? decoded.text : undefined,\n base64,\n size: meta.size,\n offset: meta.offset,\n bytesRead: meta.bytesRead,\n eof: meta.eof,\n },\n input.transformTimeout ?? DEFAULT_TRANSFORM_TIMEOUT,\n );\n return textResult({ ...meta, result });\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check the expression. Available variables: text, base64, size, offset, bytesRead, eof.\",\n );\n }\n }\n if (decoded.encoding === \"utf-8\") return textResult({ ...meta, text: decoded.text });\n return textResult(input.base64 === true ? { ...meta, base64 } : meta);\n}\n\nexport function registerFileTools(server: ToolRegistrar, ctx: ToolContext): void {\n const drivers = () => {\n const kit = ctx.requireMl().internalDriverKit;\n const ls: FileLsDriver = kit.lsDriver;\n const blob: FileBlobDriver = kit.blobDriver;\n return { ls, blob };\n };\n\n server.registerTool(\n \"list_files\",\n {\n title: \"List Files\",\n annotations: hints.read,\n description:\n \"List the storages files can be taken from, or the entries of a folder in one. With no \" +\n \"arguments: the storages, `[{ id, name, kind: local|remote, initialPath }]` (local: \" +\n \"this computer; remote: data libraries of the server). With `storage` (an id) and \" +\n \"`path`: the folder's entries `{ name, type: file|dir, path, size? }`, sorted by name, \" +\n \"a page at a time (`total`, `hasMore`, `nextOffset`). `path` alone lists a folder of \" +\n \"this computer. Listing gives no handles: get_file_handles makes them for the files \" +\n \"you pick, and that is how files are given to a block.\",\n inputSchema: z.object({\n storage: z\n .string()\n .optional()\n .describe(\"Storage id (or name) from the storage list. Omit for this computer.\"),\n path: z\n .string()\n .optional()\n .describe(\n \"Folder to list. Local: absolute, or relative to the storage's root; omitted, the \" +\n \"storage's initial folder. Remote: the folder's path in the storage, '' for its top.\",\n ),\n pattern: z\n .string()\n .optional()\n .describe(\n \"JavaScript regular expression the entry name must match (tested anywhere in the \" +\n \"name: anchor it with ^…$ for the whole name), e.g. `^S\\\\d+_R[12]\\\\.fastq\\\\.gz$`. \" +\n `Matching one folder may take at most ${PATTERN_TIME_BUDGET_MS} ms.`,\n ),\n type: z.enum([\"file\", \"dir\"]).optional().describe(\"Only files, or only folders.\"),\n offset: z.number().optional().describe(\"Entries to skip (default 0).\"),\n limit: z\n .number()\n .optional()\n .describe(`Entries per page (default ${LIST_DEFAULT_LIMIT}, at most ${LIST_MAX_LIMIT}).`),\n }),\n },\n async (input) => listFilesResult(drivers().ls, input),\n );\n\n server.registerTool(\n \"get_file_handles\",\n {\n title: \"Get File Handles\",\n annotations: hints.read,\n description:\n \"Make import handles for files: this is how files are given to a block. Put a handle \" +\n \"into the block's data where the block takes a file (set_block_data). When the block \" +\n \"uses the file (its pre-run, which follows every change of the data, or its run), a \" +\n \"file of this computer is uploaded to the server, a file of a data library is used \" +\n \"where it is. get_block_state shows the progress under `imports`; await_block_done \" +\n \"with waitForImports waits for it.\\n\\n\" +\n \"`paths`: absolute paths of files of this computer, or with `storage`, paths in that \" +\n \"storage (as list_files gives them). Result: `{ handles: [{ path, handle, size? }], \" +\n `errors?: [{ path, error }] }\\`, in the order asked. At most ${MAX_HANDLES} files per ` +\n \"call. Copy handles as they are; a local file's handle stops working when the file \" +\n \"changes.\",\n inputSchema: z.object({\n paths: z.array(z.string()).describe(\"File paths.\"),\n storage: z\n .string()\n .optional()\n .describe(\"Storage id (or name) the paths are in. Omit for this computer.\"),\n }),\n },\n async (input) => fileHandlesResult(drivers().ls, input),\n );\n\n server.registerTool(\n \"read_file\",\n {\n title: \"Read File\",\n annotations: hints.read,\n description:\n \"Read a part of a file: a local file (`path`), an upload:// import handle, or a blob \" +\n \"handle from a block's outputs (blob+local://, blob+remote://). Reads \" +\n `\\`length\\` bytes from \\`offset\\` (default ${READ_DEFAULT_BYTES}, at most ` +\n `${READ_MAX_BYTES}); a range past the end is cut to it. Result: \\`{ size, offset, ` +\n \"bytesRead, eof, nextOffset?, encoding: utf-8|binary, text? , base64? }`: text when the \" +\n \"bytes are UTF-8, otherwise only their count (base64 with `base64: true`). Text keeps \" +\n \"whole characters: a range that starts inside one starts after it (`offset` says where) \" +\n \"and one that ends inside one stops before it (`nextOffset`). With `base64: true` the \" +\n \"range is returned as it is. With \" +\n \"`transform` the server reads up to 4 MiB and returns only the expression's value. \" +\n \"index:// handles (files of a data library) cannot be read here: read the block's \" +\n \"output blob instead.\",\n inputSchema: z.object({\n path: z.string().optional().describe(\"Absolute path of a local file.\"),\n handle: z\n .string()\n .optional()\n .describe(\"An upload:// import handle, or a blob handle from a block's outputs.\"),\n projectId: projectIdInput\n .optional()\n .describe(\"With a blob handle (required): the project whose block outputs gave it.\"),\n offset: z.number().optional().describe(\"Byte to start at (default 0).\"),\n length: z\n .number()\n .optional()\n .describe(\n `Bytes to read (default ${READ_DEFAULT_BYTES}; at most ${READ_MAX_BYTES}, or ` +\n `${READ_MAX_TRANSFORM_BYTES} with \\`transform\\`).`,\n ),\n base64: z\n .boolean()\n .optional()\n .describe(\"Return binary content as base64 (default false: its byte count only).\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated in the server against the content: `text` (UTF-8 content, \" +\n \"or undefined), `base64` (binary content, or undefined), `size`, `offset`, \" +\n \"`bytesRead`, `eof`. Example: `text.split('\\\\n').slice(0, 3)` for the first lines.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .describe(expressionTimeoutText(\"the transform\", DEFAULT_TRANSFORM_TIMEOUT)),\n }),\n },\n async (input, call) =>\n readFileResult(\n drivers().ls,\n drivers().blob,\n input,\n readSignal(call?.mcpReq.signal),\n (projectId, read) => ctx.withProject(projectId, () => read()),\n ),\n );\n}\n"],"mappings":";;;;;;;;;;AAuCA,MAAa,qBAAqB;;AAElC,MAAa,iBAAiB;;AAE9B,MAAa,2BAA2B;;AAIxC,MAAM,4BAA4B;AAgClC,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;;AAQvB,SAAgB,gBAAgB,GAAyC;CACvE,IAAI,cAAc,KAAK,CAAC,GAAG,OAAO;EAAE,MAAM;EAAS,QAAQ;CAAqB;CAChF,MAAM,SAAS,eAAe,KAAK,CAAC;CACpC,IAAI,WAAW,MACb,OAAO;EAAE,MAAM;EAAU,QAAQ;EAAuB,MAAM,OAAO,OAAO,EAAE;CAAE;AAEpF;;AAOA,SAAgB,Y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EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,aAAa;GACjD,SAAS,EACN,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,gEAAgE;EAC9E,CAAC;CACH,GACA,OAAO,UAAU,kBAAkB,QAAQ,CAAC,CAAC,IAAI,KAAK,CACxD;CAEA,OAAO,aACL,aACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE,wMAE6C,mBAAmB,YAC7D,eAAe;EASpB,aAAa,EAAE,OAAO;GACpB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,gCAAgC;GACrE,QAAQ,EACL,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,sEAAsE;GAClF,WAAW,eACR,SAAS,CAAC,CACV,SAAS,yEAAyE;GACrF,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,+BAA+B;GACtE,QAAQ,EACL,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,0BAA0B,mBAAmB,YAAY,eAAe,OACnE,yBAAyB,sBAChC;GACF,QAAQ,EACL,QAAQ,CAAC,CACT,SAAS,CAAC,CACV,SAAS,uEAAuE;GACnF,WAAW,EACR,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,+OAGF;GACF,kBAAkB,EACf,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,sBAAsB,iBAAiB,yBAAyB,CAAC;EAC/E,CAAC;CACH,GACA,OAAO,OAAO,SACZ,eACE,QAAQ,CAAC,CAAC,IACV,QAAQ,CAAC,CAAC,MACV,OACA,WAAW,MAAM,OAAO,MAAM,IAC7B,WAAW,SAAS,IAAI,YAAY,iBAAiB,KAAK,CAAC,CAC9D,CACJ;AACF"}
@@ -1,6 +1,26 @@
1
1
  let zod = require("zod");
2
2
  let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
3
3
  // src/tools/ids.ts
4
+ /**
5
+ * A column id an agent handed back, as a `ColumnUniversalId`, or `undefined` when it is not one.
6
+ * A string may come escaped once or more (an id copied out of JSON): the escaping is peeled. The
7
+ * key is checked to be one of the five forms and serialized canonically at its top level; ids
8
+ * nested in it stay as written. A PlRef, as an object or as JSON, becomes its `GlobalPObjectId`,
9
+ * without `requireEnrichments`.
10
+ */
11
+ function columnIdFromAgent(raw) {
12
+ const key = typeof raw === "string" ? (0, _milaboratories_pl_model_common.peelJsonLayers)(raw)?.value : raw;
13
+ if ((0, _milaboratories_pl_model_common.isPlRef)(key)) return (0, _milaboratories_pl_model_common.createGlobalPObjectId)(key.blockId, key.name);
14
+ return (0, _milaboratories_pl_model_common.isColumnUniversalKey)(key) ? (0, _milaboratories_pl_model_common.stringifyColumnId)(key) : void 0;
15
+ }
16
+ /** Brands a plugin handle: a key of a block's plugins, as get_block_state lists them. */
17
+ function asPluginHandle(handle) {
18
+ return handle;
19
+ }
20
+ /** Brands a plugin name (a plugin type) read from a block's plugin registry. */
21
+ function asPluginName(name) {
22
+ return name;
23
+ }
4
24
  /** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */
5
25
  function asPFrameHandle(handle) {
6
26
  return handle;
@@ -16,15 +36,51 @@ function asPTableHandle(handle) {
16
36
  const projectIdInput = zod.z.string().transform(_milaboratories_pl_model_common.asProjectId);
17
37
  /** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */
18
38
  const blockIdInput = zod.z.string().transform(_milaboratories_pl_model_common.asBlockId);
39
+ /** A plugin handle argument of a tool. */
40
+ const pluginHandleInput = zod.z.string().transform(asPluginHandle);
19
41
  /** A PFrame handle argument of a tool, as get_block_outputs gave it. */
20
42
  const pFrameHandleInput = zod.z.string().transform(asPFrameHandle);
43
+ /** A PlRef object: the object form of a block output's `GlobalPObjectId`. */
44
+ const plRefObject = zod.z.object({
45
+ __isRef: zod.z.literal(true),
46
+ blockId: zod.z.string(),
47
+ name: zod.z.string(),
48
+ requireEnrichments: zod.z.literal(true).optional()
49
+ });
50
+ /**
51
+ * A column id argument of a tool: any `ColumnUniversalId`, escaped or not, or a PlRef object.
52
+ * The tool receives it as {@link columnIdFromAgent} gives it; anything else is refused with a message.
53
+ */
54
+ const columnIdInput = zod.z.union([zod.z.string(), plRefObject]).transform((raw, ctx) => {
55
+ const id = columnIdFromAgent(raw);
56
+ if (id !== void 0) return id;
57
+ ctx.addIssue({
58
+ code: "custom",
59
+ message: "not a column id: copy `columnId` whole from the tool that listed the column"
60
+ });
61
+ return zod.z.NEVER;
62
+ });
63
+ /**
64
+ * The column id argument of a column of a block's PFrame, as list_columns gave it. A frame built
65
+ * by an older block API can list ids that are not `ColumnUniversalId`s, so the string stays as
66
+ * written and the tool finds it in the frame's listing; a PlRef object becomes its
67
+ * `GlobalPObjectId`.
68
+ */
69
+ const frameColumnIdInput = zod.z.union([zod.z.string(), plRefObject]).transform((raw) => typeof raw === "string" ? raw : (0, _milaboratories_pl_model_common.createGlobalPObjectId)(raw.blockId, raw.name));
21
70
  /** A PTable handle argument of a tool, as get_block_outputs gave it. */
22
71
  const pTableHandleInput = zod.z.string().transform(asPTableHandle);
23
72
  exports.asPFrameHandle = asPFrameHandle;
24
73
  exports.asPTableHandle = asPTableHandle;
74
+ exports.asPluginHandle = asPluginHandle;
75
+ exports.asPluginName = asPluginName;
25
76
  exports.blockIdInput = blockIdInput;
77
+ exports.columnIdFromAgent = columnIdFromAgent;
78
+ exports.columnIdInput = columnIdInput;
79
+ exports.frameColumnIdInput = frameColumnIdInput;
26
80
  exports.pFrameHandleInput = pFrameHandleInput;
27
81
  exports.pTableHandleInput = pTableHandleInput;
82
+ exports.plRefObject = plRefObject;
83
+ exports.pluginHandleInput = pluginHandleInput;
28
84
  exports.projectIdInput = projectIdInput;
29
85
 
30
86
  //# sourceMappingURL=ids.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ids.cjs","names":["z","asProjectId","asBlockId"],"sources":["../../src/tools/ids.ts"],"sourcesContent":["import {\n asBlockId,\n asProjectId,\n type PFrameHandle,\n type PTableHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\n\n/** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */\nexport function asPFrameHandle(handle: string): PFrameHandle {\n return handle as PFrameHandle;\n}\n\n/** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */\nexport function asPTableHandle(handle: string): PTableHandle {\n return handle as PTableHandle;\n}\n\n/**\n * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.\n * Each tool adds its own description.\n */\nexport const projectIdInput = z.string().transform(asProjectId);\n\n/** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */\nexport const blockIdInput = z.string().transform(asBlockId);\n\n/** A PFrame handle argument of a tool, as get_block_outputs gave it. */\nexport const pFrameHandleInput = z.string().transform(asPFrameHandle);\n\n/** A PTable handle argument of a tool, as get_block_outputs gave it. */\nexport const pTableHandleInput = z.string().transform(asPTableHandle);\n"],"mappings":";;;;AASA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;;;;AAMA,MAAa,iBAAiBA,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAUC,gCAAAA,WAAW;;AAG9D,MAAa,eAAeD,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAUE,gCAAAA,SAAS;;AAG1D,MAAa,oBAAoBF,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,oBAAoBA,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc"}
1
+ {"version":3,"file":"ids.cjs","names":["peelJsonLayers","isPlRef","createGlobalPObjectId","isColumnUniversalKey","stringifyColumnId","z","asProjectId","asBlockId"],"sources":["../../src/tools/ids.ts"],"sourcesContent":["import {\n asBlockId,\n asProjectId,\n createGlobalPObjectId,\n isColumnUniversalKey,\n isPlRef,\n peelJsonLayers,\n stringifyColumnId,\n type ColumnUniversalId,\n type PFrameHandle,\n type PTableHandle,\n} from \"@milaboratories/pl-model-common\";\nimport type { PluginHandle, PluginName } from \"@platforma-sdk/model\";\nimport { z } from \"zod\";\n\n/**\n * A column id an agent handed back, as a `ColumnUniversalId`, or `undefined` when it is not one.\n * A string may come escaped once or more (an id copied out of JSON): the escaping is peeled. The\n * key is checked to be one of the five forms and serialized canonically at its top level; ids\n * nested in it stay as written. A PlRef, as an object or as JSON, becomes its `GlobalPObjectId`,\n * without `requireEnrichments`.\n */\nexport function columnIdFromAgent(raw: unknown): ColumnUniversalId | undefined {\n const key = typeof raw === \"string\" ? peelJsonLayers(raw)?.value : raw;\n if (isPlRef(key)) return createGlobalPObjectId(key.blockId, key.name) as ColumnUniversalId;\n return isColumnUniversalKey(key) ? stringifyColumnId(key) : undefined;\n}\n\n/** Brands a plugin handle: a key of a block's plugins, as get_block_state lists them. */\nexport function asPluginHandle(handle: string): PluginHandle {\n return handle as PluginHandle;\n}\n\n/** Brands a plugin name (a plugin type) read from a block's plugin registry. */\nexport function asPluginName(name: string): PluginName {\n return name as PluginName;\n}\n\n/** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */\nexport function asPFrameHandle(handle: string): PFrameHandle {\n return handle as PFrameHandle;\n}\n\n/** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */\nexport function asPTableHandle(handle: string): PTableHandle {\n return handle as PTableHandle;\n}\n\n/**\n * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.\n * Each tool adds its own description.\n */\nexport const projectIdInput = z.string().transform(asProjectId);\n\n/** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */\nexport const blockIdInput = z.string().transform(asBlockId);\n\n/** A plugin handle argument of a tool. */\nexport const pluginHandleInput = z.string().transform(asPluginHandle);\n\n/** A PFrame handle argument of a tool, as get_block_outputs gave it. */\nexport const pFrameHandleInput = z.string().transform(asPFrameHandle);\n\n/** A PlRef object: the object form of a block output's `GlobalPObjectId`. */\nexport const plRefObject = z.object({\n __isRef: z.literal(true),\n blockId: z.string(),\n name: z.string(),\n requireEnrichments: z.literal(true).optional(),\n});\n\n/**\n * A column id argument of a tool: any `ColumnUniversalId`, escaped or not, or a PlRef object.\n * The tool receives it as {@link columnIdFromAgent} gives it; anything else is refused with a message.\n */\nexport const columnIdInput = z.union([z.string(), plRefObject]).transform((raw, ctx) => {\n const id = columnIdFromAgent(raw);\n if (id !== undefined) return id;\n ctx.addIssue({\n code: \"custom\",\n message: \"not a column id: copy `columnId` whole from the tool that listed the column\",\n });\n return z.NEVER;\n});\n\n/**\n * The column id argument of a column of a block's PFrame, as list_columns gave it. A frame built\n * by an older block API can list ids that are not `ColumnUniversalId`s, so the string stays as\n * written and the tool finds it in the frame's listing; a PlRef object becomes its\n * `GlobalPObjectId`.\n */\nexport const frameColumnIdInput = z\n .union([z.string(), plRefObject])\n .transform((raw): string =>\n typeof raw === \"string\" ? raw : createGlobalPObjectId(raw.blockId, raw.name),\n );\n\n/** A PTable handle argument of a tool, as get_block_outputs gave it. */\nexport const pTableHandleInput = z.string().transform(asPTableHandle);\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,kBAAkB,KAA6C;CAC7E,MAAM,MAAM,OAAO,QAAQ,YAAA,GAAWA,gCAAAA,eAAAA,CAAe,GAAG,CAAC,EAAE,QAAQ;CACnE,KAAA,GAAIC,gCAAAA,QAAAA,CAAQ,GAAG,GAAG,QAAA,GAAOC,gCAAAA,sBAAAA,CAAsB,IAAI,SAAS,IAAI,IAAI;CACpE,QAAA,GAAOC,gCAAAA,qBAAAA,CAAqB,GAAG,KAAA,GAAIC,gCAAAA,kBAAAA,CAAkB,GAAG,IAAI,KAAA;AAC9D;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,aAAa,MAA0B;CACrD,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;;;;AAMA,MAAa,iBAAiBC,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAUC,gCAAAA,WAAW;;AAG9D,MAAa,eAAeD,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAUE,gCAAAA,SAAS;;AAG1D,MAAa,oBAAoBF,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,oBAAoBA,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,cAAcA,IAAAA,EAAE,OAAO;CAClC,SAASA,IAAAA,EAAE,QAAQ,IAAI;CACvB,SAASA,IAAAA,EAAE,OAAO;CAClB,MAAMA,IAAAA,EAAE,OAAO;CACf,oBAAoBA,IAAAA,EAAE,QAAQ,IAAI,CAAC,CAAC,SAAS;AAC/C,CAAC;;;;;AAMD,MAAa,gBAAgBA,IAAAA,EAAE,MAAM,CAACA,IAAAA,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,WAAW,KAAK,QAAQ;CACtF,MAAM,KAAK,kBAAkB,GAAG;CAChC,IAAI,OAAO,KAAA,GAAW,OAAO;CAC7B,IAAI,SAAS;EACX,MAAM;EACN,SAAS;CACX,CAAC;CACD,OAAOA,IAAAA,EAAE;AACX,CAAC;;;;;;;AAQD,MAAa,qBAAqBA,IAAAA,EAC/B,MAAM,CAACA,IAAAA,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAChC,WAAW,QACV,OAAO,QAAQ,WAAW,OAAA,GAAMH,gCAAAA,sBAAAA,CAAsB,IAAI,SAAS,IAAI,IAAI,CAC7E;;AAGF,MAAa,oBAAoBG,IAAAA,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc"}
package/dist/tools/ids.js CHANGED
@@ -1,6 +1,26 @@
1
1
  import { z } from "zod";
2
- import { asBlockId, asProjectId } from "@milaboratories/pl-model-common";
2
+ import { asBlockId, asProjectId, createGlobalPObjectId, isColumnUniversalKey, isPlRef, peelJsonLayers, stringifyColumnId } from "@milaboratories/pl-model-common";
3
3
  // src/tools/ids.ts
4
+ /**
5
+ * A column id an agent handed back, as a `ColumnUniversalId`, or `undefined` when it is not one.
6
+ * A string may come escaped once or more (an id copied out of JSON): the escaping is peeled. The
7
+ * key is checked to be one of the five forms and serialized canonically at its top level; ids
8
+ * nested in it stay as written. A PlRef, as an object or as JSON, becomes its `GlobalPObjectId`,
9
+ * without `requireEnrichments`.
10
+ */
11
+ function columnIdFromAgent(raw) {
12
+ const key = typeof raw === "string" ? peelJsonLayers(raw)?.value : raw;
13
+ if (isPlRef(key)) return createGlobalPObjectId(key.blockId, key.name);
14
+ return isColumnUniversalKey(key) ? stringifyColumnId(key) : void 0;
15
+ }
16
+ /** Brands a plugin handle: a key of a block's plugins, as get_block_state lists them. */
17
+ function asPluginHandle(handle) {
18
+ return handle;
19
+ }
20
+ /** Brands a plugin name (a plugin type) read from a block's plugin registry. */
21
+ function asPluginName(name) {
22
+ return name;
23
+ }
4
24
  /** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */
5
25
  function asPFrameHandle(handle) {
6
26
  return handle;
@@ -16,10 +36,39 @@ function asPTableHandle(handle) {
16
36
  const projectIdInput = z.string().transform(asProjectId);
17
37
  /** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */
18
38
  const blockIdInput = z.string().transform(asBlockId);
39
+ /** A plugin handle argument of a tool. */
40
+ const pluginHandleInput = z.string().transform(asPluginHandle);
19
41
  /** A PFrame handle argument of a tool, as get_block_outputs gave it. */
20
42
  const pFrameHandleInput = z.string().transform(asPFrameHandle);
43
+ /** A PlRef object: the object form of a block output's `GlobalPObjectId`. */
44
+ const plRefObject = z.object({
45
+ __isRef: z.literal(true),
46
+ blockId: z.string(),
47
+ name: z.string(),
48
+ requireEnrichments: z.literal(true).optional()
49
+ });
50
+ /**
51
+ * A column id argument of a tool: any `ColumnUniversalId`, escaped or not, or a PlRef object.
52
+ * The tool receives it as {@link columnIdFromAgent} gives it; anything else is refused with a message.
53
+ */
54
+ const columnIdInput = z.union([z.string(), plRefObject]).transform((raw, ctx) => {
55
+ const id = columnIdFromAgent(raw);
56
+ if (id !== void 0) return id;
57
+ ctx.addIssue({
58
+ code: "custom",
59
+ message: "not a column id: copy `columnId` whole from the tool that listed the column"
60
+ });
61
+ return z.NEVER;
62
+ });
63
+ /**
64
+ * The column id argument of a column of a block's PFrame, as list_columns gave it. A frame built
65
+ * by an older block API can list ids that are not `ColumnUniversalId`s, so the string stays as
66
+ * written and the tool finds it in the frame's listing; a PlRef object becomes its
67
+ * `GlobalPObjectId`.
68
+ */
69
+ const frameColumnIdInput = z.union([z.string(), plRefObject]).transform((raw) => typeof raw === "string" ? raw : createGlobalPObjectId(raw.blockId, raw.name));
21
70
  /** A PTable handle argument of a tool, as get_block_outputs gave it. */
22
71
  const pTableHandleInput = z.string().transform(asPTableHandle);
23
- export { asPFrameHandle, asPTableHandle, blockIdInput, pFrameHandleInput, pTableHandleInput, projectIdInput };
72
+ export { asPFrameHandle, asPTableHandle, asPluginHandle, asPluginName, blockIdInput, columnIdFromAgent, columnIdInput, frameColumnIdInput, pFrameHandleInput, pTableHandleInput, plRefObject, pluginHandleInput, projectIdInput };
24
73
 
25
74
  //# sourceMappingURL=ids.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ids.js","names":[],"sources":["../../src/tools/ids.ts"],"sourcesContent":["import {\n asBlockId,\n asProjectId,\n type PFrameHandle,\n type PTableHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\n\n/** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */\nexport function asPFrameHandle(handle: string): PFrameHandle {\n return handle as PFrameHandle;\n}\n\n/** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */\nexport function asPTableHandle(handle: string): PTableHandle {\n return handle as PTableHandle;\n}\n\n/**\n * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.\n * Each tool adds its own description.\n */\nexport const projectIdInput = z.string().transform(asProjectId);\n\n/** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */\nexport const blockIdInput = z.string().transform(asBlockId);\n\n/** A PFrame handle argument of a tool, as get_block_outputs gave it. */\nexport const pFrameHandleInput = z.string().transform(asPFrameHandle);\n\n/** A PTable handle argument of a tool, as get_block_outputs gave it. */\nexport const pTableHandleInput = z.string().transform(asPTableHandle);\n"],"mappings":";;;;AASA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;;;;AAMA,MAAa,iBAAiB,EAAE,OAAO,CAAC,CAAC,UAAU,WAAW;;AAG9D,MAAa,eAAe,EAAE,OAAO,CAAC,CAAC,UAAU,SAAS;;AAG1D,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc"}
1
+ {"version":3,"file":"ids.js","names":[],"sources":["../../src/tools/ids.ts"],"sourcesContent":["import {\n asBlockId,\n asProjectId,\n createGlobalPObjectId,\n isColumnUniversalKey,\n isPlRef,\n peelJsonLayers,\n stringifyColumnId,\n type ColumnUniversalId,\n type PFrameHandle,\n type PTableHandle,\n} from \"@milaboratories/pl-model-common\";\nimport type { PluginHandle, PluginName } from \"@platforma-sdk/model\";\nimport { z } from \"zod\";\n\n/**\n * A column id an agent handed back, as a `ColumnUniversalId`, or `undefined` when it is not one.\n * A string may come escaped once or more (an id copied out of JSON): the escaping is peeled. The\n * key is checked to be one of the five forms and serialized canonically at its top level; ids\n * nested in it stay as written. A PlRef, as an object or as JSON, becomes its `GlobalPObjectId`,\n * without `requireEnrichments`.\n */\nexport function columnIdFromAgent(raw: unknown): ColumnUniversalId | undefined {\n const key = typeof raw === \"string\" ? peelJsonLayers(raw)?.value : raw;\n if (isPlRef(key)) return createGlobalPObjectId(key.blockId, key.name) as ColumnUniversalId;\n return isColumnUniversalKey(key) ? stringifyColumnId(key) : undefined;\n}\n\n/** Brands a plugin handle: a key of a block's plugins, as get_block_state lists them. */\nexport function asPluginHandle(handle: string): PluginHandle {\n return handle as PluginHandle;\n}\n\n/** Brands a plugin name (a plugin type) read from a block's plugin registry. */\nexport function asPluginName(name: string): PluginName {\n return name as PluginName;\n}\n\n/** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */\nexport function asPFrameHandle(handle: string): PFrameHandle {\n return handle as PFrameHandle;\n}\n\n/** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */\nexport function asPTableHandle(handle: string): PTableHandle {\n return handle as PTableHandle;\n}\n\n/**\n * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.\n * Each tool adds its own description.\n */\nexport const projectIdInput = z.string().transform(asProjectId);\n\n/** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */\nexport const blockIdInput = z.string().transform(asBlockId);\n\n/** A plugin handle argument of a tool. */\nexport const pluginHandleInput = z.string().transform(asPluginHandle);\n\n/** A PFrame handle argument of a tool, as get_block_outputs gave it. */\nexport const pFrameHandleInput = z.string().transform(asPFrameHandle);\n\n/** A PlRef object: the object form of a block output's `GlobalPObjectId`. */\nexport const plRefObject = z.object({\n __isRef: z.literal(true),\n blockId: z.string(),\n name: z.string(),\n requireEnrichments: z.literal(true).optional(),\n});\n\n/**\n * A column id argument of a tool: any `ColumnUniversalId`, escaped or not, or a PlRef object.\n * The tool receives it as {@link columnIdFromAgent} gives it; anything else is refused with a message.\n */\nexport const columnIdInput = z.union([z.string(), plRefObject]).transform((raw, ctx) => {\n const id = columnIdFromAgent(raw);\n if (id !== undefined) return id;\n ctx.addIssue({\n code: \"custom\",\n message: \"not a column id: copy `columnId` whole from the tool that listed the column\",\n });\n return z.NEVER;\n});\n\n/**\n * The column id argument of a column of a block's PFrame, as list_columns gave it. A frame built\n * by an older block API can list ids that are not `ColumnUniversalId`s, so the string stays as\n * written and the tool finds it in the frame's listing; a PlRef object becomes its\n * `GlobalPObjectId`.\n */\nexport const frameColumnIdInput = z\n .union([z.string(), plRefObject])\n .transform((raw): string =>\n typeof raw === \"string\" ? raw : createGlobalPObjectId(raw.blockId, raw.name),\n );\n\n/** A PTable handle argument of a tool, as get_block_outputs gave it. */\nexport const pTableHandleInput = z.string().transform(asPTableHandle);\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,kBAAkB,KAA6C;CAC7E,MAAM,MAAM,OAAO,QAAQ,WAAW,eAAe,GAAG,CAAC,EAAE,QAAQ;CACnE,IAAI,QAAQ,GAAG,GAAG,OAAO,sBAAsB,IAAI,SAAS,IAAI,IAAI;CACpE,OAAO,qBAAqB,GAAG,IAAI,kBAAkB,GAAG,IAAI,KAAA;AAC9D;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,aAAa,MAA0B;CACrD,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,OAAO;AACT;;;;;AAMA,MAAa,iBAAiB,EAAE,OAAO,CAAC,CAAC,UAAU,WAAW;;AAG9D,MAAa,eAAe,EAAE,OAAO,CAAC,CAAC,UAAU,SAAS;;AAG1D,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc;;AAGpE,MAAa,cAAc,EAAE,OAAO;CAClC,SAAS,EAAE,QAAQ,IAAI;CACvB,SAAS,EAAE,OAAO;CAClB,MAAM,EAAE,OAAO;CACf,oBAAoB,EAAE,QAAQ,IAAI,CAAC,CAAC,SAAS;AAC/C,CAAC;;;;;AAMD,MAAa,gBAAgB,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,WAAW,KAAK,QAAQ;CACtF,MAAM,KAAK,kBAAkB,GAAG;CAChC,IAAI,OAAO,KAAA,GAAW,OAAO;CAC7B,IAAI,SAAS;EACX,MAAM;EACN,SAAS;CACX,CAAC;CACD,OAAO,EAAE;AACX,CAAC;;;;;;;AAQD,MAAa,qBAAqB,EAC/B,MAAM,CAAC,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAChC,WAAW,QACV,OAAO,QAAQ,WAAW,MAAM,sBAAsB,IAAI,SAAS,IAAI,IAAI,CAC7E;;AAGF,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,UAAU,cAAc"}
@@ -0,0 +1,195 @@
1
+ const require_settle = require("./settle.cjs");
2
+ const require_tokens = require("./tokens.cjs");
3
+ let _milaboratories_helpers = require("@milaboratories/helpers");
4
+ let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
5
+ /** How deep into an output value import progress is looked for. */
6
+ const MAX_DEPTH = 8;
7
+ /** The most nodes of all outputs of one block walked when looking for import progress. */
8
+ const MAX_NODES = 2e4;
9
+ /** The most characters of an import's last error an entry carries. */
10
+ const IMPORT_ERROR_CHARS = 300;
11
+ /**
12
+ * Whether `v` is the import progress a block model returns from `getImportProgress()`: an object
13
+ * with boolean `done` and `isUpload` (`ImportProgress` of the SDK).
14
+ */
15
+ function isImportProgress(v) {
16
+ return (0, _milaboratories_helpers.isPlainObject)(v) && typeof v.done === "boolean" && typeof v.isUpload === "boolean";
17
+ }
18
+ const IMPORT_HANDLE_RE = /^(upload:\/\/upload\/|index:\/\/index\/)/;
19
+ /** Whether `v` is an import handle (`upload://…` or `index://…`). */
20
+ function isImportHandle(v) {
21
+ return typeof v === "string" && IMPORT_HANDLE_RE.test(v);
22
+ }
23
+ /** The file name an import handle names; `undefined` when it does not parse. */
24
+ function fileNameOfHandle(handle) {
25
+ if (!isImportHandle(handle)) return void 0;
26
+ try {
27
+ return (0, _milaboratories_pl_model_common.getFileNameFromHandle)(handle);
28
+ } catch {
29
+ return;
30
+ }
31
+ }
32
+ function stateOf(p) {
33
+ if (p.done === true) return "done";
34
+ if (p.isUpload === true && p.isUploadSignMatch === false) return "foreign";
35
+ if (typeof p.lastError === "string" && p.lastError !== "") return "failed";
36
+ const status = (0, _milaboratories_helpers.isPlainObject)(p.status) ? p.status : void 0;
37
+ const progress = typeof status?.progress === "number" ? status.progress : 0;
38
+ const processed = typeof status?.bytesProcessed === "number" ? status.bytesProcessed : 0;
39
+ return progress > 0 || processed > 0 ? "inProgress" : "notStarted";
40
+ }
41
+ function keyPath(path, key) {
42
+ return `${path}[${JSON.stringify(key)}]`;
43
+ }
44
+ /**
45
+ * Finds every import progress in a block's outputs (output key → `{ok, value}`), in output order,
46
+ * values depth-first. Recognized wherever a model puts it: as the output value, in a record keyed
47
+ * by import handle or any other key, in an array, or as the second item of `[handle, progress]`
48
+ * pairs. Failed outputs are skipped. The walk stops at {@link MAX_DEPTH} and {@link MAX_NODES}.
49
+ */
50
+ function collectImports(outputs) {
51
+ if (outputs === void 0) return [];
52
+ const found = [];
53
+ let nodes = 0;
54
+ const walk = (output, v, path, depth, file) => {
55
+ if (++nodes > MAX_NODES || depth > MAX_DEPTH) return;
56
+ if (isImportProgress(v)) {
57
+ const status = (0, _milaboratories_helpers.isPlainObject)(v.status) ? v.status : void 0;
58
+ const entry = {
59
+ output,
60
+ path: path === "" ? "(value)" : path,
61
+ state: stateOf(v),
62
+ isUpload: v.isUpload
63
+ };
64
+ if (file !== void 0) entry.file = file;
65
+ if (typeof status?.progress === "number") entry.progress = status.progress;
66
+ if (typeof status?.bytesProcessed === "number") entry.bytesProcessed = status.bytesProcessed;
67
+ if (typeof status?.bytesTotal === "number") entry.bytesTotal = status.bytesTotal;
68
+ if (typeof v.lastError === "string" && v.lastError !== "") entry.lastError = require_tokens.clip(v.lastError, IMPORT_ERROR_CHARS);
69
+ found.push(entry);
70
+ return;
71
+ }
72
+ if (Array.isArray(v)) {
73
+ const pairFile = v.length === 2 && isImportHandle(v[0]) ? fileNameOfHandle(v[0]) : void 0;
74
+ v.forEach((item, i) => walk(output, item, `${path}[${i}]`, depth + 1, pairFile));
75
+ return;
76
+ }
77
+ if ((0, _milaboratories_helpers.isPlainObject)(v)) for (const [key, item] of Object.entries(v)) walk(output, item, keyPath(path, key), depth + 1, fileNameOfHandle(key));
78
+ };
79
+ for (const [key, out] of Object.entries(outputs)) {
80
+ if (!(0, _milaboratories_helpers.isPlainObject)(out) || out.ok !== true) continue;
81
+ walk(key, out.value, "", 0);
82
+ }
83
+ return found;
84
+ }
85
+ const PENDING_ORDER = {
86
+ failed: 0,
87
+ inProgress: 1,
88
+ notStarted: 2,
89
+ foreign: 3,
90
+ done: 4
91
+ };
92
+ /**
93
+ * Sums up a block's imports; `undefined` when it has none. Bytes are summed over the imports
94
+ * whose status gives them.
95
+ */
96
+ function summarizeImports(entries) {
97
+ if (entries.length === 0) return void 0;
98
+ const count = (state) => entries.filter((e) => e.state === state).length;
99
+ const failed = count("failed");
100
+ const foreign = count("foreign");
101
+ const notDone = entries.filter((e) => e.state !== "done").toSorted((a, b) => PENDING_ORDER[a.state] - PENDING_ORDER[b.state]);
102
+ const summary = {
103
+ total: entries.length,
104
+ done: count("done"),
105
+ inProgress: count("inProgress"),
106
+ notStarted: count("notStarted"),
107
+ ...failed > 0 ? { failed } : {},
108
+ ...foreign > 0 ? { foreign } : {},
109
+ bytesProcessed: entries.reduce((s, e) => s + (e.bytesProcessed ?? 0), 0),
110
+ bytesTotal: entries.reduce((s, e) => s + (e.bytesTotal ?? 0), 0)
111
+ };
112
+ if (notDone.length > 0) summary.pending = notDone.slice(0, 20);
113
+ if (notDone.length > 20) summary.morePending = notDone.length - 20;
114
+ return summary;
115
+ }
116
+ /** The imports summary of a block's outputs; `undefined` when they carry no import progress. */
117
+ function importsOf(outputs) {
118
+ return summarizeImports(collectImports(outputs));
119
+ }
120
+ /**
121
+ * How many imports are still to finish here: not done and not foreign (a foreign upload is for
122
+ * another computer to send).
123
+ */
124
+ function unfinishedImports(summary) {
125
+ if (summary === void 0) return 0;
126
+ return summary.total - summary.done - (summary.foreign ?? 0);
127
+ }
128
+ /**
129
+ * The uploads among `entries` that are still to go: files of this computer whose upload is in
130
+ * progress or not started. Not counted: done ones, foreign ones (another computer sends them),
131
+ * failed ones (retrying after an error; they may never succeed) and files of a data library
132
+ * (indexed where they are; the project need not stay loaded for them).
133
+ */
134
+ function uploadsToFinish(entries) {
135
+ return entries.filter((e) => e.isUpload && (e.state === "inProgress" || e.state === "notStarted"));
136
+ }
137
+ /**
138
+ * The uploads still to go of every block of a project (Q-002): a block's pre-run starts uploads
139
+ * as well as its run, so no block is skipped. Reading a block's outputs computes them, so this is
140
+ * meant for the moment a kept hold's idle time is over, not for every call; a block whose state
141
+ * cannot be read counts as having none.
142
+ */
143
+ async function pendingUploadsOfProject(project) {
144
+ const overview = await project.overview.getValue();
145
+ const pending = {
146
+ count: 0,
147
+ bytesProcessed: 0
148
+ };
149
+ for (const block of overview?.blocks ?? []) try {
150
+ const state = await project.getBlockState((0, _milaboratories_pl_model_common.asBlockId)(block.id)).getValue();
151
+ const uploads = collectImports((0, _milaboratories_helpers.isPlainObject)(state.outputs) ? state.outputs : void 0).filter((e) => e.isUpload);
152
+ pending.count += uploadsToFinish(uploads).length;
153
+ pending.bytesProcessed += uploads.reduce((sum, e) => sum + (e.bytesProcessed ?? 0), 0);
154
+ } catch {}
155
+ return pending;
156
+ }
157
+ /**
158
+ * Waits until no import of a block is left to finish here ({@link unfinishedImports} is 0), or
159
+ * `timeoutMs` runs out, or `signal` fires. Every change of the block state is a look (the state
160
+ * changes as the upload progress does), and so is every 5 s without one ({@link awaitChangeOrWake}),
161
+ * for the progress notifications.
162
+ */
163
+ async function awaitImportsDone(computable, options) {
164
+ const start = Date.now();
165
+ return await require_settle.withDeadline(options.timeoutMs, options.signal, async (signal) => {
166
+ for (;;) {
167
+ const lookStart = Date.now();
168
+ const full = await computable.getFullValue();
169
+ const imports = importsOf(full.value.outputs);
170
+ const ended = (done) => ({
171
+ done,
172
+ aborted: options.signal?.aborted ?? false,
173
+ waitedMs: Date.now() - start,
174
+ state: full.value,
175
+ imports
176
+ });
177
+ if (unfinishedImports(imports) === 0) return ended(true);
178
+ if (signal.aborted) return ended(false);
179
+ options.onProgress?.(Date.now() - start, options.timeoutMs);
180
+ await require_settle.awaitChangeOrWake(computable, full.uTag, signal, lookStart);
181
+ }
182
+ });
183
+ }
184
+ exports.awaitImportsDone = awaitImportsDone;
185
+ exports.collectImports = collectImports;
186
+ exports.fileNameOfHandle = fileNameOfHandle;
187
+ exports.importsOf = importsOf;
188
+ exports.isImportHandle = isImportHandle;
189
+ exports.isImportProgress = isImportProgress;
190
+ exports.pendingUploadsOfProject = pendingUploadsOfProject;
191
+ exports.summarizeImports = summarizeImports;
192
+ exports.unfinishedImports = unfinishedImports;
193
+ exports.uploadsToFinish = uploadsToFinish;
194
+
195
+ //# sourceMappingURL=imports.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imports.cjs","names":["isPlainObject","getFileNameFromHandle","clip","asBlockId","withDeadline","awaitChangeOrWake"],"sources":["../../src/tools/imports.ts"],"sourcesContent":["import {\n asBlockId,\n type BlockId,\n getFileNameFromHandle,\n type ImportFileHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\nimport { awaitChangeOrWake, withDeadline } from \"./settle\";\nimport { clip } from \"./tokens\";\n\n/** The most unfinished or failed imports a block view lists one by one. */\nexport const MAX_IMPORT_ENTRIES = 20;\n\n/** How deep into an output value import progress is looked for. */\nconst MAX_DEPTH = 8;\n\n/** The most nodes of all outputs of one block walked when looking for import progress. */\nconst MAX_NODES = 20_000;\n\n/** The most characters of an import's last error an entry carries. */\nconst IMPORT_ERROR_CHARS = 300;\n\n/** Where one import stands. */\nexport type ImportState = \"done\" | \"inProgress\" | \"notStarted\" | \"failed\" | \"foreign\";\n\n/** One import of a block, found in its outputs. */\nexport type ImportEntry = {\n /** The output that carries the progress. */\n output: string;\n /** Where in the output's value: `(value)`, `[\"<key>\"]`, `[2][1]`. */\n path: string;\n /** The file name, when the progress is keyed by its import handle. */\n file?: string;\n state: ImportState;\n /** True for a file uploaded from this computer, false for a file indexed in a data library. */\n isUpload: boolean;\n /** From 0 to 1. */\n progress?: number;\n bytesProcessed?: number;\n bytesTotal?: number;\n lastError?: string;\n};\n\n/** The imports of a block in numbers, and those that are not done. */\nexport type ImportsSummary = {\n total: number;\n done: number;\n inProgress: number;\n notStarted: number;\n /** Retrying after an error (`lastError`); an upload that fails for good fails its output. */\n failed?: number;\n /** Uploads that were started on another computer (signature mismatch): never finished here. */\n foreign?: number;\n bytesProcessed: number;\n bytesTotal: number;\n /** Not done, at most {@link MAX_IMPORT_ENTRIES}: failed first, then in progress, then not started. */\n pending?: ImportEntry[];\n /** How many more not-done imports there are past `pending`. */\n morePending?: number;\n};\n\n/**\n * Whether `v` is the import progress a block model returns from `getImportProgress()`: an object\n * with boolean `done` and `isUpload` (`ImportProgress` of the SDK).\n */\nexport function isImportProgress(v: unknown): v is Record<string, unknown> & {\n done: boolean;\n isUpload: boolean;\n} {\n return isPlainObject(v) && typeof v.done === \"boolean\" && typeof v.isUpload === \"boolean\";\n}\n\nconst IMPORT_HANDLE_RE = /^(upload:\\/\\/upload\\/|index:\\/\\/index\\/)/;\n\n/** Whether `v` is an import handle (`upload://…` or `index://…`). */\nexport function isImportHandle(v: unknown): v is ImportFileHandle {\n return typeof v === \"string\" && IMPORT_HANDLE_RE.test(v);\n}\n\n/** The file name an import handle names; `undefined` when it does not parse. */\nexport function fileNameOfHandle(handle: string): string | undefined {\n if (!isImportHandle(handle)) return undefined;\n try {\n return getFileNameFromHandle(handle);\n } catch {\n return undefined;\n }\n}\n\nfunction stateOf(p: Record<string, unknown>): ImportState {\n if (p.done === true) return \"done\";\n if (p.isUpload === true && p.isUploadSignMatch === false) return \"foreign\";\n if (typeof p.lastError === \"string\" && p.lastError !== \"\") return \"failed\";\n const status = isPlainObject(p.status) ? p.status : undefined;\n const progress = typeof status?.progress === \"number\" ? status.progress : 0;\n const processed = typeof status?.bytesProcessed === \"number\" ? status.bytesProcessed : 0;\n return progress > 0 || processed > 0 ? \"inProgress\" : \"notStarted\";\n}\n\nfunction keyPath(path: string, key: string): string {\n return `${path}[${JSON.stringify(key)}]`;\n}\n\n/**\n * Finds every import progress in a block's outputs (output key → `{ok, value}`), in output order,\n * values depth-first. Recognized wherever a model puts it: as the output value, in a record keyed\n * by import handle or any other key, in an array, or as the second item of `[handle, progress]`\n * pairs. Failed outputs are skipped. The walk stops at {@link MAX_DEPTH} and {@link MAX_NODES}.\n */\nexport function collectImports(outputs: Record<string, unknown> | undefined): ImportEntry[] {\n if (outputs === undefined) return [];\n const found: ImportEntry[] = [];\n let nodes = 0;\n\n const walk = (output: string, v: unknown, path: string, depth: number, file?: string) => {\n if (++nodes > MAX_NODES || depth > MAX_DEPTH) return;\n if (isImportProgress(v)) {\n const status = isPlainObject(v.status) ? v.status : undefined;\n const entry: ImportEntry = {\n output,\n path: path === \"\" ? \"(value)\" : path,\n state: stateOf(v),\n isUpload: v.isUpload,\n };\n if (file !== undefined) entry.file = file;\n if (typeof status?.progress === \"number\") entry.progress = status.progress;\n if (typeof status?.bytesProcessed === \"number\") entry.bytesProcessed = status.bytesProcessed;\n if (typeof status?.bytesTotal === \"number\") entry.bytesTotal = status.bytesTotal;\n if (typeof v.lastError === \"string\" && v.lastError !== \"\")\n entry.lastError = clip(v.lastError, IMPORT_ERROR_CHARS);\n found.push(entry);\n return;\n }\n if (Array.isArray(v)) {\n // `[handle, progress]`: the progress is named by the handle's file.\n const pairFile = v.length === 2 && isImportHandle(v[0]) ? fileNameOfHandle(v[0]) : undefined;\n v.forEach((item, i) => walk(output, item, `${path}[${i}]`, depth + 1, pairFile));\n return;\n }\n if (isPlainObject(v)) {\n for (const [key, item] of Object.entries(v))\n walk(output, item, keyPath(path, key), depth + 1, fileNameOfHandle(key));\n }\n };\n\n for (const [key, out] of Object.entries(outputs)) {\n if (!isPlainObject(out) || out.ok !== true) continue;\n walk(key, out.value, \"\", 0);\n }\n return found;\n}\n\nconst PENDING_ORDER: Record<ImportState, number> = {\n failed: 0,\n inProgress: 1,\n notStarted: 2,\n foreign: 3,\n done: 4,\n};\n\n/**\n * Sums up a block's imports; `undefined` when it has none. Bytes are summed over the imports\n * whose status gives them.\n */\nexport function summarizeImports(entries: ImportEntry[]): ImportsSummary | undefined {\n if (entries.length === 0) return undefined;\n const count = (state: ImportState) => entries.filter((e) => e.state === state).length;\n const failed = count(\"failed\");\n const foreign = count(\"foreign\");\n const notDone = entries\n .filter((e) => e.state !== \"done\")\n .toSorted((a, b) => PENDING_ORDER[a.state] - PENDING_ORDER[b.state]);\n const summary: ImportsSummary = {\n total: entries.length,\n done: count(\"done\"),\n inProgress: count(\"inProgress\"),\n notStarted: count(\"notStarted\"),\n ...(failed > 0 ? { failed } : {}),\n ...(foreign > 0 ? { foreign } : {}),\n bytesProcessed: entries.reduce((s, e) => s + (e.bytesProcessed ?? 0), 0),\n bytesTotal: entries.reduce((s, e) => s + (e.bytesTotal ?? 0), 0),\n };\n if (notDone.length > 0) summary.pending = notDone.slice(0, MAX_IMPORT_ENTRIES);\n if (notDone.length > MAX_IMPORT_ENTRIES)\n summary.morePending = notDone.length - MAX_IMPORT_ENTRIES;\n return summary;\n}\n\n/** The imports summary of a block's outputs; `undefined` when they carry no import progress. */\nexport function importsOf(\n outputs: Record<string, unknown> | undefined,\n): ImportsSummary | undefined {\n return summarizeImports(collectImports(outputs));\n}\n\n/**\n * How many imports are still to finish here: not done and not foreign (a foreign upload is for\n * another computer to send).\n */\nexport function unfinishedImports(summary: ImportsSummary | undefined): number {\n if (summary === undefined) return 0;\n return summary.total - summary.done - (summary.foreign ?? 0);\n}\n\n/** What {@link pendingUploadsOfProject} reads of a project; a middle-layer `Project` has it. */\nexport type ImportsProject = {\n overview: { getValue(): Promise<{ blocks: { id: string }[] } | undefined> };\n getBlockState(blockId: BlockId): { getValue(): Promise<{ outputs?: unknown }> };\n};\n\n/**\n * The uploads among `entries` that are still to go: files of this computer whose upload is in\n * progress or not started. Not counted: done ones, foreign ones (another computer sends them),\n * failed ones (retrying after an error; they may never succeed) and files of a data library\n * (indexed where they are; the project need not stay loaded for them).\n */\nexport function uploadsToFinish(entries: readonly ImportEntry[]): ImportEntry[] {\n return entries.filter(\n (e) => e.isUpload && (e.state === \"inProgress\" || e.state === \"notStarted\"),\n );\n}\n\n/** The uploads of a project still to go ({@link uploadsToFinish}), and how far they got. */\nexport type PendingUploads = {\n count: number;\n /** Bytes uploaded so far, summed over every upload of the project, done ones included. */\n bytesProcessed: number;\n};\n\n/**\n * The uploads still to go of every block of a project (Q-002): a block's pre-run starts uploads\n * as well as its run, so no block is skipped. Reading a block's outputs computes them, so this is\n * meant for the moment a kept hold's idle time is over, not for every call; a block whose state\n * cannot be read counts as having none.\n */\nexport async function pendingUploadsOfProject(project: ImportsProject): Promise<PendingUploads> {\n const overview = await project.overview.getValue();\n const pending: PendingUploads = { count: 0, bytesProcessed: 0 };\n for (const block of overview?.blocks ?? []) {\n try {\n const state = await project.getBlockState(asBlockId(block.id)).getValue();\n const uploads = collectImports(\n isPlainObject(state.outputs) ? state.outputs : undefined,\n ).filter((e) => e.isUpload);\n pending.count += uploadsToFinish(uploads).length;\n pending.bytesProcessed += uploads.reduce((sum, e) => sum + (e.bytesProcessed ?? 0), 0);\n } catch {\n // a block removed meanwhile, or outputs that fail as a whole: nothing to wait for here\n }\n }\n return pending;\n}\n\n/** The block state computable as {@link awaitImportsDone} uses it; a middle-layer `Computable`. */\nexport type ImportsStateComputable<S extends { outputs?: Record<string, unknown> | undefined }> = {\n getFullValue(): Promise<{ value: S; uTag: string }>;\n awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void>;\n};\n\n/** How {@link awaitImportsDone} ended. */\nexport type ImportsWait<S> = {\n /** No import of the block is left to finish here. */\n done: boolean;\n /** The request was cancelled (otherwise an unfinished wait ran out of time). */\n aborted: boolean;\n waitedMs: number;\n state: S;\n imports: ImportsSummary | undefined;\n};\n\n/**\n * Waits until no import of a block is left to finish here ({@link unfinishedImports} is 0), or\n * `timeoutMs` runs out, or `signal` fires. Every change of the block state is a look (the state\n * changes as the upload progress does), and so is every 5 s without one ({@link awaitChangeOrWake}),\n * for the progress notifications.\n */\nexport async function awaitImportsDone<S extends { outputs?: Record<string, unknown> | undefined }>(\n computable: ImportsStateComputable<S>,\n options: {\n timeoutMs: number;\n signal?: AbortSignal;\n onProgress?: (elapsedMs: number, timeoutMs: number) => void;\n },\n): Promise<ImportsWait<S>> {\n const start = Date.now();\n return await withDeadline(options.timeoutMs, options.signal, async (signal) => {\n for (;;) {\n const lookStart = Date.now();\n const full = await computable.getFullValue();\n const imports = importsOf(full.value.outputs);\n const ended = (done: boolean): ImportsWait<S> => ({\n done,\n aborted: options.signal?.aborted ?? false,\n waitedMs: Date.now() - start,\n state: full.value,\n imports,\n });\n if (unfinishedImports(imports) === 0) return ended(true);\n if (signal.aborted) return ended(false);\n options.onProgress?.(Date.now() - start, options.timeoutMs);\n await awaitChangeOrWake(computable, full.uTag, signal, lookStart);\n }\n });\n}\n"],"mappings":";;;;;AAcA,MAAM,YAAY;;AAGlB,MAAM,YAAY;;AAGlB,MAAM,qBAAqB;;;;;AA6C3B,SAAgB,iBAAiB,GAG/B;CACA,QAAA,GAAOA,wBAAAA,cAAAA,CAAc,CAAC,KAAK,OAAO,EAAE,SAAS,aAAa,OAAO,EAAE,aAAa;AAClF;AAEA,MAAM,mBAAmB;;AAGzB,SAAgB,eAAe,GAAmC;CAChE,OAAO,OAAO,MAAM,YAAY,iBAAiB,KAAK,CAAC;AACzD;;AAGA,SAAgB,iBAAiB,QAAoC;CACnE,IAAI,CAAC,eAAe,MAAM,GAAG,OAAO,KAAA;CACpC,IAAI;EACF,QAAA,GAAOC,gCAAAA,sBAAAA,CAAsB,MAAM;CACrC,QAAQ;EACN;CACF;AACF;AAEA,SAAS,QAAQ,GAAyC;CACxD,IAAI,EAAE,SAAS,MAAM,OAAO;CAC5B,IAAI,EAAE,aAAa,QAAQ,EAAE,sBAAsB,OAAO,OAAO;CACjE,IAAI,OAAO,EAAE,cAAc,YAAY,EAAE,cAAc,IAAI,OAAO;CAClE,MAAM,UAAA,GAASD,wBAAAA,cA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