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
@@ -8,6 +8,7 @@ const normalize_path_1 = require("./utils/normalize-path");
8
8
  const template_value_1 = require("./utils/template-value");
9
9
  const portable_path_1 = require("./utils/portable-path");
10
10
  const abort_1 = require("../executer/abort");
11
+ const secret_catalog_1 = require("../secrets/secret-catalog");
11
12
  const provider_values_1 = require("../secrets/provider-values");
12
13
  // Where the value comes from, for messages and for what makes a service
13
14
  // different: never the value.
@@ -30,6 +31,8 @@ function getPortableSecretName(projectRoot, secret) {
30
31
  }
31
32
  exports.getPortableSecretName = getPortableSecretName;
32
33
  function parseWorkSecrets(cwd, projectRoot, secrets, envs, environment, catalog,
34
+ // what the secrets belong to, for messages: `task build` or `service db`
35
+ owner,
33
36
  // the service account of the task or service the secrets belong to
34
37
  account) {
35
38
  return (secrets ?? []).map((secret) => {
@@ -38,7 +41,7 @@ account) {
38
41
  ? { type: 'env', name: secret.env }
39
42
  : { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, cwd, (0, template_value_1.templateValue)(secret.path ?? '', envs)) };
40
43
  const name = target.type === 'env' ? target.name : secret.path;
41
- const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, `secret ${name}`);
44
+ const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, owner, `secret ${name}`);
42
45
  const workSecret = {
43
46
  source,
44
47
  target,
@@ -49,7 +52,7 @@ account) {
49
52
  });
50
53
  }
51
54
  exports.parseWorkSecrets = parseWorkSecrets;
52
- function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label) {
55
+ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, owner, label) {
53
56
  const kind = secret.from.substring(0, secret.from.indexOf(':'));
54
57
  if (kind === 'env') {
55
58
  return { type: 'env', name: ref };
@@ -57,30 +60,29 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
57
60
  if (kind === 'file') {
58
61
  return { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, (0, os_1.homedir)(), (0, template_value_1.templateValue)(ref, envs)) };
59
62
  }
60
- const provider = catalog.providers[kind];
63
+ const reads = `${owner} reads ${label} from ${secret.from}`;
64
+ const provider = (0, secret_catalog_1.declared)(catalog.providers, kind);
61
65
  if (!provider) {
62
- const declared = Object.keys(catalog.providers);
63
- throw new Error(`${label}: unknown secret provider ${kind}, ${declared.length > 0 ? `declared: ${declared.join(', ')}` : 'none is declared'}`);
66
+ throw new Error(unknownProviderMessage(catalog, reads, kind));
64
67
  }
65
68
  const providerRef = (0, template_value_1.templateValue)(ref, envs);
66
69
  if (providerRef.length === 0 || providerRef.startsWith('-')) {
67
- throw new Error(`${label}: a reference for ${kind} must not be empty or start with -`);
70
+ throw new Error(`${reads}: a reference for ${kind} must not be empty or start with -`);
68
71
  }
69
72
  const accountName = catalog.explicitAccounts
70
73
  ? secret.account
71
74
  : secret.account ?? taskAccount ?? Object.values(catalog.accounts).find((a) => a.default)?.name;
72
75
  if (!accountName) {
73
- throw new Error(catalog.explicitAccounts
74
- ? `${label}: ${kind}:${providerRef} needs account: on the secret, a server uses neither a task's account nor a default`
75
- : `${label}: ${kind}:${providerRef} needs an account, and none is named or marked default: true`);
76
+ throw new Error(missingAccountMessage(catalog, reads, owner));
76
77
  }
77
- const account = catalog.accounts[accountName];
78
+ const account = (0, secret_catalog_1.declared)(catalog.accounts, accountName);
78
79
  if (!account) {
79
- throw new Error(`${label}: unknown secret account ${accountName}, declared: ${Object.keys(catalog.accounts).join(', ') || 'none'}`);
80
+ const namedBy = secret.account ? 'the account: of the secret' : `the account: of ${owner}`;
81
+ throw new Error(unknownAccountMessage(catalog, reads, owner, accountName, namedBy, kind));
80
82
  }
81
- const credentials = account.providers[kind];
83
+ const credentials = (0, secret_catalog_1.declared)(account.providers, kind);
82
84
  if (!credentials) {
83
- throw new Error(`${label}: account ${accountName} has no credentials for provider ${kind}`);
85
+ throw new Error(missingCredentialsMessage(catalog, reads, account, kind));
84
86
  }
85
87
  return {
86
88
  type: 'provider',
@@ -90,6 +92,126 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
90
92
  binding: { definition: provider, account: { name: accountName, env: credentials.env } },
91
93
  };
92
94
  }
95
+ // The messages below say what is wrong, where the names come from and what to write: a
96
+ // person who only ran a task should not need to know how secrets are declared. On a
97
+ // server the build file can only change what it names, the operator declares the rest.
98
+ const SECRET_PROVIDERS_DOCS = 'https://hammerkit.dev/docs/task/secret-providers';
99
+ // `tests, dev in ~/.hammerkit/config.yaml and ci in .hammerkit.yaml`, or `none`
100
+ function listDeclared(definitions, server) {
101
+ if (definitions.length === 0) {
102
+ return 'none';
103
+ }
104
+ if (server) {
105
+ return definitions.map((d) => d.name).join(', ');
106
+ }
107
+ const byFile = new Map();
108
+ for (const definition of definitions) {
109
+ byFile.set(definition.declaredIn, [...(byFile.get(definition.declaredIn) ?? []), definition.name]);
110
+ }
111
+ return [...byFile.entries()].map(([file, names]) => `${names.join(', ')} in ${file}`).join(' and ');
112
+ }
113
+ // A build file is checked as a whole when it is read, so one wrong secret stops
114
+ // the tasks that don't read it, too.
115
+ function seeDocs(anchor) {
116
+ return `Every task of the build file is checked when it is read, so this stops other tasks too. See ${SECRET_PROVIDERS_DOCS}#${anchor}`;
117
+ }
118
+ function hostConfigOf(catalog) {
119
+ return catalog.hostConfig ?? 'the host config';
120
+ }
121
+ function indent(lines) {
122
+ return lines.map((line) => ` ${line}`).join('\n');
123
+ }
124
+ // A variable of this machine to hold the credential, for snippets: `${OPERATOR_CREDENTIALS}`
125
+ function credentialVariable(account, key, keys) {
126
+ const prefix = account.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
127
+ return `\${${prefix}_${keys === 1 ? 'CREDENTIALS' : key}}`;
128
+ }
129
+ // The credential variables a provider's command reads, as another account passes them;
130
+ // a placeholder when no account has credentials for the provider yet
131
+ function credentialLines(catalog, account, provider) {
132
+ const sibling = Object.values(catalog.accounts).find((a) => (0, secret_catalog_1.declared)(a.providers, provider));
133
+ const keys = sibling ? Object.keys(sibling.providers[provider].env) : [];
134
+ if (keys.length === 0) {
135
+ return [`<VARIABLE>: \${<VARIABLE OF THIS MACHINE>} # what ${provider} reads its credential from`];
136
+ }
137
+ return keys.map((key) => `${key}: ${credentialVariable(account, key, keys.length)}`);
138
+ }
139
+ function unknownProviderMessage(catalog, reads, kind) {
140
+ const declaredProviders = listDeclared(Object.values(catalog.providers), !!catalog.explicitAccounts);
141
+ if (catalog.explicitAccounts) {
142
+ return (`${reads}, but this server has no secret provider ${kind} (it has: ${declaredProviders}). ` +
143
+ `Use one of its providers, or ask the operator of the server to add ${kind} to its config.`);
144
+ }
145
+ return [
146
+ `${reads}, but no secret provider ${kind} is declared (declared: ${declaredProviders}).`,
147
+ `A provider is the command that prints a secret's value. Declare it in the host config, ${hostConfigOf(catalog)}:`,
148
+ '',
149
+ indent(['secretProviders:', ` ${kind}:`, ` command: [<command>, <its arguments>, '{{ref}}']`]),
150
+ '',
151
+ seeDocs('providers'),
152
+ ].join('\n');
153
+ }
154
+ function missingAccountMessage(catalog, reads, owner) {
155
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
156
+ if (catalog.explicitAccounts) {
157
+ return (`${reads}, but names no account. A server reads every secret as the account the secret names, ` +
158
+ `never as the account of a task or a default: add account: to the secret (this server has: ${declaredAccounts}).`);
159
+ }
160
+ return [
161
+ `${reads}, but neither the secret nor ${owner} names an account, and no account is marked default: true (declared: ${declaredAccounts}).`,
162
+ `An account says which credential a secret is read with. Name one with account: on the secret or on ${owner}, ` +
163
+ `or mark one as the default in ${hostConfigOf(catalog)}:`,
164
+ '',
165
+ indent(['secretAccounts:', ' <account>:', ' default: true']),
166
+ '',
167
+ seeDocs('accounts'),
168
+ ].join('\n');
169
+ }
170
+ function unknownAccountMessage(catalog, reads, owner, account, namedBy, provider) {
171
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
172
+ if (catalog.explicitAccounts) {
173
+ return (`${reads} as account ${account}, but this server has no account ${account} (it has: ${declaredAccounts}). ` +
174
+ `Name one of its accounts with account: on the secret, or ask the operator of the server to add ${account} to its config.`);
175
+ }
176
+ return [
177
+ `${reads} as account ${account} (${namedBy}), but no account ${account} is declared (declared: ${declaredAccounts}).`,
178
+ `An account says which credential a secret is read with, and each machine declares its own in its host config, ` +
179
+ `${hostConfigOf(catalog)}. Add ${account} there:`,
180
+ '',
181
+ indent([
182
+ 'secretAccounts:',
183
+ ` ${account}:`,
184
+ ' providers:',
185
+ ` ${provider}:`,
186
+ ' env:',
187
+ ...credentialLines(catalog, account, provider).map((line) => ` ${line}`),
188
+ ]),
189
+ '',
190
+ `Or read the secret as one of the declared accounts with account: on the secret${namedBy === 'the account: of the secret' ? '' : ` or on ${owner}`}.`,
191
+ seeDocs('accounts'),
192
+ ].join('\n');
193
+ }
194
+ function missingCredentialsMessage(catalog, reads, account, provider) {
195
+ if (catalog.explicitAccounts) {
196
+ return (`${reads} as account ${account.name}, but that account of this server has no credentials for ${provider}. ` +
197
+ `Ask the operator of the server to add them to its config.`);
198
+ }
199
+ return [
200
+ `${reads} as account ${account.name}, but account ${account.name} (in ${account.declaredIn}) has no credentials for provider ${provider}.`,
201
+ `Add the variables that make ${provider} act as ${account.name}:`,
202
+ '',
203
+ indent([
204
+ 'secretAccounts:',
205
+ ` ${account.name}:`,
206
+ ' providers:',
207
+ ` ${provider}:`,
208
+ ' env:',
209
+ ...credentialLines(catalog, account.name, provider).map((line) => ` ${line}`),
210
+ ]),
211
+ '',
212
+ seeDocs('accounts'),
213
+ ].join('\n');
214
+ }
93
215
  function readSecretValueSync(secret, environment) {
94
216
  if (secret.source.type === 'env') {
95
217
  const value = environment.processEnvs[secret.source.name];
@@ -1,3 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAskedByName = void 0;
4
+ // Whether a task was asked for by name: one of the tasks named, or the one task the run
5
+ // was asked for. An init task asked for by name starts its service and runs.
6
+ function isAskedByName(workTree, name) {
7
+ if (workTree.named) {
8
+ return workTree.named.includes(name);
9
+ }
10
+ return workTree.requested?.length === 1 && workTree.requested[0] === name;
11
+ }
12
+ exports.isAskedByName = isAskedByName;
3
13
  //# sourceMappingURL=work-tree.js.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collectBundle = void 0;
4
+ const promises_1 = require("node:fs/promises");
4
5
  const path_1 = require("path");
5
6
  const resolve_git_source_1 = require("../includes/resolve-git-source");
6
7
  const schema_parser_1 = require("../schema/schema-parser");
@@ -10,7 +11,10 @@ const bundle_1 = require("./bundle");
10
11
  // The build file is read with the parser of a run, so what it pulls in is what a
11
12
  // run would read. Git includes are not part of it (the server fetches them, at
12
13
  // the commit they are pinned to), and neither is anything outside of the
13
- // directory of the build file, which a server could not reproduce.
14
+ // directory of the build file, which a server could not reproduce. That holds for
15
+ // where a file really is too: a link to a file outside of the directory is refused
16
+ // rather than followed, so publishing a checkout never sends a file of this machine
17
+ // that the checkout only points to.
14
18
  async function collectBundle(fileName, environment) {
15
19
  if (!(await environment.file.exists(fileName))) {
16
20
  throw new Error(`there is no build file at ${fileName}`);
@@ -24,11 +28,15 @@ async function collectBundle(fileName, environment) {
24
28
  paths.add((0, path_1.resolve)(scope.fileName));
25
29
  }
26
30
  }
31
+ const realRoot = await (0, promises_1.realpath)(root);
27
32
  const files = {};
28
33
  for (const path of [...paths].sort()) {
29
34
  if (!(0, resolve_git_source_1.isWithin)(root, path)) {
30
35
  throw new Error(`${path} is outside of ${root}: a published build file can only include files below its own directory`);
31
36
  }
37
+ if (!(0, resolve_git_source_1.isWithin)(realRoot, await (0, promises_1.realpath)(path))) {
38
+ throw new Error(`${path} links to a file outside of ${root}: a published build file can only include files below its own directory`);
39
+ }
32
40
  files[(0, path_1.relative)(root, path).split(path_1.sep).join('/')] = await environment.file.read(path);
33
41
  }
34
42
  const result = bundle_1.bundleSchema.safeParse({ entry: (0, path_1.relative)(root, entryPath).split(path_1.sep).join('/'), files });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
3
+ exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.chooseServer = exports.notRegisteredMessage = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
4
4
  const path_1 = require("path");
5
5
  const zod_1 = require("zod");
6
6
  const yaml_1 = require("yaml");
@@ -69,6 +69,52 @@ function getRegisteredServer(config, name) {
69
69
  return { ...config.servers[name], ...(tokenCommand ? { tokenCommand } : {}) };
70
70
  }
71
71
  exports.getRegisteredServer = getRegisteredServer;
72
+ // `a, b and c`
73
+ function listNames(names) {
74
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names.join('');
75
+ }
76
+ // `(registered: a and b)`, for a name that is not one of them
77
+ function registeredNote(config) {
78
+ const names = Object.keys(config.servers).sort();
79
+ return names.length === 0 ? '(no server is registered yet)' : `(registered: ${listNames(names)})`;
80
+ }
81
+ // `server nope is not registered (registered: a and b)`, with how to add it unless it is being removed
82
+ function notRegisteredMessage(config, name, howToAdd = true) {
83
+ const add = howToAdd ? `, add it with: hammerkit remote add ${name} <url> --issuer <url>` : '';
84
+ return `server ${name} is not registered ${registeredNote(config)}${add}`;
85
+ }
86
+ exports.notRegisteredMessage = notRegisteredMessage;
87
+ // The server a remote command talks to: the one it names, else the default of `remote use`,
88
+ // else the only one registered. With several and no default, the person names one.
89
+ // A default that names a server no longer registered is an error, as it is for `hammerkit run`:
90
+ // a call never goes to another server than the one chosen. `how` says how a name is given,
91
+ // for the message: `with --server <name>`.
92
+ function chooseServer(config, name, how = 'as the last argument') {
93
+ if (name !== undefined) {
94
+ if (!hasServer(config.servers, name)) {
95
+ throw new Error(notRegisteredMessage(config, name));
96
+ }
97
+ return name;
98
+ }
99
+ const on = config.run.on;
100
+ if (on && !exports.RESERVED_SERVER_NAMES.includes(on)) {
101
+ if (!hasServer(config.servers, on)) {
102
+ throw new Error(`the default of remote use, server ${on}, is not registered ${registeredNote(config)}; ` +
103
+ `pick another with: hammerkit remote use <name>, or add it with: hammerkit remote add ${on} <url> --issuer <url>`);
104
+ }
105
+ return on;
106
+ }
107
+ const names = Object.keys(config.servers).sort();
108
+ if (names.length === 1) {
109
+ return names[0];
110
+ }
111
+ if (names.length === 0) {
112
+ throw new Error('no server is registered, add one with: hammerkit remote add <name> <url> --issuer <url>');
113
+ }
114
+ throw new Error(`${names.length} servers are registered (${listNames(names)}), name one ${how}, ` +
115
+ `or make one the default with: hammerkit remote use <name>`);
116
+ }
117
+ exports.chooseServer = chooseServer;
72
118
  function setTokenCommand(config, name, entry) {
73
119
  const commands = { ...(config.tokenCommands ?? {}) };
74
120
  if (entry) {
@@ -201,7 +247,7 @@ exports.addServer = addServer;
201
247
  async function removeServer(environment, name) {
202
248
  const config = await readHostConfig(environment);
203
249
  if (!hasServer(config.servers, name)) {
204
- throw new Error(`server "${name}" is not registered`);
250
+ throw new Error(notRegisteredMessage(config, name, false));
205
251
  }
206
252
  delete config.servers[name];
207
253
  setTokenCommand(config, name, undefined);
@@ -216,7 +262,7 @@ exports.removeServer = removeServer;
216
262
  async function setDefaultLocation(environment, on) {
217
263
  const config = await readHostConfig(environment);
218
264
  if (!exports.RESERVED_SERVER_NAMES.includes(on) && !hasServer(config.servers, on)) {
219
- throw new Error(`server "${on}" is not registered; add it with: hammerkit remote add ${on} <url> --issuer <url>`);
265
+ throw new Error(notRegisteredMessage(config, on));
220
266
  }
221
267
  config.run.on = on;
222
268
  await writeHostConfig(environment, config);
@@ -14,7 +14,7 @@ async function resolveRunLocation(workTree, environment, options = {}) {
14
14
  const config = await (0, host_config_1.readHostConfig)(environment);
15
15
  const explicit = options.local ? 'local' : options.on ?? (environment.processEnvs.HAMMERKIT_ON || undefined);
16
16
  if (explicit && explicit !== 'auto') {
17
- return explicit === 'local' ? { type: 'local' } : lookup(config.servers, explicit);
17
+ return explicit === 'local' ? { type: 'local' } : lookup(config, explicit);
18
18
  }
19
19
  const runners = getTaskRunners(workTree);
20
20
  if (runners.length > 1) {
@@ -24,13 +24,13 @@ async function resolveRunLocation(workTree, environment, options = {}) {
24
24
  if (!requested || requested === 'local' || requested === 'auto') {
25
25
  return { type: 'local' };
26
26
  }
27
- return lookup(config.servers, requested);
27
+ return lookup(config, requested);
28
28
  }
29
29
  exports.resolveRunLocation = resolveRunLocation;
30
- function lookup(servers, name) {
31
- const server = (0, host_config_1.hasServer)(servers, name) ? servers[name] : undefined;
30
+ function lookup(config, name) {
31
+ const server = (0, host_config_1.hasServer)(config.servers, name) ? config.servers[name] : undefined;
32
32
  if (!server) {
33
- throw new Error(`server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`);
33
+ throw new Error((0, host_config_1.notRegisteredMessage)(config, name));
34
34
  }
35
35
  return { type: 'server', name, server };
36
36
  }
@@ -94,21 +94,17 @@ passthrough = []) {
94
94
  await (0, host_config_1.setDefaultLocation)(environment, location);
95
95
  environment.stdout.write(`default location: ${location}\n`);
96
96
  }));
97
- const getServer = async (name) => {
97
+ // a command that takes a server: the named one, the default or the only one, see chooseServer
98
+ const getServer = async (name, how) => {
98
99
  const config = await (0, host_config_1.readHostConfig)(environment);
99
- const chosen = name ?? config.run.on;
100
- if (!chosen || !(0, host_config_1.hasServer)(config.servers, chosen)) {
101
- throw new Error(name
102
- ? `server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`
103
- : 'name a server, or set one as the default with: hammerkit remote use <name>');
104
- }
100
+ const chosen = (0, host_config_1.chooseServer)(config, name, how);
105
101
  return { name: chosen, server: (0, host_config_1.getRegisteredServer)(config, chosen) };
106
102
  };
107
103
  remote
108
- .command('login <name>')
109
- .description('sign in to a registered server with your identity provider (device code, works headless)')
110
- .action(guarded('Remote login was not successful', async (name) => {
111
- const { server } = await getServer(name);
104
+ .command('login [name]')
105
+ .description('sign in to a registered server with your identity provider (device code, works headless); the name can be left out when only one server is registered or one is set with remote use')
106
+ .action(guarded('Remote login was not successful', async (given) => {
107
+ const { name, server } = await getServer(given);
112
108
  if (server.tokenCommand) {
113
109
  // a sign-in would never be used: the command's token goes first
114
110
  throw new Error(`${name} takes its tokens from its token command (${server.tokenCommand}), it needs no sign-in; ` +
@@ -145,9 +141,11 @@ passthrough = []) {
145
141
  }
146
142
  }));
147
143
  remote
148
- .command('logout <name>')
149
- .description('forget the sign-in to a server')
150
- .action(guarded('Remote logout was not successful', async (name) => {
144
+ .command('logout [name]')
145
+ .description('forget the sign-in to a server; the name can be left out as for login')
146
+ .action(guarded('Remote logout was not successful', async (given) => {
147
+ // a sign-in outlives its server's registration, so a name given is taken as it is
148
+ const name = given ?? (0, host_config_1.chooseServer)(await (0, host_config_1.readHostConfig)(environment), undefined);
151
149
  const removed = await (0, credentials_1.removeToken)(environment, name);
152
150
  environment.stdout.write(removed ? `signed out of ${name}\n` : `not signed in to ${name}\n`);
153
151
  }));
@@ -186,8 +186,8 @@ function registerWorkCommands(remote, context) {
186
186
  }
187
187
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
188
  };
189
- const connect = async (name) => {
190
- const chosen = await getServer(name);
189
+ const connect = async (name, how) => {
190
+ const chosen = await getServer(name, how);
191
191
  // a CI job or an agent brings its own token, a person signs in
192
192
  const token = await (0, token_source_1.getTokenSource)(environment, chosen.name, chosen.server).token();
193
193
  return { ...chosen, token };
@@ -340,7 +340,7 @@ function registerWorkCommands(remote, context) {
340
340
  remote
341
341
  .command('run <tasks...>')
342
342
  .description('run tasks of a published build file on a server from a git ref, print their output and exit as they did')
343
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
343
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
344
344
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
345
345
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
346
346
  .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out'))
@@ -355,7 +355,7 @@ function registerWorkCommands(remote, context) {
355
355
  const { definition, local } = await runDefinition(options);
356
356
  const source = await refSource(options);
357
357
  const ref = source.ref;
358
- const { name: serverName, server } = await getServer(options.server);
358
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
359
359
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
360
360
  const runOptions = {};
361
361
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
@@ -407,7 +407,7 @@ function registerWorkCommands(remote, context) {
407
407
  .command('up <services...>')
408
408
  .description('start services of a published build file on a server from a git ref and keep them up until their ttl ends, ' +
409
409
  'with their endpoints at addresses of their own behind the sign-in of the server')
410
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
410
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
411
411
  .addOption(new commander_1.Option('--endpoint <service:port>', 'publish this port of a service, such as web:8080; may be given more than once').argParser(collectOption))
412
412
  .addOption(new commander_1.Option('--ttl <duration>', 'how long they stay once ready, such as 2h, then they are removed; the server default when left out'))
413
413
  .addOption(new commander_1.Option('--sleep-ttl <duration>', 'how long they stay up without a request, such as 30m, then they sleep until the next request wakes them; ' +
@@ -424,7 +424,7 @@ function registerWorkCommands(remote, context) {
424
424
  const { definition, local } = await runDefinition(options);
425
425
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
426
426
  const source = await refSource(options);
427
- const { name: serverName, server } = await getServer(options.server);
427
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
428
428
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
429
429
  const submitted = await submitPublishing({ serverName, server, connection }, {
430
430
  definition,
@@ -683,11 +683,23 @@ function registerWorkCommands(remote, context) {
683
683
  const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/cancel`)).body;
684
684
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName}: ${run.state === 'up' || run.state === 'running' ? 'stopping' : (0, server_client_1.printable)(run.state)}\n`);
685
685
  }));
686
+ remote
687
+ .command('retry <run> [server]')
688
+ .description('start a run that is over again, as a new run of yours: the same tasks or services, settings and commit')
689
+ .action(guarded('Remote retry was not successful', async (id, name) => {
690
+ if (!RUN_ID.test(id)) {
691
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...)`);
692
+ }
693
+ const { name: serverName, server, token } = await connect(name);
694
+ const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/retry`)).body;
695
+ environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName} retries ${(0, server_client_1.printable)(id)}: ${(0, server_client_1.printable)(run.state)}, ` +
696
+ `follow it with hammerkit remote logs ${(0, server_client_1.printable)(run.id)} --follow\n`);
697
+ }));
686
698
  remote
687
699
  .command('verify <tasks...>')
688
700
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
689
701
  'exits 1 at once for any it did not')
690
- .addOption(new commander_1.Option('--server <name>', 'the server to ask; the default of remote use when left out'))
702
+ .addOption(new commander_1.Option('--server <name>', 'the server to ask; when left out, the default of remote use or the only registered server'))
691
703
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
692
704
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
693
705
  .action(guarded('Remote verify was not successful', async (tasks, options) => {
@@ -709,7 +721,7 @@ function registerWorkCommands(remote, context) {
709
721
  keys.push({ task, key: found.key });
710
722
  }
711
723
  }
712
- const { name: serverName, server, token } = await connect(options.server);
724
+ const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
713
725
  const answer = keys.length > 0
714
726
  ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
715
727
  : { body: { checks: [] } };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFileImageBuildTaskSchema = exports.buildFileImageBuildSchema = exports.buildFileRegistryLoginSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const build_file_base_task_schema_1 = require("./build-file-base-task-schema");
6
+ const size_schema_1 = require("./size-schema");
7
+ // A registry host, with a port where it has one: europe-west4-docker.pkg.dev, ghcr.io, localhost:5000
8
+ const REGISTRY = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/i;
9
+ // The name of an image with its tag or digest, as `docker build --tag` takes it. A comma, a
10
+ // quote or a space would end it in BuildKit's `--output`, so none of them is in one. `$NAME`
11
+ // and `${NAME}` take the value of a variable, and the name is checked again with it.
12
+ const IMAGE = /^[a-z0-9$][a-z0-9._/:@${}-]*$/i;
13
+ // A platform as BuildKit takes it: os/arch, with a variant where it has one (linux/arm/v7)
14
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9_]+(\/[a-z0-9]+)?$/;
15
+ // the password of a registry login, read like a secret of the task, never written in the build file
16
+ const registryPasswordSchema = (0, zod_1.object)({
17
+ from: (0, zod_1.string)().regex(/^[A-Za-z][A-Za-z0-9_-]*:.+$/, 'from must be env:NAME, file:path or <provider>:<ref>'),
18
+ account: (0, zod_1.string)().optional(),
19
+ })
20
+ .strict()
21
+ .describe('the password, a secret from env:NAME, file:path or <provider>:<ref>');
22
+ exports.buildFileRegistryLoginSchema = (0, zod_1.object)({
23
+ registry: (0, zod_1.string)().regex(REGISTRY, 'registry must be a host, with a port where it has one (ghcr.io, localhost:5000)'),
24
+ // a user name of basic auth holds no colon; a quote or a backslash would end it in the JSON
25
+ user: (0, zod_1.string)().regex(/^[^:"\\\s]+$/, 'user must not hold a colon, a quote, a backslash or a space'),
26
+ password: registryPasswordSchema,
27
+ })
28
+ .strict()
29
+ .describe('a sign-in to a registry, for the push and the cache');
30
+ exports.buildFileImageBuildSchema = (0, zod_1.object)({
31
+ // the folder sent to the build, relative to the task's directory
32
+ context: (0, zod_1.string)().optional().describe('the build context, `.` when left out'),
33
+ // the Dockerfile, relative to the task's directory
34
+ dockerfile: (0, zod_1.string)().optional().describe('the Dockerfile, Dockerfile in the context when left out'),
35
+ tags: (0, zod_1.union)([(0, zod_1.string)().regex(IMAGE, 'a tag must be an image name'), (0, zod_1.array)((0, zod_1.string)().regex(IMAGE)).min(1)])
36
+ .optional()
37
+ .describe('the names of the image, with their tags, as docker build --tag'),
38
+ push: (0, zod_1.boolean)().optional().describe('push the image to its registry, as docker build --push'),
39
+ // an image the layers are read from before the build and written to after it
40
+ cache: (0, zod_1.string)()
41
+ .regex(IMAGE, 'cache must be an image name, such as ghcr.io/acme/app:buildcache')
42
+ .optional()
43
+ .describe('an image in a registry the build reads its layers from and writes them to'),
44
+ // a file the task writes <name>@<digest> of the image to, which another task deploys
45
+ digest: (0, zod_1.string)().optional().describe('a file the task writes <image>@<digest> to'),
46
+ login: (0, zod_1.array)(exports.buildFileRegistryLoginSchema).optional(),
47
+ // the registries of the tags and the cache speak plain HTTP, as a registry:2 on a network of
48
+ // your own does (docker's --insecure-registry)
49
+ insecure: (0, zod_1.boolean)().optional().describe('reach the registries over plain HTTP'),
50
+ // the platforms of the image, as docker build --platform: one image for each, under one name.
51
+ // A RUN step for a platform other than the machine's runs in BuildKit's own QEMU.
52
+ platforms: (0, zod_1.union)([
53
+ (0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64'),
54
+ (0, zod_1.array)((0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64')).min(1),
55
+ ])
56
+ .optional()
57
+ .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
+ })
59
+ .strict()
60
+ .refine((build) => !build.push || build.tags !== undefined, {
61
+ message: 'push needs tags, the names of the image to push',
62
+ })
63
+ .refine((build) => build.digest === undefined || build.tags !== undefined, {
64
+ message: 'digest needs tags, the name the digest is written with',
65
+ })
66
+ .describe('builds a Dockerfile with BuildKit, as docker build does');
67
+ // A task that builds an image: hammerkit runs BuildKit for it, so it names no image, commands or
68
+ // shell of its own, and doesn't extend another task or take arguments.
69
+ exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
+ .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
71
+ .extend({
72
+ build: exports.buildFileImageBuildSchema,
73
+ volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
74
+ })
75
+ .strict()
76
+ .describe('task that builds an image');
77
+ //# sourceMappingURL=build-file-image-build-schema.js.map
@@ -1,16 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBuildFileLocalTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
3
+ exports.isBuildFileLocalTaskSchema = exports.isBuildFileImageBuildTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const build_file_container_task_schema_1 = require("./build-file-container-task-schema");
6
6
  const build_file_local_task_schema_1 = require("./build-file-local-task-schema");
7
+ const build_file_image_build_schema_1 = require("./build-file-image-build-schema");
8
+ // A task with `build` is tried first: it fails at once without one, and with one its own
9
+ // errors are reported, not that the other kinds don't know `build` (zod gives the first
10
+ // option's errors that aren't fatal).
7
11
  exports.buildFileTaskSchema = (0, zod_1.union)([
12
+ build_file_image_build_schema_1.buildFileImageBuildTaskSchema,
8
13
  build_file_container_task_schema_1.buildFileContainerTaskSchema,
9
14
  build_file_local_task_schema_1.buildFileLocalTaskSchema,
10
15
  build_file_container_task_schema_1.buildFileExtendingContainerTaskSchema,
11
16
  ]);
12
17
  const isBuildFileContainerTaskSchema = (val) => 'image' in val;
13
18
  exports.isBuildFileContainerTaskSchema = isBuildFileContainerTaskSchema;
14
- const isBuildFileLocalTaskSchema = (val) => !('image' in val);
19
+ const isBuildFileImageBuildTaskSchema = (val) => 'build' in val;
20
+ exports.isBuildFileImageBuildTaskSchema = isBuildFileImageBuildTaskSchema;
21
+ const isBuildFileLocalTaskSchema = (val) => !('image' in val) && !('build' in val);
15
22
  exports.isBuildFileLocalTaskSchema = isBuildFileLocalTaskSchema;
16
23
  //# sourceMappingURL=build-file-task-schema.js.map
@@ -188,6 +188,11 @@ function applySchemaExtension(reference, task) {
188
188
  task.extension = 'applying';
189
189
  task.depBases = [];
190
190
  task.needBases = [];
191
+ // a task that builds an image extends nothing (its schema has no `extend`)
192
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
193
+ task.extension = 'applied';
194
+ return;
195
+ }
191
196
  const reset = new Set(task.schema.reset ?? []);
192
197
  if (!task.schema.extend) {
193
198
  if (reset.size > 0) {
@@ -198,6 +203,10 @@ function applySchemaExtension(reference, task) {
198
203
  }
199
204
  const name = task.schema.extend;
200
205
  const extend = findPublished(task.relativeName, 'extends', () => findTask(reference, task.scope, name, null)).task;
206
+ // hammerkit makes the commands of a task that builds an image (see image-build.ts)
207
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(extend.schema)) {
208
+ throw new Error(`task ${task.relativeName} extends ${name}, which builds an image: such a task can't be extended`);
209
+ }
201
210
  applySchemaExtension(reference, extend);
202
211
  task.schema.shell = task.schema.shell ?? extend.schema.shell;
203
212
  task.schema.cache = task.schema.cache ?? extend.schema.cache;
@@ -239,7 +248,7 @@ function applySchemaExtension(reference, task) {
239
248
  task.extension = 'applied';
240
249
  }
241
250
  function rejectContainerPropertiesWithoutImage(task) {
242
- if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema)) {
251
+ if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
243
252
  return;
244
253
  }
245
254
  const schema = task.schema;