hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unavailableExecutor = exports.RunRegistry = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.RunError = exports.isFinal = void 0;
3
+ exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ const oauth_1 = require("./oauth");
5
6
  const run_logs_1 = require("./run-logs");
6
7
  const units_1 = require("../utils/units");
7
8
  const FINAL_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
@@ -9,6 +10,11 @@ function isFinal(state) {
9
10
  return FINAL_STATES.includes(state);
10
11
  }
11
12
  exports.isFinal = isFinal;
13
+ // What an executor reports while it works. `seq` and `time` are added by the registry.
14
+ // The steps of a run before its tasks: `source` gets its files (a checkout of the commit, or
15
+ // those of the sandbox), `namespace` prepares its place on the cluster, `plan` starts the
16
+ // process of the run and reads its build files.
17
+ exports.RUN_PHASES = ['source', 'namespace', 'plan'];
12
18
  // The server can not take the run now; `status` is what the caller is told
13
19
  class RunError extends Error {
14
20
  constructor() {
@@ -27,9 +33,31 @@ class QuotaError extends RunError {
27
33
  exports.QuotaError = QuotaError;
28
34
  exports.RUN_ID_PATTERN = /^run_[A-Za-z0-9_-]{16}$/;
29
35
  exports.SANDBOX_ID_PATTERN = /^sbx_[A-Za-z0-9_-]{16}$/;
36
+ // A service run that is starting, up or asleep is listed as open.
37
+ function isOpenService(run) {
38
+ return !!run.up && !isFinal(run.state);
39
+ }
40
+ // Whether a run executes, for the limit of its caller: a move beside its services counts too
41
+ function executes(entry) {
42
+ return entry.run.state === 'running' || !!entry.mover?.counted;
43
+ }
44
+ // The places of runs.up.limits that service runs take: one per caller and name of the runs
45
+ // that are starting or up, an asleep one takes none (as checkUpLimits counts). Per place the
46
+ // newest run, which is the one that stays.
47
+ function servicePlaces(runs, asleep = false) {
48
+ const places = new Map();
49
+ for (const run of runs) {
50
+ if (run.up && !isFinal(run.state) && (run.state === 'asleep') === asleep) {
51
+ places.set(JSON.stringify([run.owner.iss, run.owner.sub, run.up.name]), run);
52
+ }
53
+ }
54
+ return [...places.values()];
55
+ }
30
56
  function onSandbox(run, sandbox) {
31
57
  return run.source.type === 'sandbox' && run.source.id === sandbox;
32
58
  }
59
+ // the tasks of a run whose check keys are kept, a build file has fewer
60
+ const MAX_KEYED_TASKS = 1000;
33
61
  // how much of the end of a task's output its result carries
34
62
  const TAIL_LINES = 20;
35
63
  const TAIL_LINE_LENGTH = 1000;
@@ -38,6 +66,11 @@ const TAIL_LINE_LENGTH = 1000;
38
66
  // does not can still not make a result of any size.
39
67
  exports.MAX_CAUSES = 20;
40
68
  exports.MAX_TASK_ERROR = 2 * 1024;
69
+ // the command times a task result keeps
70
+ exports.MAX_COMMANDS = 50;
71
+ function isTimestamp(value) {
72
+ return typeof value === 'string' && value.length <= 40 && !Number.isNaN(Date.parse(value));
73
+ }
41
74
  function bounded(event) {
42
75
  const causes = event.causes;
43
76
  return {
@@ -51,12 +84,20 @@ function bounded(event) {
51
84
  }
52
85
  : {}),
53
86
  ...(event.error !== undefined ? { error: event.error.slice(0, exports.MAX_TASK_ERROR) } : {}),
87
+ ...(event.commands
88
+ ? {
89
+ commands: event.commands
90
+ .filter((c) => isTimestamp(c?.startedAt) && isTimestamp(c?.finishedAt))
91
+ .slice(0, exports.MAX_COMMANDS)
92
+ .map(({ startedAt, finishedAt }) => ({ startedAt, finishedAt })),
93
+ }
94
+ : {}),
54
95
  };
55
96
  }
56
97
  // what a task event weighs against the log limits of a run
57
98
  function taskEventSize(event) {
58
99
  const causes = (event.causes ?? []).reduce((sum, cause) => sum + Buffer.byteLength(cause) + 4, 0);
59
- return 64 + causes + Buffer.byteLength(event.error ?? '');
100
+ return 64 + causes + Buffer.byteLength(event.error ?? '') + (event.commands?.length ?? 0) * 64;
60
101
  }
61
102
  // Where runs are kept while the server is up. Everything is scoped to the
62
103
  // caller that submitted the run: the same id asked for by someone else is
@@ -70,6 +111,10 @@ class RunRegistry {
70
111
  this.closed = false;
71
112
  // callers that wait for a run to finish, let go when the server stops
72
113
  this.waiters = new Set();
114
+ // the moves of service runs that execute beside their services
115
+ this.moving = new Set();
116
+ // the records of evicted runs still being removed from the store, waited for by close
117
+ this.removing = new Set();
73
118
  this.maxConcurrent = options.maxConcurrent ?? 4;
74
119
  this.keep = options.keep ?? 200;
75
120
  this.maxEvents = options.maxEvents ?? 5000;
@@ -86,11 +131,15 @@ class RunRegistry {
86
131
  async restore() {
87
132
  const store = this.options.store;
88
133
  if (!store) {
134
+ // what a server before this one kept for its runs is nobody's now
135
+ this.options.executor.restored?.([]);
89
136
  return;
90
137
  }
91
138
  const { records, skipped } = await store.load();
92
139
  skipped.forEach((name) => this.options.log?.(`skip run record ${name}: it can not be read`));
93
140
  for (const { run, events } of records) {
141
+ // a move that executed went with the server
142
+ delete run.moving;
94
143
  const entry = {
95
144
  run,
96
145
  events,
@@ -100,6 +149,7 @@ class RunRegistry {
100
149
  bytes: 0,
101
150
  tails: new Map(Object.entries(run.results ?? {}).map(([task, result]) => [task, result.lastLog])),
102
151
  saving: Promise.resolve(),
152
+ keys: {},
103
153
  };
104
154
  this.entries.set(run.id, entry);
105
155
  if (run.state === 'awaiting-approval') {
@@ -112,11 +162,41 @@ class RunRegistry {
112
162
  this.finish(entry, 'rejected', 'nobody approved it in time');
113
163
  }
114
164
  }
165
+ else if (this.maySleep(entry) && ['queued', 'running', 'up', 'asleep'].includes(run.state)) {
166
+ // the services went with the process that held them, the next request wakes them
167
+ if (run.state === 'queued' || run.state === 'running' || run.state === 'up') {
168
+ // a server that stopped without putting the run to sleep left its volumes where they
169
+ // were, for the wake to mount
170
+ if (this.keepsVolumes()) {
171
+ run.volumesKept = true;
172
+ }
173
+ this.sleep(entry);
174
+ }
175
+ else {
176
+ this.expireLater(entry);
177
+ }
178
+ if (!this.keepsVolumes()) {
179
+ // the backend no longer keeps them, the sweep below removes them
180
+ delete run.volumesKept;
181
+ }
182
+ }
183
+ else if (run.state === 'asleep') {
184
+ // its time ran out while the server was down: it ends now, and gives its place back
185
+ run.stoppedBy ?? (run.stoppedBy = 'ttl');
186
+ this.finish(entry, 'succeeded');
187
+ }
115
188
  else if (run.state === 'queued' || run.state === 'running') {
116
189
  this.finish(entry, 'failed', `the server stopped while the run was ${run.state}, submit it again`);
117
190
  }
191
+ else if (run.state === 'up') {
192
+ // the services went with the process that held them
193
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
194
+ }
118
195
  }
119
196
  this.evict();
197
+ this.options.executor.restored?.([...this.entries.values()]
198
+ .filter((entry) => entry.run.volumesKept && !isFinal(entry.run.state))
199
+ .map((entry) => this.copy(entry.run)));
120
200
  }
121
201
  // A run that needs approvals (for the accounts named) waits for them, the others
122
202
  // are queued at once.
@@ -129,13 +209,26 @@ class RunRegistry {
129
209
  throw new RunError('too many runs are waiting for an approval');
130
210
  }
131
211
  this.checkLimits(owner, waiting);
212
+ if (spec.up) {
213
+ this.checkUpLimits(owner, spec.up.name);
214
+ this.checkHosts(owner, spec.up);
215
+ }
216
+ const name = (0, oauth_1.displayName)(owner);
132
217
  const run = {
133
218
  ...spec,
134
219
  id: `run_${(0, crypto_1.randomBytes)(12).toString('base64url')}`,
135
- owner: { iss: owner.iss, sub: owner.sub },
220
+ owner: {
221
+ iss: owner.iss,
222
+ sub: owner.sub,
223
+ ...(name ? { name } : {}),
224
+ ...(spec.up?.sleepTtl ? { groups: [...(owner.groups ?? [])], claims: { ...(owner.claims ?? {}) } } : {}),
225
+ },
136
226
  state: waiting ? 'awaiting-approval' : 'queued',
137
227
  createdAt: this.timestamp(),
138
228
  };
229
+ if (!waiting) {
230
+ run.queuedAt = run.createdAt;
231
+ }
139
232
  const entry = {
140
233
  run,
141
234
  events: [],
@@ -145,6 +238,7 @@ class RunRegistry {
145
238
  bytes: 0,
146
239
  tails: new Map(),
147
240
  saving: Promise.resolve(),
241
+ keys: {},
148
242
  };
149
243
  this.entries.set(run.id, entry);
150
244
  if (waiting) {
@@ -179,30 +273,153 @@ class RunRegistry {
179
273
  .map((entry) => this.copy(entry.run))
180
274
  .reverse();
181
275
  }
182
- // A queued run is cancelled at once; a running one when its executor stops.
183
- cancel(owner, id, canUse) {
184
- const entry = this.find(owner, id, canUse);
276
+ // one run of any caller: who may see it is for the caller to decide
277
+ peek(id) {
278
+ const entry = this.entries.get(id);
279
+ return entry ? this.copy(entry.run) : undefined;
280
+ }
281
+ // every run it keeps, of every caller, newest first: who may see which is for the caller
282
+ all() {
283
+ return [...this.entries.values()].map((entry) => this.copy(entry.run)).reverse();
284
+ }
285
+ // What the caller has against each of their limits.
286
+ usage(owner) {
287
+ const mine = [...this.entries.values()].filter((entry) => this.owns(owner, entry));
288
+ const ids = (keep) => mine.filter(keep).map((entry) => entry.run.id);
289
+ return {
290
+ waiting: ids((entry) => entry.run.state === 'awaiting-approval'),
291
+ queued: ids((entry) => entry.run.state === 'queued'),
292
+ running: ids(executes),
293
+ services: servicePlaces(mine.map((entry) => entry.run)).map((run) => run.id),
294
+ asleep: servicePlaces(mine.map((entry) => entry.run), true).map((run) => run.id),
295
+ };
296
+ }
297
+ snapshot() {
298
+ const all = [...this.entries.values()];
299
+ const up = this.options.up;
300
+ const executing = new Map();
301
+ const key = (owner) => `${owner.iss}\0${owner.sub}`;
302
+ for (const entry of all) {
303
+ if (executes(entry)) {
304
+ executing.set(key(entry.run.owner), (executing.get(key(entry.run.owner)) ?? 0) + 1);
305
+ }
306
+ }
307
+ const runningOf = (owner) => executing.get(key(owner)) ?? 0;
308
+ return {
309
+ places: { max: this.maxConcurrent, used: this.running },
310
+ running: all.filter((entry) => entry.run.state === 'running').map((entry) => this.copy(entry.run)),
311
+ queue: this.queue.map((entry) => ({ run: this.copy(entry.run), waitsFor: this.waitReason(entry, runningOf) })),
312
+ awaiting: {
313
+ runs: all.filter((entry) => entry.run.state === 'awaiting-approval').map((entry) => this.copy(entry.run)),
314
+ max: this.maxWaiting,
315
+ },
316
+ services: {
317
+ runs: all.filter((entry) => isOpenService(entry.run)).map((entry) => this.copy(entry.run)),
318
+ taken: servicePlaces(all.map((entry) => entry.run)).length,
319
+ ...(up ? { max: up.total, perCaller: up.perCaller } : {}),
320
+ ...(up?.asleep !== undefined ? { asleepPerCaller: up.asleep } : {}),
321
+ },
322
+ ...(this.options.limits ? { limits: { ...this.options.limits } } : {}),
323
+ };
324
+ }
325
+ // Where a queued run stands in the queue (from 1), and why it waits.
326
+ queued(id) {
327
+ const index = this.queue.findIndex((entry) => entry.run.id === id);
328
+ return index < 0 ? undefined : { position: index + 1, waitsFor: this.waitReason(this.queue[index]) };
329
+ }
330
+ // A queued run is cancelled at once; a running one when its executor stops. A service run
331
+ // that is up stops its services, and says who stopped it.
332
+ // Stops a run for its owner, who decides about it, and, a service run, whoever `mayStop` says.
333
+ cancel(owner, id, canUse, mayStop) {
334
+ const other = this.entries.get(id);
335
+ const entry = this.find(owner, id, canUse) ?? (other?.run.up && mayStop?.(this.copy(other.run)) ? other : undefined);
185
336
  if (!entry) {
186
337
  return undefined;
187
338
  }
188
- this.stop(entry);
339
+ this.stop(entry, undefined, { iss: owner.iss, sub: owner.sub });
189
340
  return this.copy(entry.run);
190
341
  }
342
+ /**
343
+ * Moves the end of a service run that is up (or asleep) to `ttl` (ms) from now, at most
344
+ * the server's maxTtl, and never sooner than it was. Its owner may, and whoever `mayOpen`
345
+ * says may open its endpoints.
346
+ */
347
+ extend(caller, id, ttl, mayOpen) {
348
+ const entry = this.entries.get(id);
349
+ if (!entry || !(this.owns(caller, entry) || (entry.run.up && mayOpen?.(this.copy(entry.run))))) {
350
+ return { status: 'not-found' };
351
+ }
352
+ // up, asleep, or woken and starting again
353
+ if (!entry.run.upAt || isFinal(entry.run.state)) {
354
+ return { status: 'not-up', state: entry.run.state };
355
+ }
356
+ // never sooner than it was: who wants it gone stops it
357
+ const ms = Math.min(ttl, this.options.up?.maxTtl ?? ttl);
358
+ const expiresAt = Math.max(Date.parse(entry.run.expiresAt ?? '') || 0, this.now() + ms);
359
+ entry.run.expiresAt = new Date(expiresAt).toISOString();
360
+ this.record(entry, { type: 'extended', by: { iss: caller.iss, sub: caller.sub }, expiresAt: entry.run.expiresAt });
361
+ this.expireLater(entry);
362
+ return { status: 'ok', run: this.copy(entry.run) };
363
+ }
364
+ /**
365
+ * Wakes a service run that sleeps, for its owner or who `mayOpen` it, as a request to its
366
+ * endpoints would (visit): with the same check of its owner (`mayWake`) and the same places.
367
+ * Answers why it did not wake when it could not.
368
+ */
369
+ wake(caller, id, mayOpen, mayWake) {
370
+ const entry = this.entries.get(id);
371
+ if (!entry?.run.up || !(this.owns(caller, entry) || mayOpen?.(this.copy(entry.run)))) {
372
+ return { status: 'not-found' };
373
+ }
374
+ if (entry.run.state !== 'asleep') {
375
+ return { status: 'not-asleep', state: entry.run.state };
376
+ }
377
+ const refused = this.visit(id, mayWake);
378
+ return refused
379
+ ? { status: 'refused', reason: refused, run: this.copy(entry.run) }
380
+ : { status: 'ok', run: this.copy(entry.run) };
381
+ }
382
+ /**
383
+ * The service run an endpoint host belongs to: the newest that is up, so one that replaces
384
+ * a run of the same name takes its hosts over as soon as it is up; else the newest that
385
+ * had it, for a page that says how it stands. With the address of the endpoint when up.
386
+ */
387
+ endpoint(host) {
388
+ let found;
389
+ for (const entry of this.entries.values()) {
390
+ const endpoint = entry.run.up?.endpoints.find((candidate) => candidate.host === host);
391
+ if (endpoint && (entry.run.state === 'up' || found?.entry.run.state !== 'up')) {
392
+ found = { entry, endpoint };
393
+ }
394
+ }
395
+ if (!found) {
396
+ return undefined;
397
+ }
398
+ const { entry, endpoint } = found;
399
+ const target = entry.run.state === 'up'
400
+ ? entry.targets?.find((candidate) => candidate.service === endpoint.service && candidate.port === endpoint.port)
401
+ : undefined;
402
+ return { run: this.copy(entry.run), endpoint: { ...endpoint }, ...(target ? { target } : {}) };
403
+ }
191
404
  // The run that holds a sandbox: the oldest on it that is not over. It holds it from
192
- // when it is submitted, so the files are not moved under what an approver saw.
405
+ // when it is submitted, so the files are not moved under what an approver saw. A service
406
+ // run that is up works on a copy of the files, and holds it no longer.
193
407
  holder(sandbox) {
194
- return [...this.entries.values()].find((entry) => onSandbox(entry.run, sandbox) && !isFinal(entry.run.state))?.run
195
- .id;
408
+ return [...this.entries.values()].find((entry) => onSandbox(entry.run, sandbox) &&
409
+ !isFinal(entry.run.state) &&
410
+ entry.run.state !== 'up' &&
411
+ entry.run.state !== 'asleep')?.run.id;
196
412
  }
197
413
  // Cancels every run on a sandbox and resolves when none of them runs anymore.
198
414
  async stopSandbox(sandbox, reason) {
199
415
  const on = () => [...this.entries.values()].filter((entry) => onSandbox(entry.run, sandbox));
200
416
  on().forEach((entry) => this.stop(entry, reason));
201
- while (on().some((entry) => entry.run.state === 'running')) {
417
+ while (on().some((entry) => entry.run.state === 'running' || entry.run.state === 'up')) {
202
418
  await new Promise((resolve) => setTimeout(resolve, 20));
203
419
  }
204
420
  }
205
- stop(entry, reason) {
421
+ stop(entry, reason, by) {
422
+ var _a, _b;
206
423
  if (entry.run.state === 'queued') {
207
424
  this.queue.splice(this.queue.indexOf(entry), 1);
208
425
  this.finish(entry, 'cancelled', reason);
@@ -213,6 +430,17 @@ class RunRegistry {
213
430
  else if (entry.run.state === 'running') {
214
431
  entry.abort.abort();
215
432
  }
433
+ else if (entry.run.state === 'up') {
434
+ (_a = entry.run).stoppedBy ?? (_a.stoppedBy = by ?? 'replaced');
435
+ entry.sleeping = false;
436
+ entry.restartTo = undefined;
437
+ entry.mover?.abort.abort();
438
+ entry.abort.abort();
439
+ }
440
+ else if (entry.run.state === 'asleep') {
441
+ (_b = entry.run).stoppedBy ?? (_b.stoppedBy = by ?? 'replaced');
442
+ this.finish(entry, 'succeeded');
443
+ }
216
444
  }
217
445
  // The runs that wait for an approval, of anybody, oldest first. Who may see
218
446
  // them is for the caller to decide.
@@ -268,6 +496,7 @@ class RunRegistry {
268
496
  }
269
497
  this.clearTimer(entry);
270
498
  entry.run.state = 'queued';
499
+ entry.run.queuedAt = this.timestamp();
271
500
  this.record(entry, { type: 'state', state: 'queued' });
272
501
  this.queue.push(entry);
273
502
  const approved = this.copy(entry.run);
@@ -289,18 +518,21 @@ class RunRegistry {
289
518
  return { events, finished, stop: () => entry.listeners.delete(listener) };
290
519
  }
291
520
  /**
292
- * The run once it is over, or as it is after `ms` or when `signal` aborts, for clients
293
- * that can not hold a stream of events open (a tool call of an agent).
521
+ * The run once it is over (a service run: once it is up), or as it is after `ms` or when
522
+ * `signal` aborts, for clients that can not hold a stream of events open (a tool call of
523
+ * an agent).
294
524
  */
295
525
  async wait(owner, id, ms, canUse, signal) {
296
526
  const entry = this.find(owner, id, canUse);
297
527
  if (!entry) {
298
528
  return undefined;
299
529
  }
300
- if (!isFinal(entry.run.state) && ms > 0 && !this.closed && !signal?.aborted) {
530
+ // a service run is there once it is up, and at the commit it moves to
531
+ const there = () => isFinal(entry.run.state) || (entry.run.state === 'up' && !entry.run.moving);
532
+ if (!there() && ms > 0 && !this.closed && !signal?.aborted) {
301
533
  await new Promise((resolve) => {
302
534
  const listener = (event) => {
303
- if (event.type === 'state' && isFinal(event.state)) {
535
+ if ((event.type === 'state' || event.type === 'moved') && there()) {
304
536
  done();
305
537
  }
306
538
  };
@@ -331,14 +563,34 @@ class RunRegistry {
331
563
  entry.index.update(entry.events);
332
564
  return { events: entry.events, index: entry.index, truncated: entry.truncated };
333
565
  }
566
+ // The log of any run, for a caller whose right to read it was checked already (an
567
+ // entitlement with `observe`).
568
+ logsOf(id) {
569
+ const entry = this.entries.get(id);
570
+ if (!entry) {
571
+ return undefined;
572
+ }
573
+ entry.index ?? (entry.index = new run_logs_1.LogIndex());
574
+ entry.index.update(entry.events);
575
+ return { events: entry.events, index: entry.index, truncated: entry.truncated };
576
+ }
334
577
  // Stops accepting runs and aborts the ones in flight.
335
578
  async close() {
336
579
  this.closed = true;
337
580
  for (const entry of this.queue.splice(0)) {
338
- this.finish(entry, 'cancelled');
581
+ if (this.maySleep(entry) && this.options.store) {
582
+ // a woken service run sleeps again, the next start keeps it
583
+ this.sleep(entry);
584
+ }
585
+ else {
586
+ this.finish(entry, 'cancelled');
587
+ }
339
588
  }
340
589
  for (const entry of this.entries.values()) {
341
- if (entry.run.state === 'awaiting-approval') {
590
+ if (entry.run.state === 'asleep') {
591
+ this.clearTimer(entry);
592
+ }
593
+ else if (entry.run.state === 'awaiting-approval') {
342
594
  if (this.options.store) {
343
595
  // the record keeps it waiting, the next start takes it back
344
596
  this.clearTimer(entry);
@@ -353,15 +605,23 @@ class RunRegistry {
353
605
  done();
354
606
  }
355
607
  for (const entry of this.entries.values()) {
356
- if (entry.run.state === 'running') {
608
+ if (entry.run.state === 'running' || entry.run.state === 'up') {
609
+ // a service run that may sleep is asleep in its record, the next request after the
610
+ // start wakes it
611
+ entry.sleeping = this.maySleep(entry) && !!this.options.store;
612
+ entry.mover?.abort.abort();
357
613
  entry.abort.abort();
358
614
  }
359
615
  }
360
- while (this.running > 0) {
616
+ while (this.running > 0 ||
617
+ this.moving.size > 0 ||
618
+ [...this.entries.values()].some((entry) => entry.run.state === 'running' || entry.run.state === 'up')) {
361
619
  await new Promise((resolve) => setTimeout(resolve, 10));
362
620
  }
363
- // the runs that were stopped are written down before the server is gone
621
+ // the runs that were stopped are written down before the server is gone, and the records
622
+ // of evicted runs are gone from the store
364
623
  await Promise.all([...this.entries.values()].map((entry) => entry.saving));
624
+ await Promise.all([...this.removing]);
365
625
  }
366
626
  find(owner, id, canUse) {
367
627
  const entry = this.entries.get(id);
@@ -388,6 +648,8 @@ class RunRegistry {
388
648
  copy(run) {
389
649
  return {
390
650
  ...run,
651
+ ...(run.up ? { up: JSON.parse(JSON.stringify(run.up)) } : {}),
652
+ ...(run.stoppedBy && typeof run.stoppedBy === 'object' ? { stoppedBy: { ...run.stoppedBy } } : {}),
391
653
  tasks: [...run.tasks],
392
654
  source: { ...run.source },
393
655
  options: JSON.parse(JSON.stringify(run.options)),
@@ -395,6 +657,9 @@ class RunRegistry {
395
657
  accounts: [...run.accounts],
396
658
  ...(run.approvals ? { approvals: JSON.parse(JSON.stringify(run.approvals)) } : {}),
397
659
  ...(run.results ? { results: JSON.parse(JSON.stringify(run.results)) } : {}),
660
+ ...(run.phases ? { phases: run.phases.map((phase) => ({ ...phase })) } : {}),
661
+ ...(run.moves ? { moves: run.moves.map((move) => ({ ...move })) } : {}),
662
+ ...(run.moving ? { moving: { ...run.moving } } : {}),
398
663
  };
399
664
  }
400
665
  timestamp() {
@@ -406,30 +671,128 @@ class RunRegistry {
406
671
  if (!limits) {
407
672
  return;
408
673
  }
409
- const mine = [...this.entries.values()].filter((entry) => this.owns(owner, entry));
410
- const count = (state) => mine.filter((entry) => entry.run.state === state).length;
411
- if (waiting && count('awaiting-approval') >= limits.waiting) {
674
+ const usage = this.usage(owner);
675
+ if (waiting && usage.waiting.length >= limits.waiting) {
412
676
  throw new QuotaError(`you have ${limits.waiting} runs waiting for an approval, wait for a decision or cancel one`);
413
677
  }
414
- if (!waiting && count('queued') >= limits.queued) {
678
+ if (!waiting && usage.queued.length >= limits.queued) {
415
679
  throw new QuotaError(`you have ${limits.queued} runs in the queue, wait for one to start or cancel one`);
416
680
  }
417
681
  }
682
+ // Service runs that are starting or up, of the caller and of everybody, against what may
683
+ // be. One that is asleep does not count: it asks for a place when it wakes (visit). The runs
684
+ // of a caller with one name take one place: the newest replaces the others once it is up,
685
+ // and an older one that gets up after it goes (markUp), so a new run of a name the caller
686
+ // has does not need another. Several of one name that are still starting share it too:
687
+ // what they take while they start is held by runs.limits.running and maxConcurrent.
688
+ checkUpLimits(owner, name) {
689
+ // what a caller keeps asleep is held by a limit of its own: a run that sleeps may keep the
690
+ // volumes of its services. A run of a name the caller has a run of (asleep, up or
691
+ // starting) replaces it, it is not one more.
692
+ const asleep = this.options.up?.asleep;
693
+ if (asleep !== undefined) {
694
+ const open = [...this.entries.values()].filter((entry) => entry.run.up && !isFinal(entry.run.state) && this.owns(owner, entry));
695
+ const sleeping = new Set(open.filter((entry) => entry.run.state === 'asleep').map((entry) => entry.run.up?.name));
696
+ if (!open.some((entry) => entry.run.up?.name === name) && sleeping.size >= asleep) {
697
+ throw new QuotaError(`you have ${asleep} service runs asleep, stop one or wait for its end`);
698
+ }
699
+ }
700
+ const full = this.upLimitReached(owner, name);
701
+ if (full === 'caller') {
702
+ throw new QuotaError(`you have ${this.options.up?.perCaller} service runs starting or up, stop one or wait for its end`);
703
+ }
704
+ if (full === 'server') {
705
+ throw new RunError(`the server has ${this.options.up?.total} service runs starting or up, try again later`);
706
+ }
707
+ }
708
+ // Whose limit a service run of the caller with this name would go over, if any
709
+ upLimitReached(owner, name) {
710
+ const limits = this.options.up;
711
+ if (!limits) {
712
+ return undefined;
713
+ }
714
+ const places = new Set();
715
+ const mine = new Set();
716
+ for (const entry of this.entries.values()) {
717
+ if (!entry.run.up || isFinal(entry.run.state) || entry.run.state === 'asleep') {
718
+ continue;
719
+ }
720
+ places.add(JSON.stringify([entry.run.owner.iss, entry.run.owner.sub, entry.run.up.name]));
721
+ if (this.owns(owner, entry)) {
722
+ mine.add(entry.run.up.name);
723
+ }
724
+ }
725
+ if (mine.has(name)) {
726
+ return undefined;
727
+ }
728
+ if (mine.size >= limits.perCaller) {
729
+ return 'caller';
730
+ }
731
+ if (places.size >= limits.total) {
732
+ return 'server';
733
+ }
734
+ return undefined;
735
+ }
736
+ // A host is one run's, or a run's that replaces it (same owner and name) once it is up:
737
+ // two labels that come out the same are refused, they would reach each other's services.
738
+ checkHosts(owner, up) {
739
+ const hosts = new Set(up.endpoints.map((endpoint) => endpoint.host));
740
+ for (const entry of this.entries.values()) {
741
+ if (isFinal(entry.run.state) || !entry.run.up) {
742
+ continue;
743
+ }
744
+ const taken = entry.run.up.endpoints.find((endpoint) => hosts.has(endpoint.host));
745
+ if (taken && !(this.owns(owner, entry) && entry.run.up.name === up.name)) {
746
+ const error = new RunError(`the address ${taken.host} is another service run's, pick another name`);
747
+ error.status = 409;
748
+ throw error;
749
+ }
750
+ }
751
+ }
418
752
  runningOf(owner) {
419
- return [...this.entries.values()].filter((entry) => entry.run.state === 'running' && this.owns(owner, entry)).length;
753
+ return this.usage(owner).running.length;
420
754
  }
421
- // Whether a run on the same sandbox executes: a sandbox runs one at a time.
755
+ // The run on the same sandbox that executes: a sandbox runs one at a time.
422
756
  sandboxBusy(run) {
423
757
  const source = run.source;
424
- return (source.type === 'sandbox' &&
425
- [...this.entries.values()].some((entry) => entry.run.state === 'running' && onSandbox(entry.run, source.id)));
758
+ if (source.type !== 'sandbox') {
759
+ return undefined;
760
+ }
761
+ return [...this.entries.values()].find((entry) => entry.run.state === 'running' && onSandbox(entry.run, source.id))
762
+ ?.run.id;
426
763
  }
427
- // Whether a run that executes holds what the run would (RunExecutor.exclusive)
764
+ // The run that executes and holds what the run would (RunExecutor.exclusive)
428
765
  held(run) {
429
766
  const exclusive = this.options.executor.exclusive?.bind(this.options.executor);
430
767
  const key = exclusive?.(run);
431
- return (key !== undefined &&
432
- [...this.entries.values()].some((entry) => entry.run.state === 'running' && exclusive?.(entry.run) === key));
768
+ if (key === undefined) {
769
+ return undefined;
770
+ }
771
+ return [...this.entries.values()].find((entry) => entry.run.state === 'running' && exclusive?.(entry.run) === key)
772
+ ?.run.id;
773
+ }
774
+ // What keeps a queued run from starting, checked as dispatch checks it: what holds it
775
+ // even when a place frees up is named first.
776
+ // `runningOf` counts the runs of the owner that execute; a snapshot passes one that
777
+ // counted all owners once, so a look at the queue costs the runs once and not per entry
778
+ waitReason(entry, runningOf = (owner) => this.runningOf(owner)) {
779
+ const limit = this.options.limits?.running ?? Infinity;
780
+ const running = runningOf(entry.run.owner);
781
+ if (running >= limit) {
782
+ return { type: 'own-limit', running, limit };
783
+ }
784
+ const sandbox = this.sandboxBusy(entry.run);
785
+ if (sandbox) {
786
+ return { type: 'sandbox', run: sandbox };
787
+ }
788
+ const holder = this.held(entry.run);
789
+ if (holder) {
790
+ return { type: 'held', run: holder };
791
+ }
792
+ if (this.running >= this.maxConcurrent) {
793
+ return { type: 'place', used: this.running, max: this.maxConcurrent };
794
+ }
795
+ return { type: 'starting' };
433
796
  }
434
797
  // The first run in the queue whose caller has a place left: one caller with many runs
435
798
  // does not keep the others from the machine. A run on a sandbox another run works on
@@ -439,12 +802,21 @@ class RunRegistry {
439
802
  const perCaller = this.options.limits?.running ?? Infinity;
440
803
  const index = this.queue.findIndex((entry) => this.runningOf(entry.run.owner) < perCaller && !this.sandboxBusy(entry.run) && !this.held(entry.run));
441
804
  if (index < 0) {
805
+ // the moves that wait for a place
806
+ for (const entry of this.entries.values()) {
807
+ if (entry.pendingMove && entry.run.state === 'up' && !entry.mover) {
808
+ this.beginMove(entry);
809
+ }
810
+ }
442
811
  return;
443
812
  }
444
813
  const [entry] = this.queue.splice(index, 1);
445
814
  this.running++;
446
815
  this.execute(entry).finally(() => {
447
- this.running--;
816
+ // a service run that is up gave its place back already
817
+ if (!entry.released) {
818
+ this.running--;
819
+ }
448
820
  this.dispatch();
449
821
  });
450
822
  }
@@ -453,27 +825,597 @@ class RunRegistry {
453
825
  entry.run.state = 'running';
454
826
  entry.run.startedAt = this.timestamp();
455
827
  this.record(entry, { type: 'state', state: 'running' });
828
+ // a service run gets this long to be up, then its ttl counts
456
829
  const limit = this.options.maxDuration;
457
- const timer = limit
830
+ entry.durationTimer = limit
458
831
  ? setTimeout(() => {
459
832
  entry.timedOut = true;
460
833
  entry.abort.abort();
461
834
  }, limit)
462
835
  : undefined;
463
- timer?.unref();
836
+ entry.durationTimer?.unref();
837
+ const token = {};
838
+ entry.holder = token;
839
+ // the commit of a move whose services are not up there yet
840
+ const landing = entry.landing && !entry.landing.recorded ? entry.landing.change : undefined;
841
+ const run = landing
842
+ ? { ...this.copy(entry.run), source: { ...landing.source }, ...(landing.plan ? { plan: landing.plan } : {}) }
843
+ : this.copy(entry.run);
464
844
  try {
465
- await this.options.executor.execute(this.copy(entry.run), {
845
+ await this.options.executor.execute(run, {
466
846
  emit: (event) => this.record(entry, event),
467
847
  signal: entry.abort.signal,
848
+ ...(entry.run.up
849
+ ? {
850
+ up: (targets) => this.markUp(entry, targets),
851
+ keep: () => (entry.holder === token ? this.keepOf(entry) : 'everything'),
852
+ }
853
+ : {}),
468
854
  });
469
- this.finish(entry, entry.timedOut ? 'failed' : entry.abort.signal.aborted ? 'cancelled' : 'succeeded', entry.timedOut ? this.tooLong() : undefined);
855
+ if (entry.holder !== token) {
856
+ // a move took the services over
857
+ return;
858
+ }
859
+ if (this.fallBack(entry, entry.timedOut ? this.tooLong() : 'its services stopped before they were up')) {
860
+ return;
861
+ }
862
+ if (entry.restartTo || entry.sleeping) {
863
+ this.stopped(entry);
864
+ }
865
+ else if (entry.run.upAt) {
866
+ // services stay until they are stopped: ones that stopped on their own failed
867
+ this.endServices(entry, 'the services stopped on their own');
868
+ }
869
+ else {
870
+ this.finish(entry, entry.timedOut ? 'failed' : entry.abort.signal.aborted ? 'cancelled' : 'succeeded', entry.timedOut ? this.tooLong() : undefined);
871
+ }
470
872
  }
471
873
  catch (e) {
472
- const cancelled = entry.abort.signal.aborted && !entry.timedOut;
473
- this.finish(entry, cancelled ? 'cancelled' : 'failed', entry.timedOut ? this.tooLong() : cancelled ? undefined : e instanceof Error ? e.message : String(e));
874
+ const message = e instanceof Error ? e.message : String(e);
875
+ if (entry.holder !== token) {
876
+ return;
877
+ }
878
+ if (this.fallBack(entry, entry.timedOut ? this.tooLong() : message)) {
879
+ return;
880
+ }
881
+ if (entry.restartTo || entry.sleeping) {
882
+ this.stopped(entry);
883
+ }
884
+ else if (entry.run.upAt) {
885
+ this.endServices(entry, message);
886
+ }
887
+ else {
888
+ const cancelled = entry.abort.signal.aborted && !entry.timedOut;
889
+ this.finish(entry, cancelled ? 'cancelled' : 'failed', entry.timedOut ? this.tooLong() : cancelled ? undefined : message);
890
+ }
474
891
  }
475
892
  finally {
476
- clearTimeout(timer);
893
+ clearTimeout(entry.durationTimer);
894
+ }
895
+ }
896
+ // The services of a service run are ready: its ttl counts from now, its place of
897
+ // maxConcurrent goes to the next run, and an older run of its owner with the same name
898
+ // stops, so its hosts are this run's.
899
+ markUp(entry, targets) {
900
+ const spec = entry.run.up;
901
+ if (!spec || entry.run.state !== 'running' || entry.abort.signal.aborted) {
902
+ return;
903
+ }
904
+ clearTimeout(entry.durationTimer);
905
+ entry.durationTimer = undefined;
906
+ entry.targets = targets.map((target) => ({ ...target, address: { ...target.address } }));
907
+ // the services got up at the commit of a move: the run is there now
908
+ const landing = entry.landing;
909
+ entry.landing = undefined;
910
+ if (landing && !landing.recorded) {
911
+ this.moveTo(entry, landing.change);
912
+ }
913
+ entry.run.state = 'up';
914
+ // one reading of the clock, so the ttl is exactly expiresAt - upAt
915
+ const now = this.now();
916
+ // the ttl counts from the first time, not from a wake
917
+ if (!entry.run.upAt) {
918
+ entry.run.upAt = new Date(now).toISOString();
919
+ entry.run.expiresAt = new Date(now + spec.ttl).toISOString();
920
+ }
921
+ if (spec.sleepTtl) {
922
+ entry.run.sleepsAt = new Date(now + spec.sleepTtl).toISOString();
923
+ }
924
+ this.record(entry, { type: 'state', state: 'up' });
925
+ this.expireLater(entry);
926
+ entry.released = true;
927
+ this.running--;
928
+ const entries = [...this.entries.values()];
929
+ for (const other of entries.slice(0, entries.indexOf(entry))) {
930
+ if (other.run.up?.name === spec.name &&
931
+ this.owns(entry.run.owner, other) &&
932
+ !isFinal(other.run.state) &&
933
+ other.run.state !== 'awaiting-approval') {
934
+ other.run.stoppedBy = 'replaced';
935
+ this.stop(other, `replaced by ${entry.run.id}`);
936
+ }
937
+ }
938
+ // A newer run of the name that is up or asleep already (this one waited for an approval
939
+ // while it got up) is what the owner started last: this one goes, so the runs of a name,
940
+ // which take one place of runs.up.limits, never hold more than one set of services.
941
+ const newer = entries
942
+ .slice(entries.indexOf(entry) + 1)
943
+ .find((other) => other.run.up?.name === spec.name &&
944
+ this.owns(entry.run.owner, other) &&
945
+ (other.run.state === 'up' || other.run.state === 'asleep'));
946
+ if (newer) {
947
+ entry.run.stoppedBy = 'replaced';
948
+ this.stop(entry, `replaced by ${newer.run.id}`);
949
+ }
950
+ this.dispatch();
951
+ if (!newer) {
952
+ // a move that came while it started or woke
953
+ this.beginMove(entry);
954
+ }
955
+ }
956
+ /**
957
+ * The service run of the caller of this name that a run of theirs would replace: the newest
958
+ * that is not over and waits for no approval. RunRegistry.move moves it instead, when it
959
+ * runs the same.
960
+ */
961
+ named(owner, name) {
962
+ const entry = [...this.entries.values()]
963
+ .reverse()
964
+ .find((candidate) => candidate.run.up?.name === name &&
965
+ this.owns(owner, candidate) &&
966
+ !isFinal(candidate.run.state) &&
967
+ candidate.run.state !== 'awaiting-approval');
968
+ return entry ? this.copy(entry.run) : undefined;
969
+ }
970
+ /**
971
+ * Moves a service run of the caller to another commit of its repository, in place of a new
972
+ * run that replaces it: it keeps its id, its addresses, its volumes and its place. Queued or
973
+ * asleep, it starts the new commit when it starts; up, it moves there now (see
974
+ * RunExecutor.movesBeside), starting or waking, once it is up. A later move takes the place
975
+ * of one that did not begin yet, and stops one that executes. `ttl` moves its end to that
976
+ * long from now, if that is later. Undefined when the run is not the caller's to move.
977
+ */
978
+ move(owner, id, change) {
979
+ const entry = this.entries.get(id);
980
+ const state = entry?.run.state;
981
+ if (!entry ||
982
+ !this.owns(owner, entry) ||
983
+ !entry.run.up ||
984
+ entry.run.source.type !== 'ref' ||
985
+ !state ||
986
+ isFinal(state) ||
987
+ state === 'awaiting-approval' ||
988
+ this.closed) {
989
+ return undefined;
990
+ }
991
+ const by = { iss: owner.iss, sub: owner.sub };
992
+ if (change.owner) {
993
+ entry.run.owner = { ...change.owner };
994
+ }
995
+ if (change.ttl !== undefined) {
996
+ if (entry.run.upAt) {
997
+ const ms = Math.min(change.ttl, this.options.up?.maxTtl ?? change.ttl);
998
+ const expiresAt = Math.max(Date.parse(entry.run.expiresAt ?? '') || 0, this.now() + ms);
999
+ if (new Date(expiresAt).toISOString() !== entry.run.expiresAt) {
1000
+ entry.run.expiresAt = new Date(expiresAt).toISOString();
1001
+ this.record(entry, { type: 'extended', by, expiresAt: entry.run.expiresAt });
1002
+ }
1003
+ }
1004
+ else {
1005
+ entry.run.up.ttl = Math.max(entry.run.up.ttl, change.ttl);
1006
+ }
1007
+ }
1008
+ if (state === 'queued' && entry.landing && !entry.landing.recorded) {
1009
+ // it starts again at the commit of a move: at this one instead
1010
+ entry.landing.change = change;
1011
+ entry.run.moving = { commit: change.source.commit, ref: change.source.ref, since: this.timestamp() };
1012
+ return this.copy(entry.run);
1013
+ }
1014
+ if (state === 'queued' || state === 'asleep') {
1015
+ if (entry.run.upAt) {
1016
+ // it was up at the commit it is at: a wake that fails at the new one goes back there
1017
+ entry.landing = {
1018
+ change,
1019
+ from: entry.landing?.from ?? this.landingFrom(entry),
1020
+ recorded: true,
1021
+ };
1022
+ }
1023
+ this.moveTo(entry, change);
1024
+ if (state === 'asleep') {
1025
+ this.expireLater(entry);
1026
+ }
1027
+ return this.copy(entry.run);
1028
+ }
1029
+ // running or up: once it is up, beside its services
1030
+ entry.pendingMove = change;
1031
+ entry.run.moving = { commit: change.source.commit, ref: change.source.ref, since: this.timestamp() };
1032
+ // one that executes goes, the newer commit is what is wanted
1033
+ entry.mover?.abort.abort();
1034
+ if (state === 'up') {
1035
+ // a move counts as a request: the run does not sleep under it
1036
+ this.keepAwake(entry);
1037
+ this.beginMove(entry);
1038
+ }
1039
+ return this.copy(entry.run);
1040
+ }
1041
+ // The run is at the commit of `change` now
1042
+ moveTo(entry, change, error) {
1043
+ const move = {
1044
+ commit: change.source.commit,
1045
+ ref: change.source.ref,
1046
+ at: this.timestamp(),
1047
+ ...(error ? { error } : {}),
1048
+ };
1049
+ if (!error) {
1050
+ entry.run.source = { ...change.source };
1051
+ if (change.plan) {
1052
+ entry.run.plan = change.plan;
1053
+ }
1054
+ }
1055
+ entry.run.moves = [...(entry.run.moves ?? []), move];
1056
+ if (!entry.pendingMove && !entry.mover) {
1057
+ delete entry.run.moving;
1058
+ }
1059
+ this.record(entry, {
1060
+ type: 'moved',
1061
+ commit: move.commit,
1062
+ ref: move.ref,
1063
+ ...(error ? { error } : {}),
1064
+ });
1065
+ }
1066
+ keepAwake(entry) {
1067
+ const sleepTtl = entry.run.up?.sleepTtl;
1068
+ if (sleepTtl && entry.run.state === 'up') {
1069
+ entry.run.sleepsAt = new Date(this.now() + sleepTtl).toISOString();
1070
+ this.expireLater(entry);
1071
+ }
1072
+ }
1073
+ // The move that waits, once the run is up and no other move executes
1074
+ beginMove(entry) {
1075
+ const change = entry.pendingMove;
1076
+ if (!change || entry.run.state !== 'up' || entry.mover || entry.restartTo || entry.abort.signal.aborted) {
1077
+ return;
1078
+ }
1079
+ const beside = !!this.options.executor.movesBeside?.(this.copy(entry.run));
1080
+ if (beside &&
1081
+ (this.running >= this.maxConcurrent ||
1082
+ this.runningOf(entry.run.owner) >= (this.options.limits?.running ?? Infinity))) {
1083
+ // it executes as a run does: it waits for a place (dispatch)
1084
+ return;
1085
+ }
1086
+ entry.pendingMove = undefined;
1087
+ entry.run.moving = { commit: change.source.commit, ref: change.source.ref, since: this.timestamp() };
1088
+ this.record(entry, {
1089
+ type: 'log',
1090
+ task: 'hammerkit',
1091
+ stream: 'stdout',
1092
+ text: `moving ${entry.run.source.type === 'ref' ? `from ${entry.run.source.commit} ` : ''}to ${change.source.commit}`,
1093
+ });
1094
+ if (!beside) {
1095
+ // its services stop, their volumes kept, and it starts again at the commit
1096
+ entry.restartTo = change;
1097
+ entry.abort.abort();
1098
+ return;
1099
+ }
1100
+ const token = {};
1101
+ const abort = new AbortController();
1102
+ const mover = { token, abort, change, counted: true };
1103
+ this.running++;
1104
+ // it gets as long as a run gets to be up
1105
+ const limit = this.options.maxDuration;
1106
+ if (limit) {
1107
+ mover.timer = setTimeout(() => {
1108
+ mover.timedOut = true;
1109
+ abort.abort();
1110
+ }, limit);
1111
+ mover.timer.unref();
1112
+ }
1113
+ entry.mover = mover;
1114
+ const run = {
1115
+ ...this.copy(entry.run),
1116
+ source: { ...change.source },
1117
+ ...(change.plan ? { plan: change.plan } : {}),
1118
+ };
1119
+ const execution = this.executeMove(entry, token, abort, run);
1120
+ this.moving.add(execution);
1121
+ void execution.finally(() => this.moving.delete(execution));
1122
+ }
1123
+ // A move beside the services of a run that is up: once its services are ready it holds them
1124
+ // (moved), and its end is the run's. One that ends before leaves the run where it was.
1125
+ async executeMove(entry, token, abort, run) {
1126
+ let failure;
1127
+ try {
1128
+ await this.options.executor.execute(run, {
1129
+ emit: (event) => this.record(entry, event),
1130
+ signal: abort.signal,
1131
+ up: (targets) => this.moved(entry, token, targets),
1132
+ keep: () => (entry.holder === token ? this.keepOf(entry) : 'everything'),
1133
+ });
1134
+ failure = abort.signal.aborted ? 'the move was stopped' : 'its services stopped before they were up';
1135
+ }
1136
+ catch (e) {
1137
+ failure = e instanceof Error ? e.message : String(e);
1138
+ }
1139
+ const mover = entry.mover?.token === token ? entry.mover : undefined;
1140
+ if (mover?.timedOut) {
1141
+ failure = `the move took longer than ${(0, units_1.formatDuration)(this.options.maxDuration)} and was stopped`;
1142
+ }
1143
+ this.releaseMover(mover);
1144
+ if (entry.holder === token) {
1145
+ // the run's services were this execution's
1146
+ if (entry.restartTo || entry.sleeping) {
1147
+ this.stopped(entry);
1148
+ }
1149
+ else {
1150
+ this.endServices(entry, failure === 'the move was stopped' ? 'the services stopped on their own' : failure);
1151
+ }
1152
+ return;
1153
+ }
1154
+ if (entry.mover?.token !== token) {
1155
+ return;
1156
+ }
1157
+ entry.mover = undefined;
1158
+ if (isFinal(entry.run.state)) {
1159
+ return;
1160
+ }
1161
+ this.moveTo(entry, { source: run.source }, failure);
1162
+ this.beginMove(entry);
1163
+ this.dispatch();
1164
+ }
1165
+ // A move that took the services over or ended gives its place back
1166
+ releaseMover(mover) {
1167
+ if (!mover?.counted) {
1168
+ return;
1169
+ }
1170
+ mover.counted = false;
1171
+ clearTimeout(mover.timer);
1172
+ this.running--;
1173
+ }
1174
+ // The services of a move are ready: they are the run's from now, at its commit, and the
1175
+ // execution that held the services until now leaves them to it.
1176
+ moved(entry, token, targets) {
1177
+ const mover = entry.mover;
1178
+ if (!mover || mover.token !== token || mover.abort.signal.aborted || entry.run.state !== 'up') {
1179
+ return;
1180
+ }
1181
+ entry.mover = undefined;
1182
+ this.releaseMover(mover);
1183
+ const previous = entry.abort;
1184
+ entry.abort = mover.abort;
1185
+ entry.holder = token;
1186
+ entry.targets = targets.map((target) => ({ ...target, address: { ...target.address } }));
1187
+ this.moveTo(entry, mover.change);
1188
+ this.keepAwake(entry);
1189
+ previous.abort();
1190
+ this.beginMove(entry);
1191
+ this.dispatch();
1192
+ }
1193
+ // The services of a run stopped to sleep, or to start again at the commit of a move
1194
+ stopped(entry) {
1195
+ if (!entry.restartTo) {
1196
+ if (entry.run.stoppedBy) {
1197
+ // a stop came while its services stopped to sleep: it ends
1198
+ this.finish(entry, 'succeeded');
1199
+ return;
1200
+ }
1201
+ this.sleep(entry);
1202
+ return;
1203
+ }
1204
+ // the newest move, one that came while the services stopped
1205
+ const restart = entry.pendingMove ?? entry.restartTo;
1206
+ entry.restartTo = undefined;
1207
+ entry.pendingMove = undefined;
1208
+ if (this.closed) {
1209
+ // the record keeps it asleep, at the commit it was up at
1210
+ this.moveTo(entry, restart, 'the server stopped before the services were up at the commit');
1211
+ if (this.maySleep(entry) && this.options.store) {
1212
+ this.sleep(entry);
1213
+ }
1214
+ else {
1215
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1216
+ }
1217
+ return;
1218
+ }
1219
+ // up at its commit, the run is there (markUp); else it goes back (fallBack)
1220
+ entry.landing = {
1221
+ change: restart,
1222
+ from: this.landingFrom(entry),
1223
+ recorded: false,
1224
+ };
1225
+ entry.run.moving = { commit: restart.source.commit, ref: restart.source.ref, since: this.timestamp() };
1226
+ this.requeue(entry);
1227
+ }
1228
+ /**
1229
+ * The execution that started the services at the commit of a move ended before they were
1230
+ * up: the run goes back to the commit it was up at, with its volumes, and starts there
1231
+ * again. The move says why it did not get there. False when no move was landing, or the
1232
+ * run was stopped.
1233
+ */
1234
+ fallBack(entry, error) {
1235
+ const landing = entry.landing;
1236
+ if (!landing || entry.run.stoppedBy) {
1237
+ return false;
1238
+ }
1239
+ entry.landing = undefined;
1240
+ const from = landing.from.source;
1241
+ entry.run.source = { ...from };
1242
+ if (landing.from.plan) {
1243
+ entry.run.plan = landing.from.plan;
1244
+ }
1245
+ this.moveTo(entry, landing.change, error);
1246
+ this.record(entry, {
1247
+ type: 'log',
1248
+ task: 'hammerkit',
1249
+ stream: 'stderr',
1250
+ text: `did not get up at ${landing.change.source.commit}, starting again at ${from.commit}: ${error}`,
1251
+ });
1252
+ if (this.closed) {
1253
+ if (this.maySleep(entry) && this.options.store) {
1254
+ this.sleep(entry);
1255
+ }
1256
+ else {
1257
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1258
+ }
1259
+ return true;
1260
+ }
1261
+ this.requeue(entry);
1262
+ return true;
1263
+ }
1264
+ // where a run that moves goes back to: the commit it is at (service runs start from a ref)
1265
+ landingFrom(entry) {
1266
+ return {
1267
+ source: { ...entry.run.source },
1268
+ ...(entry.run.plan ? { plan: entry.run.plan } : {}),
1269
+ };
1270
+ }
1271
+ // The run starts again, its volumes kept
1272
+ requeue(entry) {
1273
+ entry.sleeping = false;
1274
+ entry.targets = undefined;
1275
+ entry.abort = new AbortController();
1276
+ entry.released = false;
1277
+ entry.timedOut = false;
1278
+ entry.run.state = 'queued';
1279
+ this.record(entry, { type: 'state', state: 'queued' });
1280
+ this.queue.push(entry);
1281
+ this.dispatch();
1282
+ }
1283
+ // Stops a service run at its expiry, and puts one that is up to sleep at its sleepsAt. A
1284
+ // timer can't wait longer than about 24 days, so a longer one looks again then.
1285
+ expireLater(entry) {
1286
+ this.clearTimer(entry);
1287
+ const expiresAt = Date.parse(entry.run.expiresAt ?? '');
1288
+ const sleepsAt = entry.run.state === 'up' ? Date.parse(entry.run.sleepsAt ?? '') : NaN;
1289
+ const next = Number.isFinite(sleepsAt) ? Math.min(expiresAt, sleepsAt) : expiresAt;
1290
+ entry.timer = setTimeout(() => {
1291
+ var _a;
1292
+ if (isFinal(entry.run.state)) {
1293
+ return;
1294
+ }
1295
+ if (Date.parse(entry.run.expiresAt ?? '') <= this.now()) {
1296
+ (_a = entry.run).stoppedBy ?? (_a.stoppedBy = 'ttl');
1297
+ entry.sleeping = false;
1298
+ if (entry.run.state === 'asleep') {
1299
+ this.finish(entry, 'succeeded');
1300
+ }
1301
+ else {
1302
+ this.stop(entry);
1303
+ }
1304
+ return;
1305
+ }
1306
+ if (entry.run.state === 'up' && Date.parse(entry.run.sleepsAt ?? '') <= this.now()) {
1307
+ if (entry.run.stoppedBy || entry.abort.signal.aborted) {
1308
+ // it stops already: it ends, it does not sleep
1309
+ return;
1310
+ }
1311
+ if (entry.mover || entry.pendingMove || entry.restartTo) {
1312
+ // it moves: it sleeps once its services are at the new commit
1313
+ this.keepAwake(entry);
1314
+ return;
1315
+ }
1316
+ entry.sleeping = true;
1317
+ entry.abort.abort();
1318
+ return;
1319
+ }
1320
+ this.expireLater(entry);
1321
+ }, Math.max(0, Math.min(next - this.now(), 2 ** 31 - 1)));
1322
+ entry.timer.unref();
1323
+ }
1324
+ keepsVolumes() {
1325
+ return this.options.up?.keepVolumes !== false;
1326
+ }
1327
+ // What the executor of a service run keeps of its services once they stopped, as it asks:
1328
+ // the volumes of a run that sleeps, on a server that keeps them. What it was told stays in
1329
+ // the record, so the volumes are removed (RunExecutor.forget) when the run ends asleep, or
1330
+ // when a stop came after the sleep began.
1331
+ keepOf(entry) {
1332
+ // a run that starts again at another commit keeps them on any server
1333
+ if (entry.restartTo || entry.landing || (entry.sleeping && this.keepsVolumes())) {
1334
+ entry.run.volumesKept = true;
1335
+ return 'volumes';
1336
+ }
1337
+ delete entry.run.volumesKept;
1338
+ return undefined;
1339
+ }
1340
+ // Whether a service run sleeps instead of ending: it has a sleepTtl, its ttl has not
1341
+ // ended, and it starts from a commit (the files of a sandbox change under it).
1342
+ maySleep(entry) {
1343
+ return (!!entry.run.up?.sleepTtl &&
1344
+ !!entry.run.upAt &&
1345
+ entry.run.source.type === 'ref' &&
1346
+ Date.parse(entry.run.expiresAt ?? '') > this.now());
1347
+ }
1348
+ // The services stopped, the run waits for a request to wake it, or for its end.
1349
+ sleep(entry) {
1350
+ entry.sleeping = false;
1351
+ entry.targets = undefined;
1352
+ entry.run.state = 'asleep';
1353
+ delete entry.run.sleepsAt;
1354
+ this.record(entry, { type: 'state', state: 'asleep' });
1355
+ this.expireLater(entry);
1356
+ }
1357
+ /**
1358
+ * A request to an endpoint of a service run: one that is up stays up for its sleepTtl from
1359
+ * now, one that is asleep is started again, if `mayWake` finds its owner may still run it
1360
+ * (else it ends) and there is a place of runs.up.limits for it (else it sleeps on, and the
1361
+ * next request asks again). Answers why it was not woken, or undefined.
1362
+ */
1363
+ visit(id, mayWake) {
1364
+ const entry = this.entries.get(id);
1365
+ if (!entry?.run.up) {
1366
+ return undefined;
1367
+ }
1368
+ const sleepTtl = entry.run.up.sleepTtl;
1369
+ if (entry.run.state === 'up' && sleepTtl) {
1370
+ // only kept in memory: a server that stops puts the run to sleep anyway
1371
+ entry.run.sleepsAt = new Date(this.now() + sleepTtl).toISOString();
1372
+ return undefined;
1373
+ }
1374
+ if (entry.run.state !== 'asleep' || this.closed) {
1375
+ return undefined;
1376
+ }
1377
+ if (!this.maySleep(entry)) {
1378
+ this.expireLater(entry);
1379
+ return 'its time ran out';
1380
+ }
1381
+ const refused = mayWake?.(this.copy(entry.run));
1382
+ if (refused) {
1383
+ this.finish(entry, 'failed', refused);
1384
+ return refused;
1385
+ }
1386
+ const full = this.upLimitReached(entry.run.owner, entry.run.up.name);
1387
+ if (full === 'caller') {
1388
+ return 'its owner has as many service runs starting or up as they may, it wakes once one of them stops or sleeps';
1389
+ }
1390
+ if (full === 'server') {
1391
+ return 'the server has as many service runs starting or up as it may, it wakes once one of them stops or sleeps';
1392
+ }
1393
+ this.clearTimer(entry);
1394
+ entry.abort = new AbortController();
1395
+ entry.released = false;
1396
+ entry.timedOut = false;
1397
+ entry.run.wakes = (entry.run.wakes ?? 0) + 1;
1398
+ entry.run.state = 'queued';
1399
+ entry.run.queuedAt = this.timestamp();
1400
+ this.record(entry, { type: 'state', state: 'queued' });
1401
+ this.queue.push(entry);
1402
+ this.dispatch();
1403
+ return undefined;
1404
+ }
1405
+ // The end of a run that was up: stopped by somebody, its ttl or a newer run it succeeded,
1406
+ // stopped by the server going away it failed, as its record says after a restart.
1407
+ endServices(entry, failure) {
1408
+ if (entry.timedOut) {
1409
+ this.finish(entry, 'failed', this.tooLong());
1410
+ }
1411
+ else if (!entry.abort.signal.aborted) {
1412
+ this.finish(entry, 'failed', failure);
1413
+ }
1414
+ else if (entry.run.stoppedBy) {
1415
+ this.finish(entry, 'succeeded');
1416
+ }
1417
+ else {
1418
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
477
1419
  }
478
1420
  }
479
1421
  tooLong() {
@@ -481,6 +1423,22 @@ class RunRegistry {
481
1423
  }
482
1424
  finish(entry, state, error) {
483
1425
  this.clearTimer(entry);
1426
+ clearTimeout(entry.durationTimer);
1427
+ entry.targets = undefined;
1428
+ entry.pendingMove = undefined;
1429
+ entry.restartTo = undefined;
1430
+ entry.landing = undefined;
1431
+ entry.mover?.abort.abort();
1432
+ entry.mover = undefined;
1433
+ delete entry.run.moving;
1434
+ if (entry.run.volumesKept) {
1435
+ // it ends without waking: what was kept for it goes
1436
+ delete entry.run.volumesKept;
1437
+ const run = this.copy(entry.run);
1438
+ Promise.resolve()
1439
+ .then(() => this.options.executor.forget?.(run))
1440
+ .catch((e) => this.options.log?.(`the volumes run ${run.id} kept could not be removed: ${e instanceof Error ? e.message : e}`));
1441
+ }
484
1442
  entry.run.state = state;
485
1443
  entry.run.finishedAt = this.timestamp();
486
1444
  if (error) {
@@ -495,9 +1453,27 @@ class RunRegistry {
495
1453
  }
496
1454
  this.record(entry, { type: 'state', state, ...(error ? { error } : {}) }, true);
497
1455
  entry.listeners.clear();
1456
+ try {
1457
+ this.options.onFinished?.(this.copy(entry.run), { ...entry.keys });
1458
+ }
1459
+ catch (e) {
1460
+ this.options.log?.(`run ${entry.run.id} ended, but what it passed was not kept: ${e instanceof Error ? e.message : e}`);
1461
+ }
498
1462
  this.evict();
499
1463
  }
500
1464
  record(entry, recorded, force = false) {
1465
+ if (recorded.type === 'key') {
1466
+ // a task name is the executor's; the first key it reports for a task is the one
1467
+ // computed before anything of the run had run
1468
+ if (!(recorded.task in entry.keys) && Object.keys(entry.keys).length < MAX_KEYED_TASKS) {
1469
+ entry.keys[recorded.task] = recorded.key;
1470
+ }
1471
+ return;
1472
+ }
1473
+ if (recorded.type === 'phase') {
1474
+ this.keepPhase(entry, recorded);
1475
+ return;
1476
+ }
501
1477
  const event = recorded.type === 'task' ? bounded(recorded) : recorded;
502
1478
  if (event.type === 'log') {
503
1479
  this.keepTail(entry, event.task, event.text);
@@ -520,6 +1496,19 @@ class RunRegistry {
520
1496
  }
521
1497
  this.push(entry, event);
522
1498
  }
1499
+ // once each, from the executor: a phase it reports again (a service run that wakes) is the
1500
+ // newest
1501
+ keepPhase(entry, event) {
1502
+ if (!exports.RUN_PHASES.includes(event.phase) ||
1503
+ !isTimestamp(event.startedAt) ||
1504
+ !isTimestamp(event.finishedAt) ||
1505
+ Date.parse(event.finishedAt) < Date.parse(event.startedAt)) {
1506
+ return;
1507
+ }
1508
+ const phases = (entry.run.phases ?? []).filter((phase) => phase.phase !== event.phase);
1509
+ phases.push({ phase: event.phase, startedAt: event.startedAt, finishedAt: event.finishedAt });
1510
+ entry.run.phases = phases.sort((a, b) => exports.RUN_PHASES.indexOf(a.phase) - exports.RUN_PHASES.indexOf(b.phase));
1511
+ }
523
1512
  keepTail(entry, task, text) {
524
1513
  let tail = entry.tails.get(task);
525
1514
  if (!tail) {
@@ -561,6 +1550,7 @@ class RunRegistry {
561
1550
  ...(event.durationMs !== undefined ? { durationMs: event.durationMs } : {}),
562
1551
  ...(event.exitCode !== undefined ? { exitCode: event.exitCode } : {}),
563
1552
  ...(event.error ? { error: event.error } : {}),
1553
+ ...(event.commands?.length ? { commands: event.commands } : {}),
564
1554
  ...(event.state === 'cached'
565
1555
  ? { cache: { hit: true } }
566
1556
  : event.state === 'succeeded' || event.state === 'failed'
@@ -579,7 +1569,7 @@ class RunRegistry {
579
1569
  }
580
1570
  // what a restart must not lose: the runs that wait, and how a run ended. A running
581
1571
  // run is not kept up to date, it fails with the server.
582
- if (event.type === 'state' || event.type === 'approval') {
1572
+ if (event.type === 'state' || event.type === 'approval' || event.type === 'extended' || event.type === 'moved') {
583
1573
  this.persist(entry);
584
1574
  }
585
1575
  }
@@ -598,7 +1588,11 @@ class RunRegistry {
598
1588
  const finished = [...this.entries.values()].filter((entry) => FINAL_STATES.includes(entry.run.state));
599
1589
  for (const entry of finished.slice(0, Math.max(0, finished.length - this.keep))) {
600
1590
  this.entries.delete(entry.run.id);
601
- void entry.saving.then(() => this.options.store?.remove(entry.run.id)).catch(() => undefined);
1591
+ const removal = entry.saving
1592
+ .then(() => this.options.store?.remove(entry.run.id))
1593
+ .catch(() => undefined)
1594
+ .finally(() => this.removing.delete(removal));
1595
+ this.removing.add(removal);
602
1596
  }
603
1597
  }
604
1598
  }