@milaboratories/pl-mcp-server 53.1.0 → 55.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +30 -37
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +16 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +16 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +122 -0
  14. package/dist/project-holds.cjs.map +1 -0
  15. package/dist/project-holds.js +122 -0
  16. package/dist/project-holds.js.map +1 -0
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +48 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +48 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +71 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +37 -24
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +71 -19
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -72
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -74
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +14 -9
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +14 -9
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +275 -6
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +273 -8
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +343 -57
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +337 -61
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +199 -76
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +193 -76
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +470 -101
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +465 -106
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +72 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +63 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +111 -30
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +108 -31
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +68 -38
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +69 -40
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +16 -12
  143. package/src/project-holds.test.ts +362 -0
  144. package/src/project-holds.ts +207 -0
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +71 -6
  148. package/src/server-log.ts +58 -27
  149. package/src/server.logging.test.ts +46 -51
  150. package/src/server.test.ts +166 -22
  151. package/src/server.ts +97 -37
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -122
  156. package/src/tools/block-action-context.ts +17 -13
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +626 -10
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +678 -83
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +354 -113
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +839 -145
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +89 -1
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +154 -44
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +136 -48
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +84 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -0,0 +1,87 @@
1
+ import {
2
+ createColumnDiscoveredId,
3
+ createColumnFilteredId,
4
+ createColumnOverriddenId,
5
+ createColumnValueId,
6
+ createGlobalPObjectId,
7
+ createLocalPObjectId,
8
+ } from "@milaboratories/pl-model-common";
9
+ import { describe, expect, test } from "vitest";
10
+ import { columnIdFromAgent, columnIdInput, frameColumnIdInput } from "./ids";
11
+
12
+ const GLOBAL = createGlobalPObjectId("block1", "clones");
13
+ const LOCAL = createLocalPObjectId(["outputs", "frame"], "clones");
14
+ const DISCOVERED = createColumnDiscoveredId({
15
+ column: GLOBAL,
16
+ path: [{ type: "linker", column: createGlobalPObjectId("block2", "linker") }],
17
+ });
18
+ const FILTERED = createColumnFilteredId({ source: GLOBAL, axisFilters: [[0, "s1"]] });
19
+ const OVERRIDDEN = createColumnOverriddenId({
20
+ source: GLOBAL,
21
+ specOverrides: { annotations: { "pl7.app/label": "Clones" } },
22
+ });
23
+
24
+ describe("columnIdFromAgent", () => {
25
+ test("a canonical id is kept as it is", () => {
26
+ for (const id of [GLOBAL, LOCAL]) expect(columnIdFromAgent(id)).toBe(id);
27
+ });
28
+
29
+ test("other spacing or key order is canonicalised", () => {
30
+ expect(columnIdFromAgent('{ "name": "clones", "blockId": "block1", "__isRef": true }')).toBe(
31
+ GLOBAL,
32
+ );
33
+ expect(columnIdFromAgent(JSON.stringify(JSON.parse(LOCAL), null, 2))).toBe(LOCAL);
34
+ });
35
+
36
+ test("an id escaped once or twice is peeled", () => {
37
+ expect(columnIdFromAgent(JSON.stringify(GLOBAL))).toBe(GLOBAL);
38
+ expect(columnIdFromAgent(JSON.stringify(JSON.stringify(DISCOVERED)))).toBe(DISCOVERED);
39
+ });
40
+
41
+ test("a PlRef object, or one requiring enrichments, is its GlobalPObjectId", () => {
42
+ const ref = { __isRef: true, blockId: "block1", name: "clones" } as const;
43
+ expect(columnIdFromAgent(ref)).toBe(GLOBAL);
44
+ expect(columnIdFromAgent({ ...ref, requireEnrichments: true })).toBe(GLOBAL);
45
+ expect(columnIdFromAgent(JSON.stringify({ ...ref, requireEnrichments: true }))).toBe(GLOBAL);
46
+ });
47
+
48
+ test("discovered, filtered and overridden ids stay canonical", () => {
49
+ for (const id of [DISCOVERED, FILTERED, OVERRIDDEN]) expect(columnIdFromAgent(id)).toBe(id);
50
+ });
51
+
52
+ test("anchored ids, column value ids and free text are refused", () => {
53
+ const anchored = JSON.stringify({ name: "clones", domainAnchor: "main", axes: [] });
54
+ const value = createColumnValueId({ column: GLOBAL, value: "s1" });
55
+ for (const raw of [anchored, value, "clones", "", "{not json", 42, null])
56
+ expect(columnIdFromAgent(raw)).toBeUndefined();
57
+ });
58
+ });
59
+
60
+ describe("columnIdInput", () => {
61
+ test("gives the canonical id of a string or a PlRef object", () => {
62
+ expect(columnIdInput.parse(JSON.stringify(FILTERED))).toBe(FILTERED);
63
+ expect(columnIdInput.parse({ __isRef: true, blockId: "block1", name: "clones" })).toBe(GLOBAL);
64
+ });
65
+
66
+ test("refuses anything else, saying where ids come from without naming one tool", () => {
67
+ const r = columnIdInput.safeParse("clones");
68
+ expect(r.success).toBe(false);
69
+ expect(r.error?.issues[0].message).toBe(
70
+ "not a column id: copy `columnId` whole from the tool that listed the column",
71
+ );
72
+ });
73
+ });
74
+
75
+ describe("frameColumnIdInput", () => {
76
+ test("keeps a string as written and turns a PlRef object into its GlobalPObjectId", () => {
77
+ expect(frameColumnIdInput.parse("legacy-id")).toBe("legacy-id");
78
+ expect(
79
+ frameColumnIdInput.parse({
80
+ __isRef: true,
81
+ blockId: "block1",
82
+ name: "clones",
83
+ requireEnrichments: true,
84
+ }),
85
+ ).toBe(GLOBAL);
86
+ });
87
+ });
package/src/tools/ids.ts CHANGED
@@ -1,6 +1,51 @@
1
- import { asBlockId, asProjectId } from "@milaboratories/pl-model-common";
1
+ import {
2
+ asBlockId,
3
+ asProjectId,
4
+ createGlobalPObjectId,
5
+ isColumnUniversalKey,
6
+ isPlRef,
7
+ peelJsonLayers,
8
+ stringifyColumnId,
9
+ type ColumnUniversalId,
10
+ type PFrameHandle,
11
+ type PTableHandle,
12
+ } from "@milaboratories/pl-model-common";
13
+ import type { PluginHandle, PluginName } from "@platforma-sdk/model";
2
14
  import { z } from "zod";
3
15
 
16
+ /**
17
+ * A column id an agent handed back, as a `ColumnUniversalId`, or `undefined` when it is not one.
18
+ * A string may come escaped once or more (an id copied out of JSON): the escaping is peeled. The
19
+ * key is checked to be one of the five forms and serialized canonically at its top level; ids
20
+ * nested in it stay as written. A PlRef, as an object or as JSON, becomes its `GlobalPObjectId`,
21
+ * without `requireEnrichments`.
22
+ */
23
+ export function columnIdFromAgent(raw: unknown): ColumnUniversalId | undefined {
24
+ const key = typeof raw === "string" ? peelJsonLayers(raw)?.value : raw;
25
+ if (isPlRef(key)) return createGlobalPObjectId(key.blockId, key.name) as ColumnUniversalId;
26
+ return isColumnUniversalKey(key) ? stringifyColumnId(key) : undefined;
27
+ }
28
+
29
+ /** Brands a plugin handle: a key of a block's plugins, as get_block_state lists them. */
30
+ export function asPluginHandle(handle: string): PluginHandle {
31
+ return handle as PluginHandle;
32
+ }
33
+
34
+ /** Brands a plugin name (a plugin type) read from a block's plugin registry. */
35
+ export function asPluginName(name: string): PluginName {
36
+ return name as PluginName;
37
+ }
38
+
39
+ /** Brands a string handed back by an agent as a PFrame handle; the driver says whether it is one. */
40
+ export function asPFrameHandle(handle: string): PFrameHandle {
41
+ return handle as PFrameHandle;
42
+ }
43
+
44
+ /** Brands a string handed back by an agent as a PTable handle; the driver says whether it is one. */
45
+ export function asPTableHandle(handle: string): PTableHandle {
46
+ return handle as PTableHandle;
47
+ }
48
+
4
49
  /**
5
50
  * A project id argument of a tool. The agent sends a string; the tool receives a `ProjectId`.
6
51
  * Each tool adds its own description.
@@ -9,3 +54,46 @@ export const projectIdInput = z.string().transform(asProjectId);
9
54
 
10
55
  /** A block id argument of a tool. The agent sends a string; the tool receives a `BlockId`. */
11
56
  export const blockIdInput = z.string().transform(asBlockId);
57
+
58
+ /** A plugin handle argument of a tool. */
59
+ export const pluginHandleInput = z.string().transform(asPluginHandle);
60
+
61
+ /** A PFrame handle argument of a tool, as get_block_outputs gave it. */
62
+ export const pFrameHandleInput = z.string().transform(asPFrameHandle);
63
+
64
+ /** A PlRef object: the object form of a block output's `GlobalPObjectId`. */
65
+ export const plRefObject = z.object({
66
+ __isRef: z.literal(true),
67
+ blockId: z.string(),
68
+ name: z.string(),
69
+ requireEnrichments: z.literal(true).optional(),
70
+ });
71
+
72
+ /**
73
+ * A column id argument of a tool: any `ColumnUniversalId`, escaped or not, or a PlRef object.
74
+ * The tool receives it as {@link columnIdFromAgent} gives it; anything else is refused with a message.
75
+ */
76
+ export const columnIdInput = z.union([z.string(), plRefObject]).transform((raw, ctx) => {
77
+ const id = columnIdFromAgent(raw);
78
+ if (id !== undefined) return id;
79
+ ctx.addIssue({
80
+ code: "custom",
81
+ message: "not a column id: copy `columnId` whole from the tool that listed the column",
82
+ });
83
+ return z.NEVER;
84
+ });
85
+
86
+ /**
87
+ * The column id argument of a column of a block's PFrame, as list_columns gave it. A frame built
88
+ * by an older block API can list ids that are not `ColumnUniversalId`s, so the string stays as
89
+ * written and the tool finds it in the frame's listing; a PlRef object becomes its
90
+ * `GlobalPObjectId`.
91
+ */
92
+ export const frameColumnIdInput = z
93
+ .union([z.string(), plRefObject])
94
+ .transform((raw): string =>
95
+ typeof raw === "string" ? raw : createGlobalPObjectId(raw.blockId, raw.name),
96
+ );
97
+
98
+ /** A PTable handle argument of a tool, as get_block_outputs gave it. */
99
+ export const pTableHandleInput = z.string().transform(asPTableHandle);
@@ -0,0 +1,304 @@
1
+ import {
2
+ asBlockId,
3
+ type BlockId,
4
+ getFileNameFromHandle,
5
+ type ImportFileHandle,
6
+ } from "@milaboratories/pl-model-common";
7
+ import { isPlainObject } from "@milaboratories/helpers";
8
+ import { awaitChangeOrWake, withDeadline } from "./settle";
9
+ import { clip } from "./tokens";
10
+
11
+ /** The most unfinished or failed imports a block view lists one by one. */
12
+ export const MAX_IMPORT_ENTRIES = 20;
13
+
14
+ /** How deep into an output value import progress is looked for. */
15
+ const MAX_DEPTH = 8;
16
+
17
+ /** The most nodes of all outputs of one block walked when looking for import progress. */
18
+ const MAX_NODES = 20_000;
19
+
20
+ /** The most characters of an import's last error an entry carries. */
21
+ const IMPORT_ERROR_CHARS = 300;
22
+
23
+ /** Where one import stands. */
24
+ export type ImportState = "done" | "inProgress" | "notStarted" | "failed" | "foreign";
25
+
26
+ /** One import of a block, found in its outputs. */
27
+ export type ImportEntry = {
28
+ /** The output that carries the progress. */
29
+ output: string;
30
+ /** Where in the output's value: `(value)`, `["<key>"]`, `[2][1]`. */
31
+ path: string;
32
+ /** The file name, when the progress is keyed by its import handle. */
33
+ file?: string;
34
+ state: ImportState;
35
+ /** True for a file uploaded from this computer, false for a file indexed in a data library. */
36
+ isUpload: boolean;
37
+ /** From 0 to 1. */
38
+ progress?: number;
39
+ bytesProcessed?: number;
40
+ bytesTotal?: number;
41
+ lastError?: string;
42
+ };
43
+
44
+ /** The imports of a block in numbers, and those that are not done. */
45
+ export type ImportsSummary = {
46
+ total: number;
47
+ done: number;
48
+ inProgress: number;
49
+ notStarted: number;
50
+ /** Retrying after an error (`lastError`); an upload that fails for good fails its output. */
51
+ failed?: number;
52
+ /** Uploads that were started on another computer (signature mismatch): never finished here. */
53
+ foreign?: number;
54
+ bytesProcessed: number;
55
+ bytesTotal: number;
56
+ /** Not done, at most {@link MAX_IMPORT_ENTRIES}: failed first, then in progress, then not started. */
57
+ pending?: ImportEntry[];
58
+ /** How many more not-done imports there are past `pending`. */
59
+ morePending?: number;
60
+ };
61
+
62
+ /**
63
+ * Whether `v` is the import progress a block model returns from `getImportProgress()`: an object
64
+ * with boolean `done` and `isUpload` (`ImportProgress` of the SDK).
65
+ */
66
+ export function isImportProgress(v: unknown): v is Record<string, unknown> & {
67
+ done: boolean;
68
+ isUpload: boolean;
69
+ } {
70
+ return isPlainObject(v) && typeof v.done === "boolean" && typeof v.isUpload === "boolean";
71
+ }
72
+
73
+ const IMPORT_HANDLE_RE = /^(upload:\/\/upload\/|index:\/\/index\/)/;
74
+
75
+ /** Whether `v` is an import handle (`upload://…` or `index://…`). */
76
+ export function isImportHandle(v: unknown): v is ImportFileHandle {
77
+ return typeof v === "string" && IMPORT_HANDLE_RE.test(v);
78
+ }
79
+
80
+ /** The file name an import handle names; `undefined` when it does not parse. */
81
+ export function fileNameOfHandle(handle: string): string | undefined {
82
+ if (!isImportHandle(handle)) return undefined;
83
+ try {
84
+ return getFileNameFromHandle(handle);
85
+ } catch {
86
+ return undefined;
87
+ }
88
+ }
89
+
90
+ function stateOf(p: Record<string, unknown>): ImportState {
91
+ if (p.done === true) return "done";
92
+ if (p.isUpload === true && p.isUploadSignMatch === false) return "foreign";
93
+ if (typeof p.lastError === "string" && p.lastError !== "") return "failed";
94
+ const status = isPlainObject(p.status) ? p.status : undefined;
95
+ const progress = typeof status?.progress === "number" ? status.progress : 0;
96
+ const processed = typeof status?.bytesProcessed === "number" ? status.bytesProcessed : 0;
97
+ return progress > 0 || processed > 0 ? "inProgress" : "notStarted";
98
+ }
99
+
100
+ function keyPath(path: string, key: string): string {
101
+ return `${path}[${JSON.stringify(key)}]`;
102
+ }
103
+
104
+ /**
105
+ * Finds every import progress in a block's outputs (output key → `{ok, value}`), in output order,
106
+ * values depth-first. Recognized wherever a model puts it: as the output value, in a record keyed
107
+ * by import handle or any other key, in an array, or as the second item of `[handle, progress]`
108
+ * pairs. Failed outputs are skipped. The walk stops at {@link MAX_DEPTH} and {@link MAX_NODES}.
109
+ */
110
+ export function collectImports(outputs: Record<string, unknown> | undefined): ImportEntry[] {
111
+ if (outputs === undefined) return [];
112
+ const found: ImportEntry[] = [];
113
+ let nodes = 0;
114
+
115
+ const walk = (output: string, v: unknown, path: string, depth: number, file?: string) => {
116
+ if (++nodes > MAX_NODES || depth > MAX_DEPTH) return;
117
+ if (isImportProgress(v)) {
118
+ const status = isPlainObject(v.status) ? v.status : undefined;
119
+ const entry: ImportEntry = {
120
+ output,
121
+ path: path === "" ? "(value)" : path,
122
+ state: stateOf(v),
123
+ isUpload: v.isUpload,
124
+ };
125
+ if (file !== undefined) entry.file = file;
126
+ if (typeof status?.progress === "number") entry.progress = status.progress;
127
+ if (typeof status?.bytesProcessed === "number") entry.bytesProcessed = status.bytesProcessed;
128
+ if (typeof status?.bytesTotal === "number") entry.bytesTotal = status.bytesTotal;
129
+ if (typeof v.lastError === "string" && v.lastError !== "")
130
+ entry.lastError = clip(v.lastError, IMPORT_ERROR_CHARS);
131
+ found.push(entry);
132
+ return;
133
+ }
134
+ if (Array.isArray(v)) {
135
+ // `[handle, progress]`: the progress is named by the handle's file.
136
+ const pairFile = v.length === 2 && isImportHandle(v[0]) ? fileNameOfHandle(v[0]) : undefined;
137
+ v.forEach((item, i) => walk(output, item, `${path}[${i}]`, depth + 1, pairFile));
138
+ return;
139
+ }
140
+ if (isPlainObject(v)) {
141
+ for (const [key, item] of Object.entries(v))
142
+ walk(output, item, keyPath(path, key), depth + 1, fileNameOfHandle(key));
143
+ }
144
+ };
145
+
146
+ for (const [key, out] of Object.entries(outputs)) {
147
+ if (!isPlainObject(out) || out.ok !== true) continue;
148
+ walk(key, out.value, "", 0);
149
+ }
150
+ return found;
151
+ }
152
+
153
+ const PENDING_ORDER: Record<ImportState, number> = {
154
+ failed: 0,
155
+ inProgress: 1,
156
+ notStarted: 2,
157
+ foreign: 3,
158
+ done: 4,
159
+ };
160
+
161
+ /**
162
+ * Sums up a block's imports; `undefined` when it has none. Bytes are summed over the imports
163
+ * whose status gives them.
164
+ */
165
+ export function summarizeImports(entries: ImportEntry[]): ImportsSummary | undefined {
166
+ if (entries.length === 0) return undefined;
167
+ const count = (state: ImportState) => entries.filter((e) => e.state === state).length;
168
+ const failed = count("failed");
169
+ const foreign = count("foreign");
170
+ const notDone = entries
171
+ .filter((e) => e.state !== "done")
172
+ .toSorted((a, b) => PENDING_ORDER[a.state] - PENDING_ORDER[b.state]);
173
+ const summary: ImportsSummary = {
174
+ total: entries.length,
175
+ done: count("done"),
176
+ inProgress: count("inProgress"),
177
+ notStarted: count("notStarted"),
178
+ ...(failed > 0 ? { failed } : {}),
179
+ ...(foreign > 0 ? { foreign } : {}),
180
+ bytesProcessed: entries.reduce((s, e) => s + (e.bytesProcessed ?? 0), 0),
181
+ bytesTotal: entries.reduce((s, e) => s + (e.bytesTotal ?? 0), 0),
182
+ };
183
+ if (notDone.length > 0) summary.pending = notDone.slice(0, MAX_IMPORT_ENTRIES);
184
+ if (notDone.length > MAX_IMPORT_ENTRIES)
185
+ summary.morePending = notDone.length - MAX_IMPORT_ENTRIES;
186
+ return summary;
187
+ }
188
+
189
+ /** The imports summary of a block's outputs; `undefined` when they carry no import progress. */
190
+ export function importsOf(
191
+ outputs: Record<string, unknown> | undefined,
192
+ ): ImportsSummary | undefined {
193
+ return summarizeImports(collectImports(outputs));
194
+ }
195
+
196
+ /**
197
+ * How many imports are still to finish here: not done and not foreign (a foreign upload is for
198
+ * another computer to send).
199
+ */
200
+ export function unfinishedImports(summary: ImportsSummary | undefined): number {
201
+ if (summary === undefined) return 0;
202
+ return summary.total - summary.done - (summary.foreign ?? 0);
203
+ }
204
+
205
+ /** What {@link pendingUploadsOfProject} reads of a project; a middle-layer `Project` has it. */
206
+ export type ImportsProject = {
207
+ overview: { getValue(): Promise<{ blocks: { id: string }[] } | undefined> };
208
+ getBlockState(blockId: BlockId): { getValue(): Promise<{ outputs?: unknown }> };
209
+ };
210
+
211
+ /**
212
+ * The uploads among `entries` that are still to go: files of this computer whose upload is in
213
+ * progress or not started. Not counted: done ones, foreign ones (another computer sends them),
214
+ * failed ones (retrying after an error; they may never succeed) and files of a data library
215
+ * (indexed where they are; the project need not stay loaded for them).
216
+ */
217
+ export function uploadsToFinish(entries: readonly ImportEntry[]): ImportEntry[] {
218
+ return entries.filter(
219
+ (e) => e.isUpload && (e.state === "inProgress" || e.state === "notStarted"),
220
+ );
221
+ }
222
+
223
+ /** The uploads of a project still to go ({@link uploadsToFinish}), and how far they got. */
224
+ export type PendingUploads = {
225
+ count: number;
226
+ /** Bytes uploaded so far, summed over every upload of the project, done ones included. */
227
+ bytesProcessed: number;
228
+ };
229
+
230
+ /**
231
+ * The uploads still to go of every block of a project (Q-002): a block's pre-run starts uploads
232
+ * as well as its run, so no block is skipped. Reading a block's outputs computes them, so this is
233
+ * meant for the moment a kept hold's idle time is over, not for every call; a block whose state
234
+ * cannot be read counts as having none.
235
+ */
236
+ export async function pendingUploadsOfProject(project: ImportsProject): Promise<PendingUploads> {
237
+ const overview = await project.overview.getValue();
238
+ const pending: PendingUploads = { count: 0, bytesProcessed: 0 };
239
+ for (const block of overview?.blocks ?? []) {
240
+ try {
241
+ const state = await project.getBlockState(asBlockId(block.id)).getValue();
242
+ const uploads = collectImports(
243
+ isPlainObject(state.outputs) ? state.outputs : undefined,
244
+ ).filter((e) => e.isUpload);
245
+ pending.count += uploadsToFinish(uploads).length;
246
+ pending.bytesProcessed += uploads.reduce((sum, e) => sum + (e.bytesProcessed ?? 0), 0);
247
+ } catch {
248
+ // a block removed meanwhile, or outputs that fail as a whole: nothing to wait for here
249
+ }
250
+ }
251
+ return pending;
252
+ }
253
+
254
+ /** The block state computable as {@link awaitImportsDone} uses it; a middle-layer `Computable`. */
255
+ export type ImportsStateComputable<S extends { outputs?: Record<string, unknown> | undefined }> = {
256
+ getFullValue(): Promise<{ value: S; uTag: string }>;
257
+ awaitChange(abortSignal?: AbortSignal, uTag?: string): Promise<void>;
258
+ };
259
+
260
+ /** How {@link awaitImportsDone} ended. */
261
+ export type ImportsWait<S> = {
262
+ /** No import of the block is left to finish here. */
263
+ done: boolean;
264
+ /** The request was cancelled (otherwise an unfinished wait ran out of time). */
265
+ aborted: boolean;
266
+ waitedMs: number;
267
+ state: S;
268
+ imports: ImportsSummary | undefined;
269
+ };
270
+
271
+ /**
272
+ * Waits until no import of a block is left to finish here ({@link unfinishedImports} is 0), or
273
+ * `timeoutMs` runs out, or `signal` fires. Every change of the block state is a look (the state
274
+ * changes as the upload progress does), and so is every 5 s without one ({@link awaitChangeOrWake}),
275
+ * for the progress notifications.
276
+ */
277
+ export async function awaitImportsDone<S extends { outputs?: Record<string, unknown> | undefined }>(
278
+ computable: ImportsStateComputable<S>,
279
+ options: {
280
+ timeoutMs: number;
281
+ signal?: AbortSignal;
282
+ onProgress?: (elapsedMs: number, timeoutMs: number) => void;
283
+ },
284
+ ): Promise<ImportsWait<S>> {
285
+ const start = Date.now();
286
+ return await withDeadline(options.timeoutMs, options.signal, async (signal) => {
287
+ for (;;) {
288
+ const lookStart = Date.now();
289
+ const full = await computable.getFullValue();
290
+ const imports = importsOf(full.value.outputs);
291
+ const ended = (done: boolean): ImportsWait<S> => ({
292
+ done,
293
+ aborted: options.signal?.aborted ?? false,
294
+ waitedMs: Date.now() - start,
295
+ state: full.value,
296
+ imports,
297
+ });
298
+ if (unfinishedImports(imports) === 0) return ended(true);
299
+ if (signal.aborted) return ended(false);
300
+ options.onProgress?.(Date.now() - start, options.timeoutMs);
301
+ await awaitChangeOrWake(computable, full.uTag, signal, lookStart);
302
+ }
303
+ });
304
+ }
@@ -0,0 +1,70 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { collectLogHandles, cutNote, logKey, MAX_NODES } from "./logs";
3
+
4
+ const READY = (name: string) => `log+ready://log/${name}`;
5
+ const LIVE = (name: string) => `log+live://log/${name}`;
6
+
7
+ describe("collectLogHandles", () => {
8
+ test("finds logs per sample, a log as the value, and logs at any depth", () => {
9
+ const { entries } = collectLogHandles({
10
+ perSample: {
11
+ ok: true,
12
+ value: {
13
+ data: [
14
+ { key: ["s1"], value: READY("a") },
15
+ { key: ["s2", 1], value: LIVE("b") },
16
+ ],
17
+ },
18
+ },
19
+ single: { ok: true, value: READY("c") },
20
+ nested: { ok: true, value: { runs: [{ log: LIVE("d") }] } },
21
+ });
22
+ expect(entries.map((e) => [logKey(e), e.handle])).toEqual([
23
+ ["perSample/s1", READY("a")],
24
+ ["perSample/s2/1", LIVE("b")],
25
+ ["single", READY("c")],
26
+ ["nested/runs/0/log", LIVE("d")],
27
+ ]);
28
+ });
29
+
30
+ test("logs of one sample in two outputs keep apart", () => {
31
+ const { entries } = collectLogHandles({
32
+ align: { ok: true, value: { data: [{ key: ["s1"], value: READY("a") }] } },
33
+ assemble: { ok: true, value: { data: [{ key: ["s1"], value: READY("b") }] } },
34
+ });
35
+ expect(entries.map(logKey)).toEqual(["align/s1", "assemble/s1"]);
36
+ });
37
+
38
+ test("passes over failed outputs, data that is not an array and entries that are null", () => {
39
+ const { entries } = collectLogHandles({
40
+ failed: { ok: false, errors: ["boom"] },
41
+ notArray: { ok: true, value: { data: "text" } },
42
+ nullEntries: { ok: true, value: { data: [null, 7, { key: "s1", value: READY("x") }] } },
43
+ empty: { ok: true, value: null },
44
+ nothing: null,
45
+ });
46
+ // An entry whose key is not an array is still read, by its place.
47
+ expect(entries.map(logKey)).toEqual(["nullEntries/data/2/value"]);
48
+ });
49
+
50
+ test("each output has its own budget; numbers are not counted", () => {
51
+ const { entries, cutOutputs } = collectLogHandles({
52
+ counts: { ok: true, value: Array.from({ length: MAX_NODES }, (_, i) => i) },
53
+ log: { ok: true, value: { data: [{ key: ["s1"], value: READY("a") }] } },
54
+ });
55
+ expect(entries.map(logKey)).toEqual(["log/s1"]);
56
+ expect(cutOutputs).toEqual([]);
57
+ });
58
+
59
+ test("an output whose walk stops at the limit is named", () => {
60
+ const { entries, cutOutputs } = collectLogHandles({
61
+ rows: { ok: true, value: Array.from({ length: MAX_NODES }, () => ({ n: 1 })) },
62
+ log: { ok: true, value: READY("a") },
63
+ });
64
+ expect(entries.map(logKey)).toEqual(["log"]);
65
+ expect(cutOutputs).toEqual(["rows"]);
66
+ expect(cutNote(cutOutputs)).toBe(
67
+ "Output rows is too large or too deep to search whole: some of its logs may be missed.",
68
+ );
69
+ });
70
+ });