hammerkit 2.1.0-next.9 → 2.2.0-next.1

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 (70) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -1,20 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runRequestSchema = exports.runOptionsSchema = exports.MAX_ARGS_BYTES = exports.MAX_ARGS = exports.MAX_ENDPOINTS = exports.SERVICE_RUN_NAME_PATTERN = void 0;
3
+ exports.runRequestSchema = exports.runOptionsSchema = exports.MAX_ARGS_BYTES = exports.MAX_ARGS = exports.MAX_PUBLIC_PATHS = exports.MAX_ENDPOINTS = exports.SERVICE_RUN_NAME_PATTERN = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const units_1 = require("../utils/units");
6
6
  const bundle_1 = require("../remote/bundle");
7
7
  const repo_1 = require("./repo");
8
8
  const runs_1 = require("./runs");
9
+ const public_paths_1 = require("./public-paths");
9
10
  const name = zod_1.z.string().min(1).max(200);
10
11
  // The name of a service run, one DNS label: the hosts of its endpoints carry it, and a run of
11
12
  // the same caller with the same name replaces it
12
13
  exports.SERVICE_RUN_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$/;
13
14
  // endpoints one service run may publish
14
15
  exports.MAX_ENDPOINTS = 5;
16
+ // public paths one endpoint may have
17
+ exports.MAX_PUBLIC_PATHS = 10;
15
18
  // what one run may pass after `--`
16
19
  exports.MAX_ARGS = 100;
17
20
  exports.MAX_ARGS_BYTES = 16 * 1024;
21
+ // a path of an endpoint that needs no sign-in of the server, see isPublicPath
22
+ const publicPath = zod_1.z.string().superRefine((path, ctx) => {
23
+ const problem = (0, public_paths_1.publicPathProblem)(path);
24
+ if (problem) {
25
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: problem });
26
+ }
27
+ });
18
28
  // What `POST /v1/runs` takes. Who is asking and which accounts they may use is
19
29
  // decided from the token, never from this body; the accounts a run uses are those
20
30
  // its secrets are read as, which the server derives from the published build file.
@@ -124,6 +134,25 @@ exports.runRequestSchema = zod_1.z
124
134
  .array(zod_1.z.object({ service: name, port: zod_1.z.number().int().min(1).max(65535) }).strict())
125
135
  .max(exports.MAX_ENDPOINTS)
126
136
  .default([]),
137
+ // the services that start again with the files of their sandbox after an edit of it; the
138
+ // others keep the files they started with (see ServiceRunSpec.restart)
139
+ restart: zod_1.z.array(name).max(20).optional(),
140
+ // paths of those endpoints that need no sign-in of the server, such as an app's own sign-in
141
+ // for an MCP client; the run they are written for must be the one the run gets (see
142
+ // refusePublicPaths), and the endpoint one the run publishes
143
+ publicPaths: zod_1.z
144
+ .array(zod_1.z
145
+ .object({
146
+ run: zod_1.z
147
+ .string()
148
+ .regex(exports.SERVICE_RUN_NAME_PATTERN, 'expected lower case letters, digits and -, at most 40, as a DNS label'),
149
+ service: name,
150
+ port: zod_1.z.number().int().min(1).max(65535),
151
+ paths: zod_1.z.array(publicPath).min(1).max(exports.MAX_PUBLIC_PATHS),
152
+ })
153
+ .strict())
154
+ .max(exports.MAX_ENDPOINTS)
155
+ .default([]),
127
156
  })
128
157
  .strict()
129
158
  .refine((request) => request.services.length > 0 || request.tasks.length > 0 || (request.options.filter ?? []).length > 0, {
@@ -145,8 +174,41 @@ exports.runRequestSchema = zod_1.z
145
174
  request.sleepTtl === undefined &&
146
175
  request.name === undefined &&
147
176
  request.endpoints.length === 0), { message: 'ttl, sleepTtl, name and endpoints are for a run of services', path: ['services'] })
177
+ .refine((request) => (request.restart ?? []).every((service) => request.services.includes(service)), {
178
+ message: 'restart names services the run starts',
179
+ path: ['restart'],
180
+ })
181
+ .refine((request) => !request.restart?.length || request.source.type === 'sandbox', {
182
+ message: 'restart is for a service run from a sandbox, which changes with its files',
183
+ path: ['restart'],
184
+ })
148
185
  .refine((request) => new Set(request.endpoints.map((endpoint) => `${endpoint.service}:${endpoint.port}`)).size ===
149
186
  request.endpoints.length, { message: 'an endpoint is named twice', path: ['endpoints'] })
187
+ .refine((request) => request.publicPaths.length === 0 || request.services.length > 0, {
188
+ message: 'public paths are for a run of services',
189
+ path: ['publicPaths'],
190
+ })
191
+ .superRefine((request, ctx) => {
192
+ const seen = new Set();
193
+ for (const entry of request.publicPaths) {
194
+ const endpoint = `${entry.service}:${entry.port}`;
195
+ if (!request.endpoints.some((published) => published.service === entry.service && published.port === entry.port)) {
196
+ ctx.addIssue({
197
+ code: zod_1.z.ZodIssueCode.custom,
198
+ message: `a public path names ${endpoint}, which the run does not publish`,
199
+ path: ['publicPaths'],
200
+ });
201
+ }
202
+ if (seen.has(endpoint)) {
203
+ ctx.addIssue({
204
+ code: zod_1.z.ZodIssueCode.custom,
205
+ message: 'an endpoint has its public paths named twice',
206
+ path: ['publicPaths'],
207
+ });
208
+ }
209
+ seen.add(endpoint);
210
+ }
211
+ })
150
212
  .refine((request) => (request.options.args ?? []).length === 0 || request.tasks.length === 1, {
151
213
  message: 'arguments go to one task, name exactly one in tasks',
152
214
  path: ['options', 'args'],
@@ -3,6 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRetryRequest = void 0;
4
4
  const runs_1 = require("./runs");
5
5
  const run_request_1 = require("./run-request");
6
+ // The public paths of the endpoints of a service run, for the run started again under its name
7
+ function publicPathsOf(up) {
8
+ const { name } = up;
9
+ return up.endpoints.flatMap(({ service, port, publicPaths }) => publicPaths ? [{ run: name, service, port, paths: publicPaths }] : []);
10
+ }
6
11
  /**
7
12
  * A retry (`POST /v1/runs/<id>/retry`) is the request the run was started with, sent again by
8
13
  * who retries it: the same published build file, tasks or services, settings and arguments,
@@ -44,6 +49,7 @@ function getRetryRequest(run, owner) {
44
49
  ...(run.up.sleepTtl ? { sleepTtl: `${run.up.sleepTtl}ms` } : {}),
45
50
  name: run.up.name,
46
51
  endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
52
+ publicPaths: publicPathsOf(run.up),
47
53
  }
48
54
  : {}),
49
55
  });
@@ -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.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
  /**
@@ -75,6 +79,7 @@ exports.workerInputSchema = zod_1.z
75
79
  .object({
76
80
  services: zod_1.z.array(zod_1.z.string()).min(1),
77
81
  endpoints: zod_1.z.array(zod_1.z.object({ service: zod_1.z.string(), port: zod_1.z.number().int() }).strict()),
82
+ restart: zod_1.z.array(zod_1.z.string()).optional(),
78
83
  })
79
84
  .strict()
80
85
  .optional(),
@@ -82,6 +87,32 @@ exports.workerInputSchema = zod_1.z
82
87
  check: zod_1.z.boolean().optional(),
83
88
  // what its tasks took in past runs, in ms by name, so the longest chain starts first
84
89
  durations: zod_1.z.record(zod_1.z.number().nonnegative()).optional(),
90
+ // where the outputs the tasks export are kept for a download once the tasks ended, and
91
+ // what they may take together; left out for a run that keeps none (refuseArtifacts)
92
+ artifacts: zod_1.z
93
+ .object({ directory: zod_1.z.string().min(1), maxBytes: zod_1.z.number().int().positive() })
94
+ .strict()
95
+ .optional(),
96
+ // the run executed before a restart of the server: how far its log holds the output of
97
+ // each command in a sandbox's runner (RunContext.resumed)
98
+ resumed: zod_1.z
99
+ .object({
100
+ outputs: zod_1.z
101
+ .record(zod_1.z.string().regex(runner_commands_1.COMMAND_ID_PATTERN), zod_1.z
102
+ .object({
103
+ task: zod_1.z.string().max(1024),
104
+ step: zod_1.z.number().int().nonnegative(),
105
+ execution: zod_1.z.number().int().nonnegative(),
106
+ stdout: zod_1.z.number().int().nonnegative(),
107
+ stderr: zod_1.z.number().int().nonnegative(),
108
+ done: zod_1.z.literal(true).optional(),
109
+ cut: zod_1.z.literal(true).optional(),
110
+ })
111
+ .strict())
112
+ .refine((outputs) => Object.keys(outputs).length <= runner_commands_1.MAX_OUTPUT_COMMANDS, 'too many commands'),
113
+ })
114
+ .strict()
115
+ .optional(),
85
116
  })
86
117
  .strict();
87
118
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -145,6 +176,72 @@ function getEndpointTargets(workTree, up, kubernetes) {
145
176
  return targets;
146
177
  }
147
178
  exports.getEndpointTargets = getEndpointTargets;
179
+ // What the run says of a message of the engine: the output of its tasks and services, and
180
+ // what went wrong; where the log of a pod got to with a line of it (RunEventData)
181
+ function getLogEvent(message) {
182
+ if (message.type === 'console') {
183
+ return {
184
+ type: 'log',
185
+ task: message.context.name,
186
+ stream: message.console,
187
+ text: message.message.slice(0, MAX_LOG_TEXT),
188
+ ...(message.cursor ? { cursor: message.cursor } : {}),
189
+ };
190
+ }
191
+ if (message.level === 'error' || message.level === 'warn') {
192
+ return { type: 'log', task: message.context.name, stream: 'stderr', text: message.message.slice(0, MAX_LOG_TEXT) };
193
+ }
194
+ return undefined;
195
+ }
196
+ exports.getLogEvent = getLogEvent;
197
+ // What the commands of the run in a sandbox's runner know of it: the ones it started before a
198
+ // restart and how far its log held their output, and the `output` events that say how far it
199
+ // holds it now. They go out through `emit` after the log lines they count, so the registry
200
+ // never keeps an offset ahead of its log.
201
+ function getRunnerCommands(input, emit) {
202
+ return (0, runner_commands_1.createRunnerCommands)({
203
+ ...(input.resumed ? { resumed: input.resumed.outputs } : {}),
204
+ reached: (command, record) => emit({ type: 'output', command, ...record }),
205
+ });
206
+ }
207
+ exports.getRunnerCommands = getRunnerCommands;
208
+ // What the commands of a run that ended left in the sandbox goes: they are killed and their
209
+ // directory removed. Not when the server went (it stops, or died): the run resumes with the
210
+ // next one, which takes its commands up again. A server that stops kills this process before.
211
+ async function removeCommandsOfRun(input, commands, emit) {
212
+ const kubernetes = input.kubernetes;
213
+ const workspace = kubernetes?.server?.workspace;
214
+ if (!kubernetes || !workspace?.runner || commands.executions.size === 0) {
215
+ return;
216
+ }
217
+ try {
218
+ await (0, sandbox_runner_1.removeRunCommands)((0, kubernetes_instance_1.createKubernetesInstances)(kubernetes), kubernetes.namespace, workspace.label, kubernetes.server.run, {
219
+ clean: true,
220
+ });
221
+ }
222
+ catch (e) {
223
+ emit({
224
+ type: 'log',
225
+ task: 'hammerkit',
226
+ stream: 'stderr',
227
+ text: `what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
228
+ });
229
+ }
230
+ }
231
+ exports.removeCommandsOfRun = removeCommandsOfRun;
232
+ // What a task says in the process of a run, as events: the lines it prints (with where the log
233
+ // of its pod got to) and its warnings and errors, in the order they come. The `output` events
234
+ // of the commands in a runner are emitted after the lines they count, on the same way (see
235
+ // getRunnerCommands).
236
+ function relayStatus(status, emit) {
237
+ return status.on((message) => {
238
+ const event = getLogEvent(message);
239
+ if (event) {
240
+ emit(event);
241
+ }
242
+ });
243
+ }
244
+ exports.relayStatus = relayStatus;
148
245
  /**
149
246
  * Executes the tasks of a run with the engine of `hammerkit run`. The caller says which
150
247
  * process this is in: it reports what happens through `emit` and stops when `abortCtrl`
@@ -154,7 +251,12 @@ async function runTasks(input, cwd, processEnvs, abortCtrl,
154
251
  // whether the run was stopped from outside; the engine aborts too when a task fails
155
252
  cancelled, emit,
156
253
  // a service run: its services are ready, at these addresses
157
- up) {
254
+ up,
255
+ // its commands in a sandbox's runner
256
+ commands = getRunnerCommands(input, emit),
257
+ // a service run: hands the changed files of its sandbox to the services that are up while
258
+ // they are up (undefined once they are not)
259
+ register) {
158
260
  const secrets = (0, redact_1.createSecretRegistry)();
159
261
  const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
160
262
  // the process starts in a directory of the server, the tasks work on the run's files
@@ -168,6 +270,7 @@ up) {
168
270
  accounts: input.accounts,
169
271
  kubernetes: input.kubernetes,
170
272
  capabilityRuntime: input.capabilityRuntime,
273
+ runnerCommands: commands,
171
274
  },
172
275
  abortCtrl,
173
276
  cwd: work,
@@ -179,24 +282,7 @@ up) {
179
282
  stderr: (0, empty_writable_1.emptyWritable)(),
180
283
  stdoutColumns: 120,
181
284
  };
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
- });
285
+ const listener = relayStatus(status, emit);
200
286
  try {
201
287
  const options = input.options;
202
288
  const execOptions = {
@@ -260,6 +346,10 @@ up) {
260
346
  const execution = input.up
261
347
  ? cli.up({ ...execOptions, workers: cli.defaultWorkers(), daemon: false, wait: 'ready' })
262
348
  : cli.exec({ ...execOptions, workers: cli.defaultWorkers() });
349
+ if (input.up) {
350
+ const up = input.up;
351
+ register?.((changes) => syncServices(workTree, up, changes));
352
+ }
263
353
  const seen = new Map();
264
354
  const failedServices = new Set();
265
355
  let ready = false;
@@ -278,6 +368,9 @@ up) {
278
368
  try {
279
369
  const result = await execution.start();
280
370
  report();
371
+ if (input.artifacts && !input.up) {
372
+ await keepRunArtifacts(workTree, environment, input.artifacts, work, cancelled, emit, (text) => secrets.redact(text));
373
+ }
281
374
  // on a cluster the services stay in their Deployments once they are ready, until
282
375
  // the namespace of the run goes
283
376
  if (input.up && input.kubernetes && ready && result.success && !abortCtrl.signal.aborted) {
@@ -320,6 +413,9 @@ up) {
320
413
  }
321
414
  finally {
322
415
  watch.close();
416
+ if (input.up) {
417
+ register?.(undefined);
418
+ }
323
419
  if (input.up && input.kubernetes?.server?.serviceRun && !ready && service_rollouts_1.serviceRollouts.size > 0) {
324
420
  // a move (or a start) whose services did not all get up: the run stays where it was
325
421
  await service_rollouts_1.serviceRollouts.undo((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), (text) => emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
@@ -332,6 +428,24 @@ up) {
332
428
  }
333
429
  }
334
430
  exports.runTasks = runTasks;
431
+ // The outputs the tasks export, kept for a download whether the run failed or not: when a
432
+ // test failed its screenshots matter most. Into the log goes what was kept and what was not;
433
+ // a run ends as its tasks did, whatever happened to its outputs.
434
+ async function keepRunArtifacts(workTree, environment, artifacts, root, cancelled, emit, redact) {
435
+ const say = (stream, text) => emit({ type: 'log', task: 'hammerkit', stream, text: redact(text).slice(0, MAX_LOG_TEXT) });
436
+ try {
437
+ const kept = await (0, keep_artifacts_1.keepArtifacts)(workTree, environment, { ...artifacts, root, cancelled, redact });
438
+ for (const output of kept.outputs) {
439
+ say('stdout', `kept ${output.path} of ${output.task} for a download (${(0, units_2.formatSize)(output.bytes)})`);
440
+ }
441
+ for (const output of kept.left) {
442
+ say('stderr', `did not keep ${output.path} of ${output.task}: ${output.reason}`);
443
+ }
444
+ }
445
+ catch (e) {
446
+ say('stderr', `the outputs of the run could not be kept: ${(0, log_1.getErrorMessage)(e)}`);
447
+ }
448
+ }
335
449
  // What the cluster said of a run that failed, into its log: the server removes its pods
336
450
  // once it ended.
337
451
  async function reportClusterState(kubernetes, workTree, ownNamespace, emit, redact) {
@@ -497,11 +611,106 @@ redact) {
497
611
  }
498
612
  }
499
613
  }
614
+ /**
615
+ * Hands the files of a sandbox that changed to the services of a service run that are up:
616
+ * each one that takes files (its runtime says so) syncs them, and starts again when the run
617
+ * lists it in `restart`. The other services are not touched.
618
+ */
619
+ async function syncServices(workTree, up, changes) {
620
+ // one service that fails does not hold back the others: they are all tried, and the failures
621
+ // are said together
622
+ const failed = [];
623
+ for (const service of Object.values(workTree.services)) {
624
+ if (!up.services.includes(service.name)) {
625
+ continue;
626
+ }
627
+ try {
628
+ await service.runtime.syncFiles?.({ ...changes, restart: (up.restart ?? []).includes(service.name) });
629
+ }
630
+ catch (e) {
631
+ failed.push(`${service.name}: ${(0, log_1.getErrorMessage)(e)}`);
632
+ }
633
+ }
634
+ if (failed.length > 0) {
635
+ throw new Error(`the changed files were not synced to ${failed.join('; ')}`);
636
+ }
637
+ }
638
+ exports.syncServices = syncServices;
639
+ // The line `sync <json>` the server writes for a batch of changes: FileChanges, with its archive
640
+ // in base64
641
+ exports.syncLine = zod_1.z
642
+ .object({
643
+ archive: zod_1.z.string(),
644
+ written: zod_1.z.array(zod_1.z.string()),
645
+ deleted: zod_1.z.array(zod_1.z.string()),
646
+ restart: zod_1.z.boolean(),
647
+ })
648
+ .strict();
649
+ // The changes of a sync line, or undefined when the line does not match
650
+ function parseChanges(request) {
651
+ let json;
652
+ try {
653
+ json = JSON.parse(request);
654
+ }
655
+ catch {
656
+ return undefined;
657
+ }
658
+ const parsed = exports.syncLine.safeParse(json);
659
+ if (!parsed.success) {
660
+ return undefined;
661
+ }
662
+ return { ...parsed.data, archive: Buffer.from(parsed.data.archive, 'base64') };
663
+ }
664
+ exports.parseChanges = parseChanges;
665
+ /**
666
+ * Applies one batch of changes to the services that are up (`sync`). A line that does not parse
667
+ * is logged, and nothing else is done.
668
+ */
669
+ async function applyChanges(request, sync, log,
670
+ // told when the batch was not applied: the server then sends the full set again
671
+ failed = () => undefined) {
672
+ const changes = parseChanges(request);
673
+ if (!changes) {
674
+ log('the changed files of the sandbox could not be read');
675
+ failed();
676
+ return;
677
+ }
678
+ if (!sync) {
679
+ log('no service of the run is up to take the changed files of the sandbox');
680
+ failed();
681
+ return;
682
+ }
683
+ try {
684
+ await sync(changes);
685
+ }
686
+ catch (e) {
687
+ log(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`);
688
+ failed();
689
+ }
690
+ }
691
+ exports.applyChanges = applyChanges;
692
+ /**
693
+ * The batches of changes of a run, applied one after another in the order they came. A batch
694
+ * that fails does not stop the ones after it.
695
+ */
696
+ class ChangeQueue {
697
+ constructor(apply, fail) {
698
+ this.apply = apply;
699
+ this.fail = fail;
700
+ this.last = Promise.resolve();
701
+ }
702
+ push(request) {
703
+ this.last = this.last.then(() => this.apply(request)).catch((e) => this.fail(e));
704
+ return this.last;
705
+ }
706
+ }
707
+ exports.ChangeQueue = ChangeQueue;
500
708
  // The run is the first line of the standard input. The server keeps it open and writes
501
709
  // `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.
710
+ // on Windows ends the process without letting it stop its tasks. It writes `sync <json>` on
711
+ // it for the files of a sandbox that changed (FileChanges), which `sync` takes.
503
712
  // `onEnd` is told when the input ends before the run does: the server is gone.
504
- function readInput(stdin, cancel) {
713
+ function readInput(stdin, cancel, sync = () => undefined) {
505
714
  const lines = (0, readline_1.createInterface)({ input: stdin, crlfDelay: Infinity });
506
715
  let first;
507
716
  let closing = false;
@@ -516,6 +725,9 @@ function readInput(stdin, cancel) {
516
725
  else if (line.trim() === 'cancel') {
517
726
  cancel();
518
727
  }
728
+ else if (line.startsWith('sync ')) {
729
+ sync(line.slice('sync '.length));
730
+ }
519
731
  });
520
732
  lines.on('close', () => {
521
733
  resolve(first ?? '');
@@ -555,7 +767,13 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
555
767
  };
556
768
  const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
557
769
  signals.forEach((signal) => process.on(signal, stop));
558
- const reader = readInput(stdin, stop);
770
+ // the changes of the sandbox, one batch after the other, for the services that are up
771
+ let sync;
772
+ const logLine = (text) => say({ kind: 'event', event: { type: 'log', task: 'hammerkit', stream: 'stderr', text } });
773
+ 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)}`));
774
+ const reader = readInput(stdin, stop, (request) => {
775
+ void batches.push(request);
776
+ });
559
777
  let input;
560
778
  try {
561
779
  input = exports.workerInputSchema.parse(JSON.parse(await reader.input));
@@ -566,17 +784,33 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
566
784
  say({ kind: 'result', ok: false, error: `the run could not be read: ${e instanceof Error ? e.message : e}` });
567
785
  return;
568
786
  }
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
- }
787
+ // the input ends before the run does: the server is gone
788
+ let gone = false;
789
+ reader.onEnd(() => {
790
+ gone = true;
791
+ if (input.up) {
792
+ // services stay until they are stopped: without the server that would stop them, at
793
+ // their ttl or on a cancel, nothing would
794
+ stop();
795
+ }
796
+ });
797
+ const emit = (event) => say({ kind: 'event', event });
798
+ const commands = getRunnerCommands(input, emit);
574
799
  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) });
800
+ let result;
801
+ try {
802
+ await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands, (handler) => {
803
+ sync = handler;
804
+ });
805
+ result = { kind: 'result', ok: true };
806
+ }
807
+ catch (e) {
808
+ result = { kind: 'result', ok: false, error: e instanceof Error ? e.message : String(e) };
809
+ }
810
+ if (!gone) {
811
+ await removeCommandsOfRun(input, commands, emit);
812
+ }
813
+ say(result);
580
814
  }
581
815
  finally {
582
816
  reader.close();