@milaboratories/pl-mcp-server 54.0.0 → 55.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +15 -25
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -123
  156. package/src/tools/block-action-context.ts +3 -0
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +135 -25
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +77 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1,8 +1,61 @@
1
+ import type { ProjectHolder, ProjectId } from "@milaboratories/pl-middle-layer";
1
2
  import { isProjectInUseError } from "@milaboratories/pl-middle-layer";
2
3
  import { z } from "zod";
3
4
  import { projectIdInput } from "./ids";
4
5
  import type { ToolContext, ToolRegistrar } from "./types";
5
6
  import { errorResult, hints, textResult } from "./types";
7
+ import { page, pagingArgs } from "./paging";
8
+ import {
9
+ exportProjectTemplate,
10
+ TEMPLATE_HANDLES_DEFAULT,
11
+ TEMPLATE_HANDLES_MAX,
12
+ } from "./project-template";
13
+
14
+ /** How many projects list_projects returns when the caller does not say. */
15
+ export const LIST_PROJECTS_DEFAULT_LIMIT = 100;
16
+ /** The most projects one list_projects call returns. */
17
+ export const LIST_PROJECTS_MAX_LIMIT = 500;
18
+
19
+ /** What {@link deleteProject} needs: the middle layer's delete and this server's holds. */
20
+ export type DeleteProjectDeps = {
21
+ resolveProject: (projectId: ProjectId) => Promise<{ id: ProjectId }>;
22
+ deleteProject: (
23
+ id: ProjectId,
24
+ ops: { refuseIfHeldBy: (holder: ProjectHolder) => boolean },
25
+ ) => Promise<void>;
26
+ /** The holder of this server's holds. */
27
+ projectHolder: ProjectHolder;
28
+ /** How many calls of this server are in flight on the project (the delete is not one). */
29
+ callsInFlight: (id: ProjectId) => number;
30
+ onDeleted?: (projectId: ProjectId) => void | Promise<void>;
31
+ };
32
+
33
+ /**
34
+ * Deletes a project, unless it is in use: by a holder that is not this server (an agent of
35
+ * another server, the user in the application), or by another call of this server still running
36
+ * on it (an agent of this server). This server's kept hold does not count: it ends with the
37
+ * delete. The check of this server's calls is made inside the middle layer's check, where no
38
+ * acquire comes in between, and once before it for a call that has not got its hold yet.
39
+ */
40
+ export async function deleteProject(deps: DeleteProjectDeps, projectId: ProjectId) {
41
+ const entry = await deps.resolveProject(projectId);
42
+ const inUse = () =>
43
+ errorResult(
44
+ `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +
45
+ "user in the application.",
46
+ );
47
+ if (deps.callsInFlight(entry.id) > 0) return inUse();
48
+ try {
49
+ await deps.deleteProject(entry.id, {
50
+ refuseIfHeldBy: (holder) => holder !== deps.projectHolder || deps.callsInFlight(entry.id) > 0,
51
+ });
52
+ } catch (e: unknown) {
53
+ if (!isProjectInUseError(e)) throw e;
54
+ return inUse();
55
+ }
56
+ await deps.onDeleted?.(projectId);
57
+ return textResult({ ok: true });
58
+ }
6
59
 
7
60
  export function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {
8
61
  server.registerTool(
@@ -10,19 +63,43 @@ export function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): v
10
63
  {
11
64
  title: "List Projects",
12
65
  annotations: hints.read,
13
- description: "List all projects with their IDs, labels, and creation and modification times",
66
+ description:
67
+ "List projects with their IDs, labels, and creation and modification times, " +
68
+ `${LIST_PROJECTS_DEFAULT_LIMIT} at a time. Result: \`{ projects, total, offset, hasMore }\`; ` +
69
+ "page with `offset` and `limit`, or narrow with `nameContains`.",
70
+ inputSchema: z.object({
71
+ ...pagingArgs("projects", LIST_PROJECTS_DEFAULT_LIMIT, LIST_PROJECTS_MAX_LIMIT),
72
+ nameContains: z
73
+ .string()
74
+ .optional()
75
+ .describe("Only projects whose label contains this text (case-insensitive)."),
76
+ }),
14
77
  },
15
- async () => {
78
+ async ({ limit, offset, nameContains }) => {
16
79
  const ml = ctx.requireMl();
17
80
  await ml.projectList.refreshState();
18
81
  const projects = await ml.projectList.awaitStableValue();
82
+ const needle = nameContains?.toLowerCase();
83
+ const matching =
84
+ needle === undefined
85
+ ? projects
86
+ : projects.filter((p) => p.meta.label.toLowerCase().includes(needle));
87
+ const { items, ...paging } = page(matching, offset, limit ?? LIST_PROJECTS_DEFAULT_LIMIT);
19
88
  return textResult(
20
- projects.map((p) => ({
21
- projectId: p.id,
22
- label: p.meta.label,
23
- created: p.created.toISOString(),
24
- lastModified: p.lastModified.toISOString(),
25
- })),
89
+ {
90
+ projects: items.map((p) => ({
91
+ projectId: p.id,
92
+ label: p.meta.label,
93
+ created: p.created.toISOString(),
94
+ lastModified: p.lastModified.toISOString(),
95
+ })),
96
+ ...paging,
97
+ },
98
+ {
99
+ hint:
100
+ "Ask for fewer projects: a smaller `limit` with `offset` to page, or `nameContains` " +
101
+ "to narrow by label.",
102
+ },
26
103
  );
27
104
  },
28
105
  );
@@ -49,26 +126,59 @@ export function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): v
49
126
  annotations: hints.destructive,
50
127
  description:
51
128
  "Delete a project permanently, with all its blocks and results. Refused while the project " +
52
- "is in use by another agent or by the user in the application.",
129
+ "is in use by another agent (another call working on it, through this server or " +
130
+ "another) or by the user in the application.",
53
131
  inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") }),
54
132
  },
55
133
  async ({ projectId }) => {
56
- const entry = await ctx.resolveProject(projectId);
57
- try {
58
- // This server's own holds, kept or of calls still running, end with the delete: a deleted
59
- // project is not snapshotted. Anyone else's hold refuses it.
60
- await ctx.requireMl().deleteProject(entry.id, {
61
- refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,
62
- });
63
- } catch (e: unknown) {
64
- if (!isProjectInUseError(e)) throw e;
65
- return errorResult(
66
- `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +
67
- "user in the application.",
68
- );
69
- }
70
- await ctx.callbacks.onProjectDeleted?.(projectId);
71
- return textResult({ ok: true });
134
+ const ml = ctx.requireMl();
135
+ return await deleteProject(
136
+ {
137
+ resolveProject: (id) => ctx.resolveProject(id),
138
+ deleteProject: (id, ops) => ml.deleteProject(id, ops),
139
+ projectHolder: ctx.projectHolder,
140
+ callsInFlight: (id) => ctx.callsInFlight(id),
141
+ onDeleted: ctx.callbacks.onProjectDeleted,
142
+ },
143
+ projectId,
144
+ );
145
+ },
146
+ );
147
+
148
+ server.registerTool(
149
+ "export_project_template",
150
+ {
151
+ title: "Export Project Template",
152
+ annotations: hints.additive,
153
+ description:
154
+ "Export a project as a template file, to hand it over or reproduce it elsewhere: writes " +
155
+ "the `template-v1` YAML the application's Export Project as Template… writes, unchanged, " +
156
+ "to `savePath`, a new file (an existing one is never overwritten), so the application's " +
157
+ "import reads it. All or nothing: when any block cannot be written, nothing is written " +
158
+ "and the error names every such block (id, label, reason). read_file reads the file.\n\n" +
159
+ "Returns `{ path, bytes, fileHandlesTotal, offset, hasMore, fileHandles }`: a page of the " +
160
+ "file handles the params hold, each with `blockId`, `paramsPath`, `handle`, and the file " +
161
+ "it names (`localPath`, or `storage` and `storagePath`). Page on without `savePath`. " +
162
+ "Handles work only on the desktop that made them; on another, replace each with a handle " +
163
+ "of the file there (get_file_handles).",
164
+ inputSchema: z.object({
165
+ projectId: projectIdInput.describe("Project ID"),
166
+ savePath: z
167
+ .string()
168
+ .optional()
169
+ .describe("Absolute path of the new file to write. Omit to list the file handles only."),
170
+ ...pagingArgs("file handles", TEMPLATE_HANDLES_DEFAULT, TEMPLATE_HANDLES_MAX),
171
+ }),
172
+ },
173
+ async (input) => {
174
+ const ml = ctx.requireMl();
175
+ return await exportProjectTemplate(
176
+ {
177
+ resolveProject: (id) => ctx.resolveProject(id),
178
+ exportProjectAsTemplate: (id) => ml.exportProjectAsTemplate(id),
179
+ },
180
+ input,
181
+ );
72
182
  },
73
183
  );
74
184
  }
@@ -0,0 +1,195 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { BlockReadiness } from "@milaboratories/pl-middle-layer";
3
+ import { asBlockId, asProjectId } from "@milaboratories/pl-model-common";
4
+ import type { ReadinessOverviewBlock } from "./readiness";
5
+ import { buildReadiness, findBlock } from "./readiness";
6
+ import { dedupeHandleSummaries } from "./data-query";
7
+
8
+ function overviewBlock(
9
+ overrides: Partial<ReadinessOverviewBlock> & { id: string },
10
+ ): ReadinessOverviewBlock {
11
+ return {
12
+ calculationStatus: "NotCalculated",
13
+ stale: true,
14
+ canRun: true,
15
+ outputErrors: false,
16
+ missingReference: false,
17
+ upstreams: [],
18
+ title: overrides.id.toUpperCase(),
19
+ ...overrides,
20
+ };
21
+ }
22
+
23
+ function model(overrides: Partial<BlockReadiness> = {}): BlockReadiness {
24
+ return {
25
+ args: { type: "runnable", issues: [] },
26
+ prerun: { type: "staged", issues: [] },
27
+ missingReferences: [],
28
+ ...overrides,
29
+ };
30
+ }
31
+
32
+ describe("buildReadiness", () => {
33
+ test("a block that can run has no blockers and a staged pre-run", () => {
34
+ const b = overviewBlock({ id: "b" });
35
+ expect(buildReadiness(b, [b], model())).toEqual({
36
+ status: "ready",
37
+ blockers: [],
38
+ warnings: [],
39
+ prerun: "staged",
40
+ });
41
+ });
42
+
43
+ test("args the model refuses are blockers in the model's words; warnings are kept apart", () => {
44
+ const b = overviewBlock({ id: "b", canRun: false });
45
+ const absent = buildReadiness(
46
+ b,
47
+ [b],
48
+ model({ args: { type: "absent", error: "args() threw: Numbers are required!" } }),
49
+ );
50
+ expect(absent.status).toBe("blocked");
51
+ expect(absent.blockers).toEqual([
52
+ { kind: "args", message: "args() threw: Numbers are required!" },
53
+ ]);
54
+
55
+ const blocked = buildReadiness(
56
+ b,
57
+ [b],
58
+ model({
59
+ args: {
60
+ type: "blocked",
61
+ issues: [
62
+ { severity: "warning", message: "Only two samples" },
63
+ { severity: "error", message: "Set a threshold" },
64
+ ],
65
+ },
66
+ prerun: {
67
+ type: "blocked",
68
+ error: "argsIssues() found errors (fallback): Set a threshold",
69
+ issues: [{ severity: "warning", message: "Only two samples" }],
70
+ },
71
+ }),
72
+ );
73
+ expect(blocked).toEqual({
74
+ status: "blocked",
75
+ blockers: [{ kind: "args", message: "Set a threshold" }],
76
+ warnings: ["Only two samples"],
77
+ prerun: "blocked",
78
+ prerunReason: "argsIssues() found errors (fallback): Set a threshold",
79
+ });
80
+ });
81
+
82
+ test("missing references and blocked upstreams are blockers naming the block", () => {
83
+ const up = overviewBlock({ id: "up", canRun: false });
84
+ const below = overviewBlock({ id: "below" });
85
+ const b = overviewBlock({ id: "b", canRun: false, upstreams: ["up"] });
86
+ const readiness = buildReadiness(
87
+ b,
88
+ [up, b, below],
89
+ model({
90
+ missingReferences: [
91
+ { blockId: asBlockId("gone"), reason: "unknown-block" },
92
+ { blockId: asBlockId("below"), reason: "not-above" },
93
+ ],
94
+ }),
95
+ );
96
+ expect(readiness.blockers).toEqual([
97
+ {
98
+ kind: "missing-reference",
99
+ blockId: "gone",
100
+ message: "The data refers to block gone, which is not in the project.",
101
+ },
102
+ {
103
+ kind: "missing-reference",
104
+ blockId: "below",
105
+ message: 'The data refers to block "BELOW" (below), which is not above this block.',
106
+ },
107
+ {
108
+ kind: "upstream",
109
+ blockId: "up",
110
+ message: 'Block "UP" (up) above cannot run; get_block_state on it says why.',
111
+ },
112
+ ]);
113
+ });
114
+
115
+ test("a pre-run that does not run on the data says why", () => {
116
+ const b = overviewBlock({ id: "b" });
117
+ expect(
118
+ buildReadiness(b, [b], model({ prerun: { type: "failed", error: "prerunArgs() threw: x" } })),
119
+ ).toMatchObject({ prerun: "failed", prerunReason: "prerunArgs() threw: x" });
120
+ expect(
121
+ buildReadiness(b, [b], model({ prerun: { type: "skipped", issues: [] } })),
122
+ ).toMatchObject({ prerun: "skipped", prerunReason: expect.any(String) });
123
+ });
124
+
125
+ test("without model readiness there is no pre-run and the stored facts stay", () => {
126
+ const b = overviewBlock({ id: "b", canRun: false, missingReference: true });
127
+ const readiness = buildReadiness(b, [b], undefined);
128
+ expect(readiness.prerun).toBeUndefined();
129
+ expect(readiness.blockers).toEqual([
130
+ { kind: "missing-reference", message: expect.any(String) },
131
+ ]);
132
+ });
133
+
134
+ test("status follows the stored fields", () => {
135
+ const status = (o: Partial<ReadinessOverviewBlock>) =>
136
+ buildReadiness(overviewBlock({ id: "b", ...o }), [], model()).status;
137
+ expect(status({ calculationStatus: "Running" })).toBe("running");
138
+ expect(status({ calculationStatus: "Limbo" })).toBe("limbo");
139
+ expect(status({ calculationStatus: "Done", stale: false })).toBe("up-to-date");
140
+ expect(status({ calculationStatus: "Done", stale: false, outputErrors: true })).toBe("failed");
141
+ expect(status({ calculationStatus: "Done", stale: true, outputErrors: true })).toBe("ready");
142
+ });
143
+ });
144
+
145
+ describe("findBlock", () => {
146
+ const project = { overview: { getValue: async () => ({ blocks: [{ id: "b", x: 1 }] }) } };
147
+
148
+ test("finds a block of the project", async () => {
149
+ expect(await findBlock(project, asProjectId("p"), asBlockId("b"))).toEqual({
150
+ block: { id: "b", x: 1 },
151
+ });
152
+ });
153
+
154
+ test("an unknown block is an error result naming it and pointing to the overview", async () => {
155
+ const { error } = await findBlock(project, asProjectId("p"), asBlockId("zz"));
156
+ expect(error?.isError).toBe(true);
157
+ expect(error?.content[0].text).toContain("Block zz is not in project p.");
158
+ expect(error?.content[0].text).toContain("get_project_overview");
159
+ });
160
+ });
161
+
162
+ describe("dedupeHandleSummaries", () => {
163
+ const table = (handle: string) => ({ _type: "PTable", handle, columns: [{ index: 0 }] });
164
+
165
+ test("a repeated handle is given by the path to its first summary", () => {
166
+ expect(
167
+ dedupeHandleSummaries({
168
+ main: { table: table("h1") },
169
+ alsoMain: table("h1"),
170
+ list: [table("h2"), table("h1"), table("h2")],
171
+ plain: "h1",
172
+ }),
173
+ ).toEqual({
174
+ main: { table: table("h1") },
175
+ alsoMain: { sameAs: "main.table" },
176
+ list: [table("h2"), { sameAs: "main.table" }, { sameAs: "list[0]" }],
177
+ plain: "h1",
178
+ });
179
+ });
180
+
181
+ test("two tables of one output, each repeated, stay told apart", () => {
182
+ expect(
183
+ dedupeHandleSummaries({
184
+ "the tables": { counts: table("h1"), "per sample": [table("h2")] },
185
+ again: [table("h2"), { nested: table("h1") }],
186
+ }),
187
+ ).toEqual({
188
+ "the tables": { counts: table("h1"), "per sample": [table("h2")] },
189
+ again: [
190
+ { sameAs: '["the tables"]["per sample"][0]' },
191
+ { nested: { sameAs: '["the tables"].counts' } },
192
+ ],
193
+ });
194
+ });
195
+ });
@@ -0,0 +1,189 @@
1
+ import { asBlockId, type BlockId, type ProjectId } from "@milaboratories/pl-model-common";
2
+ import type { BlockReadiness, BlockStateOverview } from "@milaboratories/pl-middle-layer";
3
+ import { errorResult } from "./types";
4
+
5
+ /**
6
+ * Where a block stands, from the stored fields of its overview entry only (nothing is run):
7
+ * `running`, `limbo` (its results are from before an upstream changed: an upstream failed, was
8
+ * stopped or ran again), `failed` (the last run, of the current configuration, ended with errors
9
+ * in its outputs), `up-to-date` (results match the configuration), `ready` (can run now),
10
+ * `blocked` (cannot run: its inputs or an upstream are not valid, or a reference is missing).
11
+ * A stale block whose outputs failed is `ready` or `blocked`: the failure is of an older
12
+ * configuration.
13
+ */
14
+ export type BlockStatus = "running" | "limbo" | "failed" | "up-to-date" | "ready" | "blocked";
15
+
16
+ export function blockStatus(
17
+ b: Pick<BlockStateOverview, "calculationStatus" | "stale" | "canRun" | "outputErrors">,
18
+ ): BlockStatus {
19
+ if (b.calculationStatus === "Running") return "running";
20
+ if (b.calculationStatus === "Limbo") return "limbo";
21
+ if (b.calculationStatus === "Done" && !b.stale) return b.outputErrors ? "failed" : "up-to-date";
22
+ return b.canRun ? "ready" : "blocked";
23
+ }
24
+
25
+ /** What a block's results are when its data, or the data of a block above, changed after its run. */
26
+ export const STALE_RESULTS_NOTE =
27
+ "The results are from an earlier configuration: the block's data, or the data of a block " +
28
+ "above, changed after its last run. run_block runs it again.";
29
+
30
+ /**
31
+ * `{ stale: true, note }` for a block whose run is over but whose results no longer follow its
32
+ * data ({@link STALE_RESULTS_NOTE}); nothing for any other block.
33
+ */
34
+ export function staleResults(
35
+ b: Pick<BlockStateOverview, "calculationStatus" | "stale">,
36
+ ): { stale: true; note: string } | Record<string, never> {
37
+ return b.calculationStatus === "Done" && b.stale ? { stale: true, note: STALE_RESULTS_NOTE } : {};
38
+ }
39
+
40
+ /** One thing that keeps a block from running. */
41
+ export type ReadinessBlocker = {
42
+ /**
43
+ * `args`: the block's own model refuses its data (the message is the model's);
44
+ * `missing-reference`: the data refers to a block that is not in the project or not above;
45
+ * `upstream`: a block above cannot run.
46
+ */
47
+ kind: "args" | "missing-reference" | "upstream";
48
+ message: string;
49
+ /** The block a `missing-reference` or `upstream` blocker is about. */
50
+ blockId?: BlockId;
51
+ };
52
+
53
+ /**
54
+ * Whether a block can run, and why not, as per-block tools return it. The messages come from the
55
+ * block's own model (its `args()`, `argsIssues()`, `prerunArgs()` and `prerunArgsIssues()`) and
56
+ * from stored facts of the project (references, the state of the blocks above); the server adds
57
+ * no judgement of its own about the data.
58
+ */
59
+ export type Readiness = {
60
+ status: BlockStatus;
61
+ blockers: ReadinessBlocker[];
62
+ /** Warnings the block's model found in its data; they do not keep it from running. */
63
+ warnings: string[];
64
+ /**
65
+ * Whether the block's pre-run (the part of the workflow that runs on every change of the data,
66
+ * before run_block) runs on the current data: `staged`; `skipped` (the model gives no pre-run
67
+ * args), `blocked` (the model found errors) or `failed` (the model threw) mean the pre-run
68
+ * outputs still show an earlier configuration. Absent when the block has no model readiness.
69
+ */
70
+ prerun?: "staged" | "skipped" | "blocked" | "failed";
71
+ /** Why the pre-run does not run on the current data, in the model's words where it has them. */
72
+ prerunReason?: string;
73
+ };
74
+
75
+ /** What {@link buildReadiness} reads of a block of the project overview. */
76
+ export type ReadinessOverviewBlock = Pick<
77
+ BlockStateOverview,
78
+ | "id"
79
+ | "calculationStatus"
80
+ | "stale"
81
+ | "canRun"
82
+ | "outputErrors"
83
+ | "missingReference"
84
+ | "upstreams"
85
+ > & { title?: string; label?: string };
86
+
87
+ /**
88
+ * Builds the readiness of `block` from its overview entry, the overview entries of the blocks
89
+ * above, and what its model makes of its current data (`model`, from the middle layer's
90
+ * `getBlockReadiness`; `undefined` while it has none).
91
+ */
92
+ export function buildReadiness(
93
+ block: ReadinessOverviewBlock,
94
+ blocks: readonly ReadinessOverviewBlock[],
95
+ model: BlockReadiness | undefined,
96
+ ): Readiness {
97
+ const byId = new Map(blocks.map((b) => [b.id, b]));
98
+ const name = (id: string) => {
99
+ const b = byId.get(id);
100
+ const title = b?.title ?? b?.label;
101
+ return title === undefined ? id : `"${title}" (${id})`;
102
+ };
103
+
104
+ const blockers: ReadinessBlocker[] = [];
105
+ const warnings: string[] = [];
106
+ const warn = (message: string) => {
107
+ if (!warnings.includes(message)) warnings.push(message);
108
+ };
109
+
110
+ if (model !== undefined) {
111
+ if (model.args.type === "absent") blockers.push({ kind: "args", message: model.args.error });
112
+ else
113
+ for (const issue of model.args.issues)
114
+ if (issue.severity === "error") blockers.push({ kind: "args", message: issue.message });
115
+ else warn(issue.message);
116
+
117
+ for (const ref of model.missingReferences)
118
+ blockers.push({
119
+ kind: "missing-reference",
120
+ blockId: ref.blockId,
121
+ message:
122
+ ref.reason === "unknown-block"
123
+ ? `The data refers to block ${ref.blockId}, which is not in the project.`
124
+ : `The data refers to block ${name(ref.blockId)}, which is not above this block.`,
125
+ });
126
+ } else if (block.missingReference) {
127
+ blockers.push({
128
+ kind: "missing-reference",
129
+ message: "The data refers to a block that is not in the project or not above this block.",
130
+ });
131
+ }
132
+
133
+ for (const id of block.upstreams) {
134
+ const upstream = byId.get(id);
135
+ if (upstream !== undefined && blockStatus(upstream) === "blocked")
136
+ blockers.push({
137
+ kind: "upstream",
138
+ blockId: asBlockId(id),
139
+ message: `Block ${name(id)} above cannot run; get_block_state on it says why.`,
140
+ });
141
+ }
142
+
143
+ const readiness: Readiness = { status: blockStatus(block), blockers, warnings };
144
+ if (model !== undefined) {
145
+ const { prerun } = model;
146
+ readiness.prerun = prerun.type;
147
+ if (prerun.type === "blocked" || prerun.type === "failed")
148
+ readiness.prerunReason = prerun.error;
149
+ else if (prerun.type === "skipped")
150
+ readiness.prerunReason = "The block's model gives no pre-run args for this data.";
151
+ if (prerun.type !== "failed")
152
+ for (const issue of prerun.issues) if (issue.severity !== "error") warn(issue.message);
153
+ }
154
+ return readiness;
155
+ }
156
+
157
+ /** The error of a tool given a block id the project does not have. */
158
+ export function unknownBlockResult(projectId: ProjectId, blockId: BlockId, nothingChanged = false) {
159
+ return errorResult(
160
+ `Block ${blockId} is not in project ${projectId}.${nothingChanged ? " Nothing was changed." : ""}`,
161
+ "Use get_project_overview to list the block ids of the project.",
162
+ );
163
+ }
164
+
165
+ /** What {@link findBlock} needs of a project. */
166
+ export type BlockLookupProject<B extends { id: string }> = {
167
+ overview: { getValue(): Promise<{ blocks: B[] } | undefined> };
168
+ };
169
+
170
+ /**
171
+ * Finds a block in the project overview. A block the project does not have, or a project whose
172
+ * overview is not ready, comes back as the error result to return.
173
+ */
174
+ export async function findBlock<B extends { id: string }>(
175
+ project: BlockLookupProject<B>,
176
+ projectId: ProjectId,
177
+ blockId: BlockId,
178
+ options: { nothingChanged?: boolean } = {},
179
+ ): Promise<{ block: B; error?: undefined } | { block?: undefined; error: ToolErrorResult }> {
180
+ const overview = await project.overview.getValue();
181
+ if (overview === undefined)
182
+ return { error: errorResult("Project overview not available yet. Try again.") };
183
+ const block = overview.blocks.find((b) => b.id === blockId);
184
+ if (block === undefined)
185
+ return { error: unknownBlockResult(projectId, blockId, options.nothingChanged) };
186
+ return { block };
187
+ }
188
+
189
+ type ToolErrorResult = ReturnType<typeof errorResult>;