@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,4 +1,3 @@
1
- // src/project-holds.ts
2
1
  /**
3
2
  * The MCP server's holds on projects.
4
3
  *
@@ -7,10 +6,21 @@
7
6
  * run of calls on a project does not load it again for each call; the idle time restarts with
8
7
  * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
9
8
  * is forgotten.
9
+ *
10
+ * When the idle time is over and the project still has work that needs it loaded (Q-002: files
11
+ * being uploaded, which stop when the project is unloaded), the hold is kept for another idle
12
+ * time, as long as the work makes progress: after
13
+ * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given
14
+ * back.
15
+ *
16
+ * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that
17
+ * another call of this server still works on the project.
10
18
  */
11
19
  var ProjectHolds = class {
12
20
  options;
13
21
  kept = /* @__PURE__ */ new Map();
22
+ /** The calls running on each project, from before their acquire until their hold is let go. */
23
+ running = /* @__PURE__ */ new Map();
14
24
  /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
15
25
  generation = 0;
16
26
  constructor(options) {
@@ -19,14 +29,25 @@ var ProjectHolds = class {
19
29
  /** Runs `fn` on the project while holding it. */
20
30
  async use(source, id, fn) {
21
31
  const generation = this.generation;
22
- const hold = await source.acquireProject(id, this.options.holder);
32
+ this.running.set(id, (this.running.get(id) ?? 0) + 1);
23
33
  try {
24
- return await fn(hold.project);
34
+ const hold = await source.acquireProject(id, this.options.holder);
35
+ try {
36
+ return await fn(hold.project);
37
+ } finally {
38
+ if (generation === this.generation) this.keep(id, hold);
39
+ else hold.release();
40
+ }
25
41
  } finally {
26
- if (generation === this.generation) this.keep(id, hold);
27
- else hold.release();
42
+ const left = (this.running.get(id) ?? 1) - 1;
43
+ if (left > 0) this.running.set(id, left);
44
+ else this.running.delete(id);
28
45
  }
29
46
  }
47
+ /** How many calls of {@link use} are running on the project, those still acquiring included. */
48
+ callsInFlight(id) {
49
+ return this.running.get(id) ?? 0;
50
+ }
30
51
  /**
31
52
  * Gives back every kept hold. Holds of calls still running are given back when those calls end,
32
53
  * not kept.
@@ -41,23 +62,52 @@ var ProjectHolds = class {
41
62
  const kept = this.kept.get(id);
42
63
  if (kept !== void 0) {
43
64
  hold.release();
65
+ kept.uses++;
66
+ kept.lastWork = void 0;
67
+ kept.idleWithoutProgress = 0;
44
68
  kept.timer.refresh();
45
69
  return;
46
70
  }
47
71
  const entry = {
48
72
  hold,
49
- timer: setTimeout(() => {
50
- if (this.kept.get(id) === entry) this.release(id, "idle");
51
- }, this.options.idleMs)
73
+ uses: 0,
74
+ idleWithoutProgress: 0,
75
+ timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs)
52
76
  };
53
77
  entry.timer.unref();
54
78
  hold.signal.addEventListener("abort", () => {
55
79
  if (this.kept.get(id) !== entry) return;
56
80
  clearTimeout(entry.timer);
57
81
  this.kept.delete(id);
82
+ this.options.onEnded?.(id);
58
83
  }, { once: true });
59
84
  this.kept.set(id, entry);
60
85
  }
86
+ /** The idle time of a kept hold is over: keep it while the project has pending work. */
87
+ async idle(id, entry) {
88
+ if (this.kept.get(id) !== entry) return;
89
+ const check = this.options.pendingWork;
90
+ if (check === void 0) return this.release(id, "idle");
91
+ const uses = entry.uses;
92
+ let work;
93
+ try {
94
+ work = await check(id, entry.hold.project);
95
+ } catch {
96
+ work = {
97
+ count: 0,
98
+ progress: 0
99
+ };
100
+ }
101
+ if (this.kept.get(id) !== entry || entry.uses !== uses) return;
102
+ if (work.count <= 0) return this.release(id, "idle");
103
+ const last = entry.lastWork;
104
+ entry.lastWork = work;
105
+ entry.idleWithoutProgress = last !== void 0 && last.count === work.count && last.progress === work.progress ? entry.idleWithoutProgress + 1 : 0;
106
+ const limit = this.options.maxIdleWithoutProgress ?? 5;
107
+ if (entry.idleWithoutProgress >= limit) return this.release(id, "uploads-stalled");
108
+ entry.timer.refresh();
109
+ this.options.onKeep?.(id, "imports", work.count);
110
+ }
61
111
  release(id, reason) {
62
112
  const entry = this.kept.get(id);
63
113
  if (entry === void 0) return;
@@ -1 +1 @@
1
- {"version":3,"file":"project-holds.cjs","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/** Why {@link ProjectHolds} gave a kept hold back. */\nexport type KeptHoldRelease = \"idle\" | \"release-all\";\n\nexport interface ProjectHoldsOptions {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n}\n\ntype Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n timer: setTimeout(() => {\n if (this.kept.get(id) === entry) this.release(id, \"idle\");\n }, this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,eAAb,MAA6B;CAKE;CAJ7B,uBAAwB,IAAI,IAAwB;;CAEpD,aAAqB;CAErB,YAAY,SAA+C;EAA9B,KAAA,UAAA;CAA+B;;CAG5D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;EAChE,IAAI;GACF,OAAO,MAAM,GAAG,KAAK,OAAO;EAC9B,UAAU;GACR,IAAI,eAAe,KAAK,YAAY,KAAK,KAAK,IAAI,IAAI;QACjD,KAAU,QAAQ;EACzB;CACF;;;;;CAMA,aAAmB;EACjB,KAAK;EACL,KAAK,MAAM,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK,QAAQ,IAAI,aAAa;CACnE;;CAGA,KAAa,IAAe,MAAqB;EAC/C,IAAI,KAAK,OAAO;EAEhB,MAAM,OAAO,KAAK,KAAK,IAAI,EAAE;EAC7B,IAAI,SAAS,KAAA,GAAW;GACtB,KAAU,QAAQ;GAClB,KAAK,MAAM,QAAQ;GACnB;EACF;EAEA,MAAM,QAAiB;GACrB;GACA,OAAO,iBAAiB;IACtB,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM;GAC1D,GAAG,KAAK,QAAQ,MAAM;EACxB;EACA,MAAM,MAAM,MAAM;EAClB,KAAK,OAAO,iBACV,eACM;GACJ,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO;GACjC,aAAa,MAAM,KAAK;GACxB,KAAK,KAAK,OAAO,EAAE;EACrB,GACA,EAAE,MAAM,KAAK,CACf;EACA,KAAK,KAAK,IAAI,IAAI,KAAK;CACzB;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
1
+ {"version":3,"file":"project-holds.cjs","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/**\n * Why {@link ProjectHolds} gave a kept hold back. `uploads-stalled`: the project still had work\n * pending, but it made no progress for {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times\n * in a row.\n */\nexport type KeptHoldRelease = \"idle\" | \"release-all\" | \"uploads-stalled\";\n\n/** Work a project still does that needs it loaded, as {@link ProjectHoldsOptions.pendingWork} tells it. */\nexport type PendingWork = {\n /** How many pieces of work are left. */\n count: number;\n /** How far the work got (bytes uploaded); the same number at two checks means no progress. */\n progress: number;\n};\n\n/** Default of {@link ProjectHoldsOptions.maxIdleWithoutProgress}. */\nexport const DEFAULT_MAX_IDLE_WITHOUT_PROGRESS = 5;\n\nexport interface ProjectHoldsOptions<P = unknown> {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n /**\n * Told about every kept hold the middle layer ended (the project was deleted, the middle layer\n * closed), when it is forgotten.\n */\n onEnded?: (id: ProjectId) => void;\n /**\n * Asked when the idle time of a kept hold is over: how much work the project still does that\n * needs it loaded (Q-002: files to upload). A count over 0 keeps the hold for another idle time;\n * 0, or a failed check, gives it back.\n */\n pendingWork?: (id: ProjectId, project: P) => Promise<PendingWork>;\n /**\n * How many idle times in a row a kept hold may stay for pending work whose count and progress\n * do not change; at the next such check it is given back (`uploads-stalled`), so an upload\n * that never moves does not keep its project loaded for ever. A call on the project starts the\n * count again. Default {@link DEFAULT_MAX_IDLE_WITHOUT_PROGRESS}.\n */\n maxIdleWithoutProgress?: number;\n /** Told about every kept hold the idle time did not end, with what {@link pendingWork} said. */\n onKeep?: (id: ProjectId, reason: KeptHoldKeep, pending: number) => void;\n}\n\n/** Why {@link ProjectHolds} kept a hold past its idle time. */\nexport type KeptHoldKeep = \"imports\";\n\ntype Kept<P> = {\n hold: Hold<P>;\n timer: NodeJS.Timeout;\n /** Counts the calls that ended on the project: a check that started before one is stale. */\n uses: number;\n /** What the last check of pending work found, since the last call. */\n lastWork?: PendingWork;\n /** Idle times in a row whose check found the same pending work as the one before. */\n idleWithoutProgress: number;\n};\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n *\n * When the idle time is over and the project still has work that needs it loaded (Q-002: files\n * being uploaded, which stop when the project is unloaded), the hold is kept for another idle\n * time, as long as the work makes progress: after\n * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given\n * back.\n *\n * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that\n * another call of this server still works on the project.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** The calls running on each project, from before their acquire until their hold is let go. */\n private readonly running = new Map<ProjectId, number>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions<P>) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n this.running.set(id, (this.running.get(id) ?? 0) + 1);\n try {\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n } finally {\n const left = (this.running.get(id) ?? 1) - 1;\n if (left > 0) this.running.set(id, left);\n else this.running.delete(id);\n }\n }\n\n /** How many calls of {@link use} are running on the project, those still acquiring included. */\n callsInFlight(id: ProjectId): number {\n return this.running.get(id) ?? 0;\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.uses++;\n kept.lastWork = undefined;\n kept.idleWithoutProgress = 0;\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n uses: 0,\n idleWithoutProgress: 0,\n timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n this.options.onEnded?.(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n /** The idle time of a kept hold is over: keep it while the project has pending work. */\n private async idle(id: ProjectId, entry: Kept<P>): Promise<void> {\n if (this.kept.get(id) !== entry) return;\n const check = this.options.pendingWork;\n if (check === undefined) return this.release(id, \"idle\");\n const uses = entry.uses;\n let work: PendingWork;\n try {\n work = await check(id, entry.hold.project);\n } catch {\n work = { count: 0, progress: 0 };\n }\n // Released, replaced, or used meanwhile: a call that ended restarted the idle time.\n if (this.kept.get(id) !== entry || entry.uses !== uses) return;\n if (work.count <= 0) return this.release(id, \"idle\");\n\n const last = entry.lastWork;\n entry.lastWork = work;\n entry.idleWithoutProgress =\n last !== undefined && last.count === work.count && last.progress === work.progress\n ? entry.idleWithoutProgress + 1\n : 0;\n const limit = this.options.maxIdleWithoutProgress ?? DEFAULT_MAX_IDLE_WITHOUT_PROGRESS;\n if (entry.idleWithoutProgress >= limit) return this.release(id, \"uploads-stalled\");\n entry.timer.refresh();\n this.options.onKeep?.(id, \"imports\", work.count);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8FA,IAAa,eAAb,MAA6B;CAOE;CAN7B,uBAAwB,IAAI,IAAwB;;CAEpD,0BAA2B,IAAI,IAAuB;;CAEtD,aAAqB;CAErB,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;;CAG/D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,KAAK,QAAQ,IAAI,KAAK,KAAK,QAAQ,IAAI,EAAE,KAAK,KAAK,CAAC;EACpD,IAAI;GACF,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;GAChE,IAAI;IACF,OAAO,MAAM,GAAG,KAAK,OAAO;GAC9B,UAAU;IACR,IAAI,eAAe,KAAK,YAA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,IAAI;EACJ,IAAI;GACF,OAAO,MAAM,MAAM,IAAI,MAAM,KAAK,OAAO;EAC3C,QAAQ;GACN,OAAO;IAAE,OAAO;IAAG,UAAU;GAAE;EACjC;EAEA,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,SAAS,MAAM,SAAS,MAAM;EACxD,IAAI,KAAK,SAAS,GAAG,OAAO,KAAK,QAAQ,IAAI,MAAM;EAEnD,MAAM,OAAO,MAAM;EACnB,MAAM,WAAW;EACjB,MAAM,sBACJ,SAAS,KAAA,KAAa,KAAK,UAAU,KAAK,SAAS,KAAK,aAAa,KAAK,WACtE,MAAM,sBAAsB,IAC5B;EACN,MAAM,QAAQ,KAAK,QAAQ,0BAAA;EAC3B,IAAI,MAAM,uBAAuB,OAAO,OAAO,KAAK,QAAQ,IAAI,iBAAiB;EACjF,MAAM,MAAM,QAAQ;EACpB,KAAK,QAAQ,SAAS,IAAI,WAAW,KAAK,KAAK;CACjD;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
@@ -1,4 +1,3 @@
1
- // src/project-holds.ts
2
1
  /**
3
2
  * The MCP server's holds on projects.
4
3
  *
@@ -7,10 +6,21 @@
7
6
  * run of calls on a project does not load it again for each call; the idle time restarts with
8
7
  * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
9
8
  * is forgotten.
9
+ *
10
+ * When the idle time is over and the project still has work that needs it loaded (Q-002: files
11
+ * being uploaded, which stop when the project is unloaded), the hold is kept for another idle
12
+ * time, as long as the work makes progress: after
13
+ * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given
14
+ * back.
15
+ *
16
+ * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that
17
+ * another call of this server still works on the project.
10
18
  */
11
19
  var ProjectHolds = class {
12
20
  options;
13
21
  kept = /* @__PURE__ */ new Map();
22
+ /** The calls running on each project, from before their acquire until their hold is let go. */
23
+ running = /* @__PURE__ */ new Map();
14
24
  /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
15
25
  generation = 0;
16
26
  constructor(options) {
@@ -19,14 +29,25 @@ var ProjectHolds = class {
19
29
  /** Runs `fn` on the project while holding it. */
20
30
  async use(source, id, fn) {
21
31
  const generation = this.generation;
22
- const hold = await source.acquireProject(id, this.options.holder);
32
+ this.running.set(id, (this.running.get(id) ?? 0) + 1);
23
33
  try {
24
- return await fn(hold.project);
34
+ const hold = await source.acquireProject(id, this.options.holder);
35
+ try {
36
+ return await fn(hold.project);
37
+ } finally {
38
+ if (generation === this.generation) this.keep(id, hold);
39
+ else hold.release();
40
+ }
25
41
  } finally {
26
- if (generation === this.generation) this.keep(id, hold);
27
- else hold.release();
42
+ const left = (this.running.get(id) ?? 1) - 1;
43
+ if (left > 0) this.running.set(id, left);
44
+ else this.running.delete(id);
28
45
  }
29
46
  }
47
+ /** How many calls of {@link use} are running on the project, those still acquiring included. */
48
+ callsInFlight(id) {
49
+ return this.running.get(id) ?? 0;
50
+ }
30
51
  /**
31
52
  * Gives back every kept hold. Holds of calls still running are given back when those calls end,
32
53
  * not kept.
@@ -41,23 +62,52 @@ var ProjectHolds = class {
41
62
  const kept = this.kept.get(id);
42
63
  if (kept !== void 0) {
43
64
  hold.release();
65
+ kept.uses++;
66
+ kept.lastWork = void 0;
67
+ kept.idleWithoutProgress = 0;
44
68
  kept.timer.refresh();
45
69
  return;
46
70
  }
47
71
  const entry = {
48
72
  hold,
49
- timer: setTimeout(() => {
50
- if (this.kept.get(id) === entry) this.release(id, "idle");
51
- }, this.options.idleMs)
73
+ uses: 0,
74
+ idleWithoutProgress: 0,
75
+ timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs)
52
76
  };
53
77
  entry.timer.unref();
54
78
  hold.signal.addEventListener("abort", () => {
55
79
  if (this.kept.get(id) !== entry) return;
56
80
  clearTimeout(entry.timer);
57
81
  this.kept.delete(id);
82
+ this.options.onEnded?.(id);
58
83
  }, { once: true });
59
84
  this.kept.set(id, entry);
60
85
  }
86
+ /** The idle time of a kept hold is over: keep it while the project has pending work. */
87
+ async idle(id, entry) {
88
+ if (this.kept.get(id) !== entry) return;
89
+ const check = this.options.pendingWork;
90
+ if (check === void 0) return this.release(id, "idle");
91
+ const uses = entry.uses;
92
+ let work;
93
+ try {
94
+ work = await check(id, entry.hold.project);
95
+ } catch {
96
+ work = {
97
+ count: 0,
98
+ progress: 0
99
+ };
100
+ }
101
+ if (this.kept.get(id) !== entry || entry.uses !== uses) return;
102
+ if (work.count <= 0) return this.release(id, "idle");
103
+ const last = entry.lastWork;
104
+ entry.lastWork = work;
105
+ entry.idleWithoutProgress = last !== void 0 && last.count === work.count && last.progress === work.progress ? entry.idleWithoutProgress + 1 : 0;
106
+ const limit = this.options.maxIdleWithoutProgress ?? 5;
107
+ if (entry.idleWithoutProgress >= limit) return this.release(id, "uploads-stalled");
108
+ entry.timer.refresh();
109
+ this.options.onKeep?.(id, "imports", work.count);
110
+ }
61
111
  release(id, reason) {
62
112
  const entry = this.kept.get(id);
63
113
  if (entry === void 0) return;
@@ -1 +1 @@
1
- {"version":3,"file":"project-holds.js","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/** Why {@link ProjectHolds} gave a kept hold back. */\nexport type KeptHoldRelease = \"idle\" | \"release-all\";\n\nexport interface ProjectHoldsOptions {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n}\n\ntype Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n timer: setTimeout(() => {\n if (this.kept.get(id) === entry) this.release(id, \"idle\");\n }, this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,eAAb,MAA6B;CAKE;CAJ7B,uBAAwB,IAAI,IAAwB;;CAEpD,aAAqB;CAErB,YAAY,SAA+C;EAA9B,KAAA,UAAA;CAA+B;;CAG5D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;EAChE,IAAI;GACF,OAAO,MAAM,GAAG,KAAK,OAAO;EAC9B,UAAU;GACR,IAAI,eAAe,KAAK,YAAY,KAAK,KAAK,IAAI,IAAI;QACjD,KAAU,QAAQ;EACzB;CACF;;;;;CAMA,aAAmB;EACjB,KAAK;EACL,KAAK,MAAM,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK,QAAQ,IAAI,aAAa;CACnE;;CAGA,KAAa,IAAe,MAAqB;EAC/C,IAAI,KAAK,OAAO;EAEhB,MAAM,OAAO,KAAK,KAAK,IAAI,EAAE;EAC7B,IAAI,SAAS,KAAA,GAAW;GACtB,KAAU,QAAQ;GAClB,KAAK,MAAM,QAAQ;GACnB;EACF;EAEA,MAAM,QAAiB;GACrB;GACA,OAAO,iBAAiB;IACtB,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM;GAC1D,GAAG,KAAK,QAAQ,MAAM;EACxB;EACA,MAAM,MAAM,MAAM;EAClB,KAAK,OAAO,iBACV,eACM;GACJ,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO;GACjC,aAAa,MAAM,KAAK;GACxB,KAAK,KAAK,OAAO,EAAE;EACrB,GACA,EAAE,MAAM,KAAK,CACf;EACA,KAAK,KAAK,IAAI,IAAI,KAAK;CACzB;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
1
+ {"version":3,"file":"project-holds.js","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/**\n * Why {@link ProjectHolds} gave a kept hold back. `uploads-stalled`: the project still had work\n * pending, but it made no progress for {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times\n * in a row.\n */\nexport type KeptHoldRelease = \"idle\" | \"release-all\" | \"uploads-stalled\";\n\n/** Work a project still does that needs it loaded, as {@link ProjectHoldsOptions.pendingWork} tells it. */\nexport type PendingWork = {\n /** How many pieces of work are left. */\n count: number;\n /** How far the work got (bytes uploaded); the same number at two checks means no progress. */\n progress: number;\n};\n\n/** Default of {@link ProjectHoldsOptions.maxIdleWithoutProgress}. */\nexport const DEFAULT_MAX_IDLE_WITHOUT_PROGRESS = 5;\n\nexport interface ProjectHoldsOptions<P = unknown> {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n /**\n * Told about every kept hold the middle layer ended (the project was deleted, the middle layer\n * closed), when it is forgotten.\n */\n onEnded?: (id: ProjectId) => void;\n /**\n * Asked when the idle time of a kept hold is over: how much work the project still does that\n * needs it loaded (Q-002: files to upload). A count over 0 keeps the hold for another idle time;\n * 0, or a failed check, gives it back.\n */\n pendingWork?: (id: ProjectId, project: P) => Promise<PendingWork>;\n /**\n * How many idle times in a row a kept hold may stay for pending work whose count and progress\n * do not change; at the next such check it is given back (`uploads-stalled`), so an upload\n * that never moves does not keep its project loaded for ever. A call on the project starts the\n * count again. Default {@link DEFAULT_MAX_IDLE_WITHOUT_PROGRESS}.\n */\n maxIdleWithoutProgress?: number;\n /** Told about every kept hold the idle time did not end, with what {@link pendingWork} said. */\n onKeep?: (id: ProjectId, reason: KeptHoldKeep, pending: number) => void;\n}\n\n/** Why {@link ProjectHolds} kept a hold past its idle time. */\nexport type KeptHoldKeep = \"imports\";\n\ntype Kept<P> = {\n hold: Hold<P>;\n timer: NodeJS.Timeout;\n /** Counts the calls that ended on the project: a check that started before one is stale. */\n uses: number;\n /** What the last check of pending work found, since the last call. */\n lastWork?: PendingWork;\n /** Idle times in a row whose check found the same pending work as the one before. */\n idleWithoutProgress: number;\n};\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n *\n * When the idle time is over and the project still has work that needs it loaded (Q-002: files\n * being uploaded, which stop when the project is unloaded), the hold is kept for another idle\n * time, as long as the work makes progress: after\n * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given\n * back.\n *\n * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that\n * another call of this server still works on the project.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** The calls running on each project, from before their acquire until their hold is let go. */\n private readonly running = new Map<ProjectId, number>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions<P>) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n this.running.set(id, (this.running.get(id) ?? 0) + 1);\n try {\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n } finally {\n const left = (this.running.get(id) ?? 1) - 1;\n if (left > 0) this.running.set(id, left);\n else this.running.delete(id);\n }\n }\n\n /** How many calls of {@link use} are running on the project, those still acquiring included. */\n callsInFlight(id: ProjectId): number {\n return this.running.get(id) ?? 0;\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.uses++;\n kept.lastWork = undefined;\n kept.idleWithoutProgress = 0;\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n uses: 0,\n idleWithoutProgress: 0,\n timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n this.options.onEnded?.(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n /** The idle time of a kept hold is over: keep it while the project has pending work. */\n private async idle(id: ProjectId, entry: Kept<P>): Promise<void> {\n if (this.kept.get(id) !== entry) return;\n const check = this.options.pendingWork;\n if (check === undefined) return this.release(id, \"idle\");\n const uses = entry.uses;\n let work: PendingWork;\n try {\n work = await check(id, entry.hold.project);\n } catch {\n work = { count: 0, progress: 0 };\n }\n // Released, replaced, or used meanwhile: a call that ended restarted the idle time.\n if (this.kept.get(id) !== entry || entry.uses !== uses) return;\n if (work.count <= 0) return this.release(id, \"idle\");\n\n const last = entry.lastWork;\n entry.lastWork = work;\n entry.idleWithoutProgress =\n last !== undefined && last.count === work.count && last.progress === work.progress\n ? entry.idleWithoutProgress + 1\n : 0;\n const limit = this.options.maxIdleWithoutProgress ?? DEFAULT_MAX_IDLE_WITHOUT_PROGRESS;\n if (entry.idleWithoutProgress >= limit) return this.release(id, \"uploads-stalled\");\n entry.timer.refresh();\n this.options.onKeep?.(id, \"imports\", work.count);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8FA,IAAa,eAAb,MAA6B;CAOE;CAN7B,uBAAwB,IAAI,IAAwB;;CAEpD,0BAA2B,IAAI,IAAuB;;CAEtD,aAAqB;CAErB,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;;CAG/D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,KAAK,QAAQ,IAAI,KAAK,KAAK,QAAQ,IAAI,EAAE,KAAK,KAAK,CAAC;EACpD,IAAI;GACF,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;GAChE,IAAI;IACF,OAAO,MAAM,GAAG,KAAK,OAAO;GAC9B,UAAU;IACR,IAAI,eAAe,KAAK,YAAY,KAAK,KAAK,IAAI,IAAI;SACjD,KAAU,QAAQ;GACzB;EACF,UAAU;GACR,MAAM,QAAQ,KAAK,QAAQ,IAAI,EAAE,KAAK,KAAK;GAC3C,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,I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MAAM,SAAS,MAAM,SAAS,MAAM;EACxD,IAAI,KAAK,SAAS,GAAG,OAAO,KAAK,QAAQ,IAAI,MAAM;EAEnD,MAAM,OAAO,MAAM;EACnB,MAAM,WAAW;EACjB,MAAM,sBACJ,SAAS,KAAA,KAAa,KAAK,UAAU,KAAK,SAAS,KAAK,aAAa,KAAK,WACtE,MAAM,sBAAsB,IAC5B;EACN,MAAM,QAAQ,KAAK,QAAQ,0BAAA;EAC3B,IAAI,MAAM,uBAAuB,OAAO,OAAO,KAAK,QAAQ,IAAI,iBAAiB;EACjF,MAAM,MAAM,QAAQ;EACpB,KAAK,QAAQ,SAAS,IAAI,WAAW,KAAK,KAAK;CACjD;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
@@ -0,0 +1,16 @@
1
+ // src/project-list.ts
2
+ /**
3
+ * The entry of project `projectId`, from the list as the middle layer last read it. Only a project
4
+ * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the
5
+ * list from the backend again: a call on a known project costs no round trip. `undefined` when the
6
+ * fresh list does not have it either.
7
+ */
8
+ async function findListedProject(list, projectId) {
9
+ const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);
10
+ if (cached !== void 0) return cached;
11
+ await list.refreshState();
12
+ return (await list.awaitStableValue()).find((p) => p.id === projectId);
13
+ }
14
+ exports.findListedProject = findListedProject;
15
+
16
+ //# sourceMappingURL=project-list.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-list.cjs","names":[],"sources":["../src/project-list.ts"],"sourcesContent":["import type { ProjectId } from \"@milaboratories/pl-model-common\";\n\n/** The middle layer's project list, as {@link findListedProject} reads it. */\nexport type ProjectList<E extends { id: string }> = {\n /** The list as last read from the backend; kept fresh by the middle layer's own polling. */\n awaitStableValue(): Promise<readonly E[]>;\n /** Reads the list from the backend now. */\n refreshState(): Promise<void>;\n};\n\n/**\n * The entry of project `projectId`, from the list as the middle layer last read it. Only a project\n * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the\n * list from the backend again: a call on a known project costs no round trip. `undefined` when the\n * fresh list does not have it either.\n */\nexport async function findListedProject<E extends { id: string }>(\n list: ProjectList<E>,\n projectId: ProjectId,\n): Promise<E | undefined> {\n const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);\n if (cached !== undefined) return cached;\n await list.refreshState();\n return (await list.awaitStableValue()).find((p) => p.id === projectId);\n}\n"],"mappings":";;;;;;;AAgBA,eAAsB,kBACpB,MACA,WACwB;CACxB,MAAM,UAAU,MAAM,KAAK,iBAAiB,EAAA,CAAG,MAAM,MAAM,EAAE,OAAO,SAAS;CAC7E,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,KAAK,aAAa;CACxB,QAAQ,MAAM,KAAK,iBAAiB,EAAA,CAAG,MAAM,MAAM,EAAE,OAAO,SAAS;AACvE"}
@@ -0,0 +1,16 @@
1
+ // src/project-list.ts
2
+ /**
3
+ * The entry of project `projectId`, from the list as the middle layer last read it. Only a project
4
+ * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the
5
+ * list from the backend again: a call on a known project costs no round trip. `undefined` when the
6
+ * fresh list does not have it either.
7
+ */
8
+ async function findListedProject(list, projectId) {
9
+ const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);
10
+ if (cached !== void 0) return cached;
11
+ await list.refreshState();
12
+ return (await list.awaitStableValue()).find((p) => p.id === projectId);
13
+ }
14
+ export { findListedProject };
15
+
16
+ //# sourceMappingURL=project-list.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-list.js","names":[],"sources":["../src/project-list.ts"],"sourcesContent":["import type { ProjectId } from \"@milaboratories/pl-model-common\";\n\n/** The middle layer's project list, as {@link findListedProject} reads it. */\nexport type ProjectList<E extends { id: string }> = {\n /** The list as last read from the backend; kept fresh by the middle layer's own polling. */\n awaitStableValue(): Promise<readonly E[]>;\n /** Reads the list from the backend now. */\n refreshState(): Promise<void>;\n};\n\n/**\n * The entry of project `projectId`, from the list as the middle layer last read it. Only a project\n * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the\n * list from the backend again: a call on a known project costs no round trip. `undefined` when the\n * fresh list does not have it either.\n */\nexport async function findListedProject<E extends { id: string }>(\n list: ProjectList<E>,\n projectId: ProjectId,\n): Promise<E | undefined> {\n const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);\n if (cached !== undefined) return cached;\n await list.refreshState();\n return (await list.awaitStableValue()).find((p) => p.id === projectId);\n}\n"],"mappings":";;;;;;;AAgBA,eAAsB,kBACpB,MACA,WACwB;CACxB,MAAM,UAAU,MAAM,KAAK,iBAAiB,EAAA,CAAG,MAAM,MAAM,EAAE,OAAO,SAAS;CAC7E,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,KAAK,aAAa;CACxB,QAAQ,MAAM,KAAK,iBAAiB,EAAA,CAAG,MAAM,MAAM,EAAE,OAAO,SAAS;AACvE"}
@@ -1,13 +1,28 @@
1
1
  const require_types = require("./tools/types.cjs");
2
+ let _milaboratories_helpers = require("@milaboratories/helpers");
2
3
  let node_util = require("node:util");
4
+ let es_toolkit = require("es-toolkit");
3
5
  // src/server-log.ts
4
6
  /**
5
- * A call taking longer than this many milliseconds is reported as slow, unless its tool is one of
6
- * {@link WAITING_TOOLS}.
7
+ * A call taking longer than this many milliseconds is reported as slow, unless it was asked to
8
+ * wait ({@link waitsByDesign}).
7
9
  */
8
10
  const SLOW_CALL_MS = 5e3;
9
- /** Tools whose job is to wait: a long call of one of these is not reported as slow. */
10
- const WAITING_TOOLS = /* @__PURE__ */ new Set(["await_block_done"]);
11
+ /**
12
+ * Whether a call of `tool` with `args` was asked to wait, so that taking long is its job and not
13
+ * slowness: `await_block_done` always; `set_block_data` and `set_block_params` unless
14
+ * `wait: false` (they wait by default); `add_block` with `wait: true`.
15
+ */
16
+ function waitsByDesign(tool, args) {
17
+ const wait = typeof args === "object" && args !== null && "wait" in args ? args.wait : void 0;
18
+ switch (tool) {
19
+ case "await_block_done": return true;
20
+ case "set_block_data":
21
+ case "set_block_params": return wait !== false;
22
+ case "add_block": return wait === true;
23
+ default: return false;
24
+ }
25
+ }
11
26
  /** Longest id written to a line; a longer one is cut, so that a line stays a line. */
12
27
  const MAX_ID_LENGTH = 200;
13
28
  /** Longest error summary written to the first line of a failure; the whole text follows it. */
@@ -131,6 +146,18 @@ var ServerLog = class {
131
146
  })}`);
132
147
  }
133
148
  /**
149
+ * The server kept its hold on a project past the idle time: the project has `pending` pieces of
150
+ * work that need it loaded (`reason`: `imports`, files still uploading).
151
+ */
152
+ projectKept(projectId, reason, pending) {
153
+ this.write("info", () => `mcp-project-keep ${fields({
154
+ id: this.instanceId,
155
+ project: projectId,
156
+ reason,
157
+ pending
158
+ })}`);
159
+ }
160
+ /**
134
161
  * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
135
162
  * when the answer had already begun.
136
163
  */
@@ -165,7 +192,7 @@ var ServerLog = class {
165
192
  attempt(() => {
166
193
  call.projectId = stringProperty(args, "projectId");
167
194
  call.blockId = stringProperty(args, "blockId");
168
- call.argKeys = isRecord(args) ? Object.keys(args) : [];
195
+ call.argKeys = (0, _milaboratories_helpers.isPlainObject)(args) ? Object.keys(args) : [];
169
196
  call.argsBytes = jsonBytes(args);
170
197
  });
171
198
  attempt(() => {
@@ -215,7 +242,7 @@ var ServerLog = class {
215
242
  ...subject,
216
243
  ms
217
244
  })}`);
218
- if (ms !== void 0 && ms > this.slowCallMs && !WAITING_TOOLS.has(call.tool)) this.write("warn", () => `mcp-call-slow ${fields({
245
+ if (ms !== void 0 && ms > this.slowCallMs && attempt(() => waitsByDesign(call.tool, call.args)) !== true) this.write("warn", () => `mcp-call-slow ${fields({
219
246
  ...subject,
220
247
  ms,
221
248
  thresholdMs: this.slowCallMs
@@ -228,7 +255,7 @@ var ServerLog = class {
228
255
  write(level, line) {
229
256
  try {
230
257
  const returned = this.logger[level](this.secrets.redact(line()));
231
- if (isThenable(returned)) returned.then(void 0, () => {});
258
+ if ((0, es_toolkit.isPromise)(returned)) returned.then(void 0, () => {});
232
259
  } catch {}
233
260
  }
234
261
  };
@@ -240,14 +267,8 @@ function attempt(fn) {
240
267
  return;
241
268
  }
242
269
  }
243
- function isThenable(value) {
244
- return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
245
- }
246
- function isRecord(value) {
247
- return typeof value === "object" && value !== null && !Array.isArray(value);
248
- }
249
270
  function stringProperty(value, key) {
250
- if (!isRecord(value)) return void 0;
271
+ if (!(0, _milaboratories_helpers.isPlainObject)(value)) return void 0;
251
272
  const property = value[key];
252
273
  return typeof property === "string" ? property : void 0;
253
274
  }
@@ -264,19 +285,19 @@ function jsonBytes(value) {
264
285
  * not a tool result.
265
286
  */
266
287
  function contentBytes(result) {
267
- if (!isRecord(result) || !Array.isArray(result.content)) return void 0;
288
+ if (!(0, _milaboratories_helpers.isPlainObject)(result) || !Array.isArray(result.content)) return void 0;
268
289
  const textBytes = (text) => text === void 0 ? 0 : Buffer.byteLength(text);
269
290
  const dataLength = (data) => data?.length ?? 0;
270
291
  let bytes = 0;
271
292
  for (const item of result.content) {
272
- const resource = isRecord(item) ? item.resource : void 0;
293
+ const resource = (0, _milaboratories_helpers.isPlainObject)(item) ? item.resource : void 0;
273
294
  bytes += textBytes(stringProperty(item, "text")) + dataLength(stringProperty(item, "data")) + textBytes(stringProperty(resource, "text")) + dataLength(stringProperty(resource, "blob"));
274
295
  }
275
296
  return bytes;
276
297
  }
277
298
  /** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */
278
299
  function secretArgumentValues(args) {
279
- if (!isRecord(args)) return [];
300
+ if (!(0, _milaboratories_helpers.isPlainObject)(args)) return [];
280
301
  return Object.entries(args).filter(([key]) => SECRET_ARGUMENTS.has(key)).map(([, value]) => value).filter((value) => typeof value === "string");
281
302
  }
282
303
  /**
@@ -344,7 +365,7 @@ function fields(values) {
344
365
  function failureOf(finish) {
345
366
  if (finish.thrown) return errorText(finish.error);
346
367
  const result = finish.result;
347
- if (!isRecord(result) || result.isError !== true) return void 0;
368
+ if (!(0, _milaboratories_helpers.isPlainObject)(result) || result.isError !== true) return void 0;
348
369
  return (Array.isArray(result.content) ? result.content : []).map((item) => stringProperty(item, "text")).filter((text) => text !== void 0).join("\n");
349
370
  }
350
371
  function errorMessage(error) {
@@ -369,5 +390,6 @@ function errorText(error) {
369
390
  exports.SLOW_CALL_MS = SLOW_CALL_MS;
370
391
  exports.ServerLog = ServerLog;
371
392
  exports.fields = fields;
393
+ exports.waitsByDesign = waitsByDesign;
372
394
 
373
395
  //# sourceMappingURL=server-log.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-log.cjs","names":["isTimedOutResult","inspect"],"sources":["../src/server-log.ts"],"sourcesContent":["import type { MiLogger } from \"@milaboratories/helpers\";\nimport type { ProjectId } from \"@milaboratories/pl-model-common\";\nimport { inspect } from \"node:util\";\nimport type { McpInstanceId } from \"./server\";\nimport type { ToolRegistrar } from \"./tools/types\";\nimport { isTimedOutResult } from \"./tools/types\";\n\n/**\n * A call taking longer than this many milliseconds is reported as slow, unless its tool is one of\n * {@link WAITING_TOOLS}.\n */\nexport const SLOW_CALL_MS = 5000;\n\n/** Tools whose job is to wait: a long call of one of these is not reported as slow. */\nconst WAITING_TOOLS: ReadonlySet<string> = new Set([\"await_block_done\"]);\n\n/** Longest id written to a line; a longer one is cut, so that a line stays a line. */\nconst MAX_ID_LENGTH = 200;\n\n/** Longest error summary written to the first line of a failure; the whole text follows it. */\nconst MAX_SUMMARY_LENGTH = 300;\n\n/**\n * How deep an error is written: each error of a `cause` chain is one level, and so is each nested\n * object in a property of an error. What lies deeper is written as its class only (`[Error]`).\n */\nconst MAX_ERROR_DEPTH = 6;\n\n/**\n * Top-level arguments whose values are secrets, by key name: their values are removed from the\n * text of a failure like the secret of the server. `password` (of `connect_to_server`) is the one\n * such argument a tool has now; the others are the names a credential would get. Block data is not\n * searched: like the rest of the application's log, this one may quote it.\n */\nconst SECRET_ARGUMENTS: ReadonlySet<string> = new Set([\"password\", \"token\", \"secret\", \"apiKey\"]);\n\n/** What replaces a secret in a line. */\nconst SECRET_MARK = \"<secret>\";\n\n/** A value that needs no quotes to stay one `key=value` token. */\nconst BARE_VALUE = /^[A-Za-z0-9_.:#+\\-/@,]+$/;\n\n/** How a tool call ended. */\nexport type CallOutcome =\n /** The handler returned a result. */\n | \"ok\"\n /** The handler returned a result with `isError: true`. */\n | \"error\"\n /** The handler threw. */\n | \"thrown\";\n\n/** The counters of one backend client, read at a moment. */\nexport type TxCounters = {\n /** The client the counters belong to: numbers of two clients are not compared. */\n client: object;\n /** Write transactions that failed to commit because of a conflict and were retried, so far. */\n conflicts: number;\n};\n\n/** What a {@link ServerLog} is made of. */\nexport type ServerLogOptions = {\n /** Where the lines go. */\n logger: MiLogger;\n /** Id of the server instance, the first part of every call id: `mcp-<8 hex>`. */\n instanceId: McpInstanceId;\n /** Reads the counters of the connected backend client; `undefined` when there is none. */\n txCounters?: () => TxCounters | undefined;\n /** Strings that must not reach the log. An occurrence in a line is replaced with `<secret>`. */\n secrets?: readonly string[];\n /** See {@link SLOW_CALL_MS}. */\n slowCallMs?: number;\n /** Clock in milliseconds; only differences are used. */\n now?: () => number;\n};\n\n/** What is known about a call when it starts. */\ntype StartedCall = {\n id: string;\n /**\n * The arguments, as the handler got them. They are not written: they are read only to find the\n * values of secret arguments (see {@link SECRET_ARGUMENTS}), and only when the call failed.\n */\n args: unknown;\n tool: string;\n /** Other calls that were being served when this one started. */\n inFlight: number;\n startedAt: number | undefined;\n projectId: string | undefined;\n blockId: string | undefined;\n argsBytes: number | undefined;\n argKeys: string[] | undefined;\n tx: TxCounters | undefined;\n};\n\n/** How a handler finished. */\ntype Finish = { thrown: false; result: unknown } | { thrown: true; error: unknown };\n\n/**\n * Writes what the MCP server does to a logger: one line per tool call, more for a call that\n * failed, was slow or ran out of time, and lines for the server's start, stop and the failures\n * that happen outside tool handlers.\n *\n * Two rules hold for everything here. No secret is ever written: neither the secret of the server\n * nor the value of a secret argument (see {@link SECRET_ARGUMENTS}); each is replaced with\n * `<secret>`. The line of a call holds of its arguments only sizes, the names of the top-level\n * ones and the project and block ids; the line of a failure holds the error as it is, which can\n * quote other arguments and data, as the rest of the application's log does. And nothing here\n * throws: a logger that fails, or a value that cannot be measured, costs a line or a field, never\n * the call.\n */\nexport class ServerLog {\n private readonly logger: MiLogger;\n private readonly instanceId: McpInstanceId;\n private readonly txCounters: () => TxCounters | undefined;\n /** Removes the secrets from a text; for the lines and fields that are not about a call's arguments. */\n private readonly secrets: Redactor;\n private readonly slowCallMs: number;\n private readonly now: () => number;\n\n /** Calls started so far; the number of the last one. */\n private calls = 0;\n /** Calls being served now. */\n private inFlight = 0;\n\n constructor(options: ServerLogOptions) {\n this.logger = options.logger;\n this.instanceId = options.instanceId;\n this.txCounters = options.txCounters ?? (() => undefined);\n this.secrets = new Redactor(options.secrets ?? []);\n this.slowCallMs = options.slowCallMs ?? SLOW_CALL_MS;\n this.now = options.now ?? (() => performance.now());\n }\n\n /**\n * Returns a registrar that registers tools with `target` and logs every call of them.\n *\n * The handler itself is left as given: the logging goes around the function the SDK calls to run\n * the tool (`RegisteredTool.executor`), which receives the arguments after validation. The SDK\n * makes that function anew when a tool's handler or input schema is replaced with\n * `RegisteredTool.update`, which would drop the logging; no tool of this server does that.\n */\n registrar(target: ToolRegistrar): ToolRegistrar {\n return {\n registerTool: (name, config, cb) => {\n const tool = target.registerTool(name, config, cb);\n const execute = tool.executor;\n tool.executor = (args, ctx) => this.run(name, args, () => execute(args, ctx));\n return tool;\n },\n };\n }\n\n /**\n * Runs one tool call and logs how it went. Returns what `execute` returns and throws what it\n * throws, whatever happens to the logging.\n */\n async run<T>(tool: string, args: unknown, execute: () => Promise<T>): Promise<T> {\n const call = this.begin(tool, args);\n let result: T;\n try {\n result = await execute();\n } catch (error: unknown) {\n this.finish(call, { thrown: true, error });\n throw error;\n }\n this.finish(call, { thrown: false, result });\n return result;\n }\n\n /** The server listens on `port`. */\n serverStarted(port: number, version: string): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-start ${fields({\n id: this.instanceId,\n port,\n url: `http://127.0.0.1:${port}/<secret>/mcp`,\n version,\n })}`,\n );\n }\n\n /** The server no longer listens on `port`. */\n serverStopped(port: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-stop ${fields({\n id: this.instanceId,\n port,\n calls: this.calls,\n inflight: this.inFlight,\n })}`,\n );\n }\n\n /** The server gave back its hold on a project it had kept loaded between calls. */\n projectReleased(projectId: ProjectId, reason: string): void {\n this.write(\n \"info\",\n () => `mcp-project-release ${fields({ id: this.instanceId, project: projectId, reason })}`,\n );\n }\n\n /**\n * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent\n * when the answer had already begun.\n */\n requestFailed(method: string | undefined, status: number | undefined, error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-request-failed ${fields({\n id: this.instanceId,\n method,\n status,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n /** The MCP handler reported an error that no tool call accounts for. */\n sdkError(error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-sdk-error ${fields({\n id: this.instanceId,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n private begin(tool: string, args: unknown): StartedCall {\n const call: StartedCall = {\n id: `${this.instanceId}#${++this.calls}`,\n args,\n tool,\n inFlight: this.inFlight++,\n startedAt: undefined,\n projectId: undefined,\n blockId: undefined,\n argsBytes: undefined,\n argKeys: undefined,\n tx: undefined,\n };\n attempt(() => {\n call.projectId = stringProperty(args, \"projectId\");\n call.blockId = stringProperty(args, \"blockId\");\n call.argKeys = isRecord(args) ? Object.keys(args) : [];\n call.argsBytes = jsonBytes(args);\n });\n attempt(() => {\n call.tx = this.txCounters();\n });\n attempt(() => {\n call.startedAt = this.now();\n });\n return call;\n }\n\n private finish(call: StartedCall, finish: Finish): void {\n this.inFlight--;\n\n const ms = attempt(() =>\n call.startedAt === undefined ? undefined : Math.round(this.now() - call.startedAt),\n );\n const failure = attempt(() => failureOf(finish));\n const outcome: CallOutcome = finish.thrown ? \"thrown\" : failure === undefined ? \"ok\" : \"error\";\n // A secret is removed before an id is cut, so that no part of it is left.\n const subject = {\n call: call.id,\n tool: call.tool,\n project: attempt(() => cut(this.secrets.redact(call.projectId))),\n block: attempt(() => cut(this.secrets.redact(call.blockId))),\n };\n\n this.write(\"info\", () => {\n const before = call.tx;\n const after = before === undefined ? undefined : attempt(() => this.txCounters());\n return `mcp-call ${fields({\n ...subject,\n argsBytes: call.argsBytes,\n ms,\n outcome,\n // Nothing was returned by a handler that threw.\n resultBytes: finish.thrown ? 0 : attempt(() => contentBytes(finish.result)),\n inflight: call.inFlight,\n // Counted on the backend client, so every call in flight at the time gets the same number.\n txConflictsDuring:\n before !== undefined && after !== undefined && before.client === after.client\n ? after.conflicts - before.conflicts\n : undefined,\n })}`;\n });\n\n if (outcome !== \"ok\")\n this.write(\"error\", () => {\n // Secrets are removed from the whole texts, before any is cut: a secret cut in two would\n // no longer be found.\n const secrets = this.secrets.with(secretArgumentValues(call.args));\n const text = secrets.redact(failure ?? \"\");\n const message = finish.thrown ? secrets.redact(errorMessage(finish.error)) : text;\n return `mcp-call-failed ${fields({\n ...subject,\n outcome,\n argKeys: (call.argKeys ?? []).join(\",\"),\n error: summary(message),\n })}\\n${text}`;\n });\n\n if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)\n this.write(\"warn\", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);\n\n if (ms !== undefined && ms > this.slowCallMs && !WAITING_TOOLS.has(call.tool))\n this.write(\n \"warn\",\n () => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,\n );\n }\n\n /**\n * Writes one line, built by `line`. Neither building it nor the logger can make this throw, and a\n * logger that returns a promise cannot make it reject unhandled.\n */\n private write(level: \"info\" | \"warn\" | \"error\", line: () => string): void {\n try {\n // The texts in a line were redacted before they were cut; this pass over the whole line is\n // for anything that still holds a secret.\n const returned: unknown = this.logger[level](this.secrets.redact(line()));\n if (isThenable(returned)) void returned.then(undefined, () => {});\n } catch {\n // A line is lost. The call it describes must not be.\n }\n }\n}\n\n/** Runs `fn`; a failure gives `undefined`. For the measurements a line can do without. */\nfunction attempt<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringProperty(value: unknown, key: string): string | undefined {\n if (!isRecord(value)) return undefined;\n const property = value[key];\n return typeof property === \"string\" ? property : undefined;\n}\n\n/** Size of `value` written as JSON, in bytes of UTF-8; 0 for a value JSON has no form for. */\nfunction jsonBytes(value: unknown): number {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : Buffer.byteLength(json);\n}\n\n/**\n * Size of what a tool result carries to the agent: the UTF-8 bytes of its texts plus the length of\n * its base64 data (images, audio, binary resources) as sent. It is the size of the content, not of\n * the JSON the result is sent as: the envelope, the escaping and `structuredContent` are not\n * counted, and the result is not serialized again to measure it. `undefined` for a value that is\n * not a tool result.\n */\nfunction contentBytes(result: unknown): number | undefined {\n if (!isRecord(result) || !Array.isArray(result.content)) return undefined;\n const textBytes = (text: string | undefined) =>\n text === undefined ? 0 : Buffer.byteLength(text);\n const dataLength = (data: string | undefined) => data?.length ?? 0;\n let bytes = 0;\n for (const item of result.content) {\n const resource = isRecord(item) ? item.resource : undefined;\n bytes +=\n textBytes(stringProperty(item, \"text\")) +\n dataLength(stringProperty(item, \"data\")) +\n textBytes(stringProperty(resource, \"text\")) +\n dataLength(stringProperty(resource, \"blob\"));\n }\n return bytes;\n}\n\n/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */\nfunction secretArgumentValues(args: unknown): string[] {\n if (!isRecord(args)) return [];\n return Object.entries(args)\n .filter(([key]) => SECRET_ARGUMENTS.has(key))\n .map(([, value]) => value)\n .filter((value) => typeof value === \"string\");\n}\n\n/**\n * Replaces each of a few strings in a text with `<secret>`, the longest first, so a secret that\n * contains another is replaced whole. A secret is also found in the escaped forms it takes in a\n * formatted text: inside a JSON string and inside a string written by `util.inspect` (the\n * properties of an error), where a backslash or a quote is written with a backslash.\n */\nclass Redactor {\n /** The secrets as given. */\n private readonly given: readonly string[];\n /** Every form of every secret, the longest first. */\n private readonly forms: readonly string[];\n\n constructor(secrets: Iterable<string>) {\n this.given = [...new Set(secrets)].filter((secret) => secret.length > 0);\n this.forms = [...new Set(this.given.flatMap(escapedForms))].sort((a, b) => b.length - a.length);\n }\n\n /** A redactor that removes `more` as well. */\n with(more: Iterable<string>): Redactor {\n return new Redactor([...this.given, ...more]);\n }\n\n redact(text: string): string;\n redact(text: string | undefined): string | undefined;\n redact(text: string | undefined): string | undefined {\n if (text === undefined) return text;\n let redacted = text;\n for (const form of this.forms) redacted = redacted.replaceAll(form, SECRET_MARK);\n return redacted;\n }\n}\n\n/** A secret as it is, and as it is written inside a JSON string and by `util.inspect`. */\nfunction escapedForms(secret: string): string[] {\n return [secret, JSON.stringify(secret).slice(1, -1), inspect(secret).slice(1, -1)];\n}\n\nfunction cut(id: string | undefined): string | undefined {\n if (id === undefined || id.length <= MAX_ID_LENGTH) return id;\n return `${id.slice(0, MAX_ID_LENGTH)}…`;\n}\n\n/** The first line of `text`, cut to a length that fits the first line of a log entry. */\nfunction summary(text: string): string {\n const firstLine = text.split(\"\\n\", 1)[0] ?? \"\";\n return firstLine.length <= MAX_SUMMARY_LENGTH\n ? firstLine\n : `${firstLine.slice(0, MAX_SUMMARY_LENGTH)}…`;\n}\n\n/**\n * Writes fields as `key=value` separated by spaces, in the order given, leaving out the undefined\n * ones. A value with a space, a quote or anything else outside {@link BARE_VALUE} is written as a\n * JSON string, so a line never breaks and a field never runs into the next one.\n */\nexport function fields(values: Record<string, string | number | undefined>): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const text = String(value);\n parts.push(`${key}=${BARE_VALUE.test(text) ? text : JSON.stringify(text)}`);\n }\n return parts.join(\" \");\n}\n\n/**\n * The text of a failed call: of a thrown error, the error with its causes (see {@link errorText});\n * of a result with `isError: true`, its text as the handler wrote it. `undefined` for a call that\n * succeeded.\n */\nfunction failureOf(finish: Finish): string | undefined {\n if (finish.thrown) return errorText(finish.error);\n const result = finish.result;\n if (!isRecord(result) || result.isError !== true) return undefined;\n const content = Array.isArray(result.content) ? result.content : [];\n return content\n .map((item: unknown) => stringProperty(item, \"text\"))\n .filter((text) => text !== undefined)\n .join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === \"string\" ? error : describeValue(error);\n}\n\nfunction describeValue(value: unknown): string {\n return attempt(() => JSON.stringify(value)) ?? String(value);\n}\n\n/**\n * Writes an error with everything a reader needs to find where it came from, as Node writes it:\n * the stack of the error, its other properties and every error of its `cause` chain with its\n * stack, up to {@link MAX_ERROR_DEPTH}. A thrown string is written as it is.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") return error;\n return attempt(() => inspect(error, { colors: false, depth: MAX_ERROR_DEPTH })) ?? String(error);\n}\n"],"mappings":";;;;;;;AAWA,MAAa,eAAe;;AAG5B,MAAM,gCAAqC,IAAI,IAAI,CAAC,kBAAkB,CAAC;;AAGvE,MAAM,gBAAgB;;AAGtB,MAAM,qBAAqB;;;;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AAChE;AAEA,SAAS,cAAc,OAAwB;CAC7C,OAAO,cAAc,KAAK,UAAU,KAAK,CAAC,KAAK,OAAO,KAAK;AAC7D;;;;;;AAOA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,eAAA,GAAcA,UAAAA,QAAAA,CAAQ,OAAO;EAAE,QAAQ;EAAO,OAAO;CAAgB,CAAC,CAAC,KAAK,OAAO,KAAK;AACjG"}
1
+ {"version":3,"file":"server-log.cjs","names":["isPlainObject","isTimedOutResult","isPromise","inspect"],"sources":["../src/server-log.ts"],"sourcesContent":["import { isPlainObject, type MiLogger } from \"@milaboratories/helpers\";\nimport type { ProjectId } from \"@milaboratories/pl-model-common\";\nimport { inspect } from \"node:util\";\nimport { isPromise } from \"es-toolkit\";\nimport type { McpInstanceId } from \"./server\";\nimport type { ToolRegistrar } from \"./tools/types\";\nimport { isTimedOutResult } from \"./tools/types\";\n\n/**\n * A call taking longer than this many milliseconds is reported as slow, unless it was asked to\n * wait ({@link waitsByDesign}).\n */\nexport const SLOW_CALL_MS = 5000;\n\n/**\n * Whether a call of `tool` with `args` was asked to wait, so that taking long is its job and not\n * slowness: `await_block_done` always; `set_block_data` and `set_block_params` unless\n * `wait: false` (they wait by default); `add_block` with `wait: true`.\n */\nexport function waitsByDesign(tool: string, args: unknown): boolean {\n const wait = typeof args === \"object\" && args !== null && \"wait\" in args ? args.wait : undefined;\n switch (tool) {\n case \"await_block_done\":\n return true;\n case \"set_block_data\":\n case \"set_block_params\":\n return wait !== false;\n case \"add_block\":\n return wait === true;\n default:\n return false;\n }\n}\n\n/** Longest id written to a line; a longer one is cut, so that a line stays a line. */\nconst MAX_ID_LENGTH = 200;\n\n/** Longest error summary written to the first line of a failure; the whole text follows it. */\nconst MAX_SUMMARY_LENGTH = 300;\n\n/**\n * How deep an error is written: each error of a `cause` chain is one level, and so is each nested\n * object in a property of an error. What lies deeper is written as its class only (`[Error]`).\n */\nconst MAX_ERROR_DEPTH = 6;\n\n/**\n * Top-level arguments whose values are secrets, by key name: their values are removed from the\n * text of a failure like the secret of the server. `password` (of `connect_to_server`) is the one\n * such argument a tool has now; the others are the names a credential would get. Block data is not\n * searched: like the rest of the application's log, this one may quote it.\n */\nconst SECRET_ARGUMENTS: ReadonlySet<string> = new Set([\"password\", \"token\", \"secret\", \"apiKey\"]);\n\n/** What replaces a secret in a line. */\nconst SECRET_MARK = \"<secret>\";\n\n/** A value that needs no quotes to stay one `key=value` token. */\nconst BARE_VALUE = /^[A-Za-z0-9_.:#+\\-/@,]+$/;\n\n/** How a tool call ended. */\nexport type CallOutcome =\n /** The handler returned a result. */\n | \"ok\"\n /** The handler returned a result with `isError: true`. */\n | \"error\"\n /** The handler threw. */\n | \"thrown\";\n\n/** The counters of one backend client, read at a moment. */\nexport type TxCounters = {\n /** The client the counters belong to: numbers of two clients are not compared. */\n client: object;\n /** Write transactions that failed to commit because of a conflict and were retried, so far. */\n conflicts: number;\n};\n\n/** What a {@link ServerLog} is made of. */\nexport type ServerLogOptions = {\n /** Where the lines go. */\n logger: MiLogger;\n /** Id of the server instance, the first part of every call id: `mcp-<8 hex>`. */\n instanceId: McpInstanceId;\n /** Reads the counters of the connected backend client; `undefined` when there is none. */\n txCounters?: () => TxCounters | undefined;\n /** Strings that must not reach the log. An occurrence in a line is replaced with `<secret>`. */\n secrets?: readonly string[];\n /** See {@link SLOW_CALL_MS}. */\n slowCallMs?: number;\n /** Clock in milliseconds; only differences are used. */\n now?: () => number;\n};\n\n/** What is known about a call when it starts. */\ntype StartedCall = {\n id: string;\n /**\n * The arguments, as the handler got them. They are not written: they are read only to find the\n * values of secret arguments (see {@link SECRET_ARGUMENTS}) when the call failed, and to tell\n * whether it was asked to wait ({@link waitsByDesign}).\n */\n args: unknown;\n tool: string;\n /** Other calls that were being served when this one started. */\n inFlight: number;\n startedAt: number | undefined;\n projectId: string | undefined;\n blockId: string | undefined;\n argsBytes: number | undefined;\n argKeys: string[] | undefined;\n tx: TxCounters | undefined;\n};\n\n/** How a handler finished. */\ntype Finish = { thrown: false; result: unknown } | { thrown: true; error: unknown };\n\n/**\n * Writes what the MCP server does to a logger: one line per tool call, more for a call that\n * failed, was slow or ran out of time, and lines for the server's start, stop and the failures\n * that happen outside tool handlers.\n *\n * Two rules hold for everything here. No secret is ever written: neither the secret of the server\n * nor the value of a secret argument (see {@link SECRET_ARGUMENTS}); each is replaced with\n * `<secret>`. The line of a call holds of its arguments only sizes, the names of the top-level\n * ones and the project and block ids; the line of a failure holds the error as it is, which can\n * quote other arguments and data, as the rest of the application's log does. And nothing here\n * throws: a logger that fails, or a value that cannot be measured, costs a line or a field, never\n * the call.\n */\nexport class ServerLog {\n private readonly logger: MiLogger;\n private readonly instanceId: McpInstanceId;\n private readonly txCounters: () => TxCounters | undefined;\n /** Removes the secrets from a text; for the lines and fields that are not about a call's arguments. */\n private readonly secrets: Redactor;\n private readonly slowCallMs: number;\n private readonly now: () => number;\n\n /** Calls started so far; the number of the last one. */\n private calls = 0;\n /** Calls being served now. */\n private inFlight = 0;\n\n constructor(options: ServerLogOptions) {\n this.logger = options.logger;\n this.instanceId = options.instanceId;\n this.txCounters = options.txCounters ?? (() => undefined);\n this.secrets = new Redactor(options.secrets ?? []);\n this.slowCallMs = options.slowCallMs ?? SLOW_CALL_MS;\n this.now = options.now ?? (() => performance.now());\n }\n\n /**\n * Returns a registrar that registers tools with `target` and logs every call of them.\n *\n * The handler itself is left as given: the logging goes around the function the SDK calls to run\n * the tool (`RegisteredTool.executor`), which receives the arguments after validation. The SDK\n * makes that function anew when a tool's handler or input schema is replaced with\n * `RegisteredTool.update`, which would drop the logging; no tool of this server does that.\n */\n registrar(target: ToolRegistrar): ToolRegistrar {\n return {\n registerTool: (name, config, cb) => {\n const tool = target.registerTool(name, config, cb);\n const execute = tool.executor;\n tool.executor = (args, ctx) => this.run(name, args, () => execute(args, ctx));\n return tool;\n },\n };\n }\n\n /**\n * Runs one tool call and logs how it went. Returns what `execute` returns and throws what it\n * throws, whatever happens to the logging.\n */\n async run<T>(tool: string, args: unknown, execute: () => Promise<T>): Promise<T> {\n const call = this.begin(tool, args);\n let result: T;\n try {\n result = await execute();\n } catch (error: unknown) {\n this.finish(call, { thrown: true, error });\n throw error;\n }\n this.finish(call, { thrown: false, result });\n return result;\n }\n\n /** The server listens on `port`. */\n serverStarted(port: number, version: string): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-start ${fields({\n id: this.instanceId,\n port,\n url: `http://127.0.0.1:${port}/<secret>/mcp`,\n version,\n })}`,\n );\n }\n\n /** The server no longer listens on `port`. */\n serverStopped(port: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-stop ${fields({\n id: this.instanceId,\n port,\n calls: this.calls,\n inflight: this.inFlight,\n })}`,\n );\n }\n\n /** The server gave back its hold on a project it had kept loaded between calls. */\n projectReleased(projectId: ProjectId, reason: string): void {\n this.write(\n \"info\",\n () => `mcp-project-release ${fields({ id: this.instanceId, project: projectId, reason })}`,\n );\n }\n\n /**\n * The server kept its hold on a project past the idle time: the project has `pending` pieces of\n * work that need it loaded (`reason`: `imports`, files still uploading).\n */\n projectKept(projectId: ProjectId, reason: string, pending: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-project-keep ${fields({ id: this.instanceId, project: projectId, reason, pending })}`,\n );\n }\n\n /**\n * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent\n * when the answer had already begun.\n */\n requestFailed(method: string | undefined, status: number | undefined, error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-request-failed ${fields({\n id: this.instanceId,\n method,\n status,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n /** The MCP handler reported an error that no tool call accounts for. */\n sdkError(error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-sdk-error ${fields({\n id: this.instanceId,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n private begin(tool: string, args: unknown): StartedCall {\n const call: StartedCall = {\n id: `${this.instanceId}#${++this.calls}`,\n args,\n tool,\n inFlight: this.inFlight++,\n startedAt: undefined,\n projectId: undefined,\n blockId: undefined,\n argsBytes: undefined,\n argKeys: undefined,\n tx: undefined,\n };\n attempt(() => {\n call.projectId = stringProperty(args, \"projectId\");\n call.blockId = stringProperty(args, \"blockId\");\n call.argKeys = isPlainObject(args) ? Object.keys(args) : [];\n call.argsBytes = jsonBytes(args);\n });\n attempt(() => {\n call.tx = this.txCounters();\n });\n attempt(() => {\n call.startedAt = this.now();\n });\n return call;\n }\n\n private finish(call: StartedCall, finish: Finish): void {\n this.inFlight--;\n\n const ms = attempt(() =>\n call.startedAt === undefined ? undefined : Math.round(this.now() - call.startedAt),\n );\n const failure = attempt(() => failureOf(finish));\n const outcome: CallOutcome = finish.thrown ? \"thrown\" : failure === undefined ? \"ok\" : \"error\";\n // A secret is removed before an id is cut, so that no part of it is left.\n const subject = {\n call: call.id,\n tool: call.tool,\n project: attempt(() => cut(this.secrets.redact(call.projectId))),\n block: attempt(() => cut(this.secrets.redact(call.blockId))),\n };\n\n this.write(\"info\", () => {\n const before = call.tx;\n const after = before === undefined ? undefined : attempt(() => this.txCounters());\n return `mcp-call ${fields({\n ...subject,\n argsBytes: call.argsBytes,\n ms,\n outcome,\n // Nothing was returned by a handler that threw.\n resultBytes: finish.thrown ? 0 : attempt(() => contentBytes(finish.result)),\n inflight: call.inFlight,\n // Counted on the backend client, so every call in flight at the time gets the same number.\n txConflictsDuring:\n before !== undefined && after !== undefined && before.client === after.client\n ? after.conflicts - before.conflicts\n : undefined,\n })}`;\n });\n\n if (outcome !== \"ok\")\n this.write(\"error\", () => {\n // Secrets are removed from the whole texts, before any is cut: a secret cut in two would\n // no longer be found.\n const secrets = this.secrets.with(secretArgumentValues(call.args));\n const text = secrets.redact(failure ?? \"\");\n const message = finish.thrown ? secrets.redact(errorMessage(finish.error)) : text;\n return `mcp-call-failed ${fields({\n ...subject,\n outcome,\n argKeys: (call.argKeys ?? []).join(\",\"),\n error: summary(message),\n })}\\n${text}`;\n });\n\n if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)\n this.write(\"warn\", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);\n\n if (\n ms !== undefined &&\n ms > this.slowCallMs &&\n attempt(() => waitsByDesign(call.tool, call.args)) !== true\n )\n this.write(\n \"warn\",\n () => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,\n );\n }\n\n /**\n * Writes one line, built by `line`. Neither building it nor the logger can make this throw, and a\n * logger that returns a promise cannot make it reject unhandled.\n */\n private write(level: \"info\" | \"warn\" | \"error\", line: () => string): void {\n try {\n // The texts in a line were redacted before they were cut; this pass over the whole line is\n // for anything that still holds a secret.\n const returned: unknown = this.logger[level](this.secrets.redact(line()));\n if (isPromise(returned)) void returned.then(undefined, () => {});\n } catch {\n // A line is lost. The call it describes must not be.\n }\n }\n}\n\n/** Runs `fn`; a failure gives `undefined`. For the measurements a line can do without. */\nfunction attempt<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n\nfunction stringProperty(value: unknown, key: string): string | undefined {\n if (!isPlainObject(value)) return undefined;\n const property = value[key];\n return typeof property === \"string\" ? property : undefined;\n}\n\n/** Size of `value` written as JSON, in bytes of UTF-8; 0 for a value JSON has no form for. */\nfunction jsonBytes(value: unknown): number {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : Buffer.byteLength(json);\n}\n\n/**\n * Size of what a tool result carries to the agent: the UTF-8 bytes of its texts plus the length of\n * its base64 data (images, audio, binary resources) as sent. It is the size of the content, not of\n * the JSON the result is sent as: the envelope, the escaping and `structuredContent` are not\n * counted, and the result is not serialized again to measure it. `undefined` for a value that is\n * not a tool result.\n */\nfunction contentBytes(result: unknown): number | undefined {\n if (!isPlainObject(result) || !Array.isArray(result.content)) return undefined;\n const textBytes = (text: string | undefined) =>\n text === undefined ? 0 : Buffer.byteLength(text);\n const dataLength = (data: string | undefined) => data?.length ?? 0;\n let bytes = 0;\n for (const item of result.content) {\n const resource = isPlainObject(item) ? item.resource : undefined;\n bytes +=\n textBytes(stringProperty(item, \"text\")) +\n dataLength(stringProperty(item, \"data\")) +\n textBytes(stringProperty(resource, \"text\")) +\n dataLength(stringProperty(resource, \"blob\"));\n }\n return bytes;\n}\n\n/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */\nfunction secretArgumentValues(args: unknown): string[] {\n if (!isPlainObject(args)) return [];\n return Object.entries(args)\n .filter(([key]) => SECRET_ARGUMENTS.has(key))\n .map(([, value]) => value)\n .filter((value) => typeof value === \"string\");\n}\n\n/**\n * Replaces each of a few strings in a text with `<secret>`, the longest first, so a secret that\n * contains another is replaced whole. A secret is also found in the escaped forms it takes in a\n * formatted text: inside a JSON string and inside a string written by `util.inspect` (the\n * properties of an error), where a backslash or a quote is written with a backslash.\n */\nclass Redactor {\n /** The secrets as given. */\n private readonly given: readonly string[];\n /** Every form of every secret, the longest first. */\n private readonly forms: readonly string[];\n\n constructor(secrets: Iterable<string>) {\n this.given = [...new Set(secrets)].filter((secret) => secret.length > 0);\n this.forms = [...new Set(this.given.flatMap(escapedForms))].sort((a, b) => b.length - a.length);\n }\n\n /** A redactor that removes `more` as well. */\n with(more: Iterable<string>): Redactor {\n return new Redactor([...this.given, ...more]);\n }\n\n redact(text: string): string;\n redact(text: string | undefined): string | undefined;\n redact(text: string | undefined): string | undefined {\n if (text === undefined) return text;\n let redacted = text;\n for (const form of this.forms) redacted = redacted.replaceAll(form, SECRET_MARK);\n return redacted;\n }\n}\n\n/** A secret as it is, and as it is written inside a JSON string and by `util.inspect`. */\nfunction escapedForms(secret: string): string[] {\n return [secret, JSON.stringify(secret).slice(1, -1), inspect(secret).slice(1, -1)];\n}\n\nfunction cut(id: string | undefined): string | undefined {\n if (id === undefined || id.length <= MAX_ID_LENGTH) return id;\n return `${id.slice(0, MAX_ID_LENGTH)}…`;\n}\n\n/** The first line of `text`, cut to a length that fits the first line of a log entry. */\nfunction summary(text: string): string {\n const firstLine = text.split(\"\\n\", 1)[0] ?? \"\";\n return firstLine.length <= MAX_SUMMARY_LENGTH\n ? firstLine\n : `${firstLine.slice(0, MAX_SUMMARY_LENGTH)}…`;\n}\n\n/**\n * Writes fields as `key=value` separated by spaces, in the order given, leaving out the undefined\n * ones. A value with a space, a quote or anything else outside {@link BARE_VALUE} is written as a\n * JSON string, so a line never breaks and a field never runs into the next one.\n */\nexport function fields(values: Record<string, string | number | undefined>): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const text = String(value);\n parts.push(`${key}=${BARE_VALUE.test(text) ? text : JSON.stringify(text)}`);\n }\n return parts.join(\" \");\n}\n\n/**\n * The text of a failed call: of a thrown error, the error with its causes (see {@link errorText});\n * of a result with `isError: true`, its text as the handler wrote it. `undefined` for a call that\n * succeeded.\n */\nfunction failureOf(finish: Finish): string | undefined {\n if (finish.thrown) return errorText(finish.error);\n const result = finish.result;\n if (!isPlainObject(result) || result.isError !== true) return undefined;\n const content = Array.isArray(result.content) ? result.content : [];\n return content\n .map((item: unknown) => stringProperty(item, \"text\"))\n .filter((text) => text !== undefined)\n .join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === \"string\" ? error : describeValue(error);\n}\n\nfunction describeValue(value: unknown): string {\n return attempt(() => JSON.stringify(value)) ?? String(value);\n}\n\n/**\n * Writes an error with everything a reader needs to find where it came from, as Node writes it:\n * the stack of the error, its other properties and every error of its `cause` chain with its\n * stack, up to {@link MAX_ERROR_DEPTH}. A thrown string is written as it is.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") return error;\n return attempt(() => inspect(error, { colors: false, depth: MAX_ERROR_DEPTH })) ?? String(error);\n}\n"],"mappings":";;;;;;;;;AAYA,MAAa,eAAe;;;;;;AAO5B,SAAgB,cAAc,MAAc,MAAw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