hammerkit 2.0.0-next.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/network-gate.js +74 -11
  37. package/dist/kubernetes/network-policy.js +32 -10
  38. package/dist/kubernetes/remove-stale-items.js +15 -2
  39. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  40. package/dist/kubernetes/sandbox-runner.js +3 -4
  41. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  42. package/dist/kubernetes/transfer-tools.js +66 -0
  43. package/dist/kubernetes/volumes.js +52 -10
  44. package/dist/optimizer/check-key.js +7 -0
  45. package/dist/optimizer/check-keys.js +19 -5
  46. package/dist/optimizer/get-work-cache-stats.js +19 -7
  47. package/dist/optimizer/work-task-cache-description.js +42 -8
  48. package/dist/planner/image-build.js +172 -0
  49. package/dist/planner/utils/append-work-dependencies.js +14 -1
  50. package/dist/planner/utils/append-work-service.js +1 -1
  51. package/dist/planner/utils/append-work-task.js +51 -1
  52. package/dist/planner/utils/assert-item-paths.js +6 -7
  53. package/dist/planner/utils/dependency-outputs.js +18 -0
  54. package/dist/planner/work-runtime-docker.js +48 -50
  55. package/dist/planner/work-runtime-kubernetes.js +1 -0
  56. package/dist/planner/work-runtime-local.js +3 -7
  57. package/dist/planner/work-secret.js +135 -13
  58. package/dist/planner/work-tree.js +10 -0
  59. package/dist/remote/collect-bundle.js +9 -1
  60. package/dist/remote/host-config.js +49 -3
  61. package/dist/remote/location.js +5 -5
  62. package/dist/remote/remote-commands.js +12 -14
  63. package/dist/remote/remote-work-commands.js +20 -8
  64. package/dist/schema/build-file-image-build-schema.js +77 -0
  65. package/dist/schema/build-file-task-schema.js +9 -2
  66. package/dist/schema/reference-parser.js +10 -1
  67. package/dist/schema/work-scope-parser.js +16 -1
  68. package/dist/secrets/secret-catalog.js +8 -1
  69. package/dist/server/dashboard.js +8 -5
  70. package/dist/server/executor.js +58 -35
  71. package/dist/server/kubernetes-backend.js +29 -4
  72. package/dist/server/overview.js +20 -2
  73. package/dist/server/plan.js +31 -3
  74. package/dist/server/policy.js +14 -7
  75. package/dist/server/repo-access.js +4 -3
  76. package/dist/server/run-environment.js +5 -2
  77. package/dist/server/run-plan.js +18 -6
  78. package/dist/server/run-retry.js +57 -0
  79. package/dist/server/run-source-environment.js +39 -0
  80. package/dist/server/run-worker.js +38 -9
  81. package/dist/server/runs.js +59 -1
  82. package/dist/server/sandbox-files.js +232 -39
  83. package/dist/server/server-config.js +24 -4
  84. package/dist/server/server.js +107 -12
  85. package/dist/server/service-runs.js +42 -4
  86. package/dist/utils/line-splitter.js +52 -0
  87. package/dist/utils/tar.js +51 -1
  88. package/package.json +1 -1
  89. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -6,7 +6,8 @@ const plan_1 = require("./plan");
6
6
  function labels(values) {
7
7
  return values && values.length > 0 ? (0, parse_label_arguments_1.parseLabelArguments)(values) : undefined;
8
8
  }
9
- // The tasks in the order they were named, one scope each; by labels when none is. A
9
+ // The tasks named, as one scope: they are planned together and run side by side as far
10
+ // as their dependencies allow, in no particular order; by labels when none is named. A
10
11
  // service run is one scope of its services.
11
12
  // The arguments, if any, go to the one task named (the request allows no more). That
12
13
  // task runs uncached unless the request names a `cache` method, as `run --cache` does.
@@ -17,11 +18,22 @@ function getRunScopes(tasks, options, services = []) {
17
18
  const args = options.args && options.args.length > 0
18
19
  ? { values: options.args, services: false, cache: options.cache !== undefined }
19
20
  : undefined;
20
- return tasks.length > 0
21
- ? tasks.map((task) => ({
22
- name: task,
23
- scope: { taskName: task, environmentName: options.env ?? null, ...(args ? { args } : {}) },
24
- }))
21
+ const named = [...new Set(tasks)];
22
+ if (named.length === 1) {
23
+ return [
24
+ {
25
+ name: named[0],
26
+ scope: { taskName: named[0], environmentName: options.env ?? null, ...(args ? { args } : {}) },
27
+ },
28
+ ];
29
+ }
30
+ return named.length > 0
31
+ ? [
32
+ {
33
+ name: named.join(', '),
34
+ scope: { taskNames: named, environmentName: options.env ?? null, ...(args ? { args } : {}) },
35
+ },
36
+ ]
25
37
  : [
26
38
  {
27
39
  name: 'labels',
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getRetryRequest = void 0;
4
+ const runs_1 = require("./runs");
5
+ const run_request_1 = require("./run-request");
6
+ /**
7
+ * A retry (`POST /v1/runs/<id>/retry`) is the request the run was started with, sent again by
8
+ * who retries it: the same published build file, tasks or services, settings and arguments,
9
+ * from the same source. A run from a branch runs the commit it ran: the server refuses the
10
+ * retry once the branch moved on, so the accounts of a branch never run a commit that is no
11
+ * longer on it. A run on a sandbox runs on the files the sandbox holds now, the work of its
12
+ * owner, who alone may retry it.
13
+ *
14
+ * It names every task the run named, not only those that failed: the tasks that passed are
15
+ * read from the cache, and a run that was stopped or rejected has no failed ones to tell.
16
+ */
17
+ function getRetryRequest(run, owner) {
18
+ if (!(0, runs_1.isFinal)(run.state)) {
19
+ return { error: `${run.id} is ${run.state}, a run is retried once it is over` };
20
+ }
21
+ let source;
22
+ if (run.source.type === 'ref') {
23
+ source = { type: 'ref', repo: run.source.repo, ref: run.source.ref, commit: run.source.commit };
24
+ }
25
+ else if (run.source.type === 'sandbox') {
26
+ // a sandbox is its owner's: nobody else may run from it
27
+ if (!owner) {
28
+ return { error: `${run.id} ran from a sandbox of its owner, only they may retry it` };
29
+ }
30
+ source = { type: 'sandbox', id: run.source.id, ...(run.source.check ? { check: true } : {}) };
31
+ }
32
+ else {
33
+ return { error: `${run.id} ran from uploaded files, which a run is not retried from` };
34
+ }
35
+ const parsed = run_request_1.runRequestSchema.safeParse({
36
+ definition: run.definition,
37
+ tasks: run.tasks,
38
+ source,
39
+ options: run.options ?? {},
40
+ ...(run.up
41
+ ? {
42
+ services: run.up.services,
43
+ ttl: `${run.up.ttl}ms`,
44
+ ...(run.up.sleepTtl ? { sleepTtl: `${run.up.sleepTtl}ms` } : {}),
45
+ name: run.up.name,
46
+ endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
47
+ }
48
+ : {}),
49
+ });
50
+ if (!parsed.success) {
51
+ const issue = parsed.error.issues[0];
52
+ return { error: `${run.id} can not be started again: ${issue.path.join('.') || 'request'}: ${issue.message}` };
53
+ }
54
+ return { request: parsed.data };
55
+ }
56
+ exports.getRetryRequest = getRetryRequest;
57
+ //# sourceMappingURL=run-retry.js.map
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runPlanningEnvironment = exports.withRunSource = exports.runSourceEnvironment = exports.RUN_SOURCE_ENVS = void 0;
4
+ const run_source_envs_1 = require("../environment/run-source-envs");
5
+ Object.defineProperty(exports, "RUN_SOURCE_ENVS", { enumerable: true, get: function () { return run_source_envs_1.RUN_SOURCE_ENVS; } });
6
+ // a ref may name a commit, which is no branch or tag (see git-checkout.ts)
7
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
8
+ // What a run is from, for the `envs` of its tasks and services (`$HAMMERKIT_RUN_REF`): the
9
+ // repository, and the branch or tag and the commit it was pinned to, or the repository and the
10
+ // sandbox. None of them is a credential, so a task that reads them still takes arguments and
11
+ // keeps its network (see PLAIN_SERVER_ENVS). A sandbox has no commit: its files may hold
12
+ // changes. A run from an upload has none of them.
13
+ function runSourceEnvironment(source) {
14
+ if (source.type === 'ref') {
15
+ return {
16
+ HAMMERKIT_RUN_REPO: source.repo,
17
+ ...(COMMIT.test(source.ref) ? {} : { HAMMERKIT_RUN_REF: source.ref }),
18
+ ...(source.commit ? { HAMMERKIT_RUN_COMMIT: source.commit } : {}),
19
+ };
20
+ }
21
+ if (source.type === 'sandbox') {
22
+ return { HAMMERKIT_RUN_REPO: source.repo, HAMMERKIT_RUN_SANDBOX: source.id };
23
+ }
24
+ return {};
25
+ }
26
+ exports.runSourceEnvironment = runSourceEnvironment;
27
+ // The variables of a process, and the run's own in place of any of the same name, in any case.
28
+ function withRunSource(envs, source) {
29
+ const kept = Object.fromEntries(Object.entries(envs).filter(([name]) => !(0, run_source_envs_1.isRunSourceEnv)(name)));
30
+ return { ...kept, ...runSourceEnvironment(source) };
31
+ }
32
+ exports.withRunSource = withRunSource;
33
+ // The environment a run's files are read with, on the server, before its process starts: so
34
+ // the plan an approver reads shows what the tasks will see.
35
+ function runPlanningEnvironment(environment, source) {
36
+ return { ...environment, processEnvs: withRunSource(environment.processEnvs, source) };
37
+ }
38
+ exports.runPlanningEnvironment = runPlanningEnvironment;
39
+ //# sourceMappingURL=run-source-environment.js.map
@@ -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.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
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;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -80,6 +80,8 @@ exports.workerInputSchema = zod_1.z
80
80
  .optional(),
81
81
  // the run's results count as checks: report each task's check key before it runs
82
82
  check: zod_1.z.boolean().optional(),
83
+ // what its tasks took in past runs, in ms by name, so the longest chain starts first
84
+ durations: zod_1.z.record(zod_1.z.number().nonnegative()).optional(),
83
85
  })
84
86
  .strict();
85
87
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -206,6 +208,7 @@ up) {
206
208
  maxTimeout: options.maxTimeout ? (0, units_1.parseDuration)(options.maxTimeout) : null,
207
209
  skipDeps: options.skipDeps !== false,
208
210
  network: getRunNetwork(input),
211
+ ...(input.durations ? { durations: input.durations } : {}),
209
212
  // why a task was not taken from the cache goes into its result
210
213
  explain: true,
211
214
  };
@@ -214,17 +217,25 @@ up) {
214
217
  // the files as they are before any task wrote to them, a second task's too: a first
215
218
  // one that formats or generates into src would key it by files no commit holds
216
219
  for (const { scope } of scopes) {
217
- for (const [task, { key }] of Object.entries(await (0, check_keys_1.getCheckKeys)(input.entry, environment, scope))) {
220
+ for (const [task, { key }] of Object.entries(await (0, check_keys_1.getCheckKeys)(input.entry, environment, scope, input.directory))) {
218
221
  emit({ type: 'key', task, key });
219
222
  }
220
223
  }
221
224
  }
222
- let planned = false;
225
+ // every scope is planned before any task runs: what the run executes is read from the
226
+ // published files as they were when it started, whatever a task does to its files
227
+ const planned = [];
223
228
  for (const { name, scope } of scopes) {
224
229
  const { ctx, scope: parsed } = await (0, schema_parser_1.createParseContext)(input.entry, environment, {
225
230
  directory: input.directory,
226
231
  });
227
- const workTree = (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, environment), scope, environment);
232
+ planned.push({
233
+ name,
234
+ workTree: (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, environment), scope, environment),
235
+ });
236
+ }
237
+ let started = false;
238
+ for (const { name, workTree } of planned) {
228
239
  await (0, assert_item_paths_1.assertWorkTreePathsWithinRoot)(workTree, work);
229
240
  if (input.volumeScope && !input.kubernetes) {
230
241
  (0, hosted_volumes_1.scopeServiceVolumes)(workTree, input.volumeScope);
@@ -236,9 +247,9 @@ up) {
236
247
  if (cli.tasks().length === 0 && (!input.up || cli.services().length === 0)) {
237
248
  throw new Error(`no tasks found for ${name}`);
238
249
  }
239
- if (!planned) {
250
+ if (!started) {
240
251
  // from the start of this process, which the executor started for the run
241
- planned = true;
252
+ started = true;
242
253
  emit({
243
254
  type: 'phase',
244
255
  phase: 'plan',
@@ -273,14 +284,19 @@ up) {
273
284
  if (input.kubernetes.server?.serviceRun) {
274
285
  // a run that moved here from another commit: what it made for items it has no more
275
286
  const ids = [...Object.values(workTree.tasks), ...Object.values(workTree.services)].map((item) => item.id());
276
- await (0, remove_stale_items_1.removeStaleItems)((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), input.kubernetes, ids).catch((e) => emit({
287
+ await (0, remove_stale_items_1.removeStaleItems)((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), input.kubernetes, ids, {
288
+ signal: abortCtrl.signal,
289
+ }).catch((e) => emit({
277
290
  type: 'log',
278
291
  task: 'hammerkit',
279
292
  stream: 'stderr',
280
293
  text: `what the run made at its previous commit could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
281
294
  }));
282
295
  }
283
- await new Promise((resolve) => abortCtrl.signal.addEventListener('abort', () => resolve(), { once: true }));
296
+ // stopped while the old pods ended, or up until it is stopped
297
+ if (!abortCtrl.signal.aborted) {
298
+ await new Promise((resolve) => abortCtrl.signal.addEventListener('abort', () => resolve(), { once: true }));
299
+ }
284
300
  return;
285
301
  }
286
302
  if (input.up && ready) {
@@ -299,7 +315,7 @@ up) {
299
315
  }
300
316
  // a service run names what failed and why: its services have no results of their own
301
317
  const failures = input.up ? describeFailures(execution.state.current, (text) => secrets.redact(text)) : [];
302
- throw new Error(failures.length > 0 ? failures.join('; ').slice(0, runs_1.MAX_TASK_ERROR) : `${name} failed`);
318
+ throw new Error(failures.length > 0 ? failures.join('; ').slice(0, runs_1.MAX_TASK_ERROR) : `${failedTasks(workTree, name)} failed`);
303
319
  }
304
320
  }
305
321
  finally {
@@ -363,6 +379,19 @@ function lastError(item) {
363
379
  }
364
380
  return last;
365
381
  }
382
+ // Of several tasks named, the ones that failed: those named first, else the dependencies
383
+ // that failed under them. One task named is the run's name, as before.
384
+ function failedTasks(workTree, name) {
385
+ const requested = workTree.requested ?? [];
386
+ if (requested.length < 2) {
387
+ return name;
388
+ }
389
+ const failed = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].filter((task) => task.state.current.type === 'error' || task.state.current.type === 'crash');
390
+ const named = failed.filter((task) => requested.includes(task.name));
391
+ const names = (named.length > 0 ? named : failed).map((task) => task.name);
392
+ return names.length > 0 ? names.join(', ') : name;
393
+ }
394
+ exports.failedTasks = failedTasks;
366
395
  /**
367
396
  * What failed in a run, one line each, for its error: the services and tasks that failed,
368
397
  * with their reason. Those that only stopped because another failed are left out.
@@ -15,6 +15,21 @@ exports.isFinal = isFinal;
15
15
  // those of the sandbox), `namespace` prepares its place on the cluster, `plan` starts the
16
16
  // process of the run and reads its build files.
17
17
  exports.RUN_PHASES = ['source', 'namespace', 'plan'];
18
+ // how many past runs of a task its expected duration is the median of
19
+ const DURATION_SAMPLES = 9;
20
+ // How long a task that succeeded ran: from its first command to the end of its last when
21
+ // they are known, as its duration also counts its wait for its dependencies and a place.
22
+ function ranFor(result) {
23
+ const commands = result.commands ?? [];
24
+ if (commands.length > 0) {
25
+ const from = Date.parse(commands[0].startedAt);
26
+ const to = Date.parse(commands[commands.length - 1].finishedAt);
27
+ if (Number.isFinite(from) && Number.isFinite(to) && to >= from) {
28
+ return to - from;
29
+ }
30
+ }
31
+ return result.durationMs;
32
+ }
18
33
  // The server can not take the run now; `status` is what the caller is told
19
34
  class RunError extends Error {
20
35
  constructor() {
@@ -278,6 +293,44 @@ class RunRegistry {
278
293
  const entry = this.entries.get(id);
279
294
  return entry ? this.copy(entry.run) : undefined;
280
295
  }
296
+ // What the tasks of a run took when they last ran in its repository, in ms by task name:
297
+ // the median of their last DURATION_SAMPLES runs that succeeded. Only times, of runs of any
298
+ // caller, and only for the scheduling of this run.
299
+ durationsOf(run) {
300
+ const repo = run.source.type === 'upload' ? undefined : run.source.repo;
301
+ if (!repo) {
302
+ return {};
303
+ }
304
+ const samples = new Map();
305
+ for (const entry of [...this.entries.values()].reverse()) {
306
+ const other = entry.run;
307
+ if (other.id === run.id || other.source.type === 'upload' || other.source.repo !== repo) {
308
+ continue;
309
+ }
310
+ for (const [task, result] of Object.entries(other.results ?? {})) {
311
+ const took = result.status === 'succeeded' ? ranFor(result) : undefined;
312
+ if (took === undefined) {
313
+ continue;
314
+ }
315
+ const times = samples.get(task) ?? [];
316
+ if (times.length < DURATION_SAMPLES) {
317
+ times.push(took);
318
+ samples.set(task, times);
319
+ }
320
+ }
321
+ }
322
+ const durations = {};
323
+ // only the tasks of this run, when its plan says which
324
+ const planned = run.plan ? new Set(Object.keys(run.plan)) : null;
325
+ for (const [task, times] of samples) {
326
+ if (planned && !planned.has(task)) {
327
+ continue;
328
+ }
329
+ times.sort((a, b) => a - b);
330
+ durations[task] = times[Math.floor((times.length - 1) / 2)];
331
+ }
332
+ return durations;
333
+ }
281
334
  // every run it keeps, of every caller, newest first: who may see which is for the caller
282
335
  all() {
283
336
  return [...this.entries.values()].map((entry) => this.copy(entry.run)).reverse();
@@ -403,7 +456,10 @@ class RunRegistry {
403
456
  }
404
457
  // The run that holds a sandbox: the oldest on it that is not over. It holds it from
405
458
  // 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.
459
+ // run that is up holds it no longer, so the agent can go on working while its services
460
+ // run: an approved one works on a copy of the files, any other (on a host) in the sandbox
461
+ // itself, which edits then write in through the directories they checked (see `write` of
462
+ // HostSandboxFiles).
407
463
  holder(sandbox) {
408
464
  return [...this.entries.values()].find((entry) => onSandbox(entry.run, sandbox) &&
409
465
  !isFinal(entry.run.state) &&
@@ -842,9 +898,11 @@ class RunRegistry {
842
898
  ? { ...this.copy(entry.run), source: { ...landing.source }, ...(landing.plan ? { plan: landing.plan } : {}) }
843
899
  : this.copy(entry.run);
844
900
  try {
901
+ const durations = this.durationsOf(run);
845
902
  await this.options.executor.execute(run, {
846
903
  emit: (event) => this.record(entry, event),
847
904
  signal: entry.abort.signal,
905
+ ...(Object.keys(durations).length > 0 ? { durations } : {}),
848
906
  ...(entry.run.up
849
907
  ? {
850
908
  up: (targets) => this.markUp(entry, targets),