hammerkit 2.0.0-next.1 → 2.0.0-next.11

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 (64) hide show
  1. package/dist/cache/explain.js +7 -5
  2. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  3. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  4. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  5. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  6. package/dist/dashboard/index.html +3 -3
  7. package/dist/dashboard/logo.png +0 -0
  8. package/dist/executer/docker-task.js +3 -0
  9. package/dist/executer/execute-work-task.js +3 -1
  10. package/dist/executer/local-task.js +3 -0
  11. package/dist/executer/scheduler/enqueue-next.js +6 -1
  12. package/dist/executer/scheduler/state-key.js +71 -34
  13. package/dist/executer/watch-loop.js +18 -5
  14. package/dist/file/get-file-context.js +5 -1
  15. package/dist/kubernetes/await-running-state.js +69 -5
  16. package/dist/kubernetes/claim-layout.js +10 -1
  17. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  18. package/dist/kubernetes/ensure-persistent-data.js +108 -20
  19. package/dist/kubernetes/follow-pod-logs.js +128 -29
  20. package/dist/kubernetes/kept-claims.js +16 -1
  21. package/dist/kubernetes/network-policy.js +4 -4
  22. package/dist/kubernetes/quota-wait.js +97 -0
  23. package/dist/kubernetes/restore-kubernetes-data.js +27 -4
  24. package/dist/kubernetes/store-kubernetes-data.js +13 -2
  25. package/dist/kubernetes/volumes.js +34 -7
  26. package/dist/optimizer/calculate-checksum.js +46 -3
  27. package/dist/optimizer/check-keys.js +4 -2
  28. package/dist/optimizer/get-work-cache-stats.js +36 -24
  29. package/dist/parser/read-build-file.js +8 -3
  30. package/dist/planner/utils/template-value.js +20 -4
  31. package/dist/planner/work-item-executions.js +27 -0
  32. package/dist/planner/work-runtime-kubernetes.js +69 -41
  33. package/dist/remote/host-config.js +1 -1
  34. package/dist/remote/remote-work-commands.js +14 -5
  35. package/dist/schema/schema-parser.js +46 -2
  36. package/dist/server/capacity.js +71 -41
  37. package/dist/server/dashboard.js +27 -9
  38. package/dist/server/endpoints.js +10 -1
  39. package/dist/server/executor.js +65 -34
  40. package/dist/server/kubernetes-backend.js +9 -3
  41. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  42. package/dist/server/oauth.js +16 -1
  43. package/dist/server/overview.js +80 -11
  44. package/dist/server/plan.js +16 -3
  45. package/dist/server/policy.js +9 -3
  46. package/dist/server/run-worker.js +47 -6
  47. package/dist/server/runs.js +74 -6
  48. package/dist/server/sandbox-files.js +107 -16
  49. package/dist/server/sandbox-patch.js +43 -17
  50. package/dist/server/sandboxes.js +57 -23
  51. package/dist/server/server-config.js +4 -1
  52. package/dist/server/server.js +45 -10
  53. package/dist/server/service-runs.js +8 -1
  54. package/dist/server/sources.js +68 -11
  55. package/dist/server/timings.js +23 -3
  56. package/dist/utils/buffer-context.js +30 -20
  57. package/dist/utils/limit.js +30 -0
  58. package/dist/utils/read-lines.js +65 -0
  59. package/dist/utils/units.js +36 -1
  60. package/dist/utils/web-links.js +34 -0
  61. package/package.json +1 -1
  62. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  63. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  64. package/dist/dashboard/favicon.svg +0 -1
@@ -43,12 +43,21 @@ exports.defaultWorker = defaultWorker;
43
43
  // owner may write in the sandbox is not part of it. It leaves entries a run from main can
44
44
  // find, keyed by the files it ran on, as a ref run of a branch does: so only a caller who
45
45
  // may push a branch of the repository and run from it may check (server.ts).
46
+ //
47
+ // An approved run on a sandbox runs on a copy of the approved files too, but its owner
48
+ // may not use its accounts without the approval: it has a cache of its own, so what the
49
+ // owner's other runs built from files nobody approved (ignored ones) is not restored in it.
46
50
  function cacheNamespace(run) {
47
51
  const repository = run.source.type === 'ref' || (run.source.type === 'sandbox' && run.source.check);
52
+ const kind = repository
53
+ ? 'ref'
54
+ : run.source.type === 'sandbox' && (run.approvals?.length ?? 0) > 0
55
+ ? 'approved'
56
+ : run.source.type;
48
57
  const key = repository
49
58
  ? `ref\0${run.source.repo}`
50
- : `${run.source.type}\0${run.owner.iss}\0${run.owner.sub}`;
51
- return `${repository ? 'ref' : run.source.type}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
59
+ : `${kind}\0${run.owner.iss}\0${run.owner.sub}`;
60
+ return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
52
61
  }
53
62
  exports.cacheNamespace = cacheNamespace;
54
63
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
@@ -212,76 +221,93 @@ class HostExecutor {
212
221
  const root = this.directoryOf(run);
213
222
  let attachment;
214
223
  try {
215
- // where the process of the run starts: the checkout of a ref, or for a sandbox the
216
- // published files, so what the process and the secret providers it starts read of
217
- // their directory is never what a task wrote
218
- let cwd;
224
+ // The process of the run starts in the published files, which it reads its build files
225
+ // from, and its tasks work on other files (`work`): a checkout, a sandbox or a copy of
226
+ // one. The published files are a directory of the run no task mounts, so what the
227
+ // process parses for each task it runs, and what the secret providers it starts read
228
+ // of their directory, is what was published and never what a task wrote.
229
+ const published = (0, path_1.join)(root, 'bundle');
230
+ await (0, promises_1.mkdir)(published, { recursive: true });
231
+ await this.writeBundle(published, bundle.files);
219
232
  let input;
220
233
  let claim;
221
- // the files of the sandbox the tasks work on
234
+ // the files the tasks work on
222
235
  let work;
223
- if (source.type === 'sandbox' && source.check) {
224
- // a check works on the files a push of the sandbox commits, copied out of it: never
225
- // on the sandbox, whose ignored files (node_modules, outputs) its owner writes
236
+ const sourceStarted = new Date();
237
+ // A check works on the files a push of the sandbox commits, copied out of it, and so
238
+ // does a run that was approved: what was approved is those files, and the sandbox has
239
+ // more (its ignored files, node_modules, outputs), which its owner and their runs write
240
+ // while the run waits and runs.
241
+ const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
242
+ // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
243
+ if (source.type === 'sandbox' && copied) {
226
244
  const { registry, network } = sandboxes;
227
- cwd = (0, path_1.join)(root, 'source');
245
+ const what = source.check ? 'the check' : 'the approved run';
246
+ if (!source.check) {
247
+ // what was approved is what runs: the files may have changed since, by a run
248
+ // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
249
+ const state = await registry.state(source.id, abortCtrl.signal);
250
+ if (state.tree !== source.tree) {
251
+ throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
252
+ }
253
+ }
254
+ work = (0, path_1.join)(root, 'source');
228
255
  try {
229
- await registry.exportTree(source.id, source.tree, cwd, abortCtrl.signal);
256
+ await registry.exportTree(source.id, source.tree, work, abortCtrl.signal);
230
257
  }
231
258
  catch (e) {
232
- throw new Error(`the files of the sandbox ${source.id} could not be copied for the check, submit it again: ${e instanceof Error ? e.message : String(e)}`);
259
+ throw new Error(`the files of the sandbox ${source.id} could not be copied for ${what}, submit it again: ${e instanceof Error ? e.message : String(e)}`);
233
260
  }
234
261
  // a repository of its own, as a checkout of the commit is: the root of the project,
235
262
  // which the paths of the tasks' keys are relative to, is the one of git
236
- await (0, git_checkout_1.git)(['init', '--quiet', cwd], {}, abortCtrl.signal, `the check of sandbox ${source.id}`, 'init');
263
+ await (0, git_checkout_1.git)(['init', '--quiet', work], {}, abortCtrl.signal, `${what} of sandbox ${source.id}`, 'init');
237
264
  context.emit({
238
265
  type: 'log',
239
266
  task: 'hammerkit',
240
267
  stream: 'stdout',
241
- text: `check of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
268
+ text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
242
269
  });
243
- await this.writeBundle(cwd, bundle.files);
270
+ // the tasks see the published build files in place of the sandbox's own
271
+ await this.writeBundle(work, bundle.files);
244
272
  input = {
245
- entry: (0, path_1.join)(cwd, version.entry),
273
+ entry: (0, path_1.join)(published, version.entry),
274
+ directory: { read: published, work },
246
275
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
247
276
  sandboxNetwork: network,
248
277
  };
249
278
  }
250
279
  else if (source.type === 'ref') {
251
- cwd = (0, path_1.join)(root, 'source');
280
+ work = (0, path_1.join)(root, 'source');
252
281
  const { repo, ref, commit: pinned } = source;
253
282
  const credentials = await repos.credentials(repo);
254
283
  let commit;
255
284
  try {
256
285
  // a woken service run starts the commit it started first, where the ref is now or not
257
286
  const fetched = run.wakes ? pinned : ref;
258
- commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, cwd, credentials.env, abortCtrl.signal, pinned);
287
+ commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, work, credentials.env, abortCtrl.signal, pinned);
259
288
  }
260
289
  catch (e) {
261
290
  throw repos.scrub(e, credentials.values);
262
291
  }
263
292
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `checked out ${repo} at ${commit}` });
264
- await this.writeBundle(cwd, bundle.files);
293
+ // the tasks see the published build files in place of the checkout's own
294
+ await this.writeBundle(work, bundle.files);
265
295
  // what the version was checked against at publish holds while it runs too
266
296
  input = {
267
- entry: (0, path_1.join)(cwd, version.entry),
297
+ entry: (0, path_1.join)(published, version.entry),
298
+ directory: { read: published, work },
268
299
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
269
300
  };
270
301
  }
271
302
  else {
272
- // the published files are read from a directory of the run and work on the
273
- // sandbox, whose own build files are just files
303
+ // a run its caller may run without an approval works on the sandbox itself, whose
304
+ // own build files are just files
274
305
  const { registry, network } = sandboxes;
275
306
  // read before the run attaches: until then the walk of the last run's measure holds
276
307
  const state = await registry.state(source.id, abortCtrl.signal);
277
308
  attachment = await registry.attach(source.id, (0, path_1.join)(root, 'sandbox'));
278
309
  work = attachment.directory;
279
310
  claim = attachment.claim;
280
- // what was approved is what runs: the files may have changed since, by a run
281
- // before this one on the sandbox
282
- if (run.approvals?.length && state.tree !== source.tree) {
283
- throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
284
- }
285
311
  if (claim && !this.options.placement) {
286
312
  throw new Error(`the sandbox ${source.id} is a claim on a cluster, this server runs tasks on its own docker`);
287
313
  }
@@ -291,10 +317,6 @@ class HostExecutor {
291
317
  stream: 'stdout',
292
318
  text: `sandbox ${source.id} of ${source.repo} at ${state.commit}, files ${state.tree}${state.clean ? '' : ' with changes'}`,
293
319
  });
294
- const published = (0, path_1.join)(root, 'bundle');
295
- await (0, promises_1.mkdir)(published, { recursive: true });
296
- await this.writeBundle(published, bundle.files);
297
- cwd = published;
298
320
  input = {
299
321
  entry: (0, path_1.join)(published, version.entry),
300
322
  directory: { read: published, work },
@@ -303,12 +325,17 @@ class HostExecutor {
303
325
  sandboxNetwork: network,
304
326
  };
305
327
  }
328
+ emitPhase(context, 'source', sourceStarted);
306
329
  const home = (0, path_1.join)(root, 'home');
307
330
  await (0, promises_1.mkdir)(home, { recursive: true });
308
331
  const cache = (0, path_1.join)(this.options.cache, cacheNamespace(run));
309
332
  await (0, promises_1.mkdir)(cache, { recursive: true });
310
333
  const placement = this.options.placement;
311
- const placed = placement ? await placement.prepare(run, context, { root: work ?? cwd, claim }) : undefined;
334
+ const namespaceStarted = new Date();
335
+ const placed = placement ? await placement.prepare(run, context, { root: work, claim }) : undefined;
336
+ if (placed) {
337
+ emitPhase(context, 'namespace', namespaceStarted);
338
+ }
312
339
  try {
313
340
  await this.runInProcess(worker, {
314
341
  ...input,
@@ -328,7 +355,7 @@ class HostExecutor {
328
355
  : {}),
329
356
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
330
357
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
331
- }, cwd, { ...this.processEnvironment(home, cache), ...placed?.env }, context, abortCtrl.signal);
358
+ }, published, { ...this.processEnvironment(home, cache), ...placed?.env }, context, abortCtrl.signal);
332
359
  }
333
360
  finally {
334
361
  if (placement && placed) {
@@ -504,4 +531,8 @@ class HostExecutor {
504
531
  }
505
532
  }
506
533
  exports.HostExecutor = HostExecutor;
534
+ // A step of a run before its tasks, for its timeline (RunPhase)
535
+ function emitPhase(context, phase, startedAt) {
536
+ context.emit({ type: 'phase', phase, startedAt: startedAt.toISOString(), finishedAt: new Date().toISOString() });
537
+ }
507
538
  //# sourceMappingURL=executor.js.map
@@ -720,13 +720,19 @@ function getPrivilegedNamespaceProblem(namespace, labels, backend) {
720
720
  `${namespace} ${ENFORCE_LABEL}=baseline ${AUDIT_LABEL}- --overwrite`);
721
721
  }
722
722
  exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
723
- // What may mount a claim a run kept: the runs of the same repository, as they share the
724
- // cache, and on a sandbox the runs of that sandbox only, whose claim is on the same node or
725
- // zone as the kept ones. The owner is the namespace's.
723
+ // What may mount a claim a run kept: the runs of the same branch or tag of a repository,
724
+ // which share its cache, so that the runs of two branches go side by side and the runs of one find what
725
+ // the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
726
+ // node or zone as the kept ones. The owner is the namespace's.
726
727
  function getVolumeScope(run) {
727
728
  if (run.source.type === 'sandbox' && !run.source.check) {
728
729
  return `sandbox-${(0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24)}`;
729
730
  }
731
+ // a ref given as a commit hash names no branch: its runs keep the repository's claims
732
+ if (run.source.type === 'ref' && !/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(run.source.ref)) {
733
+ const key = `ref\0${run.source.repo}\0${run.source.ref}`;
734
+ return `ref-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
735
+ }
730
736
  return (0, executor_1.cacheNamespace)(run);
731
737
  }
732
738
  exports.getVolumeScope = getVolumeScope;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
3
+ exports.AnswerReader = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
@@ -542,7 +542,9 @@ class KubernetesSandboxStorage {
542
542
  // the process ends when the server stops waiting for it: closing the connection does
543
543
  // not end a command in a pod
544
544
  const seconds = Math.ceil((['create', 'fetch', 'move', 'archive'].includes(request.op) ? FETCH_TIMEOUT_MS : REQUEST_TIMEOUT_MS) / 1000);
545
- const done = this.withPod(key, (pod) => this.exec(pod, ['timeout', String(seconds), 'hammerkit', 'server-sandbox', CLAIM_PATH], stream_1.Readable.from([Buffer.from(JSON.stringify(encoded))]), reader, signal));
545
+ const done = this.withPod(key, (pod) => this.exec(pod, ['timeout', String(seconds), 'hammerkit', 'server-sandbox', CLAIM_PATH], stream_1.Readable.from([Buffer.from(JSON.stringify(encoded))]), reader,
546
+ // a request that failed (an answer too large) stops the command too
547
+ AbortSignal.any([signal, reader.stopped])));
546
548
  done.then(() => reader.complete(), (e) => reader.fail(e));
547
549
  const answer = await reader.answer;
548
550
  if (!answer.header.ok) {
@@ -911,16 +913,22 @@ function holdBack(socket, stdout) {
911
913
  * memory, unless the first line says it is a stream: then it is passed on as it comes.
912
914
  */
913
915
  class AnswerReader extends stream_1.Writable {
914
- constructor(body) {
916
+ constructor(body, maxBytes = MAX_ANSWER_BYTES) {
915
917
  super();
916
918
  this.body = body;
919
+ this.maxBytes = maxBytes;
917
920
  this.chunks = [];
918
921
  this.size = 0;
922
+ this.stop = new AbortController();
923
+ // aborted once the answer failed: nothing reads the rest
924
+ this.stopped = this.stop.signal;
919
925
  this.answer = new Promise((resolve, reject) => {
920
926
  this.resolveAnswer = resolve;
921
927
  this.rejectAnswer = reject;
922
928
  });
923
929
  this.answer.catch(() => undefined);
930
+ // an answer that is too large or no answer at all fails the request, not the server
931
+ this.on('error', (e) => this.fail(e));
924
932
  }
925
933
  _write(chunk, _encoding, callback) {
926
934
  if (this.stream) {
@@ -933,7 +941,7 @@ class AnswerReader extends stream_1.Writable {
933
941
  return;
934
942
  }
935
943
  this.size += chunk.length;
936
- if (this.size > MAX_ANSWER_BYTES) {
944
+ if (this.size > this.maxBytes) {
937
945
  callback(new Error('the answer of the pod of the sandbox is too large'));
938
946
  return;
939
947
  }
@@ -986,6 +994,7 @@ class AnswerReader extends stream_1.Writable {
986
994
  }
987
995
  }
988
996
  fail(e) {
997
+ this.stop.abort();
989
998
  const error = e instanceof Error ? e : new Error(String(e));
990
999
  if (this.stream) {
991
1000
  this.stream.destroy(error);
@@ -993,6 +1002,7 @@ class AnswerReader extends stream_1.Writable {
993
1002
  this.rejectAnswer(error);
994
1003
  }
995
1004
  }
1005
+ exports.AnswerReader = AnswerReader;
996
1006
  // The files of a sandbox on a cluster: each call is a request to the pod of its files.
997
1007
  class KubernetesSandboxFiles {
998
1008
  constructor(request, rawFile) {
@@ -1,7 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TokenVerifier = exports.quote = exports.TokenError = void 0;
3
+ exports.TokenVerifier = exports.quote = exports.TokenError = exports.displayName = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ /**
6
+ * How pages name a person: the `name` of their token, else `preferred_username`, else `email`
7
+ * (with the scopes `profile email`); none with `openid` alone, which carries the subject only.
8
+ */
9
+ function displayName(principal) {
10
+ const claims = principal.claims ?? {};
11
+ for (const value of [principal.name, claims.name, claims.preferred_username, claims.email]) {
12
+ const trimmed = value?.trim();
13
+ if (trimmed) {
14
+ return trimmed.slice(0, 100);
15
+ }
16
+ }
17
+ return undefined;
18
+ }
19
+ exports.displayName = displayName;
5
20
  // The reason is for the operator's log, never for the caller.
6
21
  class TokenError extends Error {
7
22
  }
@@ -5,6 +5,7 @@ const policy_1 = require("./policy");
5
5
  const runs_1 = require("./runs");
6
6
  const service_runs_1 = require("./service-runs");
7
7
  const repo_1 = require("./repo");
8
+ const units_1 = require("../utils/units");
8
9
  var wait_reason_1 = require("./wait-reason");
9
10
  Object.defineProperty(exports, "describeWait", { enumerable: true, get: function () { return wait_reason_1.describeWait; } });
10
11
  function getViewer(config, principal) {
@@ -12,6 +13,7 @@ function getViewer(config, principal) {
12
13
  principal,
13
14
  grant: (0, policy_1.getGrant)(config.entitlements, principal),
14
15
  activity: config.runs.activity === 'everyone',
16
+ nameOf: (owner) => (0, policy_1.subjectName)(config.entitlements, owner),
15
17
  };
16
18
  }
17
19
  exports.getViewer = getViewer;
@@ -21,9 +23,14 @@ function runActions(viewer, run) {
21
23
  }
22
24
  const mine = owns(viewer, run);
23
25
  const may = {
24
- ...(mine || decides(viewer, run) ? { stop: true } : {}),
26
+ ...(mine || decides(viewer, run) || (run.up && (0, service_runs_1.mayPublishEndpoints)(viewer.grant, run))
27
+ ? { stop: true }
28
+ : {}),
25
29
  ...(run.up && run.upAt && (mine || (0, service_runs_1.mayOpenEndpoints)(viewer.grant, run)) ? { extend: true } : {}),
26
30
  ...(mayDecide(viewer, run) ? { decide: true } : {}),
31
+ ...(run.up && run.state === 'asleep' && (mine || (0, service_runs_1.mayOpenEndpoints)(viewer.grant, run))
32
+ ? { wake: true }
33
+ : {}),
27
34
  };
28
35
  return Object.keys(may).length > 0 ? may : undefined;
29
36
  }
@@ -85,7 +92,8 @@ function mayRead(viewer, run) {
85
92
  return owns(viewer, run) || viewer.grant.observe || decides(viewer, run);
86
93
  }
87
94
  exports.mayRead = mayRead;
88
- function toListedRun(viewer, run, queue) {
95
+ // `entryOf` names where in its repository the build file of a version is.
96
+ function toListedRun(viewer, run, queue, entryOf) {
89
97
  const { owner, results, plan, options, up, error, ...rest } = run;
90
98
  const mine = owns(viewer, run);
91
99
  const may = runActions(viewer, run);
@@ -100,9 +108,11 @@ function toListedRun(viewer, run, queue) {
100
108
  ...(result.cache ? { cached: result.cache.hit } : {}),
101
109
  },
102
110
  ]));
111
+ const entry = entryOf?.(run.definition);
112
+ const name = owner.name ?? viewer.nameOf?.(owner);
103
113
  return {
104
114
  ...rest,
105
- ...(mine ? { plan, options } : { owner: { iss: owner.iss, sub: owner.sub } }),
115
+ ...(mine ? { plan, options } : { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } }),
106
116
  ...(up
107
117
  ? {
108
118
  up: {
@@ -116,6 +126,7 @@ function toListedRun(viewer, run, queue) {
116
126
  ...(queue ? { queue } : {}),
117
127
  ...(may ? { may } : {}),
118
128
  ...(!mine && mayRead(viewer, run) ? { readable: true } : {}),
129
+ ...(entry ? { entry } : {}),
119
130
  };
120
131
  }
121
132
  exports.toListedRun = toListedRun;
@@ -141,7 +152,8 @@ function queuePlace(registry, viewer, run) {
141
152
  return { position: queue.position, waitsFor: visibleReason(queue.waitsFor, visible) };
142
153
  }
143
154
  exports.queuePlace = queuePlace;
144
- function getOverview(snapshot, usage, viewer) {
155
+ function getOverview(snapshot, usage, viewer, entryOf) {
156
+ const list = (run, place) => toListedRun(viewer, run, place, entryOf);
145
157
  const runs = new Map();
146
158
  for (const run of [
147
159
  ...snapshot.running,
@@ -160,7 +172,7 @@ function getOverview(snapshot, usage, viewer) {
160
172
  return {
161
173
  ...place,
162
174
  mine: owns(viewer, entry.run),
163
- ...(maySee(viewer, entry.run) ? { run: toListedRun(viewer, entry.run, place) } : {}),
175
+ ...(maySee(viewer, entry.run) ? { run: list(entry.run, place) } : {}),
164
176
  };
165
177
  });
166
178
  const running = snapshot.running.filter((run) => maySee(viewer, run));
@@ -170,19 +182,19 @@ function getOverview(snapshot, usage, viewer) {
170
182
  places: {
171
183
  max: snapshot.places.max,
172
184
  used: snapshot.places.used,
173
- runs: running.map((run) => toListedRun(viewer, run)),
185
+ runs: running.map((run) => list(run)),
174
186
  others: snapshot.running.length - running.length,
175
187
  },
176
188
  queue,
177
189
  approvals: {
178
190
  waiting: snapshot.awaiting.runs.length,
179
191
  max: snapshot.awaiting.max,
180
- runs: snapshot.awaiting.runs.filter((run) => maySee(viewer, run)).map((run) => toListedRun(viewer, run)),
192
+ runs: snapshot.awaiting.runs.filter((run) => maySee(viewer, run)).map((run) => list(run)),
181
193
  },
182
194
  services: {
183
195
  open: snapshot.services.taken,
184
196
  ...(snapshot.services.max !== undefined ? { max: snapshot.services.max } : {}),
185
- runs: snapshot.services.runs.filter((run) => maySee(viewer, run)).map((run) => toListedRun(viewer, run)),
197
+ runs: snapshot.services.runs.filter((run) => maySee(viewer, run)).map((run) => list(run)),
186
198
  },
187
199
  limits: {
188
200
  waiting: meter(usage.waiting, limits?.waiting),
@@ -209,7 +221,7 @@ const STATES = [
209
221
  'rejected',
210
222
  ];
211
223
  // `scope`, `state` (a comma separated list) and `kind` of GET /v1/runs.
212
- function parseRunFilter(params, grant) {
224
+ function parseRunFilter(params, grant, now = Date.now()) {
213
225
  const scope = params.get('scope') ?? 'mine';
214
226
  if (scope !== 'mine' && scope !== 'visible' && scope !== 'all') {
215
227
  throw new Error('scope: mine, visible or all');
@@ -234,9 +246,35 @@ function parseRunFilter(params, grant) {
234
246
  if (id !== undefined && !/^run_[A-Za-z0-9_-]{16}$/.test(id)) {
235
247
  throw new Error('id: the id of a run, run_...');
236
248
  }
237
- return { scope, ...(states ? { states } : {}), ...(kind ? { kind } : {}), ...(id ? { id } : {}) };
249
+ const since = parseMoment(params.get('since'), now, 'since');
250
+ const until = parseMoment(params.get('until'), now, 'until');
251
+ if (since !== undefined && until !== undefined && until < since) {
252
+ throw new Error('until: after since');
253
+ }
254
+ return {
255
+ scope,
256
+ ...(states ? { states } : {}),
257
+ ...(kind ? { kind } : {}),
258
+ ...(id ? { id } : {}),
259
+ ...(since !== undefined ? { since } : {}),
260
+ ...(until !== undefined ? { until } : {}),
261
+ };
238
262
  }
239
263
  exports.parseRunFilter = parseRunFilter;
264
+ // `7d` back from now, or a time such as `2026-11-01T08:00:00Z`, in ms
265
+ function parseMoment(value, now, name) {
266
+ if (value === null) {
267
+ return undefined;
268
+ }
269
+ if (/^(\d+(\.\d+)?(ms|s|m|h|d))+$/.test(value)) {
270
+ return now - (0, units_1.parseDuration)(value);
271
+ }
272
+ const at = /^\d{4}-\d{2}-\d{2}/.test(value) ? Date.parse(value) : NaN;
273
+ if (!Number.isFinite(at)) {
274
+ throw new Error(`${name}: a duration back from now, such as 1h, 24h or 7d, or a time, such as 2026-11-01T08:00:00Z`);
275
+ }
276
+ return at;
277
+ }
240
278
  class FilterRefused extends Error {
241
279
  }
242
280
  exports.FilterRefused = FilterRefused;
@@ -244,7 +282,9 @@ function filterRuns(runs, viewer, filter) {
244
282
  return runs.filter((run) => (filter.scope === 'mine' ? owns(viewer, run) : maySee(viewer, run)) &&
245
283
  (!filter.id || run.id === filter.id) &&
246
284
  (!filter.states || filter.states.includes(run.state)) &&
247
- (!filter.kind || (filter.kind === 'services') === !!run.up));
285
+ (!filter.kind || (filter.kind === 'services') === !!run.up) &&
286
+ (filter.since === undefined || Date.parse(run.createdAt) >= filter.since) &&
287
+ (filter.until === undefined || Date.parse(run.createdAt) <= filter.until));
248
288
  }
249
289
  exports.filterRuns = filterRuns;
250
290
  // The machines and what the runs take, with whose the namespaces are where the caller may
@@ -255,6 +295,35 @@ function visibleCapacity(capacity, viewer) {
255
295
  ...capacity,
256
296
  // what the cluster answered is for operators; others learn that something is missing
257
297
  problems: viewer.grant.observe || capacity.problems.length === 0 ? capacity.problems : ['some of it could not be read'],
298
+ ...(capacity.unknown
299
+ ? {
300
+ unknown: everyone
301
+ ? capacity.unknown
302
+ : {
303
+ ...(capacity.unknown.total ? { total: 'not readable' } : {}),
304
+ ...(capacity.unknown.used ? { used: 'not readable' } : {}),
305
+ },
306
+ }
307
+ : {}),
308
+ // what others' runs and sandboxes take shows, not what they are
309
+ ...(capacity.uses
310
+ ? {
311
+ uses: capacity.uses.map((use) => {
312
+ const mine = use.owner?.iss === viewer.principal.iss && use.owner?.sub === viewer.principal.sub;
313
+ const name = use.owner && !use.owner.name ? viewer.nameOf?.(use.owner) : undefined;
314
+ return everyone || mine || !use.owner
315
+ ? name && use.owner
316
+ ? { ...use, owner: { ...use.owner, name } }
317
+ : use
318
+ : {
319
+ kind: use.kind,
320
+ pods: use.pods,
321
+ requested: use.requested,
322
+ ...(use.used ? { used: use.used } : {}),
323
+ };
324
+ }),
325
+ }
326
+ : {}),
258
327
  groups: capacity.groups.map((group) => {
259
328
  const mine = group.owner?.iss === viewer.principal.iss && group.owner?.sub === viewer.principal.sub;
260
329
  if (everyone || mine || !group.owner) {
@@ -294,6 +294,13 @@ function describeMountSource(mount) {
294
294
  const home = (0, normalize_path_1.getHomeReference)(mount.mount.split(':')[0]);
295
295
  return home ? `${mount.localPath} (${home} is the home directory)` : mount.localPath;
296
296
  }
297
+ // where the build file of an item is: in the bundle, or in the repository of a git include
298
+ function declaredIn(root, scope) {
299
+ if (scope.remote) {
300
+ return `${scope.remote.git} ${(0, path_1.relative)(scope.remote.root, scope.fileName).split(path_1.sep).join('/')}`;
301
+ }
302
+ return (0, path_1.relative)(root, scope.fileName).split(path_1.sep).join('/');
303
+ }
297
304
  function toPlan(root, item) {
298
305
  const data = item.data;
299
306
  const secrets = secretsOf(item).map(describeSecret);
@@ -322,6 +329,7 @@ function toPlan(root, item) {
322
329
  const isTask = data.type === 'local-task' || data.type === 'container-task';
323
330
  return {
324
331
  kind: isTask ? 'task' : 'service',
332
+ file: declaredIn(root, data.scope),
325
333
  ...(data.description ? { description: data.description } : {}),
326
334
  runtime: (0, work_task_1.isAggregateTask)(data) ? 'none' : data.type === 'local-task' ? 'local' : 'docker',
327
335
  ...((0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data) ? { image: data.image } : {}),
@@ -330,13 +338,18 @@ function toPlan(root, item) {
330
338
  network: (0, work_network_1.toNetworkSchema)('network' in data ? data.network : { type: 'open' }),
331
339
  ...('args' in data && data.args !== null ? { args: data.args } : {}),
332
340
  deps: item.deps.map((dep) => dep.name).sort(),
333
- needs: item.needs.map((need) => need.name).sort(),
341
+ // by their names in the plan, not the names the task reaches them at (`postgres` of an include)
342
+ needs: item.needs.map((need) => need.service.name).sort(),
334
343
  accounts,
335
344
  secrets,
336
345
  serverEnvs: 'envs' in data ? data.envs.processNames ?? [] : [],
337
346
  mounts,
338
347
  ports,
339
- generates: 'generates' in data ? data.generates.map((generate) => generate.path) : [],
348
+ // where in the bundle, as the build file names them: the directory the server read it in is
349
+ // its own
350
+ generates: 'generates' in data
351
+ ? data.generates.map((generate) => insideBundle(root, data.cwd, generate.path)[0] ?? generate.path)
352
+ : [],
340
353
  ...(capAdd.length > 0 ? { capAdd: [...capAdd] } : {}),
341
354
  flags,
342
355
  };
@@ -400,7 +413,7 @@ async function planBundle(bundle, environment, options = {}) {
400
413
  ? item.data.mounts.flatMap((mount) => insideBundle(directory, item.data.cwd, mount.localPath))
401
414
  : [],
402
415
  deps: item.deps.map((dep) => dep.name).sort(),
403
- needs: item.needs.map((need) => need.name).sort(),
416
+ needs: item.needs.map((need) => need.service.name).sort(),
404
417
  };
405
418
  }
406
419
  const plan = {};
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decideRun = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = void 0;
3
+ exports.decideRun = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = exports.subjectName = void 0;
4
4
  const repo_1 = require("./repo");
5
5
  const BUILDS_ORDER = ['run', 'propose', 'publish'];
6
+ // The name an entitlement gives a subject, for the pages to name its runs by when its tokens
7
+ // name nobody.
8
+ function subjectName(entitlements, who) {
9
+ return entitlements.find((entitlement) => entitlement.subject?.name && entitlement.subject.iss === who.iss && entitlement.subject.sub === who.sub)?.subject?.name;
10
+ }
11
+ exports.subjectName = subjectName;
6
12
  function matches(entitlement, principal) {
7
13
  if (entitlement.subject) {
8
14
  return entitlement.subject.iss === principal.iss && entitlement.subject.sub === principal.sub;
@@ -34,9 +40,9 @@ const mayPublish = (grant) => atLeast(grant, 'publish');
34
40
  exports.mayPublish = mayPublish;
35
41
  // A caller who can neither run nor publish anything sees nothing of the server's
36
42
  // build files either. Someone who uses an account sees them: they have to know what
37
- // they approve.
43
+ // they approve. Who observes sees them too, as they see what every run ran.
38
44
  function maySeeDefinitions(grant) {
39
- return grant.builds !== null || Object.keys(grant.accounts).length > 0;
45
+ return grant.builds !== null || Object.keys(grant.accounts).length > 0 || grant.observe;
40
46
  }
41
47
  exports.maySeeDefinitions = maySeeDefinitions;
42
48
  // `use` includes deciding about the runs others request on the account.