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
@@ -5,6 +5,7 @@ const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const fs_1 = require("fs");
7
7
  const promises_1 = require("fs/promises");
8
+ const os_1 = require("os");
8
9
  const path_1 = require("path");
9
10
  const minimatch_1 = require("minimatch");
10
11
  const source_manifest_1 = require("../remote/source-manifest");
@@ -193,6 +194,8 @@ function fileType(stats) {
193
194
  * without following a link, and on Linux the opened file is checked to be the one in the
194
195
  * sandbox, in case a task swapped a directory for a link in between.
195
196
  */
197
+ // the ignore files ripgrep reads in the folders above the path it searches
198
+ const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
196
199
  class HostSandboxFiles {
197
200
  constructor(root, git,
198
201
  // the environment of ripgrep: the variables runs see
@@ -301,12 +304,17 @@ class HostSandboxFiles {
301
304
  }
302
305
  }
303
306
  // The opened file is the one in the sandbox: a task may have swapped a directory above it
304
- // for a link after the names were checked. Linux names the file a descriptor is open on;
305
- // elsewhere the path has to lead to the same file and to no link.
307
+ // for a link after the names were checked. Linux names the file a descriptor is open on,
308
+ // and a server that can't read that (no /proc) reads nothing: a check of the path would
309
+ // leave a moment for a swap. Elsewhere (a machine of a developer) the path has to lead to
310
+ // the same file and to no link.
306
311
  async mustBeInside(handle, absolute, path) {
307
312
  let actual;
308
313
  if (process.platform === 'linux') {
309
314
  actual = await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
315
+ if (actual === undefined) {
316
+ throw new SandboxFileError(503, `${path} can not be read: the server can not tell which file it opened, /proc/self/fd is not readable`);
317
+ }
310
318
  }
311
319
  if (actual === undefined) {
312
320
  const [opened, named] = await Promise.all([handle.stat(), (0, promises_1.lstat)(absolute)]);
@@ -534,7 +542,13 @@ class HostSandboxFiles {
534
542
  else {
535
543
  args.push('--count-matches', '--null');
536
544
  }
537
- args.push('--regexp', query.pattern, '--', path ?? '.');
545
+ // ripgrep follows a link in the path it is given, which a running task can swap in after
546
+ // the check above: it reads what was checked (see pin)
547
+ const target = await this.pin(path);
548
+ if (target.stdin) {
549
+ args.push('--with-filename');
550
+ }
551
+ args.push('--regexp', query.pattern, '--', target.arg);
538
552
  const result = { output_mode: mode, total: 0, exact: true, truncated: false, cursor: null };
539
553
  const files = [];
540
554
  const matches = [];
@@ -549,8 +563,11 @@ class HostSandboxFiles {
549
563
  };
550
564
  // the JSON of ripgrep names paths with the separator of the system, whatever --path-separator says
551
565
  const clean = (file) => {
552
- const path = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
553
- return path.startsWith('./') ? path.slice(2) : path;
566
+ if (target.stdin && file === '<stdin>') {
567
+ return path;
568
+ }
569
+ const name = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
570
+ return name.startsWith('./') ? name.slice(2) : name;
554
571
  };
555
572
  const onRecord = (record) => {
556
573
  if (mode === 'files_with_matches') {
@@ -577,7 +594,16 @@ class HostSandboxFiles {
577
594
  ...(message.type === 'context' ? { context: true } : {}),
578
595
  })));
579
596
  };
580
- const { code, stderr, stopped } = await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord);
597
+ let ran;
598
+ try {
599
+ ran = target.skip
600
+ ? { code: 1, stderr: '', stopped: false }
601
+ : await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord, target);
602
+ }
603
+ finally {
604
+ await target.release();
605
+ }
606
+ const { code, stderr, stopped } = ran;
581
607
  if (code === 2 && total === 0 && !stopped) {
582
608
  throw new SandboxFileError(400, stderr.trim() || 'ripgrep failed');
583
609
  }
@@ -596,9 +622,93 @@ class HostSandboxFiles {
596
622
  }
597
623
  return result;
598
624
  }
625
+ // What ripgrep searches for a `path` of a search, so that it reads what was checked when a
626
+ // task swaps a link into the path meanwhile (ripgrep follows the links of the path it is
627
+ // given, not those it finds below it). A file is read here, through the check of what was
628
+ // opened, and handed to ripgrep on stdin. A directory is opened here and checked the same
629
+ // way; ripgrep is given the same relative path in a folder of its own where it is a link
630
+ // to that open directory (on Linux, /proc/<pid>/fd/<n>), next to copies of the ignore
631
+ // files above it, so that globs, `.gitignore` and the paths it prints are what they were.
632
+ // Elsewhere (a machine of a developer) a directory is searched by its name.
633
+ async pin(path) {
634
+ const none = async () => undefined;
635
+ if (!path) {
636
+ return { arg: '.', cwd: this.root, release: none };
637
+ }
638
+ const found = await this.stat(path);
639
+ if (found?.type === 'file') {
640
+ const { handle, stat } = await this.open(path);
641
+ if (stat.size > exports.MAX_FILE_BYTES) {
642
+ // as ripgrep's --max-filesize leaves it out
643
+ await handle.close();
644
+ return { arg: '-', cwd: this.root, skip: true, release: none };
645
+ }
646
+ const stdin = handle.createReadStream();
647
+ return { arg: '-', cwd: this.root, stdin, release: async () => void stdin.destroy() };
648
+ }
649
+ if (process.platform !== 'linux') {
650
+ return { arg: path, cwd: this.root, release: none };
651
+ }
652
+ const absolute = this.absolute(path);
653
+ const handle = await (0, promises_1.open)(absolute, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | fs_1.constants.O_NOFOLLOW).catch((e) => {
654
+ if (e.code === 'ELOOP' || e.code === 'ENOTDIR') {
655
+ throw new SandboxFileError(409, `${path} changed while it was searched, search again`);
656
+ }
657
+ throw e;
658
+ });
659
+ let folder;
660
+ try {
661
+ await this.mustBeInside(handle, absolute, path);
662
+ folder = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-search-'));
663
+ const parts = path.split('/');
664
+ for (let depth = 0; depth < parts.length; depth++) {
665
+ const above = parts.slice(0, depth).join('/');
666
+ await (0, promises_1.mkdir)((0, path_1.join)(folder, ...parts.slice(0, depth)), { recursive: true });
667
+ for (const name of IGNORE_FILES) {
668
+ const file = above ? `${above}/${name}` : name;
669
+ const content = await this.ignoreFile(file);
670
+ if (content !== undefined) {
671
+ await (0, promises_1.writeFile)((0, path_1.join)(folder, ...parts.slice(0, depth), name), content);
672
+ }
673
+ }
674
+ }
675
+ await (0, promises_1.symlink)(`/proc/${process.pid}/fd/${handle.fd}`, (0, path_1.join)(folder, ...parts));
676
+ }
677
+ catch (e) {
678
+ await handle.close();
679
+ if (folder) {
680
+ await (0, promises_1.rm)(folder, { recursive: true, force: true });
681
+ }
682
+ throw e;
683
+ }
684
+ const pinned = folder;
685
+ return {
686
+ arg: path,
687
+ cwd: pinned,
688
+ release: async () => {
689
+ await (0, promises_1.rm)(pinned, { recursive: true, force: true });
690
+ await handle.close();
691
+ },
692
+ };
693
+ }
694
+ // An ignore file above the path of a search, read as any file is; none when there is none
695
+ // or it can not be read as a file
696
+ async ignoreFile(path) {
697
+ const found = await this.stat(path);
698
+ if (found?.type !== 'file' || found.size > exports.MAX_FILE_BYTES) {
699
+ return undefined;
700
+ }
701
+ const { handle, stat } = await this.open(path);
702
+ try {
703
+ return await readOpened(handle, stat.size);
704
+ }
705
+ finally {
706
+ await handle.close();
707
+ }
708
+ }
599
709
  // Runs ripgrep in the files and hands each record of its output to `onRecord`, which
600
710
  // answers whether to read on.
601
- ripgrep(args, separator, onRecord) {
711
+ ripgrep(args, separator, onRecord, target = { cwd: this.root }) {
602
712
  const env = {};
603
713
  for (const [key, value] of Object.entries(this.env)) {
604
714
  if (value !== undefined && !key.toUpperCase().startsWith('RIPGREP_')) {
@@ -607,11 +717,20 @@ class HostSandboxFiles {
607
717
  }
608
718
  return new Promise((resolve, reject) => {
609
719
  const child = (0, child_process_1.spawn)('rg', args, {
610
- cwd: this.root,
720
+ cwd: target.cwd,
611
721
  env,
612
- stdio: ['ignore', 'pipe', 'pipe'],
722
+ stdio: ['pipe', 'pipe', 'pipe'],
613
723
  signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
614
724
  });
725
+ // ripgrep stops reading when it is stopped or has seen enough
726
+ child.stdin.on('error', () => undefined);
727
+ if (target.stdin) {
728
+ target.stdin.on('error', () => child.stdin.destroy());
729
+ target.stdin.pipe(child.stdin);
730
+ }
731
+ else {
732
+ child.stdin.end();
733
+ }
615
734
  let stopped = false;
616
735
  let buffered = '';
617
736
  let stderr = '';
@@ -797,50 +916,124 @@ class HostSandboxFiles {
797
916
  return state.content;
798
917
  }
799
918
  // Writes the changes: what a path held is moved aside first, and put back when a later
800
- // write fails.
919
+ // write fails. Each name is written in the directory above it, opened from the root name
920
+ // by name (see `folder`), so what a task swaps in meanwhile leads no write out of the files.
801
921
  async write(changes) {
802
922
  const backups = [];
803
923
  const written = [];
804
- // the directories above every path are still the ones the edits were planned in
805
- for (const [path] of changes) {
806
- await this.sameParents(path);
807
- }
924
+ const folders = new Map();
925
+ const folderOf = async (path, create) => {
926
+ const key = (0, path_1.dirname)(path);
927
+ let folder = folders.get(key);
928
+ if (!folder) {
929
+ folder = await this.folder(path, create);
930
+ folders.set(key, folder);
931
+ }
932
+ return folder;
933
+ };
808
934
  try {
809
- for (const [path, before] of changes) {
810
- if (before.kind === 'file' || before.kind === 'link') {
811
- const absolute = this.absolute(path);
812
- const backup = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`);
813
- await (0, promises_1.rename)(absolute, backup);
814
- backups.push([absolute, backup]);
935
+ // the directories above every path are still the ones the edits were planned in
936
+ for (const [path] of changes) {
937
+ await this.sameParents(path);
938
+ }
939
+ try {
940
+ for (const [path, before] of changes) {
941
+ if (before.kind === 'file' || before.kind === 'link') {
942
+ const folder = await folderOf(path, false);
943
+ const name = (0, path_1.basename)(path);
944
+ const backup = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`;
945
+ await (0, promises_1.rename)(folder.at(name), folder.at(backup));
946
+ backups.push([folder, name, backup]);
947
+ }
948
+ }
949
+ for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
950
+ if (after.kind !== 'file') {
951
+ continue;
952
+ }
953
+ const folder = await folderOf(path, true);
954
+ const name = (0, path_1.basename)(path);
955
+ const temporary = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`;
956
+ const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
957
+ const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
958
+ const flags = fs_1.constants.O_WRONLY | fs_1.constants.O_CREAT | fs_1.constants.O_EXCL | (fs_1.constants.O_NOFOLLOW ?? 0);
959
+ const handle = await (0, promises_1.open)(folder.at(temporary), flags, mode);
960
+ try {
961
+ await handle.writeFile(after.content ?? Buffer.alloc(0));
962
+ await handle.chmod(mode);
963
+ }
964
+ finally {
965
+ await handle.close();
966
+ }
967
+ await (0, promises_1.rename)(folder.at(temporary), folder.at(name));
968
+ written.push([folder, name]);
815
969
  }
816
970
  }
817
- for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
818
- if (after.kind !== 'file') {
819
- continue;
971
+ catch (e) {
972
+ for (const [folder, name] of written.reverse()) {
973
+ await (0, promises_1.rm)(folder.at(name), { force: true });
820
974
  }
975
+ for (const [folder, name, backup] of backups.reverse()) {
976
+ await (0, promises_1.rename)(folder.at(backup), folder.at(name)).catch(() => undefined);
977
+ }
978
+ throw e;
979
+ }
980
+ for (const [folder, , backup] of backups) {
981
+ await (0, promises_1.rm)(folder.at(backup), { force: true });
982
+ }
983
+ }
984
+ finally {
985
+ for (const folder of folders.values()) {
986
+ await folder.release();
987
+ }
988
+ }
989
+ }
990
+ // The directory above `path`, made where it is missing and `create` is set. On Linux it is
991
+ // opened from the root name by name, never through a link, and its names are reached
992
+ // through the open descriptor (/proc/self/fd/<n>/<name>): a directory a task swaps for a link
993
+ // after the checks leads no write out of the files. A server on Linux that can not read
994
+ // /proc writes nothing. Elsewhere (a machine of a developer) the names are checked on the way.
995
+ async folder(path, create) {
996
+ const parts = path.split('/').slice(0, -1);
997
+ if (process.platform !== 'linux') {
998
+ if (create) {
821
999
  await this.makeParents(path);
822
- const absolute = this.absolute(path);
823
- const temporary = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`);
824
- const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
825
- const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
826
- await (0, promises_1.writeFile)(temporary, after.content ?? Buffer.alloc(0), { flag: 'wx', mode });
827
- await (0, promises_1.chmod)(temporary, mode);
828
- await (0, promises_1.rename)(temporary, absolute);
829
- written.push(absolute);
830
1000
  }
1001
+ const absolute = (0, path_1.dirname)(this.absolute(path));
1002
+ return { at: (name) => (0, path_1.join)(absolute, name), release: async () => undefined };
831
1003
  }
832
- catch (e) {
833
- for (const absolute of written.reverse()) {
834
- await (0, promises_1.rm)(absolute, { force: true });
1004
+ let handle = await (0, promises_1.open)(this.root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
1005
+ try {
1006
+ if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
1007
+ throw new SandboxFileError(503, `${path} can not be written: the server can not reach a directory it opened, /proc/self/fd is not readable`);
835
1008
  }
836
- for (const [absolute, backup] of backups.reverse()) {
837
- await (0, promises_1.rename)(backup, absolute).catch(() => undefined);
1009
+ const flags = fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | (fs_1.constants.O_NOFOLLOW ?? 0);
1010
+ for (const part of parts) {
1011
+ const at = `/proc/self/fd/${handle.fd}/${part}`;
1012
+ const next = await (0, promises_1.open)(at, flags).catch(async (e) => {
1013
+ if (create && isNotFound(e)) {
1014
+ await (0, promises_1.mkdir)(at).catch((made) => {
1015
+ if (made.code !== 'EEXIST') {
1016
+ throw made;
1017
+ }
1018
+ });
1019
+ return (0, promises_1.open)(at, flags);
1020
+ }
1021
+ throw e;
1022
+ });
1023
+ await handle.close();
1024
+ handle = next;
838
1025
  }
839
- throw e;
840
1026
  }
841
- for (const [, backup] of backups) {
842
- await (0, promises_1.rm)(backup, { force: true });
1027
+ catch (e) {
1028
+ await handle.close().catch(() => undefined);
1029
+ const code = e.code;
1030
+ if (code === 'ELOOP' || code === 'ENOTDIR' || code === 'ENOENT') {
1031
+ throw new SandboxFileError(409, `${parts.join('/')} is not a directory any more`);
1032
+ }
1033
+ throw e;
843
1034
  }
1035
+ const opened = handle;
1036
+ return { at: (name) => `/proc/self/fd/${opened.fd}/${name}`, release: () => opened.close() };
844
1037
  }
845
1038
  async sameParents(path) {
846
1039
  const parts = path.split('/');
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
4
+ const run_source_envs_1 = require("../environment/run-source-envs");
4
5
  const net_1 = require("net");
5
6
  const zod_1 = require("zod");
6
7
  const yaml_1 = require("yaml");
@@ -298,6 +299,15 @@ const kubernetesBackendSchema = zod_1.z
298
299
  // build file's environment does: hammerkit can't tell from the API, and without it a
299
300
  // task with a limited network fails rather than runs open
300
301
  networkPolicy: zod_1.z.literal('enforced').optional(),
302
+ // what the pods with an open network wait to no longer reach before they start, under
303
+ // `networkPolicy: enforced`: an address and port `deniedEgress` covers that answers without
304
+ // the policy (the metadata endpoint by default), or `false` for no wait
305
+ openNetworkGate: zod_1.z
306
+ .union([
307
+ zod_1.z.literal(false),
308
+ zod_1.z.object({ host: zod_1.z.string().ip({ version: 'v4' }), port: zod_1.z.number().int().min(1).max(65535) }).strict(),
309
+ ])
310
+ .optional(),
301
311
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
302
312
  // add capabilities run in it
303
313
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
@@ -512,6 +522,15 @@ exports.serverConfigSchema = zod_1.z
512
522
  set: zod_1.z.record(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), zod_1.z.string()).default({}),
513
523
  })
514
524
  .strict()
525
+ // what a run is from is the run's: an operator's value would pass for it
526
+ .superRefine((env, ctx) => {
527
+ for (const name of [...env.allow, ...Object.keys(env.set)].filter(run_source_envs_1.isRunSourceEnv)) {
528
+ ctx.addIssue({
529
+ code: zod_1.z.ZodIssueCode.custom,
530
+ message: `${name} is set by the server for each run, from what the run is from`,
531
+ });
532
+ }
533
+ })
515
534
  .default({}),
516
535
  // the most any task or service of a run reaches besides its needs: none, open
517
536
  // or { allow: [hosts] }. A version that asks for more is refused at publish.
@@ -575,8 +594,9 @@ exports.serverConfigSchema = zod_1.z
575
594
  // the most open network a task or service of a run on a sandbox gets, written as
576
595
  // a task's `network`: only the services it needs by default
577
596
  network: network_schema_1.networkSchema.default('none'),
578
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
579
- // read: none by default, a sandbox holds code nobody reviewed
597
+ // the variables of runs (`runs.env.allow` and `runs.env.set`) an `env:` secret and the
598
+ // `envs` of a build file of a run on a sandbox may read, besides PATH, HOME and CI:
599
+ // none by default, a sandbox holds code nobody reviewed
580
600
  env: zod_1.z
581
601
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
582
602
  .strict()
@@ -769,11 +789,11 @@ exports.serverConfigSchema = zod_1.z
769
789
  });
770
790
  }
771
791
  config.sandboxes.env.allow.forEach((name, index) => {
772
- if (!config.runs.env.allow.includes(name)) {
792
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
773
793
  ctx.addIssue({
774
794
  code: zod_1.z.ZodIssueCode.custom,
775
795
  path: ['sandboxes', 'env', 'allow', index],
776
- message: `${name} is not in runs.env.allow, no run can read it`,
796
+ message: `${name} is not in runs.env.allow or runs.env.set, no run can read it`,
777
797
  });
778
798
  }
779
799
  });
@@ -20,10 +20,12 @@ const execute_docker_1 = require("../executer/execute-docker");
20
20
  const timings_1 = require("./timings");
21
21
  const kubernetes_backend_1 = require("./kubernetes-backend");
22
22
  const run_plan_1 = require("./run-plan");
23
+ const run_source_environment_1 = require("./run-source-environment");
23
24
  const work_network_1 = require("../planner/work-network");
24
25
  const run_environment_1 = require("./run-environment");
25
26
  const accounts_api_1 = require("./accounts-api");
26
27
  const run_request_1 = require("./run-request");
28
+ const run_retry_1 = require("./run-retry");
27
29
  const http_2 = require("./http");
28
30
  const definitions_1 = require("./definitions");
29
31
  const definitions_api_1 = require("./definitions-api");
@@ -37,6 +39,7 @@ const sandbox_storage_1 = require("./sandbox-storage");
37
39
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
38
40
  const sandbox_docker_1 = require("./sandbox-docker");
39
41
  const sandboxes_api_1 = require("./sandboxes-api");
42
+ const plan_1 = require("./plan");
40
43
  const endpoints_1 = require("./endpoints");
41
44
  const service_runs_1 = require("./service-runs");
42
45
  const units_1 = require("../utils/units");
@@ -109,7 +112,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
109
112
  });
110
113
  }
111
114
  async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res, url) {
112
- const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake))?)?$/.exec(url.pathname);
115
+ const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake|retry))?)?$/.exec(url.pathname);
113
116
  if (!match) {
114
117
  return false;
115
118
  }
@@ -151,7 +154,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
151
154
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
152
155
  const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
153
156
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
154
- run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
157
+ run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
155
158
  }
156
159
  else if (action === 'extend') {
157
160
  if (method !== 'POST') {
@@ -160,6 +163,13 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
160
163
  }
161
164
  await extendRun(config, registry, log, principal, id, req, res);
162
165
  }
166
+ else if (action === 'retry') {
167
+ if (method !== 'POST') {
168
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
169
+ return true;
170
+ }
171
+ await retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res);
172
+ }
163
173
  else if (action === 'wake') {
164
174
  if (method !== 'POST') {
165
175
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
@@ -179,7 +189,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
179
189
  (0, http_2.send)(res, 409, { error: result.reason });
180
190
  }
181
191
  else {
182
- (0, http_2.send)(res, 200, toRunResponse(result.run));
192
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
183
193
  }
184
194
  }
185
195
  else if (method !== 'GET') {
@@ -267,9 +277,18 @@ async function extendRun(config, registry, log, principal, id, req, res) {
267
277
  (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
268
278
  }
269
279
  else {
270
- (0, http_2.send)(res, 200, toRunResponse(result.run));
280
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
271
281
  }
272
282
  }
283
+ // What a stop, an extend or a wake answers: the run whole for who may read it (its owner, who
284
+ // decides about it, `observe`), else what the list shows of it. Who may only open or publish
285
+ // endpoints of its repository is told how it stands, not its arguments, plan or log.
286
+ function answerRun(config, principal, run) {
287
+ const viewer = (0, overview_1.getViewer)(config, principal);
288
+ return (0, overview_1.mayRead)(viewer, run)
289
+ ? toRunResponse(run, undefined, !(0, overview_1.owns)(viewer, run), viewer.nameOf)
290
+ : (0, overview_1.toListedRun)(viewer, run);
291
+ }
273
292
  // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
274
293
  // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
275
294
  // run of theirs would.
@@ -344,7 +363,47 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
344
363
  (0, http_2.send)(res, 400, { error: `${issue.path.join('.') || 'request'}: ${issue.message}` });
345
364
  return;
346
365
  }
347
- const request = parsed.data;
366
+ await startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, parsed.data, res);
367
+ }
368
+ // POST /v1/runs/<id>/retry: the run again, as a new run of the caller's. Who may read the run
369
+ // whole may retry it (what it runs again, its arguments too, is what they read), and it is
370
+ // decided as a run they started themselves would be: their entitlements, their accounts and
371
+ // an approval where they need one, never the owner's (run-retry.ts).
372
+ async function retryRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, id, res) {
373
+ const viewer = (0, overview_1.getViewer)(config, principal);
374
+ const run = registry.get(principal, id, accountsOf(config, principal)) ?? (viewer.grant.observe ? registry.peek(id) : undefined);
375
+ if (!run) {
376
+ (0, http_2.send)(res, 404, { error: 'not found' });
377
+ return;
378
+ }
379
+ const retry = (0, run_retry_1.getRetryRequest)(run, (0, overview_1.owns)(viewer, run));
380
+ log(`retry run ${id} iss=${principal.iss} sub=${principal.sub}${'error' in retry ? ` refused: ${retry.error}` : ''}`);
381
+ if ('error' in retry) {
382
+ (0, http_2.send)(res, 409, { error: retry.error });
383
+ return;
384
+ }
385
+ // what the run had stays up as long, at most as long as the server allows now
386
+ const { request } = retry;
387
+ if (request.ttl && (0, units_1.parseDuration)(request.ttl) > (0, units_1.parseDuration)(config.runs.up.maxTtl)) {
388
+ request.ttl = config.runs.up.maxTtl;
389
+ }
390
+ // a new service run replaces one of the caller's of the same name, with its volumes: a click
391
+ // on a run that ended must not take down the one they have now
392
+ const name = request.name;
393
+ const live = name
394
+ ? registry.list(principal).find((other) => other.up?.name === name && !(0, runs_1.isFinal)(other.state))
395
+ : undefined;
396
+ if (live) {
397
+ log(`retry run ${id} iss=${principal.iss} sub=${principal.sub} refused: ${name} is ${live.state} as ${live.id}`);
398
+ (0, http_2.send)(res, 409, {
399
+ error: `your service run ${name} is ${live.state} as ${live.id}, a retry would replace it: stop it first`,
400
+ });
401
+ return;
402
+ }
403
+ await startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, request, res, run);
404
+ }
405
+ // A run, from what `POST /v1/runs` takes or from a run it retries (`retryOf`).
406
+ async function startRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, request, res, retryOf) {
348
407
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
349
408
  // what the caller may not do is said plainly: they already know who they are
350
409
  if (!(0, policy_1.mayRun)(grant)) {
@@ -465,7 +524,13 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
465
524
  let planned;
466
525
  try {
467
526
  // a run on a sandbox may only use the runtimes of `sandboxes.runtimes`
468
- planned = await (0, run_plan_1.planRun)(bundle, request, planning.environment, sandbox ? sandboxes.policy : planning.policy);
527
+ // with what the run is from, as its tasks read it; the commit of a ref follows below
528
+ const from = request.source.type === 'ref'
529
+ ? { type: 'ref', repo: request.source.repo, ref: request.source.ref }
530
+ : sandbox
531
+ ? { type: 'sandbox', id: sandbox.id, repo: sandbox.repo }
532
+ : { type: 'upload' };
533
+ planned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, from), sandbox ? sandboxes.policy : planning.policy);
469
534
  }
470
535
  catch (e) {
471
536
  (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
@@ -509,7 +574,9 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
509
574
  try {
510
575
  const commit = await repos.resolve(request.source.repo, request.source.ref);
511
576
  if (request.source.commit && commit !== request.source.commit) {
512
- const error = `${request.source.ref} is at ${commit} now, not at ${request.source.commit}`;
577
+ const error = retryOf
578
+ ? `${request.source.ref} moved to ${commit} since ${retryOf.id} ran ${request.source.commit}, start a new run from ${request.source.ref}`
579
+ : `${request.source.ref} is at ${commit} now, not at ${request.source.commit}`;
513
580
  log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
514
581
  (0, http_2.send)(res, 409, { error });
515
582
  return;
@@ -528,6 +595,25 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
528
595
  else if (request.source.type === 'upload') {
529
596
  source = request.source;
530
597
  }
598
+ if (source?.type === 'ref') {
599
+ // what the approver reads is what the tasks see, the commit included; who may run it was
600
+ // decided without it and can't change with it
601
+ let pinned;
602
+ try {
603
+ pinned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, source), planning.policy);
604
+ }
605
+ catch (e) {
606
+ (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
607
+ return;
608
+ }
609
+ if (pinned.accounts.join(',') !== planned.accounts.join(',')) {
610
+ const error = `the accounts of the run change with its commit (${pinned.accounts.join(', ')})`;
611
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
612
+ (0, http_2.send)(res, 400, { error });
613
+ return;
614
+ }
615
+ planned = pinned;
616
+ }
531
617
  // a service run is named after its branch unless it says, and its endpoints after that
532
618
  const serviceName = request.services.length > 0
533
619
  ? request.name ??
@@ -554,7 +640,8 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
554
640
  // A service run of the caller of this name that runs the same build file, services and
555
641
  // endpoints moves to the commit, in place of a new run that would replace it: it keeps its
556
642
  // id, its addresses and its volumes. A run that needs an approval is new as before.
557
- if (up && source?.type === 'ref' && approvals.length === 0) {
643
+ // A retry is always a new run, which replaces a run of the same name as a new one would.
644
+ if (up && source?.type === 'ref' && approvals.length === 0 && !retryOf) {
558
645
  const named = registry.named(principal, up.name);
559
646
  if (named && runsTheSame(named, { definition: version.hash, accounts: planned.accounts, request, source, up })) {
560
647
  const from = (registry.logs(principal, named.id)?.index.size ?? 0) + 1;
@@ -579,6 +666,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
579
666
  source: runSource,
580
667
  options: request.options,
581
668
  ...(up ? { up } : {}),
669
+ ...(retryOf ? { retryOf: retryOf.id } : {}),
582
670
  }, approvals);
583
671
  try {
584
672
  // a sandbox is read and the run submitted while nothing else changes it: the run
@@ -597,7 +685,7 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
597
685
  ...(request.source.type === 'sandbox' && request.source.check ? { check: true } : {}),
598
686
  });
599
687
  });
600
- log(`run ${run.id} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}${run.source.check ? ' check' : ''}` : ''} tasks=${run.tasks.length}${run.up
688
+ log(`run ${run.id}${retryOf ? ` retry=${retryOf.id}` : ''} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}${run.source.check ? ' check' : ''}` : ''} tasks=${run.tasks.length}${run.up
601
689
  ? ` services=[${run.up.services.join(',')}] name=${run.up.name} endpoints=${run.up.endpoints.length}`
602
690
  : ''}${approvals.length > 0 ? ` approval=[${approvals.join(',')}]` : ''}`);
603
691
  (0, http_2.send)(res, 202, toRunResponse(run, (0, overview_1.queuePlace)(registry, (0, overview_1.getViewer)(config, principal), run)));
@@ -790,9 +878,14 @@ async function startServer(config, environment, options = {}) {
790
878
  },
791
879
  };
792
880
  const storage = config.storage.directory ?? (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'server');
793
- const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), planning.environment, {
794
- policy: planning.policy,
795
- });
881
+ // a build file nobody ran yet is read with the names of the variables, not their values
882
+ const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), {
883
+ ...planning.environment,
884
+ hosted: {
885
+ ...planning.environment.hosted,
886
+ buildFileEnvs: (0, plan_1.withSymbolicValues)(planning.environment.processEnvs),
887
+ },
888
+ }, { policy: planning.policy });
796
889
  await definitions.load();
797
890
  const repos = new repo_access_1.RepoAccess(config, planning.environment, options.repos);
798
891
  const sandboxRuntimes = (0, server_config_1.getSandboxRuntimes)(config);
@@ -821,6 +914,8 @@ async function startServer(config, environment, options = {}) {
821
914
  ...planning.policy,
822
915
  envs: config.sandboxes.env.allow,
823
916
  envsFrom: 'sandboxes.env.allow',
917
+ // and what its build files read of the run's variables, `$NAME` in its `envs`
918
+ readableEnvs: config.sandboxes.env.allow,
824
919
  runtimes: sandboxRuntimes,
825
920
  capabilities: config.sandboxes.capabilities,
826
921
  capabilitiesFrom: 'sandboxes.capabilities',