hammerkit 2.1.0 → 2.2.0-next.2

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 (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
3
+ exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.parseChanges = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.getRunHosted = exports.createRunSecrets = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -28,6 +28,10 @@ const service_rollouts_1 = require("../kubernetes/service-rollouts");
28
28
  const cluster_state_1 = require("../kubernetes/cluster-state");
29
29
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
30
30
  const check_keys_1 = require("../optimizer/check-keys");
31
+ const units_2 = require("../utils/units");
32
+ const keep_artifacts_1 = require("./keep-artifacts");
33
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
34
+ const runner_commands_1 = require("../executer/runner-commands");
31
35
  // one log line of a task is cut here, the registry caps how many events a run keeps
32
36
  const MAX_LOG_TEXT = 8 * 1024;
33
37
  /**
@@ -59,6 +63,19 @@ exports.workerInputSchema = zod_1.z
59
63
  // on the server's docker host, the runtime a container that adds capabilities runs in
60
64
  // (`backend.capabilities.runtime`)
61
65
  capabilityRuntime: zod_1.z.string().min(1).optional(),
66
+ // the server's credential to write a registry cache with, for a trusted run only (`cache.push`,
67
+ // see cache-push.ts); left out for any other run, which may only read the caches
68
+ cachePush: zod_1.z
69
+ .object({
70
+ repository: zod_1.z.string().min(1),
71
+ username: zod_1.z.string().min(1),
72
+ password: zod_1.z.string().min(1),
73
+ })
74
+ .strict()
75
+ .optional(),
76
+ // the registry hosts the run may read its caches from (`cache.registries`, and each `cache.push`
77
+ // rule's registry): a build file's cache of any other is refused
78
+ cacheRegistries: zod_1.z.array(zod_1.z.string().min(1)).optional(),
62
79
  // the most any task or service reaches besides its needs, as `--network`: `runs.network`
63
80
  network: network_schema_1.networkSchema.optional(),
64
81
  // for a run on a sandbox, `sandboxes.network`: the run gets the lower of the two
@@ -75,6 +92,7 @@ exports.workerInputSchema = zod_1.z
75
92
  .object({
76
93
  services: zod_1.z.array(zod_1.z.string()).min(1),
77
94
  endpoints: zod_1.z.array(zod_1.z.object({ service: zod_1.z.string(), port: zod_1.z.number().int() }).strict()),
95
+ restart: zod_1.z.array(zod_1.z.string()).optional(),
78
96
  })
79
97
  .strict()
80
98
  .optional(),
@@ -82,6 +100,32 @@ exports.workerInputSchema = zod_1.z
82
100
  check: zod_1.z.boolean().optional(),
83
101
  // what its tasks took in past runs, in ms by name, so the longest chain starts first
84
102
  durations: zod_1.z.record(zod_1.z.number().nonnegative()).optional(),
103
+ // where the outputs the tasks export are kept for a download once the tasks ended, and
104
+ // what they may take together; left out for a run that keeps none (refuseArtifacts)
105
+ artifacts: zod_1.z
106
+ .object({ directory: zod_1.z.string().min(1), maxBytes: zod_1.z.number().int().positive() })
107
+ .strict()
108
+ .optional(),
109
+ // the run executed before a restart of the server: how far its log holds the output of
110
+ // each command in a sandbox's runner (RunContext.resumed)
111
+ resumed: zod_1.z
112
+ .object({
113
+ outputs: zod_1.z
114
+ .record(zod_1.z.string().regex(runner_commands_1.COMMAND_ID_PATTERN), zod_1.z
115
+ .object({
116
+ task: zod_1.z.string().max(1024),
117
+ step: zod_1.z.number().int().nonnegative(),
118
+ execution: zod_1.z.number().int().nonnegative(),
119
+ stdout: zod_1.z.number().int().nonnegative(),
120
+ stderr: zod_1.z.number().int().nonnegative(),
121
+ done: zod_1.z.literal(true).optional(),
122
+ cut: zod_1.z.literal(true).optional(),
123
+ })
124
+ .strict())
125
+ .refine((outputs) => Object.keys(outputs).length <= runner_commands_1.MAX_OUTPUT_COMMANDS, 'too many commands'),
126
+ })
127
+ .strict()
128
+ .optional(),
85
129
  })
86
130
  .strict();
87
131
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -145,6 +189,96 @@ function getEndpointTargets(workTree, up, kubernetes) {
145
189
  return targets;
146
190
  }
147
191
  exports.getEndpointTargets = getEndpointTargets;
192
+ // What the run says of a message of the engine: the output of its tasks and services, and
193
+ // what went wrong; where the log of a pod got to with a line of it (RunEventData)
194
+ function getLogEvent(message) {
195
+ if (message.type === 'console') {
196
+ return {
197
+ type: 'log',
198
+ task: message.context.name,
199
+ stream: message.console,
200
+ text: message.message.slice(0, MAX_LOG_TEXT),
201
+ ...(message.cursor ? { cursor: message.cursor } : {}),
202
+ };
203
+ }
204
+ if (message.level === 'error' || message.level === 'warn') {
205
+ return { type: 'log', task: message.context.name, stream: 'stderr', text: message.message.slice(0, MAX_LOG_TEXT) };
206
+ }
207
+ return undefined;
208
+ }
209
+ exports.getLogEvent = getLogEvent;
210
+ // What the commands of the run in a sandbox's runner know of it: the ones it started before a
211
+ // restart and how far its log held their output, and the `output` events that say how far it
212
+ // holds it now. They go out through `emit` after the log lines they count, so the registry
213
+ // never keeps an offset ahead of its log.
214
+ function getRunnerCommands(input, emit) {
215
+ return (0, runner_commands_1.createRunnerCommands)({
216
+ ...(input.resumed ? { resumed: input.resumed.outputs } : {}),
217
+ reached: (command, record) => emit({ type: 'output', command, ...record }),
218
+ });
219
+ }
220
+ exports.getRunnerCommands = getRunnerCommands;
221
+ // What the commands of a run that ended left in the sandbox goes: they are killed and their
222
+ // directory removed. Not when the server went (it stops, or died): the run resumes with the
223
+ // next one, which takes its commands up again. A server that stops kills this process before.
224
+ async function removeCommandsOfRun(input, commands, emit) {
225
+ const kubernetes = input.kubernetes;
226
+ const workspace = kubernetes?.server?.workspace;
227
+ if (!kubernetes || !workspace?.runner || commands.executions.size === 0) {
228
+ return;
229
+ }
230
+ try {
231
+ await (0, sandbox_runner_1.removeRunCommands)((0, kubernetes_instance_1.createKubernetesInstances)(kubernetes), kubernetes.namespace, workspace.label, kubernetes.server.run, {
232
+ clean: true,
233
+ });
234
+ }
235
+ catch (e) {
236
+ emit({
237
+ type: 'log',
238
+ task: 'hammerkit',
239
+ stream: 'stderr',
240
+ text: `what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
241
+ });
242
+ }
243
+ }
244
+ exports.removeCommandsOfRun = removeCommandsOfRun;
245
+ // The secrets of a run, masked in what it logs: the password of its cache push, as a secret of a
246
+ // task is (ADR-0010).
247
+ function createRunSecrets(input) {
248
+ const secrets = (0, redact_1.createSecretRegistry)();
249
+ if (input.cachePush) {
250
+ secrets.register(input.cachePush.password);
251
+ }
252
+ return secrets;
253
+ }
254
+ exports.createRunSecrets = createRunSecrets;
255
+ // What the engine of a run knows of its server: the credential to write a cache with, and the
256
+ // registries it may read, which only a server run has (see HostedPolicy).
257
+ function getRunHosted(input, commands) {
258
+ return {
259
+ catalog: input.catalog,
260
+ accounts: input.accounts,
261
+ kubernetes: input.kubernetes,
262
+ capabilityRuntime: input.capabilityRuntime,
263
+ runnerCommands: commands,
264
+ cacheRegistries: input.cacheRegistries ?? [],
265
+ ...(input.cachePush ? { cachePush: input.cachePush } : {}),
266
+ };
267
+ }
268
+ exports.getRunHosted = getRunHosted;
269
+ // What a task says in the process of a run, as events: the lines it prints (with where the log
270
+ // of its pod got to) and its warnings and errors, in the order they come. The `output` events
271
+ // of the commands in a runner are emitted after the lines they count, on the same way (see
272
+ // getRunnerCommands).
273
+ function relayStatus(status, emit) {
274
+ return status.on((message) => {
275
+ const event = getLogEvent(message);
276
+ if (event) {
277
+ emit(event);
278
+ }
279
+ });
280
+ }
281
+ exports.relayStatus = relayStatus;
148
282
  /**
149
283
  * Executes the tasks of a run with the engine of `hammerkit run`. The caller says which
150
284
  * process this is in: it reports what happens through `emit` and stops when `abortCtrl`
@@ -154,8 +288,13 @@ async function runTasks(input, cwd, processEnvs, abortCtrl,
154
288
  // whether the run was stopped from outside; the engine aborts too when a task fails
155
289
  cancelled, emit,
156
290
  // a service run: its services are ready, at these addresses
157
- up) {
158
- const secrets = (0, redact_1.createSecretRegistry)();
291
+ up,
292
+ // its commands in a sandbox's runner
293
+ commands = getRunnerCommands(input, emit),
294
+ // a service run: hands the changed files of its sandbox to the services that are up while
295
+ // they are up (undefined once they are not)
296
+ register) {
297
+ const secrets = createRunSecrets(input);
159
298
  const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
160
299
  // the process starts in a directory of the server, the tasks work on the run's files
161
300
  const work = input.directory?.work ?? cwd;
@@ -163,12 +302,7 @@ up) {
163
302
  // is what is streamed: it is redacted with the secrets of this run
164
303
  const environment = {
165
304
  processEnvs,
166
- hosted: {
167
- catalog: input.catalog,
168
- accounts: input.accounts,
169
- kubernetes: input.kubernetes,
170
- capabilityRuntime: input.capabilityRuntime,
171
- },
305
+ hosted: getRunHosted(input, commands),
172
306
  abortCtrl,
173
307
  cwd: work,
174
308
  file: (0, get_file_context_1.getFileContext)(work),
@@ -179,24 +313,7 @@ up) {
179
313
  stderr: (0, empty_writable_1.emptyWritable)(),
180
314
  stdoutColumns: 120,
181
315
  };
182
- const listener = status.on((message) => {
183
- if (message.type === 'console') {
184
- emit({
185
- type: 'log',
186
- task: message.context.name,
187
- stream: message.console,
188
- text: message.message.slice(0, MAX_LOG_TEXT),
189
- });
190
- }
191
- else if (message.level === 'error' || message.level === 'warn') {
192
- emit({
193
- type: 'log',
194
- task: message.context.name,
195
- stream: 'stderr',
196
- text: message.message.slice(0, MAX_LOG_TEXT),
197
- });
198
- }
199
- });
316
+ const listener = relayStatus(status, emit);
200
317
  try {
201
318
  const options = input.options;
202
319
  const execOptions = {
@@ -260,6 +377,10 @@ up) {
260
377
  const execution = input.up
261
378
  ? cli.up({ ...execOptions, workers: cli.defaultWorkers(), daemon: false, wait: 'ready' })
262
379
  : cli.exec({ ...execOptions, workers: cli.defaultWorkers() });
380
+ if (input.up) {
381
+ const up = input.up;
382
+ register?.((changes) => syncServices(workTree, up, changes));
383
+ }
263
384
  const seen = new Map();
264
385
  const failedServices = new Set();
265
386
  let ready = false;
@@ -278,6 +399,9 @@ up) {
278
399
  try {
279
400
  const result = await execution.start();
280
401
  report();
402
+ if (input.artifacts && !input.up) {
403
+ await keepRunArtifacts(workTree, environment, input.artifacts, work, cancelled, emit, (text) => secrets.redact(text));
404
+ }
281
405
  // on a cluster the services stay in their Deployments once they are ready, until
282
406
  // the namespace of the run goes
283
407
  if (input.up && input.kubernetes && ready && result.success && !abortCtrl.signal.aborted) {
@@ -320,6 +444,9 @@ up) {
320
444
  }
321
445
  finally {
322
446
  watch.close();
447
+ if (input.up) {
448
+ register?.(undefined);
449
+ }
323
450
  if (input.up && input.kubernetes?.server?.serviceRun && !ready && service_rollouts_1.serviceRollouts.size > 0) {
324
451
  // a move (or a start) whose services did not all get up: the run stays where it was
325
452
  await service_rollouts_1.serviceRollouts.undo((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), (text) => emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
@@ -332,6 +459,24 @@ up) {
332
459
  }
333
460
  }
334
461
  exports.runTasks = runTasks;
462
+ // The outputs the tasks export, kept for a download whether the run failed or not: when a
463
+ // test failed its screenshots matter most. Into the log goes what was kept and what was not;
464
+ // a run ends as its tasks did, whatever happened to its outputs.
465
+ async function keepRunArtifacts(workTree, environment, artifacts, root, cancelled, emit, redact) {
466
+ const say = (stream, text) => emit({ type: 'log', task: 'hammerkit', stream, text: redact(text).slice(0, MAX_LOG_TEXT) });
467
+ try {
468
+ const kept = await (0, keep_artifacts_1.keepArtifacts)(workTree, environment, { ...artifacts, root, cancelled, redact });
469
+ for (const output of kept.outputs) {
470
+ say('stdout', `kept ${output.path} of ${output.task} for a download (${(0, units_2.formatSize)(output.bytes)})`);
471
+ }
472
+ for (const output of kept.left) {
473
+ say('stderr', `did not keep ${output.path} of ${output.task}: ${output.reason}`);
474
+ }
475
+ }
476
+ catch (e) {
477
+ say('stderr', `the outputs of the run could not be kept: ${(0, log_1.getErrorMessage)(e)}`);
478
+ }
479
+ }
335
480
  // What the cluster said of a run that failed, into its log: the server removes its pods
336
481
  // once it ended.
337
482
  async function reportClusterState(kubernetes, workTree, ownNamespace, emit, redact) {
@@ -497,11 +642,106 @@ redact) {
497
642
  }
498
643
  }
499
644
  }
645
+ /**
646
+ * Hands the files of a sandbox that changed to the services of a service run that are up:
647
+ * each one that takes files (its runtime says so) syncs them, and starts again when the run
648
+ * lists it in `restart`. The other services are not touched.
649
+ */
650
+ async function syncServices(workTree, up, changes) {
651
+ // one service that fails does not hold back the others: they are all tried, and the failures
652
+ // are said together
653
+ const failed = [];
654
+ for (const service of Object.values(workTree.services)) {
655
+ if (!up.services.includes(service.name)) {
656
+ continue;
657
+ }
658
+ try {
659
+ await service.runtime.syncFiles?.({ ...changes, restart: (up.restart ?? []).includes(service.name) });
660
+ }
661
+ catch (e) {
662
+ failed.push(`${service.name}: ${(0, log_1.getErrorMessage)(e)}`);
663
+ }
664
+ }
665
+ if (failed.length > 0) {
666
+ throw new Error(`the changed files were not synced to ${failed.join('; ')}`);
667
+ }
668
+ }
669
+ exports.syncServices = syncServices;
670
+ // The line `sync <json>` the server writes for a batch of changes: FileChanges, with its archive
671
+ // in base64
672
+ exports.syncLine = zod_1.z
673
+ .object({
674
+ archive: zod_1.z.string(),
675
+ written: zod_1.z.array(zod_1.z.string()),
676
+ deleted: zod_1.z.array(zod_1.z.string()),
677
+ restart: zod_1.z.boolean(),
678
+ })
679
+ .strict();
680
+ // The changes of a sync line, or undefined when the line does not match
681
+ function parseChanges(request) {
682
+ let json;
683
+ try {
684
+ json = JSON.parse(request);
685
+ }
686
+ catch {
687
+ return undefined;
688
+ }
689
+ const parsed = exports.syncLine.safeParse(json);
690
+ if (!parsed.success) {
691
+ return undefined;
692
+ }
693
+ return { ...parsed.data, archive: Buffer.from(parsed.data.archive, 'base64') };
694
+ }
695
+ exports.parseChanges = parseChanges;
696
+ /**
697
+ * Applies one batch of changes to the services that are up (`sync`). A line that does not parse
698
+ * is logged, and nothing else is done.
699
+ */
700
+ async function applyChanges(request, sync, log,
701
+ // told when the batch was not applied: the server then sends the full set again
702
+ failed = () => undefined) {
703
+ const changes = parseChanges(request);
704
+ if (!changes) {
705
+ log('the changed files of the sandbox could not be read');
706
+ failed();
707
+ return;
708
+ }
709
+ if (!sync) {
710
+ log('no service of the run is up to take the changed files of the sandbox');
711
+ failed();
712
+ return;
713
+ }
714
+ try {
715
+ await sync(changes);
716
+ }
717
+ catch (e) {
718
+ log(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`);
719
+ failed();
720
+ }
721
+ }
722
+ exports.applyChanges = applyChanges;
723
+ /**
724
+ * The batches of changes of a run, applied one after another in the order they came. A batch
725
+ * that fails does not stop the ones after it.
726
+ */
727
+ class ChangeQueue {
728
+ constructor(apply, fail) {
729
+ this.apply = apply;
730
+ this.fail = fail;
731
+ this.last = Promise.resolve();
732
+ }
733
+ push(request) {
734
+ this.last = this.last.then(() => this.apply(request)).catch((e) => this.fail(e));
735
+ return this.last;
736
+ }
737
+ }
738
+ exports.ChangeQueue = ChangeQueue;
500
739
  // The run is the first line of the standard input. The server keeps it open and writes
501
740
  // `cancel` on it to stop the run: that works the same on every platform, where a signal
502
- // on Windows ends the process without letting it stop its tasks.
741
+ // on Windows ends the process without letting it stop its tasks. It writes `sync <json>` on
742
+ // it for the files of a sandbox that changed (FileChanges), which `sync` takes.
503
743
  // `onEnd` is told when the input ends before the run does: the server is gone.
504
- function readInput(stdin, cancel) {
744
+ function readInput(stdin, cancel, sync = () => undefined) {
505
745
  const lines = (0, readline_1.createInterface)({ input: stdin, crlfDelay: Infinity });
506
746
  let first;
507
747
  let closing = false;
@@ -516,6 +756,9 @@ function readInput(stdin, cancel) {
516
756
  else if (line.trim() === 'cancel') {
517
757
  cancel();
518
758
  }
759
+ else if (line.startsWith('sync ')) {
760
+ sync(line.slice('sync '.length));
761
+ }
519
762
  });
520
763
  lines.on('close', () => {
521
764
  resolve(first ?? '');
@@ -555,7 +798,13 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
555
798
  };
556
799
  const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
557
800
  signals.forEach((signal) => process.on(signal, stop));
558
- const reader = readInput(stdin, stop);
801
+ // the changes of the sandbox, one batch after the other, for the services that are up
802
+ let sync;
803
+ const logLine = (text) => say({ kind: 'event', event: { type: 'log', task: 'hammerkit', stream: 'stderr', text } });
804
+ const batches = new ChangeQueue((request) => applyChanges(request, sync, logLine, () => say({ kind: 'sync-failed' })), (e) => logLine(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`));
805
+ const reader = readInput(stdin, stop, (request) => {
806
+ void batches.push(request);
807
+ });
559
808
  let input;
560
809
  try {
561
810
  input = exports.workerInputSchema.parse(JSON.parse(await reader.input));
@@ -566,17 +815,33 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
566
815
  say({ kind: 'result', ok: false, error: `the run could not be read: ${e instanceof Error ? e.message : e}` });
567
816
  return;
568
817
  }
569
- if (input.up) {
570
- // services stay until they are stopped: without the server that would stop them, at
571
- // their ttl or on a cancel, nothing would
572
- reader.onEnd(stop);
573
- }
818
+ // the input ends before the run does: the server is gone
819
+ let gone = false;
820
+ reader.onEnd(() => {
821
+ gone = true;
822
+ if (input.up) {
823
+ // services stay until they are stopped: without the server that would stop them, at
824
+ // their ttl or on a cancel, nothing would
825
+ stop();
826
+ }
827
+ });
828
+ const emit = (event) => say({ kind: 'event', event });
829
+ const commands = getRunnerCommands(input, emit);
574
830
  try {
575
- await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, (event) => say({ kind: 'event', event }), (targets) => say({ kind: 'up', targets }));
576
- say({ kind: 'result', ok: true });
577
- }
578
- catch (e) {
579
- say({ kind: 'result', ok: false, error: e instanceof Error ? e.message : String(e) });
831
+ let result;
832
+ try {
833
+ await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands, (handler) => {
834
+ sync = handler;
835
+ });
836
+ result = { kind: 'result', ok: true };
837
+ }
838
+ catch (e) {
839
+ result = { kind: 'result', ok: false, error: e instanceof Error ? e.message : String(e) };
840
+ }
841
+ if (!gone) {
842
+ await removeCommandsOfRun(input, commands, emit);
843
+ }
844
+ say(result);
580
845
  }
581
846
  finally {
582
847
  reader.close();