hammerkit 2.1.0-next.9 → 2.1.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 (69) hide show
  1. package/build.schema.json +28 -126
  2. package/dist/cli.js +0 -5
  3. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  4. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  5. package/dist/dashboard/assets/{index-CE5PSB3y.js → index-DRSwIRXd.js} +9 -15
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +5 -6
  8. package/dist/docker/remove-orphaned-containers.js +4 -5
  9. package/dist/environment/replace-env-variables.js +5 -8
  10. package/dist/environment/run-source-envs.js +1 -2
  11. package/dist/executer/check-readiness.js +4 -8
  12. package/dist/executer/deadline.js +63 -10
  13. package/dist/executer/docker-service.js +15 -21
  14. package/dist/executer/execute-work-task.js +15 -3
  15. package/dist/harness/sandbox-client.js +1 -0
  16. package/dist/harness/service-tools.js +25 -1
  17. package/dist/kubernetes/cluster-state.js +48 -14
  18. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +14 -62
  19. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  20. package/dist/kubernetes/kept-claims.js +9 -12
  21. package/dist/kubernetes/resources.js +5 -1
  22. package/dist/optimizer/work-task-cache-description.js +3 -5
  23. package/dist/planner/image-build.js +0 -5
  24. package/dist/planner/service-definition.js +1 -2
  25. package/dist/planner/utils/append-work-service.js +4 -12
  26. package/dist/planner/utils/dependency-outputs.js +6 -7
  27. package/dist/planner/validate.js +0 -41
  28. package/dist/planner/work-healthcheck.js +2 -23
  29. package/dist/planner/work-runtime-docker.js +1 -24
  30. package/dist/planner/work-runtime-kubernetes.js +16 -37
  31. package/dist/planner/work-secret.js +11 -33
  32. package/dist/planner/work-service-id.js +6 -30
  33. package/dist/planner/work-service.js +2 -2
  34. package/dist/program.js +1 -19
  35. package/dist/remote/annotations.js +31 -11
  36. package/dist/remote/collect-bundle.js +3 -2
  37. package/dist/remote/remote-status.js +1 -1
  38. package/dist/remote/remote-work-commands.js +53 -12
  39. package/dist/schema/build-file-base-task-schema.js +1 -16
  40. package/dist/schema/build-file-image-build-schema.js +8 -5
  41. package/dist/schema/build-file-service-container-healthcheck.js +7 -25
  42. package/dist/schema/reference-parser.js +43 -108
  43. package/dist/schema/work-scope-parser.js +0 -8
  44. package/dist/secrets/prefetch-secrets.js +1 -20
  45. package/dist/server/capacity.js +6 -18
  46. package/dist/server/endpoints.js +52 -32
  47. package/dist/server/kubernetes-backend.js +28 -114
  48. package/dist/server/kubernetes-sandbox-storage.js +2 -3
  49. package/dist/server/overview.js +1 -7
  50. package/dist/server/plan.js +0 -8
  51. package/dist/server/public-paths.js +52 -0
  52. package/dist/server/run-request.js +52 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-source-environment.js +1 -1
  55. package/dist/server/runs.js +6 -4
  56. package/dist/server/sandbox-files-api.js +12 -27
  57. package/dist/server/sandbox-files.js +2 -3
  58. package/dist/server/sandbox-pod.js +1 -1
  59. package/dist/server/sandboxes-api.js +14 -65
  60. package/dist/server/sandboxes.js +3 -19
  61. package/dist/server/server-config.js +2 -59
  62. package/dist/server/server.js +20 -8
  63. package/dist/server/service-runs.js +41 -8
  64. package/package.json +1 -1
  65. package/dist/dashboard/assets/graph-canvas-BFnEN5i0.js +0 -8
  66. package/dist/dashboard/assets/index-Dt3ITvRO.css +0 -2
  67. package/dist/executer/docker-healthcheck.js +0 -73
  68. package/dist/network/healthcheck-request.js +0 -38
  69. package/dist/server/borrowed-quota.js +0 -216
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.awaitRunObjectsGone = exports.removeRunObjects = exports.CallerNamespaces = exports.getNamespaceQuota = exports.getVolumeScope = exports.getKeptClaimTasks = exports.getPrivilegedNamespaceProblem = exports.getCapabilitiesProblem = exports.getPodSecurityLabels = exports.KubernetesExecutor = exports.getRunRoleBinding = exports.removeServiceRunNamespace = exports.getServerIngressPolicy = exports.getNamespacePolicies = exports.getClusterAccess = exports.isCallerNamespace = exports.SERVICE_RUN_LABEL = exports.getServiceRunNamespace = exports.getCallerNamespace = void 0;
3
+ exports.awaitRunObjectsGone = exports.removeRunObjects = exports.CallerNamespaces = exports.getVolumeScope = exports.getPrivilegedNamespaceProblem = exports.getCapabilitiesProblem = exports.getPodSecurityLabels = exports.KubernetesExecutor = exports.getRunRoleBinding = exports.removeServiceRunNamespace = exports.getServerIngressPolicy = exports.getNamespacePolicies = exports.getClusterAccess = exports.isCallerNamespace = exports.SERVICE_RUN_LABEL = exports.getServiceRunNamespace = exports.getCallerNamespace = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const fs_1 = require("fs");
6
6
  const os_1 = require("os");
@@ -9,7 +9,6 @@ const net_1 = require("net");
9
9
  const apply_1 = require("../kubernetes/apply");
10
10
  const job_placement_1 = require("../kubernetes/job-placement");
11
11
  const capacity_1 = require("./capacity");
12
- const borrowed_quota_1 = require("./borrowed-quota");
13
12
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
14
13
  const log_1 = require("../log");
15
14
  const network_policy_1 = require("../kubernetes/network-policy");
@@ -260,9 +259,9 @@ exports.getRunRoleBinding = getRunRoleBinding;
260
259
  * of a caller execute side by side in their namespace, up to `runs.limits.running`:
261
260
  * the objects of a run are named and found by its run label (getItemKey), so two runs
262
261
  * of the same task have their own. What two runs share are the claims the server keeps
263
- * (`backend.keepVolumes`) of a scope (getVolumeScope), one per task: two runs of one scope
264
- * with a task in common go one at a time (excludes). When a run ends, everything made for it
265
- * is removed, but for the kept claims, which go once they expired.
262
+ * (`backend.keepVolumes`) of a scope (getVolumeScope): the runs of one scope go one at
263
+ * a time (exclusive). When a run ends, everything made for it is removed, but for the
264
+ * kept claims, which go once they expired.
266
265
  */
267
266
  class KubernetesExecutor {
268
267
  constructor(config, processEnvs, options) {
@@ -270,8 +269,7 @@ class KubernetesExecutor {
270
269
  // per caller namespace, what changes objects of the whole namespace: its setup, the
271
270
  // removal of what a stopped server left, the sweeps of kept claims. The last one waiting.
272
271
  this.queues = new Map();
273
- // per caller namespace, the runs that execute in it and mount kept claims: by run label,
274
- // their volume scope
272
+ // per caller namespace, the runs that execute in it: by run label, their volume scope
275
273
  this.active = new Map();
276
274
  // per caller namespace, when its kept claims are next looked at
277
275
  this.sweeps = new Map();
@@ -304,27 +302,13 @@ class KubernetesExecutor {
304
302
  this.keep = config.backend.keepVolumes === false ? 0 : (0, units_1.parseDuration)(config.backend.keepVolumes);
305
303
  this.keepServiceRuns = config.runs.up.keepVolumes;
306
304
  this.log = options.log;
307
- const { quota, maxQuota, pools } = config.backend;
308
- if (quota && maxQuota) {
309
- this.quotas = new borrowed_quota_1.BorrowedQuotas({
310
- quota,
311
- maxQuota,
312
- room: () => (0, borrowed_quota_1.readPoolRoom)(this.instance, pools),
313
- write: async (namespace, hard) => {
314
- await (0, apply_1.replace)(this.instance, getNamespaceQuota(namespace, hard));
315
- },
316
- log: options.log,
317
- });
318
- }
319
305
  this.host = new executor_1.HostExecutor({ ...options, placement: this.placement() });
320
306
  }
321
307
  // what the namespaces of the server's callers and service runs request and use
322
308
  capacity() {
323
309
  const prefix = this.config.backend.namespacePrefix;
324
- const { quota, maxQuota } = this.config.backend;
325
310
  return new capacity_1.KubernetesCapacity(this.instance, {
326
311
  quotaName: POLICY_NAME,
327
- ...(quota && maxQuota ? { share: (0, capacity_1.getQuotaResources)(quota) } : {}),
328
312
  namespaces: async () => (await this.instance.coreApi.listNamespace({ labelSelector: `${MANAGED_LABEL}=true` })).items
329
313
  .filter((namespace) => isCallerNamespace(prefix, namespace.metadata?.name ?? ''))
330
314
  .map((namespace) => ({
@@ -359,11 +343,7 @@ class KubernetesExecutor {
359
343
  runs = new Map();
360
344
  this.active.set(namespace, runs);
361
345
  }
362
- if (this.holds(run)) {
363
- runs.set(label, getVolumeScope(run));
364
- }
365
- // the caller is promised its share while the run executes
366
- this.quotas?.enter(namespace, run.id);
346
+ runs.set(label, getVolumeScope(run));
367
347
  try {
368
348
  await this.host.execute(run, context);
369
349
  }
@@ -372,9 +352,6 @@ class KubernetesExecutor {
372
352
  if (runs.size === 0 && this.active.get(namespace) === runs) {
373
353
  this.active.delete(namespace);
374
354
  }
375
- await this.quotas
376
- ?.leave(namespace, run.id)
377
- .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
378
355
  }
379
356
  }
380
357
  // A service run moves to another commit in its namespace: unchanged services stay, the
@@ -440,41 +417,17 @@ class KubernetesExecutor {
440
417
  this.serviceRunsSwept = false;
441
418
  }
442
419
  }
443
- // The runs of a scope share the kept claim of each task, which one of them may change at a
444
- // time: what a task finds in it is what the last run left there. Two runs of a scope go
445
- // side by side when they have no task in common, and a run that mounts no kept claim holds
446
- // nothing. Without kept claims, runs share no object and nothing is held.
447
- excludes(run, other) {
448
- const held = this.holds(run);
449
- const theirs = this.holds(other);
450
- if (!held || !theirs || held.scope !== theirs.scope) {
451
- return false;
452
- }
453
- if (!held.tasks || !theirs.tasks) {
454
- return true;
455
- }
456
- const tasks = new Set(theirs.tasks);
457
- return held.tasks.some((task) => tasks.has(task));
458
- }
459
- // The kept claims a run mounts: its scope in the caller's namespace and the tasks of the
460
- // claims (getKeptClaimTasks), all of the scope's for a run without a plan. Nothing for a
461
- // run that mounts none.
462
- holds(run) {
420
+ // The runs of a scope share its kept claims, which one of them may change at a time:
421
+ // what a task finds in one is what the last run left there. Without kept claims, runs
422
+ // share no object and nothing is held.
423
+ exclusive(run) {
463
424
  if (this.keep === 0 || run.up) {
464
425
  return undefined;
465
426
  }
466
- const tasks = getKeptClaimTasks(run);
467
- if (tasks?.length === 0) {
468
- return undefined;
469
- }
470
- return {
471
- scope: `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`,
472
- tasks,
473
- };
427
+ return `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`;
474
428
  }
475
- // The scopes of the runs that execute in the namespace and mount kept claims, but
476
- // `except`'s: their kept claims are theirs to mount and stay. A server that keeps none
477
- // mounts none.
429
+ // The scopes of the runs that execute in the namespace, but `except`'s: their kept claims
430
+ // are theirs to mount and stay. A server that keeps none mounts none.
478
431
  scopesInUse(namespace, except) {
479
432
  if (this.keep === 0) {
480
433
  return new Set();
@@ -521,8 +474,6 @@ class KubernetesExecutor {
521
474
  quota: this.config.runs.up.quota,
522
475
  });
523
476
  });
524
- // its pods take room the callers can't borrow
525
- await this.quotas?.serviceRun(namespace, this.config.runs.up.quota ?? this.config.backend.quota);
526
477
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
527
478
  return { kubernetes: this.environmentOf(run, namespace), env: this.access.env };
528
479
  }
@@ -553,9 +504,6 @@ class KubernetesExecutor {
553
504
  }
554
505
  });
555
506
  this.sweepLeftClaims();
556
- // the quota of the caller, and of the callers it borrows from or lends to, before its
557
- // tasks run
558
- await this.quotas?.apply(namespace);
559
507
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
560
508
  return {
561
509
  kubernetes: this.environmentOf(run, namespace, work, capabilitiesProblem),
@@ -592,9 +540,6 @@ class KubernetesExecutor {
592
540
  }
593
541
  else {
594
542
  this.serviceRuns.delete(namespace);
595
- await this.quotas
596
- ?.serviceRunEnded(namespace)
597
- .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
598
543
  }
599
544
  }
600
545
  return;
@@ -791,22 +736,6 @@ function getPrivilegedNamespaceProblem(namespace, labels, backend) {
791
736
  `${namespace} ${ENFORCE_LABEL}=baseline ${AUDIT_LABEL}- --overwrite`);
792
737
  }
793
738
  exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
794
- // The tasks of a run whose kept claims it mounts, by name: each container task of its plan,
795
- // which mounts its own claim, while the tasks that depend on it and the services that mount its
796
- // outputs mount it too (they have it in their plan). Another task has none: an aggregate, or a
797
- // local task on a server that allows them. A kept claim is named after its task
798
- // (getClaimName), so two runs with no task in common mount no claim in common, whatever
799
- // their tasks are. Null for a run without a plan (submitted by a version that recorded none).
800
- function getKeptClaimTasks(run) {
801
- if (!run.plan) {
802
- return null;
803
- }
804
- return Object.entries(run.plan)
805
- .filter(([, task]) => task.kind === 'task' && task.runtime === 'docker')
806
- .map(([name]) => name)
807
- .sort();
808
- }
809
- exports.getKeptClaimTasks = getKeptClaimTasks;
810
739
  // What may mount a claim a run kept: the runs of the same branch or tag of a repository,
811
740
  // which share its cache, so that the runs of two branches go side by side and the runs of one find what
812
741
  // the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
@@ -826,19 +755,6 @@ function getVolumeScope(run) {
826
755
  return (0, executor_1.cacheNamespace)(run);
827
756
  }
828
757
  exports.getVolumeScope = getVolumeScope;
829
- function getPolicyMetadata(namespace) {
830
- return {
831
- name: POLICY_NAME,
832
- namespace,
833
- annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
834
- labels: { [MANAGED_LABEL]: 'true' },
835
- };
836
- }
837
- // The ResourceQuota of a namespace of the server
838
- function getNamespaceQuota(namespace, hard) {
839
- return { apiVersion: 'v1', kind: 'ResourceQuota', metadata: getPolicyMetadata(namespace), spec: { hard } };
840
- }
841
- exports.getNamespaceQuota = getNamespaceQuota;
842
758
  /**
843
759
  * The namespaces of callers on the cluster: named by the caller (getCallerNamespace),
844
760
  * made on first use, with the operator's quota.
@@ -926,9 +842,18 @@ class CallerNamespaces {
926
842
  ]) {
927
843
  await (0, apply_1.replace)(this.instance, policy);
928
844
  }
929
- const metadata = getPolicyMetadata(namespace);
930
- const hard = serviceRun?.quota ?? backend.quota;
931
- const quota = getNamespaceQuota(namespace, hard ?? {});
845
+ const metadata = {
846
+ name: POLICY_NAME,
847
+ namespace,
848
+ annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
849
+ labels: { [MANAGED_LABEL]: 'true' },
850
+ };
851
+ const quota = {
852
+ apiVersion: 'v1',
853
+ kind: 'ResourceQuota',
854
+ metadata,
855
+ spec: { hard: serviceRun?.quota ?? backend.quota },
856
+ };
932
857
  const defaults = backend.defaultResources;
933
858
  const limits = {
934
859
  apiVersion: 'v1',
@@ -944,21 +869,10 @@ class CallerNamespaces {
944
869
  ],
945
870
  },
946
871
  };
947
- // a caller who may borrow has the quota the server works out for them (BorrowedQuotas),
948
- // written once the namespace is there: here it is made with the share, never replaced
949
- const borrows = !!backend.maxQuota && !serviceRun;
950
- if (borrows) {
951
- await this.instance.objectApi.create(quota).catch((e) => {
952
- if ((0, apply_1.statusCodeOf)(e) !== 409) {
953
- throw e;
954
- }
955
- });
956
- }
957
- const objects = [
958
- ...(borrows ? [] : [[quota, !!hard]]),
872
+ for (const [object, wanted] of [
873
+ [quota, !!(serviceRun?.quota ?? backend.quota)],
959
874
  [limits, !!defaults],
960
- ];
961
- for (const [object, wanted] of objects) {
875
+ ]) {
962
876
  if (wanted) {
963
877
  await (0, apply_1.replace)(this.instance, object);
964
878
  }
@@ -1030,9 +1030,8 @@ class KubernetesSandboxFiles {
1030
1030
  changes() {
1031
1031
  return this.ask({ op: 'changes' });
1032
1032
  }
1033
- diff(format, author, paths) {
1034
- // a pod of an older image leaves `paths` out and answers the whole diff
1035
- return this.ask({ op: 'diff', format, author, ...(paths ? { paths } : {}) });
1033
+ diff(format, author) {
1034
+ return this.ask({ op: 'diff', format, author });
1036
1035
  }
1037
1036
  async commit(author) {
1038
1037
  return (await this.ask({ op: 'commit', author })) ?? undefined;
@@ -238,7 +238,7 @@ const STATES = [
238
238
  'cancelled',
239
239
  'rejected',
240
240
  ];
241
- // `scope`, `state` (a comma separated list), `kind`, `id`, `sandbox`, `since` and `until` of GET /v1/runs.
241
+ // `scope`, `state` (a comma separated list) and `kind` of GET /v1/runs.
242
242
  function parseRunFilter(params, grant, now = Date.now()) {
243
243
  const scope = params.get('scope') ?? 'mine';
244
244
  if (scope !== 'mine' && scope !== 'visible' && scope !== 'all') {
@@ -264,10 +264,6 @@ function parseRunFilter(params, grant, now = Date.now()) {
264
264
  if (id !== undefined && !/^run_[A-Za-z0-9_-]{16}$/.test(id)) {
265
265
  throw new Error('id: the id of a run, run_...');
266
266
  }
267
- const sandbox = params.get('sandbox') ?? undefined;
268
- if (sandbox !== undefined && !runs_1.SANDBOX_ID_PATTERN.test(sandbox)) {
269
- throw new Error('sandbox: the id of a sandbox, sbx_...');
270
- }
271
267
  const since = parseMoment(params.get('since'), now, 'since');
272
268
  const until = parseMoment(params.get('until'), now, 'until');
273
269
  if (since !== undefined && until !== undefined && until < since) {
@@ -278,7 +274,6 @@ function parseRunFilter(params, grant, now = Date.now()) {
278
274
  ...(states ? { states } : {}),
279
275
  ...(kind ? { kind } : {}),
280
276
  ...(id ? { id } : {}),
281
- ...(sandbox ? { sandbox } : {}),
282
277
  ...(since !== undefined ? { since } : {}),
283
278
  ...(until !== undefined ? { until } : {}),
284
279
  };
@@ -304,7 +299,6 @@ exports.FilterRefused = FilterRefused;
304
299
  function filterRuns(runs, viewer, filter) {
305
300
  return runs.filter((run) => (filter.scope === 'mine' ? owns(viewer, run) : maySee(viewer, run)) &&
306
301
  (!filter.id || run.id === filter.id) &&
307
- (!filter.sandbox || (run.source.type === 'sandbox' && run.source.id === filter.sandbox)) &&
308
302
  (!filter.states || filter.states.includes(run.state)) &&
309
303
  (!filter.kind || (filter.kind === 'services') === !!run.up) &&
310
304
  (filter.since === undefined || Date.parse(run.createdAt) >= filter.since) &&
@@ -19,7 +19,6 @@ const parse_error_1 = require("../schema/parse-error");
19
19
  const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
- const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
23
22
  class DefinitionError extends Error {
24
23
  }
25
24
  exports.DefinitionError = DefinitionError;
@@ -168,9 +167,6 @@ function describeSecret(secret) {
168
167
  if (source.type === 'provider') {
169
168
  return { from: `${source.provider}:${source.ref}`, account: source.account, target };
170
169
  }
171
- if (source.type === 'unavailable') {
172
- return { from: source.from, account: null, target };
173
- }
174
170
  return { from: source.type === 'env' ? `env:${source.name}` : `file:${source.path}`, account: null, target };
175
171
  }
176
172
  // What a server refuses to publish. A secret that reads a file or a variable of the
@@ -427,10 +423,6 @@ async function planBundle(bundle, environment, options = {}) {
427
423
  }
428
424
  const context = await (0, reference_parser_1.parseReferences)(ctx, scope, inspected);
429
425
  const workTree = (0, work_scope_parser_1.getWorkContext)(context, options.scope ?? { environmentName: null }, inspected);
430
- // the server's providers and accounts are the ones that count: a task it could never read
431
- // a secret of is refused when it is published, and a run when it is planned (only the
432
- // tasks and services of the run count then)
433
- (0, prefetch_secrets_1.requireReadableSecrets)(workTree);
434
426
  const items = itemsOf(workTree);
435
427
  if (options.policy) {
436
428
  const policyProblems = findPolicyProblems(items, options.policy, directory);
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isPublicPath = exports.publicPathProblem = void 0;
4
+ // A segment of a path a public path or a request is made of: letters, digits and . _ ~ -
5
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
6
+ const isDotSegment = (segment) => segment === '.' || segment === '..';
7
+ /**
8
+ * Why a configured public path (such as `/mcp` or `/.well-known`) can not be one, or null
9
+ * when it can. It is a path of plain segments with no `.` or `..`, and never the server's own.
10
+ */
11
+ function publicPathProblem(path) {
12
+ const segments = path.slice(1).split('/');
13
+ if (!path.startsWith('/') || segments.some((segment) => !SEGMENT.test(segment))) {
14
+ return 'expected a path like /mcp or /.well-known, with letters, digits, . _ ~ - and /';
15
+ }
16
+ if (segments.some(isDotSegment)) {
17
+ return 'a public path has no . or .. segment';
18
+ }
19
+ if (segments[0] === '.hammerkit') {
20
+ return "the server's own paths can not be public";
21
+ }
22
+ return null;
23
+ }
24
+ exports.publicPathProblem = publicPathProblem;
25
+ /**
26
+ * Whether a request for `target` (the request target, query included) is for one of the
27
+ * public paths of its endpoint, which is the path itself and everything below it, by
28
+ * segments: `/mcp` takes `/mcp/oauth/token`, not `/mcpx`. A target that is not in its plain
29
+ * form (an empty, dot, or escaped segment, a backslash, a `%`) is never public: such a path
30
+ * could read as another one to the app, so it needs the sign-in like any other.
31
+ */
32
+ function isPublicPath(publicPaths, target) {
33
+ if (!publicPaths?.length) {
34
+ return false;
35
+ }
36
+ const path = target.split('?')[0];
37
+ if (!path.startsWith('/')) {
38
+ return false;
39
+ }
40
+ const segments = path.slice(1).split('/');
41
+ // a trailing slash is an empty last segment, which a request may end with
42
+ const plain = segments.every((segment, index) => (segment !== '' || index === segments.length - 1) && (segment === '' || SEGMENT.test(segment)));
43
+ if (!plain || segments.some(isDotSegment)) {
44
+ return false;
45
+ }
46
+ return publicPaths.some((publicPath) => {
47
+ const wanted = publicPath.slice(1).split('/');
48
+ return segments.length >= wanted.length && wanted.every((segment, index) => segments[index] === segment);
49
+ });
50
+ }
51
+ exports.isPublicPath = isPublicPath;
52
+ //# sourceMappingURL=public-paths.js.map
@@ -1,20 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runRequestSchema = exports.runOptionsSchema = exports.MAX_ARGS_BYTES = exports.MAX_ARGS = exports.MAX_ENDPOINTS = exports.SERVICE_RUN_NAME_PATTERN = void 0;
3
+ exports.runRequestSchema = exports.runOptionsSchema = exports.MAX_ARGS_BYTES = exports.MAX_ARGS = exports.MAX_PUBLIC_PATHS = exports.MAX_ENDPOINTS = exports.SERVICE_RUN_NAME_PATTERN = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const units_1 = require("../utils/units");
6
6
  const bundle_1 = require("../remote/bundle");
7
7
  const repo_1 = require("./repo");
8
8
  const runs_1 = require("./runs");
9
+ const public_paths_1 = require("./public-paths");
9
10
  const name = zod_1.z.string().min(1).max(200);
10
11
  // The name of a service run, one DNS label: the hosts of its endpoints carry it, and a run of
11
12
  // the same caller with the same name replaces it
12
13
  exports.SERVICE_RUN_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$/;
13
14
  // endpoints one service run may publish
14
15
  exports.MAX_ENDPOINTS = 5;
16
+ // public paths one endpoint may have
17
+ exports.MAX_PUBLIC_PATHS = 10;
15
18
  // what one run may pass after `--`
16
19
  exports.MAX_ARGS = 100;
17
20
  exports.MAX_ARGS_BYTES = 16 * 1024;
21
+ // a path of an endpoint that needs no sign-in of the server, see isPublicPath
22
+ const publicPath = zod_1.z.string().superRefine((path, ctx) => {
23
+ const problem = (0, public_paths_1.publicPathProblem)(path);
24
+ if (problem) {
25
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: problem });
26
+ }
27
+ });
18
28
  // What `POST /v1/runs` takes. Who is asking and which accounts they may use is
19
29
  // decided from the token, never from this body; the accounts a run uses are those
20
30
  // its secrets are read as, which the server derives from the published build file.
@@ -124,6 +134,22 @@ exports.runRequestSchema = zod_1.z
124
134
  .array(zod_1.z.object({ service: name, port: zod_1.z.number().int().min(1).max(65535) }).strict())
125
135
  .max(exports.MAX_ENDPOINTS)
126
136
  .default([]),
137
+ // paths of those endpoints that need no sign-in of the server, such as an app's own sign-in
138
+ // for an MCP client; the run they are written for must be the one the run gets (see
139
+ // refusePublicPaths), and the endpoint one the run publishes
140
+ publicPaths: zod_1.z
141
+ .array(zod_1.z
142
+ .object({
143
+ run: zod_1.z
144
+ .string()
145
+ .regex(exports.SERVICE_RUN_NAME_PATTERN, 'expected lower case letters, digits and -, at most 40, as a DNS label'),
146
+ service: name,
147
+ port: zod_1.z.number().int().min(1).max(65535),
148
+ paths: zod_1.z.array(publicPath).min(1).max(exports.MAX_PUBLIC_PATHS),
149
+ })
150
+ .strict())
151
+ .max(exports.MAX_ENDPOINTS)
152
+ .default([]),
127
153
  })
128
154
  .strict()
129
155
  .refine((request) => request.services.length > 0 || request.tasks.length > 0 || (request.options.filter ?? []).length > 0, {
@@ -147,6 +173,31 @@ exports.runRequestSchema = zod_1.z
147
173
  request.endpoints.length === 0), { message: 'ttl, sleepTtl, name and endpoints are for a run of services', path: ['services'] })
148
174
  .refine((request) => new Set(request.endpoints.map((endpoint) => `${endpoint.service}:${endpoint.port}`)).size ===
149
175
  request.endpoints.length, { message: 'an endpoint is named twice', path: ['endpoints'] })
176
+ .refine((request) => request.publicPaths.length === 0 || request.services.length > 0, {
177
+ message: 'public paths are for a run of services',
178
+ path: ['publicPaths'],
179
+ })
180
+ .superRefine((request, ctx) => {
181
+ const seen = new Set();
182
+ for (const entry of request.publicPaths) {
183
+ const endpoint = `${entry.service}:${entry.port}`;
184
+ if (!request.endpoints.some((published) => published.service === entry.service && published.port === entry.port)) {
185
+ ctx.addIssue({
186
+ code: zod_1.z.ZodIssueCode.custom,
187
+ message: `a public path names ${endpoint}, which the run does not publish`,
188
+ path: ['publicPaths'],
189
+ });
190
+ }
191
+ if (seen.has(endpoint)) {
192
+ ctx.addIssue({
193
+ code: zod_1.z.ZodIssueCode.custom,
194
+ message: 'an endpoint has its public paths named twice',
195
+ path: ['publicPaths'],
196
+ });
197
+ }
198
+ seen.add(endpoint);
199
+ }
200
+ })
150
201
  .refine((request) => (request.options.args ?? []).length === 0 || request.tasks.length === 1, {
151
202
  message: 'arguments go to one task, name exactly one in tasks',
152
203
  path: ['options', 'args'],
@@ -3,6 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRetryRequest = void 0;
4
4
  const runs_1 = require("./runs");
5
5
  const run_request_1 = require("./run-request");
6
+ // The public paths of the endpoints of a service run, for the run started again under its name
7
+ function publicPathsOf(up) {
8
+ const { name } = up;
9
+ return up.endpoints.flatMap(({ service, port, publicPaths }) => publicPaths ? [{ run: name, service, port, paths: publicPaths }] : []);
10
+ }
6
11
  /**
7
12
  * A retry (`POST /v1/runs/<id>/retry`) is the request the run was started with, sent again by
8
13
  * who retries it: the same published build file, tasks or services, settings and arguments,
@@ -44,6 +49,7 @@ function getRetryRequest(run, owner) {
44
49
  ...(run.up.sleepTtl ? { sleepTtl: `${run.up.sleepTtl}ms` } : {}),
45
50
  name: run.up.name,
46
51
  endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
52
+ publicPaths: publicPathsOf(run.up),
47
53
  }
48
54
  : {}),
49
55
  });
@@ -9,7 +9,7 @@ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
9
  // repository, and the branch or tag and the commit it was pinned to, or the repository and the
10
10
  // sandbox. None of them is a credential, so a task that reads them still takes arguments and
11
11
  // keeps its network (see PLAIN_SERVER_ENVS). A sandbox has no commit: its files may hold
12
- // changes. A run from an upload has none of them. Each is a name of RUN_SOURCE_ENVS.
12
+ // changes. A run from an upload has none of them.
13
13
  function runSourceEnvironment(source) {
14
14
  if (source.type === 'ref') {
15
15
  return {
@@ -817,13 +817,15 @@ class RunRegistry {
817
817
  return [...this.entries.values()].find((entry) => entry.run.state === 'running' && onSandbox(entry.run, source.id))
818
818
  ?.run.id;
819
819
  }
820
- // The run that executes and holds what the run would (RunExecutor.excludes)
820
+ // The run that executes and holds what the run would (RunExecutor.exclusive)
821
821
  held(run) {
822
- const executor = this.options.executor;
823
- if (!executor.excludes) {
822
+ const exclusive = this.options.executor.exclusive?.bind(this.options.executor);
823
+ const key = exclusive?.(run);
824
+ if (key === undefined) {
824
825
  return undefined;
825
826
  }
826
- return [...this.entries.values()].find((entry) => entry.run.state === 'running' && entry.run.id !== run.id && executor.excludes?.(run, entry.run))?.run.id;
827
+ return [...this.entries.values()].find((entry) => entry.run.state === 'running' && exclusive?.(entry.run) === key)
828
+ ?.run.id;
827
829
  }
828
830
  // What keeps a queued run from starting, checked as dispatch checks it: what holds it
829
831
  // even when a place frees up is named first.
@@ -76,14 +76,10 @@ const searchSchema = zod_1.z.preprocess((body) => {
76
76
  * PUT /v1/sandboxes/<id>/files/<path> write bytes, If-Match: "<sha256>"
77
77
  * POST /v1/sandboxes/<id>/search ripgrep
78
78
  * POST /v1/sandboxes/<id>/edits { dryRun, ops }, all or nothing
79
- * GET /v1/sandboxes/<id>/changes?format=summary|diff|patch (diff: &path=… for some files)
79
+ * GET /v1/sandboxes/<id>/changes?format=summary|diff|patch
80
80
  *
81
81
  * Reading a file works at any time. Writes, and the reads that walk the files (tree, search,
82
82
  * changes), are `409` while a run holds the sandbox.
83
- *
84
- * Who may read the sandbox, its owner and who observes, was decided by `handleSandboxes`:
85
- * reads go as its owner. Writes go as the caller, so the registry answers anybody but the
86
- * owner `404`.
87
83
  */
88
84
  async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, path, req, res, url) {
89
85
  const who = `iss=${principal.iss} sub=${principal.sub}`;
@@ -103,7 +99,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
103
99
  limit: intParam(url, 'limit'),
104
100
  cursor: url.searchParams.get('cursor') ?? undefined,
105
101
  };
106
- const tree = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.tree(query));
102
+ const tree = await sandboxes.read(principal, sandbox.id, (files) => files.tree(query));
107
103
  (0, http_1.send)(res, 200, tree);
108
104
  }
109
105
  else if (action === 'search') {
@@ -111,7 +107,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
111
107
  return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
112
108
  }
113
109
  const query = parse(searchSchema, await (0, http_1.readJson)(req));
114
- (0, http_1.send)(res, 200, await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.search(query)));
110
+ (0, http_1.send)(res, 200, await sandboxes.read(principal, sandbox.id, (files) => files.search(query)));
115
111
  }
116
112
  else if (action === 'edits') {
117
113
  if (method !== 'POST') {
@@ -128,7 +124,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
128
124
  if (method !== 'GET') {
129
125
  return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
130
126
  }
131
- await handleChanges(sandboxes, sandbox, res, url);
127
+ await handleChanges(sandboxes, principal, sandbox, res, url);
132
128
  }
133
129
  }
134
130
  catch (e) {
@@ -144,10 +140,9 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
144
140
  exports.handleSandboxFiles = handleSandboxFiles;
145
141
  async function handleFile(sandboxes, log, principal, sandbox, path, req, res, url) {
146
142
  const method = req.method;
147
- // reading, as its owner
148
- const files = () => sandboxes.files(sandbox.owner, sandbox.id);
143
+ const files = sandboxes.files(principal, sandbox.id);
149
144
  if (method === 'HEAD') {
150
- const stat = await files().stat(path);
145
+ const stat = await files.stat(path);
151
146
  if (!stat) {
152
147
  res.writeHead(404, { 'cache-control': 'no-store' });
153
148
  res.end();
@@ -158,11 +153,11 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
158
153
  }
159
154
  else if (method === 'GET') {
160
155
  if (url.searchParams.has('stat')) {
161
- const stat = await files().stat(path);
156
+ const stat = await files.stat(path);
162
157
  return stat ? (0, http_1.send)(res, 200, stat) : (0, http_1.send)(res, 404, { error: `${path} does not exist` });
163
158
  }
164
159
  if (url.searchParams.has('raw')) {
165
- const raw = await files().raw(path);
160
+ const raw = await files.raw(path);
166
161
  const headers = { ...statHeaders(raw.stat), 'content-type': 'application/octet-stream' };
167
162
  if (raw.content) {
168
163
  res.writeHead(200, { ...headers, etag: `"${raw.sha256}"` });
@@ -184,7 +179,7 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
184
179
  });
185
180
  return;
186
181
  }
187
- (0, http_1.send)(res, 200, await files().read(path, { offset: intParam(url, 'offset'), limit: intParam(url, 'limit') }));
182
+ (0, http_1.send)(res, 200, await files.read(path, { offset: intParam(url, 'offset'), limit: intParam(url, 'limit') }));
188
183
  }
189
184
  else if (method === 'PUT') {
190
185
  const content = await readBytes(req, sandbox_files_1.MAX_FILE_BYTES);
@@ -203,12 +198,10 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
203
198
  (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, HEAD, PUT' });
204
199
  }
205
200
  }
206
- // the most files one diff may name
207
- const MAX_DIFF_PATHS = 100;
208
- async function handleChanges(sandboxes, sandbox, res, url) {
201
+ async function handleChanges(sandboxes, principal, sandbox, res, url) {
209
202
  const format = url.searchParams.get('format') ?? 'summary';
210
203
  if (format === 'summary') {
211
- const files = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.changes());
204
+ const files = await sandboxes.read(principal, sandbox.id, (files) => files.changes());
212
205
  return (0, http_1.send)(res, 200, { commit: sandbox.commit, files });
213
206
  }
214
207
  if (format !== 'diff' && format !== 'patch') {
@@ -219,15 +212,7 @@ async function handleChanges(sandboxes, sandbox, res, url) {
219
212
  email: textParam(url, 'email') ?? 'hammerkit@localhost',
220
213
  message: textParam(url, 'message', 4000, true) ?? `Changes of sandbox ${sandbox.id}`,
221
214
  };
222
- // the diff of some files only, as a list of changes opens one; a rename names both its paths
223
- const paths = url.searchParams.getAll('path');
224
- if (paths.length > 0 && format !== 'diff') {
225
- return (0, http_1.send)(res, 400, { error: 'path: only a diff takes paths, a patch is whole' });
226
- }
227
- if (paths.length > MAX_DIFF_PATHS || paths.some((path) => path === '' || path.length > 4096 || path.includes('\0'))) {
228
- return (0, http_1.send)(res, 400, { error: `path: at most ${MAX_DIFF_PATHS}, each a path of the sandbox` });
229
- }
230
- const text = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.diff(format, author, paths.length > 0 ? paths : undefined));
215
+ const text = await sandboxes.read(principal, sandbox.id, (files) => files.diff(format, author));
231
216
  res.writeHead(200, { 'content-type': 'text/x-diff; charset=utf-8', 'cache-control': 'no-store' });
232
217
  res.end(text);
233
218
  }
@@ -822,11 +822,10 @@ class HostSandboxFiles {
822
822
  return files;
823
823
  });
824
824
  }
825
- async diff(format, author, paths) {
825
+ async diff(format, author) {
826
826
  return this.withFilesIndex(async (run) => {
827
827
  if (format === 'diff') {
828
- const only = paths && paths.length > 0 ? ['--', ...paths.map((path) => `:(literal)${path}`)] : [];
829
- return run(['diff', '--cached', '-M', 'HEAD', ...only], 'read', { maxBuffer: this.maxChangesBytes });
828
+ return run(['diff', '--cached', '-M', 'HEAD'], 'read', { maxBuffer: this.maxChangesBytes });
830
829
  }
831
830
  // a commit of the changes on top of the commit the sandbox is at, which no branch
832
831
  // points to, written out as `git format-patch` writes it