hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -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");
@@ -11,6 +11,7 @@ const tar_2 = require("../utils/tar");
11
11
  const apply_1 = require("../kubernetes/apply");
12
12
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
13
13
  const network_policy_1 = require("../kubernetes/network-policy");
14
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
14
15
  const volumes_1 = require("../kubernetes/volumes");
15
16
  const log_1 = require("../log");
16
17
  const sleep_1 = require("../utils/sleep");
@@ -260,6 +261,41 @@ class KubernetesSandboxStorage {
260
261
  await (0, promises_1.rm)(repository, { recursive: true, force: true });
261
262
  }
262
263
  }
264
+ // The pod writes the tree's files beside the sandbox on the claim and sends them as a tar,
265
+ // which is extracted here as the files of `attach` are: what a run plans with, up to the
266
+ // bytes a sandbox may take.
267
+ async exportTree(key, tree, into, signal) {
268
+ await (0, promises_1.mkdir)(into, { recursive: true });
269
+ let bytes = 0;
270
+ const extract = (0, tar_1.extract)({
271
+ cwd: into,
272
+ filter: (_path, entry) => 'type' in entry && ['File', 'OldFile', 'Directory', 'SymbolicLink'].includes(entry.type),
273
+ });
274
+ const counted = new stream_1.PassThrough();
275
+ counted.on('data', (chunk) => {
276
+ bytes += chunk.length;
277
+ if (bytes > this.limits.bytes) {
278
+ counted.destroy(new Error(`the files of the sandbox ${key.id} take more than ${(0, units_1.formatSize)(this.limits.bytes)}`));
279
+ }
280
+ });
281
+ const extracted = new Promise((resolve, reject) => {
282
+ extract.on('finish', resolve);
283
+ extract.on('error', reject);
284
+ counted.on('error', reject);
285
+ });
286
+ extracted.catch(() => undefined);
287
+ counted.pipe(extract);
288
+ const answer = await this.exclusive(key.id, () => this.call(key, { op: 'archive', id: key.id, tree }, signal, true));
289
+ if ('stream' in answer) {
290
+ // a pipeline, so the answer is ended with the copy: an error of the pod after the copy
291
+ // stopped (over the size limit) lands nowhere else
292
+ await (0, promises_2.pipeline)(answer.stream, counted);
293
+ }
294
+ else {
295
+ counted.end(answer.body);
296
+ }
297
+ await extracted;
298
+ }
263
299
  async moveTo(key, commit) {
264
300
  await this.request(key, { op: 'move', id: key.id, commit }, AbortSignal.timeout(FETCH_TIMEOUT_MS));
265
301
  }
@@ -284,6 +320,8 @@ class KubernetesSandboxStorage {
284
320
  // runs on a sandbox go one at a time: a proxy the pod of the files does not own was
285
321
  // left by a run before (the server stopped, or its release could not remove it)
286
322
  await (0, network_policy_1.removeSandboxProxies)(this.instance, namespace, { sandbox: names.label }, (deployment) => isOwnedBy(deployment, pod.uid)).catch(() => undefined);
323
+ // and a runner, which the pod did not own when it made way for a run
324
+ await (0, sandbox_runner_1.removeSandboxRunners)(this.instance, namespace, names.label, (runner) => isOwnedBy(runner, pod.uid)).catch(() => undefined);
287
325
  await (0, promises_1.mkdir)(into, { recursive: true });
288
326
  await this.copyOut(key, ['tar', 'cf', '-', '-C', `${CLAIM_PATH}/${key.id}/files`, '.'], into,
289
327
  // what the run plans with: files, directories and links, nothing outside of it
@@ -388,7 +426,8 @@ class KubernetesSandboxStorage {
388
426
  async removeIn(namespace, id) {
389
427
  const names = getSandboxNames(id);
390
428
  await this.stopPod({ id, owner: { iss: '', sub: '' } }, namespace);
391
- // the cluster removes the proxies the pod owned; those it did not own go here
429
+ // the cluster removes the proxies and the runner the pod owned; those it did not own go here
430
+ await (0, sandbox_runner_1.removeSandboxRunners)(this.instance, namespace, names.label);
392
431
  await (0, network_policy_1.removeSandboxProxies)(this.instance, namespace, { sandbox: names.label });
393
432
  for (const name of [names.claim, names.git]) {
394
433
  try {
@@ -502,8 +541,10 @@ class KubernetesSandboxStorage {
502
541
  const reader = new AnswerReader(body);
503
542
  // the process ends when the server stops waiting for it: closing the connection does
504
543
  // not end a command in a pod
505
- const seconds = Math.ceil((['create', 'fetch', 'move'].includes(request.op) ? FETCH_TIMEOUT_MS : REQUEST_TIMEOUT_MS) / 1000);
506
- 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));
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,
546
+ // a request that failed (an answer too large) stops the command too
547
+ AbortSignal.any([signal, reader.stopped])));
507
548
  done.then(() => reader.complete(), (e) => reader.fail(e));
508
549
  const answer = await reader.answer;
509
550
  if (!answer.header.ok) {
@@ -872,24 +913,35 @@ function holdBack(socket, stdout) {
872
913
  * memory, unless the first line says it is a stream: then it is passed on as it comes.
873
914
  */
874
915
  class AnswerReader extends stream_1.Writable {
875
- constructor(body) {
916
+ constructor(body, maxBytes = MAX_ANSWER_BYTES) {
876
917
  super();
877
918
  this.body = body;
919
+ this.maxBytes = maxBytes;
878
920
  this.chunks = [];
879
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;
880
925
  this.answer = new Promise((resolve, reject) => {
881
926
  this.resolveAnswer = resolve;
882
927
  this.rejectAnswer = reject;
883
928
  });
884
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));
885
932
  }
886
933
  _write(chunk, _encoding, callback) {
887
934
  if (this.stream) {
935
+ if (this.stream.destroyed) {
936
+ // its reader stopped (over a size limit): the rest of the answer is nobody's
937
+ callback();
938
+ return;
939
+ }
888
940
  this.stream.write(chunk, callback);
889
941
  return;
890
942
  }
891
943
  this.size += chunk.length;
892
- if (this.size > MAX_ANSWER_BYTES) {
944
+ if (this.size > this.maxBytes) {
893
945
  callback(new Error('the answer of the pod of the sandbox is too large'));
894
946
  return;
895
947
  }
@@ -942,6 +994,7 @@ class AnswerReader extends stream_1.Writable {
942
994
  }
943
995
  }
944
996
  fail(e) {
997
+ this.stop.abort();
945
998
  const error = e instanceof Error ? e : new Error(String(e));
946
999
  if (this.stream) {
947
1000
  this.stream.destroy(error);
@@ -949,6 +1002,7 @@ class AnswerReader extends stream_1.Writable {
949
1002
  this.rejectAnswer(error);
950
1003
  }
951
1004
  }
1005
+ exports.AnswerReader = AnswerReader;
952
1006
  // The files of a sandbox on a cluster: each call is a request to the pod of its files.
953
1007
  class KubernetesSandboxFiles {
954
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
  }
@@ -0,0 +1,340 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.visibleCapacity = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.runActions = exports.getViewer = exports.describeWait = void 0;
4
+ const policy_1 = require("./policy");
5
+ const runs_1 = require("./runs");
6
+ const service_runs_1 = require("./service-runs");
7
+ const repo_1 = require("./repo");
8
+ const units_1 = require("../utils/units");
9
+ var wait_reason_1 = require("./wait-reason");
10
+ Object.defineProperty(exports, "describeWait", { enumerable: true, get: function () { return wait_reason_1.describeWait; } });
11
+ function getViewer(config, principal) {
12
+ return {
13
+ principal,
14
+ grant: (0, policy_1.getGrant)(config.entitlements, principal),
15
+ activity: config.runs.activity === 'everyone',
16
+ nameOf: (owner) => (0, policy_1.subjectName)(config.entitlements, owner),
17
+ };
18
+ }
19
+ exports.getViewer = getViewer;
20
+ function runActions(viewer, run) {
21
+ if ((0, runs_1.isFinal)(run.state)) {
22
+ return undefined;
23
+ }
24
+ const mine = owns(viewer, run);
25
+ const may = {
26
+ ...(mine || decides(viewer, run) || (run.up && (0, service_runs_1.mayPublishEndpoints)(viewer.grant, run))
27
+ ? { stop: true }
28
+ : {}),
29
+ ...(run.up && run.upAt && (mine || (0, service_runs_1.mayOpenEndpoints)(viewer.grant, run)) ? { extend: true } : {}),
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
+ : {}),
34
+ };
35
+ return Object.keys(may).length > 0 ? may : undefined;
36
+ }
37
+ exports.runActions = runActions;
38
+ // A run that waits for an approval the caller may give: not their own.
39
+ function mayDecide(viewer, run) {
40
+ return (run.state === 'awaiting-approval' &&
41
+ !owns(viewer, run) &&
42
+ (run.approvals ?? []).some((approval) => !approval.approvedBy && (0, policy_1.canUse)(viewer.grant, approval.account)));
43
+ }
44
+ exports.mayDecide = mayDecide;
45
+ function owns(viewer, run) {
46
+ return run.owner.iss === viewer.principal.iss && run.owner.sub === viewer.principal.sub;
47
+ }
48
+ exports.owns = owns;
49
+ // Whether the caller decides about the run: they use an account it asked to be approved.
50
+ function decides(viewer, run) {
51
+ return (run.approvals ?? []).some((approval) => (0, policy_1.canUse)(viewer.grant, approval.account));
52
+ }
53
+ exports.decides = decides;
54
+ /**
55
+ * Whether the caller may see a run, with the entitlements of the moment: their own; any
56
+ * with `observe`; one that asked for an approval of an account they use (they decide about
57
+ * it); a service run whose endpoints they may open; and with `runs.activity: everyone`, one
58
+ * of a repository they have access to (seesActivityOf).
59
+ */
60
+ function maySee(viewer, run) {
61
+ return (owns(viewer, run) ||
62
+ viewer.grant.observe ||
63
+ decides(viewer, run) ||
64
+ (!!run.up && (0, service_runs_1.mayOpenEndpoints)(viewer.grant, run)) ||
65
+ seesActivityOf(viewer, run));
66
+ }
67
+ exports.maySee = maySee;
68
+ /**
69
+ * With `runs.activity: everyone`, a caller with a `builds` level sees the runs of others in
70
+ * the repositories they have access to: the `repos` and the `sandboxes` repositories of their
71
+ * entitlements. Who may only open endpoints or read checks sees none, and a run of uploaded
72
+ * files has no repository: it is for its owner, who decides about it and `observe`.
73
+ */
74
+ function seesActivity(viewer) {
75
+ return !!viewer.activity && viewer.grant.builds !== null;
76
+ }
77
+ exports.seesActivity = seesActivity;
78
+ function seesActivityOf(viewer, run) {
79
+ if (!seesActivity(viewer) || run.source.type === 'upload') {
80
+ return false;
81
+ }
82
+ const repo = run.source.repo;
83
+ return ((0, repo_1.matchesAnyRepo)(viewer.grant.repos, repo) ||
84
+ viewer.grant.sandboxes.some((sandbox) => (0, repo_1.matchesRepo)(sandbox.repo, repo)));
85
+ }
86
+ exports.seesActivityOf = seesActivityOf;
87
+ /**
88
+ * Whether the caller may read a run whole: its tasks, why it failed and its log. Its owner,
89
+ * who decides about it, and `observe`.
90
+ */
91
+ function mayRead(viewer, run) {
92
+ return owns(viewer, run) || viewer.grant.observe || decides(viewer, run);
93
+ }
94
+ exports.mayRead = mayRead;
95
+ // `entryOf` names where in its repository the build file of a version is.
96
+ function toListedRun(viewer, run, queue, entryOf) {
97
+ const { owner, results, plan, options, up, error, ...rest } = run;
98
+ const mine = owns(viewer, run);
99
+ const may = runActions(viewer, run);
100
+ const opens = mine || viewer.grant.observe || (!!up && (0, service_runs_1.mayOpenEndpoints)(viewer.grant, run));
101
+ const timings = Object.fromEntries(Object.entries(results ?? {}).map(([task, result]) => [
102
+ task,
103
+ {
104
+ status: result.status,
105
+ ...(result.startedAt ? { startedAt: result.startedAt } : {}),
106
+ ...(result.finishedAt ? { finishedAt: result.finishedAt } : {}),
107
+ ...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {}),
108
+ ...(result.cache ? { cached: result.cache.hit } : {}),
109
+ },
110
+ ]));
111
+ const entry = entryOf?.(run.definition);
112
+ const name = owner.name ?? viewer.nameOf?.(owner);
113
+ return {
114
+ ...rest,
115
+ ...(mine ? { plan, options } : { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } }),
116
+ ...(up
117
+ ? {
118
+ up: {
119
+ ...up,
120
+ endpoints: opens ? up.endpoints : up.endpoints.map(({ service, port }) => ({ service, port })),
121
+ },
122
+ }
123
+ : {}),
124
+ ...(error !== undefined && mayRead(viewer, run) ? { error } : {}),
125
+ ...(Object.keys(timings).length > 0 ? { timings } : {}),
126
+ ...(queue ? { queue } : {}),
127
+ ...(may ? { may } : {}),
128
+ ...(!mine && mayRead(viewer, run) ? { readable: true } : {}),
129
+ ...(entry ? { entry } : {}),
130
+ };
131
+ }
132
+ exports.toListedRun = toListedRun;
133
+ // A reason names a run only the caller may see.
134
+ function visibleReason(reason, visible) {
135
+ if ((reason.type === 'sandbox' || reason.type === 'held') && !visible(reason.run)) {
136
+ return { type: reason.type };
137
+ }
138
+ return { ...reason };
139
+ }
140
+ exports.visibleReason = visibleReason;
141
+ // Where a queued run stands, and why it waits: the run that holds it is named when the
142
+ // caller may see it.
143
+ function queuePlace(registry, viewer, run) {
144
+ const queue = run.state === 'queued' ? registry.queued(run.id) : undefined;
145
+ if (!queue) {
146
+ return undefined;
147
+ }
148
+ const visible = (id) => {
149
+ const holder = registry.peek(id);
150
+ return !!holder && maySee(viewer, holder);
151
+ };
152
+ return { position: queue.position, waitsFor: visibleReason(queue.waitsFor, visible) };
153
+ }
154
+ exports.queuePlace = queuePlace;
155
+ function getOverview(snapshot, usage, viewer, entryOf) {
156
+ const list = (run, place) => toListedRun(viewer, run, place, entryOf);
157
+ const runs = new Map();
158
+ for (const run of [
159
+ ...snapshot.running,
160
+ ...snapshot.queue.map((entry) => entry.run),
161
+ ...snapshot.awaiting.runs,
162
+ ...snapshot.services.runs,
163
+ ]) {
164
+ runs.set(run.id, run);
165
+ }
166
+ const visible = (id) => {
167
+ const run = runs.get(id);
168
+ return !!run && maySee(viewer, run);
169
+ };
170
+ const queue = snapshot.queue.map((entry, index) => {
171
+ const place = { position: index + 1, waitsFor: visibleReason(entry.waitsFor, visible) };
172
+ return {
173
+ ...place,
174
+ mine: owns(viewer, entry.run),
175
+ ...(maySee(viewer, entry.run) ? { run: list(entry.run, place) } : {}),
176
+ };
177
+ });
178
+ const running = snapshot.running.filter((run) => maySee(viewer, run));
179
+ const limits = snapshot.limits;
180
+ return {
181
+ you: { iss: viewer.principal.iss, sub: viewer.principal.sub, observe: viewer.grant.observe },
182
+ places: {
183
+ max: snapshot.places.max,
184
+ used: snapshot.places.used,
185
+ runs: running.map((run) => list(run)),
186
+ others: snapshot.running.length - running.length,
187
+ },
188
+ queue,
189
+ approvals: {
190
+ waiting: snapshot.awaiting.runs.length,
191
+ max: snapshot.awaiting.max,
192
+ runs: snapshot.awaiting.runs.filter((run) => maySee(viewer, run)).map((run) => list(run)),
193
+ },
194
+ services: {
195
+ open: snapshot.services.taken,
196
+ ...(snapshot.services.max !== undefined ? { max: snapshot.services.max } : {}),
197
+ runs: snapshot.services.runs.filter((run) => maySee(viewer, run)).map((run) => list(run)),
198
+ },
199
+ limits: {
200
+ waiting: meter(usage.waiting, limits?.waiting),
201
+ queued: meter(usage.queued, limits?.queued),
202
+ running: meter(usage.running, limits?.running),
203
+ services: meter(usage.services, snapshot.services.perCaller),
204
+ asleep: meter(usage.asleep, snapshot.services.asleepPerCaller),
205
+ },
206
+ };
207
+ }
208
+ exports.getOverview = getOverview;
209
+ function meter(runs, limit) {
210
+ return { used: runs.length, ...(limit !== undefined ? { limit } : {}), runs: [...runs] };
211
+ }
212
+ const STATES = [
213
+ 'awaiting-approval',
214
+ 'queued',
215
+ 'running',
216
+ 'up',
217
+ 'asleep',
218
+ 'succeeded',
219
+ 'failed',
220
+ 'cancelled',
221
+ 'rejected',
222
+ ];
223
+ // `scope`, `state` (a comma separated list) and `kind` of GET /v1/runs.
224
+ function parseRunFilter(params, grant, now = Date.now()) {
225
+ const scope = params.get('scope') ?? 'mine';
226
+ if (scope !== 'mine' && scope !== 'visible' && scope !== 'all') {
227
+ throw new Error('scope: mine, visible or all');
228
+ }
229
+ if (scope === 'all' && !grant.observe) {
230
+ throw new FilterRefused('scope all needs an entitlement with observe');
231
+ }
232
+ const state = params.get('state');
233
+ const states = state
234
+ ? state.split(',').map((value) => {
235
+ if (!STATES.includes(value)) {
236
+ throw new Error(`state: one or more of ${STATES.join(', ')}`);
237
+ }
238
+ return value;
239
+ })
240
+ : undefined;
241
+ const kind = params.get('kind') ?? undefined;
242
+ if (kind !== undefined && kind !== 'tasks' && kind !== 'services') {
243
+ throw new Error('kind: tasks or services');
244
+ }
245
+ const id = params.get('id') ?? undefined;
246
+ if (id !== undefined && !/^run_[A-Za-z0-9_-]{16}$/.test(id)) {
247
+ throw new Error('id: the id of a run, run_...');
248
+ }
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
+ };
262
+ }
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
+ }
278
+ class FilterRefused extends Error {
279
+ }
280
+ exports.FilterRefused = FilterRefused;
281
+ function filterRuns(runs, viewer, filter) {
282
+ return runs.filter((run) => (filter.scope === 'mine' ? owns(viewer, run) : maySee(viewer, run)) &&
283
+ (!filter.id || run.id === filter.id) &&
284
+ (!filter.states || filter.states.includes(run.state)) &&
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));
288
+ }
289
+ exports.filterRuns = filterRuns;
290
+ // The machines and what the runs take, with whose the namespaces are where the caller may
291
+ // know: their own, and every one with `observe`.
292
+ function visibleCapacity(capacity, viewer) {
293
+ const everyone = viewer.grant.observe;
294
+ return {
295
+ ...capacity,
296
+ // what the cluster answered is for operators; others learn that something is missing
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
+ : {}),
327
+ groups: capacity.groups.map((group) => {
328
+ const mine = group.owner?.iss === viewer.principal.iss && group.owner?.sub === viewer.principal.sub;
329
+ if (everyone || mine || !group.owner) {
330
+ return group;
331
+ }
332
+ const { owner, run, ...rest } = group;
333
+ void owner;
334
+ void run;
335
+ return rest;
336
+ }),
337
+ };
338
+ }
339
+ exports.visibleCapacity = visibleCapacity;
340
+ //# sourceMappingURL=overview.js.map