@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,362 @@
1
+ import type { ProjectHolder, ProjectId } from "@milaboratories/pl-middle-layer";
2
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
3
+ import type { Hold, HoldSource, KeptHoldRelease } from "./project-holds";
4
+ import { ProjectHolds } from "./project-holds";
5
+
6
+ const P1 = "p1" as ProjectId;
7
+ const P2 = "p2" as ProjectId;
8
+ const HOLDER = "mcp:test" as ProjectHolder;
9
+ const IDLE_MS = 1_000;
10
+
11
+ type FakeProject = { id: ProjectId };
12
+
13
+ /** A middle layer that only counts holds. */
14
+ class FakeSource implements HoldSource<FakeProject> {
15
+ readonly live = new Set<FakeHold>();
16
+ acquired = 0;
17
+
18
+ async acquireProject(id: ProjectId, holder: ProjectHolder): Promise<FakeHold> {
19
+ expect(holder).toBe(HOLDER);
20
+ this.acquired++;
21
+ const hold = new FakeHold(this, { id });
22
+ this.live.add(hold);
23
+ return hold;
24
+ }
25
+
26
+ holds(id: ProjectId): number {
27
+ return [...this.live].filter((h) => h.project.id === id).length;
28
+ }
29
+ }
30
+
31
+ class FakeHold implements Hold<FakeProject> {
32
+ private readonly controller = new AbortController();
33
+ constructor(
34
+ private readonly source: FakeSource,
35
+ readonly project: FakeProject,
36
+ ) {}
37
+ get signal(): AbortSignal {
38
+ return this.controller.signal;
39
+ }
40
+ get ended(): boolean {
41
+ return this.controller.signal.aborted;
42
+ }
43
+ async release(): Promise<void> {
44
+ this.end("released");
45
+ }
46
+ /** Ends the hold the way the middle layer does on a delete or a close. */
47
+ end(reason: string): void {
48
+ if (this.ended) return;
49
+ this.source.live.delete(this);
50
+ this.controller.abort(reason);
51
+ }
52
+ }
53
+
54
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
55
+ let resolve = () => {};
56
+ const promise = new Promise<void>((res) => {
57
+ resolve = res;
58
+ });
59
+ return { promise, resolve };
60
+ }
61
+
62
+ describe("ProjectHolds", () => {
63
+ let source: FakeSource;
64
+ let released: [ProjectId, KeptHoldRelease][];
65
+ let holds: ProjectHolds<FakeProject>;
66
+
67
+ beforeEach(() => {
68
+ vi.useFakeTimers();
69
+ source = new FakeSource();
70
+ released = [];
71
+ holds = new ProjectHolds<FakeProject>({
72
+ holder: HOLDER,
73
+ idleMs: IDLE_MS,
74
+ onRelease: (id, reason) => released.push([id, reason]),
75
+ });
76
+ });
77
+
78
+ afterEach(() => {
79
+ vi.useRealTimers();
80
+ });
81
+
82
+ test("every call holds the project while it runs, and one hold is kept after", async () => {
83
+ const gates = [deferred(), deferred(), deferred()];
84
+ const calls = gates.map((gate) =>
85
+ holds.use(source, P1, async (project) => {
86
+ await gate.promise;
87
+ return project.id;
88
+ }),
89
+ );
90
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(3));
91
+
92
+ // The first call to end leaves its hold as the kept one.
93
+ gates[0].resolve();
94
+ await calls[0];
95
+ expect(source.holds(P1)).toBe(3);
96
+
97
+ // Later calls give theirs back.
98
+ gates[1].resolve();
99
+ await calls[1];
100
+ expect(source.holds(P1)).toBe(2);
101
+
102
+ gates[2].resolve();
103
+ expect(await Promise.all(calls)).toEqual([P1, P1, P1]);
104
+ expect(source.holds(P1)).toBe(1);
105
+ });
106
+
107
+ test("the kept hold is released after the idle time, which every call restarts", async () => {
108
+ await holds.use(source, P1, async () => {});
109
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 100);
110
+ await holds.use(source, P1, async () => {});
111
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 100);
112
+ expect(source.holds(P1)).toBe(1);
113
+
114
+ await vi.advanceTimersByTimeAsync(200);
115
+ expect(source.holds(P1)).toBe(0);
116
+ expect(released).toEqual([[P1, "idle"]]);
117
+ });
118
+
119
+ test("a call running past the idle time keeps the project held", async () => {
120
+ await holds.use(source, P1, async () => {});
121
+ const gate = deferred();
122
+ const long = holds.use(source, P1, () => gate.promise);
123
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(2));
124
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 3);
125
+ expect(source.holds(P1)).toBe(1);
126
+
127
+ gate.resolve();
128
+ await long;
129
+ expect(source.holds(P1)).toBe(1);
130
+ });
131
+
132
+ test("releaseAll gives back every kept hold", async () => {
133
+ await holds.use(source, P1, async () => {});
134
+ await holds.use(source, P2, async () => {});
135
+ expect(source.live.size).toBe(2);
136
+ holds.releaseAll();
137
+ expect(source.live.size).toBe(0);
138
+ });
139
+
140
+ test("a call running across releaseAll gives its hold back when it ends", async () => {
141
+ const gate = deferred();
142
+ const running = holds.use(source, P1, () => gate.promise);
143
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(1));
144
+ holds.releaseAll();
145
+ expect(source.holds(P1)).toBe(1);
146
+
147
+ gate.resolve();
148
+ await running;
149
+ expect(source.holds(P1)).toBe(0);
150
+
151
+ // Calls after it keep their hold again.
152
+ await holds.use(source, P1, async () => {});
153
+ expect(source.holds(P1)).toBe(1);
154
+ });
155
+
156
+ test("a call whose acquire was in flight at releaseAll keeps nothing", async () => {
157
+ const slow = deferred();
158
+ const acquire = source.acquireProject.bind(source);
159
+ source.acquireProject = async (id, holder) => {
160
+ await slow.promise;
161
+ return await acquire(id, holder);
162
+ };
163
+ const running = holds.use(source, P1, async () => {});
164
+ holds.releaseAll();
165
+ slow.resolve();
166
+ await running;
167
+ expect(source.live.size).toBe(0);
168
+ });
169
+
170
+ test("a kept hold the middle layer ends is forgotten", async () => {
171
+ await holds.use(source, P1, async () => {});
172
+ for (const hold of source.live) hold.end("deleted");
173
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 2);
174
+ expect(released).toEqual([]);
175
+ });
176
+
177
+ test("a kept hold the middle layer ends is told about once; one the server gives back is not", async () => {
178
+ const ended: ProjectId[] = [];
179
+ holds = new ProjectHolds<FakeProject>({
180
+ holder: HOLDER,
181
+ idleMs: IDLE_MS,
182
+ onEnded: (id) => ended.push(id),
183
+ });
184
+ await holds.use(source, P1, async () => {});
185
+ await holds.use(source, P2, async () => {});
186
+ for (const hold of source.live) if (hold.project.id === P1) hold.end("deleted");
187
+ holds.releaseAll();
188
+ expect(ended).toEqual([P1]);
189
+ });
190
+
191
+ test("a call whose hold ended during it keeps nothing", async () => {
192
+ await holds.use(source, P1, async () => {
193
+ for (const hold of source.live) hold.end("deleted");
194
+ });
195
+ expect(source.live.size).toBe(0);
196
+ });
197
+
198
+ describe("while the project has pending work (Q-002)", () => {
199
+ let pending: Map<ProjectId, number>;
200
+ let bytes: Map<ProjectId, number>;
201
+ let checks: ProjectId[];
202
+ let kept: [ProjectId, string, number][];
203
+
204
+ beforeEach(() => {
205
+ pending = new Map();
206
+ bytes = new Map();
207
+ checks = [];
208
+ kept = [];
209
+ holds = new ProjectHolds<FakeProject>({
210
+ holder: HOLDER,
211
+ idleMs: IDLE_MS,
212
+ onRelease: (id, reason) => released.push([id, reason]),
213
+ pendingWork: async (id, project) => {
214
+ expect(project.id).toBe(id);
215
+ checks.push(id);
216
+ const n = pending.get(id) ?? 0;
217
+ if (n < 0) throw new Error("cannot tell");
218
+ return { count: n, progress: bytes.get(id) ?? 0 };
219
+ },
220
+ onKeep: (id, reason, n) => kept.push([id, reason, n]),
221
+ });
222
+ });
223
+
224
+ test("the hold is kept, idle time after idle time, until the work is done", async () => {
225
+ pending.set(P1, 2);
226
+ await holds.use(source, P1, async () => {});
227
+
228
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
229
+ expect(source.holds(P1)).toBe(1);
230
+ expect(kept).toEqual([[P1, "imports", 2]]);
231
+
232
+ pending.set(P1, 1);
233
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
234
+ expect(source.holds(P1)).toBe(1);
235
+ expect(kept).toEqual([
236
+ [P1, "imports", 2],
237
+ [P1, "imports", 1],
238
+ ]);
239
+
240
+ pending.set(P1, 0);
241
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
242
+ expect(source.holds(P1)).toBe(0);
243
+ expect(released).toEqual([[P1, "idle"]]);
244
+ expect(checks).toEqual([P1, P1, P1]);
245
+ });
246
+
247
+ test("work that does not move is let go after 5 idle times in a row, saying why", async () => {
248
+ pending.set(P1, 2);
249
+ await holds.use(source, P1, async () => {});
250
+ // The first check has nothing to compare with; five more find the same work.
251
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 5);
252
+ expect(source.holds(P1)).toBe(1);
253
+ expect(kept).toHaveLength(5);
254
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
255
+ expect(source.holds(P1)).toBe(0);
256
+ expect(released).toEqual([[P1, "uploads-stalled"]]);
257
+ });
258
+
259
+ test("bytes moving keep the hold; a call starts the count again", async () => {
260
+ pending.set(P1, 1);
261
+ await holds.use(source, P1, async () => {});
262
+ for (let i = 1; i <= 8; i++) {
263
+ bytes.set(P1, i * 100);
264
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
265
+ }
266
+ expect(source.holds(P1)).toBe(1);
267
+
268
+ // Stuck now: four idle times without progress, then a call, then four more.
269
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 4);
270
+ await holds.use(source, P1, async () => {});
271
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 4);
272
+ expect(source.holds(P1)).toBe(1);
273
+ expect(released).toEqual([]);
274
+ });
275
+
276
+ test("a project with no pending work is released as before", async () => {
277
+ await holds.use(source, P1, async () => {});
278
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
279
+ expect(source.holds(P1)).toBe(0);
280
+ expect(kept).toEqual([]);
281
+ expect(released).toEqual([[P1, "idle"]]);
282
+ });
283
+
284
+ test("a check that fails releases the hold", async () => {
285
+ pending.set(P1, -1);
286
+ await holds.use(source, P1, async () => {});
287
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
288
+ expect(source.holds(P1)).toBe(0);
289
+ expect(released).toEqual([[P1, "idle"]]);
290
+ });
291
+
292
+ test("a call that ends during the check restarts the idle time; the check's answer is dropped", async () => {
293
+ const gate = deferred();
294
+ holds = new ProjectHolds<FakeProject>({
295
+ holder: HOLDER,
296
+ idleMs: IDLE_MS,
297
+ onRelease: (id, reason) => released.push([id, reason]),
298
+ pendingWork: async () => {
299
+ await gate.promise;
300
+ return { count: 0, progress: 0 };
301
+ },
302
+ });
303
+ await holds.use(source, P1, async () => {});
304
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
305
+ await holds.use(source, P1, async () => {});
306
+ gate.resolve();
307
+ await vi.advanceTimersByTimeAsync(0);
308
+ expect(source.holds(P1)).toBe(1);
309
+ expect(released).toEqual([]);
310
+ });
311
+
312
+ test("releaseAll during the check wins", async () => {
313
+ const gate = deferred();
314
+ holds = new ProjectHolds<FakeProject>({
315
+ holder: HOLDER,
316
+ idleMs: IDLE_MS,
317
+ onRelease: (id, reason) => released.push([id, reason]),
318
+ pendingWork: async () => {
319
+ await gate.promise;
320
+ return { count: 3, progress: 0 };
321
+ },
322
+ onKeep: (id, reason, n) => kept.push([id, reason, n]),
323
+ });
324
+ await holds.use(source, P1, async () => {});
325
+ await vi.advanceTimersByTimeAsync(IDLE_MS);
326
+ holds.releaseAll();
327
+ gate.resolve();
328
+ await vi.advanceTimersByTimeAsync(0);
329
+ expect(source.holds(P1)).toBe(0);
330
+ expect(kept).toEqual([]);
331
+ expect(released).toEqual([[P1, "release-all"]]);
332
+ });
333
+ });
334
+
335
+ describe("calls in flight", () => {
336
+ test("are counted per project from before the acquire until the call ends", async () => {
337
+ const gate = deferred();
338
+ const call = holds.use(source, P1, () => gate.promise);
339
+ expect(holds.callsInFlight(P1)).toBe(1);
340
+ expect(holds.callsInFlight(P2)).toBe(0);
341
+ const second = holds.use(source, P1, async () => {});
342
+ expect(holds.callsInFlight(P1)).toBe(2);
343
+ await second;
344
+ expect(holds.callsInFlight(P1)).toBe(1);
345
+ gate.resolve();
346
+ await call;
347
+ // The kept hold is no call.
348
+ expect(holds.callsInFlight(P1)).toBe(0);
349
+ expect(source.holds(P1)).toBe(1);
350
+ });
351
+
352
+ test("a call whose acquire fails is no longer counted", async () => {
353
+ const failing: HoldSource<FakeProject> = {
354
+ acquireProject: async () => {
355
+ throw new Error("not found");
356
+ },
357
+ };
358
+ await expect(holds.use(failing, P1, async () => {})).rejects.toThrow("not found");
359
+ expect(holds.callsInFlight(P1)).toBe(0);
360
+ });
361
+ });
362
+ });
@@ -0,0 +1,207 @@
1
+ import type { ProjectHolder, ProjectId } from "@milaboratories/pl-middle-layer";
2
+
3
+ /** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */
4
+ export interface Hold<P> {
5
+ readonly project: P;
6
+ readonly signal: AbortSignal;
7
+ readonly ended: boolean;
8
+ release(): Promise<void>;
9
+ }
10
+
11
+ /** Where holds come from: the middle layer, or a fake of it in tests. */
12
+ export interface HoldSource<P> {
13
+ acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;
14
+ }
15
+
16
+ /**
17
+ * Why {@link ProjectHolds} gave a kept hold back. `uploads-stalled`: the project still had work
18
+ * pending, but it made no progress for {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times
19
+ * in a row.
20
+ */
21
+ export type KeptHoldRelease = "idle" | "release-all" | "uploads-stalled";
22
+
23
+ /** Work a project still does that needs it loaded, as {@link ProjectHoldsOptions.pendingWork} tells it. */
24
+ export type PendingWork = {
25
+ /** How many pieces of work are left. */
26
+ count: number;
27
+ /** How far the work got (bytes uploaded); the same number at two checks means no progress. */
28
+ progress: number;
29
+ };
30
+
31
+ /** Default of {@link ProjectHoldsOptions.maxIdleWithoutProgress}. */
32
+ export const DEFAULT_MAX_IDLE_WITHOUT_PROGRESS = 5;
33
+
34
+ export interface ProjectHoldsOptions<P = unknown> {
35
+ /** The holder every hold is taken under. */
36
+ holder: ProjectHolder;
37
+ /** How long a project stays held after the last call on it ended. */
38
+ idleMs: number;
39
+ /** Told about every kept hold given back. */
40
+ onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;
41
+ /**
42
+ * Told about every kept hold the middle layer ended (the project was deleted, the middle layer
43
+ * closed), when it is forgotten.
44
+ */
45
+ onEnded?: (id: ProjectId) => void;
46
+ /**
47
+ * Asked when the idle time of a kept hold is over: how much work the project still does that
48
+ * needs it loaded (Q-002: files to upload). A count over 0 keeps the hold for another idle time;
49
+ * 0, or a failed check, gives it back.
50
+ */
51
+ pendingWork?: (id: ProjectId, project: P) => Promise<PendingWork>;
52
+ /**
53
+ * How many idle times in a row a kept hold may stay for pending work whose count and progress
54
+ * do not change; at the next such check it is given back (`uploads-stalled`), so an upload
55
+ * that never moves does not keep its project loaded for ever. A call on the project starts the
56
+ * count again. Default {@link DEFAULT_MAX_IDLE_WITHOUT_PROGRESS}.
57
+ */
58
+ maxIdleWithoutProgress?: number;
59
+ /** Told about every kept hold the idle time did not end, with what {@link pendingWork} said. */
60
+ onKeep?: (id: ProjectId, reason: KeptHoldKeep, pending: number) => void;
61
+ }
62
+
63
+ /** Why {@link ProjectHolds} kept a hold past its idle time. */
64
+ export type KeptHoldKeep = "imports";
65
+
66
+ type Kept<P> = {
67
+ hold: Hold<P>;
68
+ timer: NodeJS.Timeout;
69
+ /** Counts the calls that ended on the project: a check that started before one is stale. */
70
+ uses: number;
71
+ /** What the last check of pending work found, since the last call. */
72
+ lastWork?: PendingWork;
73
+ /** Idle times in a row whose check found the same pending work as the one before. */
74
+ idleWithoutProgress: number;
75
+ };
76
+
77
+ /**
78
+ * The MCP server's holds on projects.
79
+ *
80
+ * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy
81
+ * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a
82
+ * run of calls on a project does not load it again for each call; the idle time restarts with
83
+ * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
84
+ * is forgotten.
85
+ *
86
+ * When the idle time is over and the project still has work that needs it loaded (Q-002: files
87
+ * being uploaded, which stop when the project is unloaded), the hold is kept for another idle
88
+ * time, as long as the work makes progress: after
89
+ * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given
90
+ * back.
91
+ *
92
+ * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that
93
+ * another call of this server still works on the project.
94
+ */
95
+ export class ProjectHolds<P> {
96
+ private readonly kept = new Map<ProjectId, Kept<P>>();
97
+ /** The calls running on each project, from before their acquire until their hold is let go. */
98
+ private readonly running = new Map<ProjectId, number>();
99
+ /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
100
+ private generation = 0;
101
+
102
+ constructor(private readonly options: ProjectHoldsOptions<P>) {}
103
+
104
+ /** Runs `fn` on the project while holding it. */
105
+ async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {
106
+ const generation = this.generation;
107
+ this.running.set(id, (this.running.get(id) ?? 0) + 1);
108
+ try {
109
+ const hold = await source.acquireProject(id, this.options.holder);
110
+ try {
111
+ return await fn(hold.project);
112
+ } finally {
113
+ if (generation === this.generation) this.keep(id, hold);
114
+ else void hold.release();
115
+ }
116
+ } finally {
117
+ const left = (this.running.get(id) ?? 1) - 1;
118
+ if (left > 0) this.running.set(id, left);
119
+ else this.running.delete(id);
120
+ }
121
+ }
122
+
123
+ /** How many calls of {@link use} are running on the project, those still acquiring included. */
124
+ callsInFlight(id: ProjectId): number {
125
+ return this.running.get(id) ?? 0;
126
+ }
127
+
128
+ /**
129
+ * Gives back every kept hold. Holds of calls still running are given back when those calls end,
130
+ * not kept.
131
+ */
132
+ releaseAll(): void {
133
+ this.generation++;
134
+ for (const id of this.kept.keys()) this.release(id, "release-all");
135
+ }
136
+
137
+ /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */
138
+ private keep(id: ProjectId, hold: Hold<P>): void {
139
+ if (hold.ended) return;
140
+
141
+ const kept = this.kept.get(id);
142
+ if (kept !== undefined) {
143
+ void hold.release();
144
+ kept.uses++;
145
+ kept.lastWork = undefined;
146
+ kept.idleWithoutProgress = 0;
147
+ kept.timer.refresh();
148
+ return;
149
+ }
150
+
151
+ const entry: Kept<P> = {
152
+ hold,
153
+ uses: 0,
154
+ idleWithoutProgress: 0,
155
+ timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs),
156
+ };
157
+ entry.timer.unref();
158
+ hold.signal.addEventListener(
159
+ "abort",
160
+ () => {
161
+ if (this.kept.get(id) !== entry) return;
162
+ clearTimeout(entry.timer);
163
+ this.kept.delete(id);
164
+ this.options.onEnded?.(id);
165
+ },
166
+ { once: true },
167
+ );
168
+ this.kept.set(id, entry);
169
+ }
170
+
171
+ /** The idle time of a kept hold is over: keep it while the project has pending work. */
172
+ private async idle(id: ProjectId, entry: Kept<P>): Promise<void> {
173
+ if (this.kept.get(id) !== entry) return;
174
+ const check = this.options.pendingWork;
175
+ if (check === undefined) return this.release(id, "idle");
176
+ const uses = entry.uses;
177
+ let work: PendingWork;
178
+ try {
179
+ work = await check(id, entry.hold.project);
180
+ } catch {
181
+ work = { count: 0, progress: 0 };
182
+ }
183
+ // Released, replaced, or used meanwhile: a call that ended restarted the idle time.
184
+ if (this.kept.get(id) !== entry || entry.uses !== uses) return;
185
+ if (work.count <= 0) return this.release(id, "idle");
186
+
187
+ const last = entry.lastWork;
188
+ entry.lastWork = work;
189
+ entry.idleWithoutProgress =
190
+ last !== undefined && last.count === work.count && last.progress === work.progress
191
+ ? entry.idleWithoutProgress + 1
192
+ : 0;
193
+ const limit = this.options.maxIdleWithoutProgress ?? DEFAULT_MAX_IDLE_WITHOUT_PROGRESS;
194
+ if (entry.idleWithoutProgress >= limit) return this.release(id, "uploads-stalled");
195
+ entry.timer.refresh();
196
+ this.options.onKeep?.(id, "imports", work.count);
197
+ }
198
+
199
+ private release(id: ProjectId, reason: KeptHoldRelease): void {
200
+ const entry = this.kept.get(id);
201
+ if (entry === undefined) return;
202
+ clearTimeout(entry.timer);
203
+ this.kept.delete(id);
204
+ void entry.hold.release();
205
+ this.options.onRelease?.(id, reason);
206
+ }
207
+ }
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { ProjectList } from "./project-list";
3
+ import type { ProjectId } from "@milaboratories/pl-model-common";
4
+ import { findListedProject } from "./project-list";
5
+
6
+ /** A project list that has `cached` until refreshed, `fresh` after; counts the refreshes. */
7
+ function list(cached: string[], fresh: string[] = cached) {
8
+ let current = cached;
9
+ let refreshes = 0;
10
+ const projects: ProjectList<{ id: string }> = {
11
+ awaitStableValue: async () => current.map((id) => ({ id })),
12
+ refreshState: async () => {
13
+ refreshes++;
14
+ current = fresh;
15
+ },
16
+ };
17
+ return { projects, refreshes: () => refreshes };
18
+ }
19
+
20
+ describe("findListedProject", () => {
21
+ test("a project in the list is found without asking the backend", async () => {
22
+ const { projects, refreshes } = list(["a", "b"]);
23
+ expect(await findListedProject(projects, "b" as ProjectId)).toEqual({ id: "b" });
24
+ expect(refreshes()).toBe(0);
25
+ });
26
+
27
+ test("a project not in the list yet is looked for again in a fresh list", async () => {
28
+ const { projects, refreshes } = list(["a"], ["a", "new"]);
29
+ expect(await findListedProject(projects, "new" as ProjectId)).toEqual({ id: "new" });
30
+ expect(refreshes()).toBe(1);
31
+ });
32
+
33
+ test("a project in neither list is not found", async () => {
34
+ const { projects, refreshes } = list(["a"]);
35
+ expect(await findListedProject(projects, "gone" as ProjectId)).toBeUndefined();
36
+ expect(refreshes()).toBe(1);
37
+ });
38
+ });
@@ -0,0 +1,25 @@
1
+ import type { ProjectId } from "@milaboratories/pl-model-common";
2
+
3
+ /** The middle layer's project list, as {@link findListedProject} reads it. */
4
+ export type ProjectList<E extends { id: string }> = {
5
+ /** The list as last read from the backend; kept fresh by the middle layer's own polling. */
6
+ awaitStableValue(): Promise<readonly E[]>;
7
+ /** Reads the list from the backend now. */
8
+ refreshState(): Promise<void>;
9
+ };
10
+
11
+ /**
12
+ * The entry of project `projectId`, from the list as the middle layer last read it. Only a project
13
+ * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the
14
+ * list from the backend again: a call on a known project costs no round trip. `undefined` when the
15
+ * fresh list does not have it either.
16
+ */
17
+ export async function findListedProject<E extends { id: string }>(
18
+ list: ProjectList<E>,
19
+ projectId: ProjectId,
20
+ ): Promise<E | undefined> {
21
+ const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);
22
+ if (cached !== undefined) return cached;
23
+ await list.refreshState();
24
+ return (await list.awaitStableValue()).find((p) => p.id === projectId);
25
+ }