hammerkit 2.0.0-next.2 → 2.0.0-next.20

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 (111) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  7. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  8. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +19 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +27 -9
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +80 -11
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-source-environment.js +39 -0
  91. package/dist/server/run-worker.js +71 -9
  92. package/dist/server/runs.js +133 -7
  93. package/dist/server/sandbox-files.js +339 -55
  94. package/dist/server/sandbox-patch.js +43 -17
  95. package/dist/server/sandboxes.js +57 -23
  96. package/dist/server/server-config.js +28 -5
  97. package/dist/server/server.js +94 -16
  98. package/dist/server/service-runs.js +50 -5
  99. package/dist/server/sources.js +68 -11
  100. package/dist/server/timings.js +23 -3
  101. package/dist/utils/buffer-context.js +30 -20
  102. package/dist/utils/limit.js +30 -0
  103. package/dist/utils/line-splitter.js +52 -0
  104. package/dist/utils/read-lines.js +65 -0
  105. package/dist/utils/tar.js +51 -1
  106. package/dist/utils/units.js +36 -1
  107. package/dist/utils/web-links.js +34 -0
  108. package/package.json +1 -1
  109. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  110. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  111. package/dist/dashboard/favicon.svg +0 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeStateKey = exports.combineStateKeys = exports.isOwnProvable = exports.resolveEffective = void 0;
3
+ exports.computeStateKey = exports.combineStateKeys = exports.getExecutionStateKeys = exports.isOwnProvable = exports.resolveEffective = void 0;
4
4
  const get_work_cache_stats_1 = require("../../optimizer/get-work-cache-stats");
5
5
  const work_task_1 = require("../../planner/work-task");
6
6
  // The state-key engine is shared by the scheduler's hit/miss decision
@@ -29,6 +29,43 @@ function isOwnProvable(item, unmatched) {
29
29
  return unmatched.length < item.data.src.filter((src) => !src.inherited).length;
30
30
  }
31
31
  exports.isOwnProvable = isOwnProvable;
32
+ // What an item on its own way down stands for. Items that depend on or need each other in a
33
+ // loop fail to plan (checkForLoop) and never run: this only has to end. The loop is told by
34
+ // the path of one computation, never by the shared memo, which tasks checked at the same time
35
+ // read, so a placeholder can never end up in another task's key.
36
+ const LOOP = { stateKey: 'loop', provable: true };
37
+ // Keep a computation in the memo, and take it out again if it fails, so a later check
38
+ // computes it anew instead of failing the same way.
39
+ function memoized(memo, key, compute) {
40
+ const existing = memo.get(key);
41
+ if (existing) {
42
+ return existing;
43
+ }
44
+ const promise = compute();
45
+ memo.set(key, promise);
46
+ promise.catch(() => {
47
+ if (memo.get(key) === promise) {
48
+ memo.delete(key);
49
+ }
50
+ });
51
+ return promise;
52
+ }
53
+ const executionKeys = new WeakMap();
54
+ // The keys of one execution (the options of `exec`, which all its items share): its items
55
+ // are checked once, before they run, from the files as they are then. Not for watch mode,
56
+ // where a key is computed again because files changed.
57
+ // The items it holds keys of must have no loop: checkForLoop fails the tree before it runs.
58
+ // Two tasks checked at once that enter a loop of needs from opposite ends would each wait for
59
+ // the other's computation.
60
+ function getExecutionStateKeys(options) {
61
+ let memo = executionKeys.get(options);
62
+ if (!memo) {
63
+ memo = new Map();
64
+ executionKeys.set(options, memo);
65
+ }
66
+ return memo;
67
+ }
68
+ exports.getExecutionStateKeys = getExecutionStateKeys;
32
69
  // Fold a task's own state key together with the state keys of its dependencies.
33
70
  // A change anywhere in the dependency subtree must change the resulting key, so
34
71
  // that a downstream task is invalidated when an upstream source changes — even
@@ -51,34 +88,36 @@ function concreteMethod(resolved, defaultCacheMethod) {
51
88
  // state keys of its dependencies, recursively. This is derived purely from the
52
89
  // work tree and the filesystem, so it does not depend on scheduler/run state —
53
90
  // important because it runs before dependencies are awaited.
54
- async function resolveEffectiveStateKey(item, defaultCacheMethod, environment, memo) {
55
- const existing = memo.get(item.id());
56
- if (existing !== undefined) {
57
- return existing;
91
+ function resolveEffectiveStateKey(item, defaultCacheMethod, environment, memo, path) {
92
+ if (path.has(item.id())) {
93
+ return Promise.resolve(LOOP);
58
94
  }
59
- const { stateKey, provable } = await computeStateKey(item, defaultCacheMethod, environment, memo);
60
- const effective = { stateKey, provable };
61
- memo.set(item.id(), effective);
62
- return effective;
95
+ return memoized(memo, item.id(), async () => {
96
+ const { stateKey, provable } = await computeStateKey(item, defaultCacheMethod, environment, memo, path);
97
+ return { stateKey, provable };
98
+ });
63
99
  }
64
100
  // Compute the combined state key for a single item together with the source
65
101
  // stats it was derived from, sharing one filesystem walk with callers that also
66
102
  // need the stats (the scheduler, the explain engine).
67
- async function computeStateKey(item, defaultCacheMethod, environment, memo = new Map()) {
103
+ async function computeStateKey(item, defaultCacheMethod, environment, memo = new Map(),
104
+ // the items being computed on the way here, see LOOP
105
+ parentPath = new Set()) {
106
+ const path = new Set(parentPath).add(item.id());
68
107
  const resolved = resolveEffective(item, defaultCacheMethod);
69
108
  const { stats, unmatched } = await (0, get_work_cache_stats_1.getWorkItemCacheStats)(item, environment);
70
109
  const ownKey = (0, get_work_cache_stats_1.getStateKey)(stats, concreteMethod(resolved, defaultCacheMethod));
71
110
  const depKeys = [];
72
111
  let provable = isOwnProvable(item, unmatched);
73
112
  for (const dep of item.deps) {
74
- const effective = await resolveEffectiveStateKey(dep, defaultCacheMethod, environment, memo);
113
+ const effective = await resolveEffectiveStateKey(dep, defaultCacheMethod, environment, memo, path);
75
114
  depKeys.push(effective.stateKey);
76
115
  provable = provable && effective.provable;
77
116
  }
78
117
  // what a task that needs a service passed against: the sources of the service and of the
79
118
  // tasks it depends on (its definition is in the task id, getWorkServiceCacheIdentity)
80
119
  for (const need of item.needs) {
81
- const effective = await resolveNeedStateKey(need.service, defaultCacheMethod, environment, memo);
120
+ const effective = await resolveNeedStateKey(need.service, defaultCacheMethod, environment, memo, path);
82
121
  depKeys.push(`${need.name}=${effective.stateKey}`);
83
122
  }
84
123
  return { stateKey: combineStateKeys(ownKey, depKeys), stats, resolved, provable, unmatched };
@@ -87,29 +126,27 @@ exports.computeStateKey = computeStateKey;
87
126
  // A needed service's sources folded with the state keys of its dependencies and needs. It
88
127
  // does not make the task that needs it unprovable: a dependency without `src` (resetting the
89
128
  // service's data, say) is skipped with the service when the task is a cache hit.
90
- async function resolveNeedStateKey(service, defaultCacheMethod, environment, memo) {
129
+ function resolveNeedStateKey(service, defaultCacheMethod, environment, memo, parentPath) {
91
130
  const memoKey = `need\0${service.name}`;
92
- const existing = memo.get(memoKey);
93
- if (existing !== undefined) {
94
- return existing;
95
- }
96
- // services that need each other in a loop fail to plan (checkForLoop): this only has to end
97
- memo.set(memoKey, { stateKey: 'loop', provable: true });
98
- const resolved = resolveEffective(service, defaultCacheMethod);
99
- const { stats } = await (0, get_work_cache_stats_1.getWorkItemCacheStats)(service, environment);
100
- const keys = [];
101
- for (const dep of service.deps) {
102
- keys.push((await resolveEffectiveStateKey(dep, defaultCacheMethod, environment, memo)).stateKey);
103
- }
104
- for (const need of service.needs) {
105
- const effective = await resolveNeedStateKey(need.service, defaultCacheMethod, environment, memo);
106
- keys.push(`${need.name}=${effective.stateKey}`);
131
+ if (parentPath.has(memoKey)) {
132
+ return Promise.resolve(LOOP);
107
133
  }
108
- const effective = {
109
- stateKey: combineStateKeys((0, get_work_cache_stats_1.getStateKey)(stats, concreteMethod(resolved, defaultCacheMethod)), keys),
110
- provable: true,
111
- };
112
- memo.set(memoKey, effective);
113
- return effective;
134
+ const path = new Set(parentPath).add(memoKey);
135
+ return memoized(memo, memoKey, async () => {
136
+ const resolved = resolveEffective(service, defaultCacheMethod);
137
+ const { stats } = await (0, get_work_cache_stats_1.getWorkItemCacheStats)(service, environment);
138
+ const keys = [];
139
+ for (const dep of service.deps) {
140
+ keys.push((await resolveEffectiveStateKey(dep, defaultCacheMethod, environment, memo, path)).stateKey);
141
+ }
142
+ for (const need of service.needs) {
143
+ const effective = await resolveNeedStateKey(need.service, defaultCacheMethod, environment, memo, path);
144
+ keys.push(`${need.name}=${effective.stateKey}`);
145
+ }
146
+ return {
147
+ stateKey: combineStateKeys((0, get_work_cache_stats_1.getStateKey)(stats, concreteMethod(resolved, defaultCacheMethod)), keys),
148
+ provable: true,
149
+ };
150
+ });
114
151
  }
115
152
  //# sourceMappingURL=state-key.js.map
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recordTaskDuration = exports.readTaskDurations = exports.getDurationFile = exports.getTaskPriority = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const path_1 = require("path");
6
+ const work_item_1 = require("../planner/work-item");
7
+ const work_task_1 = require("../planner/work-task");
8
+ const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
9
+ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
10
+ const log_1 = require("../log");
11
+ // how many of its last durations a task keeps on this machine, the median of which it is
12
+ // expected to take
13
+ const KEPT_DURATIONS = 5;
14
+ /**
15
+ * The priority of a task waiting for a place to run: the time from its start until the end
16
+ * of the longest chain of what waits for it, its own expected duration and that of each
17
+ * task after it. A task on the longest chain of the run starts first, so a long chain does
18
+ * not wait behind short ones that could just as well run later.
19
+ *
20
+ * Expected durations come from past runs. A task without any counts as the median of the
21
+ * others; when none has one, every task counts 1 and the chain is counted in tasks. A task
22
+ * that runs nothing (it only groups others), and one that completed already (it was taken
23
+ * from the cache), count 0. A service counts 0 itself and carries on the chains of the
24
+ * tasks that need it.
25
+ */
26
+ function getTaskPriority(workTree, durations) {
27
+ const items = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree), ...(0, plan_work_tasks_1.iterateWorkServices)(workTree)];
28
+ const dependents = new Map();
29
+ const add = (on, dependent) => {
30
+ const list = dependents.get(on) ?? [];
31
+ if (!list.includes(dependent)) {
32
+ list.push(dependent);
33
+ }
34
+ dependents.set(on, list);
35
+ };
36
+ for (const item of items) {
37
+ for (const dep of item.deps) {
38
+ add(dep, item);
39
+ }
40
+ for (const need of item.needs) {
41
+ add(need.service, item);
42
+ }
43
+ }
44
+ const known = items
45
+ .filter((item) => (0, work_item_1.isWorkTaskItem)(item) && durations[item.name] !== undefined)
46
+ .map((item) => durations[item.name])
47
+ .sort((a, b) => a - b);
48
+ const fallback = known.length > 0 ? known[Math.floor((known.length - 1) / 2)] : 1;
49
+ const cost = (item) => {
50
+ if (!(0, work_item_1.isWorkTaskItem)(item)) {
51
+ return 0;
52
+ }
53
+ const state = item.state?.current;
54
+ if (state?.type === 'completed' || (0, work_task_1.isAggregateTask)(item.data)) {
55
+ return 0;
56
+ }
57
+ return durations[item.name] ?? fallback;
58
+ };
59
+ // a memo holds for one pick: what completed since the last one counts 0 now
60
+ return (item, memo = new Map()) => {
61
+ const chain = (current, path) => {
62
+ const cached = memo.get(current);
63
+ if (cached !== undefined) {
64
+ return cached;
65
+ }
66
+ // a loop is refused before a run starts, this only keeps the walk finite
67
+ if (path.has(current)) {
68
+ return 0;
69
+ }
70
+ path.add(current);
71
+ let longest = 0;
72
+ for (const dependent of dependents.get(current) ?? []) {
73
+ longest = Math.max(longest, chain(dependent, path));
74
+ }
75
+ path.delete(current);
76
+ const value = cost(current) + longest;
77
+ memo.set(current, value);
78
+ return value;
79
+ };
80
+ return chain(item, new Set());
81
+ };
82
+ }
83
+ exports.getTaskPriority = getTaskPriority;
84
+ // Where a task keeps its last durations on this machine: below hammerkit's directory, by
85
+ // the directory of its build file and its name.
86
+ function getDurationFile(task) {
87
+ const key = (0, crypto_1.createHash)('sha1').update(`${task.data.cwd}\0${task.name}`).digest('hex');
88
+ return (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations', `${key}.json`);
89
+ }
90
+ exports.getDurationFile = getDurationFile;
91
+ async function readKept(environment, task) {
92
+ const file = getDurationFile(task);
93
+ try {
94
+ if (!(await environment.file.exists(file))) {
95
+ return [];
96
+ }
97
+ const parsed = JSON.parse(await environment.file.read(file));
98
+ return Array.isArray(parsed?.durations)
99
+ ? parsed.durations.filter((value) => typeof value === 'number' && value >= 0)
100
+ : [];
101
+ }
102
+ catch {
103
+ return [];
104
+ }
105
+ }
106
+ // What the tasks of a run took the last times they ran on this machine.
107
+ async function readTaskDurations(workTree, environment) {
108
+ const durations = {};
109
+ await Promise.all([...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].map(async (task) => {
110
+ const kept = await readKept(environment, task);
111
+ if (kept.length > 0) {
112
+ const sorted = [...kept].sort((a, b) => a - b);
113
+ durations[task.name] = sorted[Math.floor((sorted.length - 1) / 2)];
114
+ }
115
+ }));
116
+ return durations;
117
+ }
118
+ exports.readTaskDurations = readTaskDurations;
119
+ // Keep what a task took, once it ran to its end. Best effort: a run never fails over it.
120
+ async function recordTaskDuration(environment, task, duration) {
121
+ try {
122
+ const kept = [...(await readKept(environment, task)), Math.max(0, Math.round(duration))].slice(-KEPT_DURATIONS);
123
+ await environment.file.createDirectory((0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations'));
124
+ await environment.file.writeFile(getDurationFile(task), JSON.stringify({ durations: kept }));
125
+ }
126
+ catch (e) {
127
+ task.status.write('debug', `${task.name} could not keep how long it took: ${(0, log_1.getErrorMessage)(e)}`);
128
+ }
129
+ }
130
+ exports.recordTaskDuration = recordTaskDuration;
131
+ //# sourceMappingURL=task-priority.js.map
@@ -1,20 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.watchLoop = void 0;
3
+ exports.watchLoop = exports.getSharedStateKeys = exports.isWatchMode = void 0;
4
4
  const watch_state_key_1 = require("./watch-state-key");
5
5
  const state_1 = require("./state");
6
6
  const abort_event_1 = require("../utils/abort-event");
7
7
  const state_resolver_1 = require("./state-resolver");
8
8
  const abort_1 = require("./abort");
9
9
  const enqueue_next_1 = require("./scheduler/enqueue-next");
10
- async function watchLoop(work, environment, options, factory) {
11
- // a container service that watches its own files (`continuous`); a kubernetes-service and a
12
- // task have no such field
10
+ const state_key_1 = require("./scheduler/state-key");
11
+ // Whether an item is rechecked when its files change: not in daemon mode, and not for a
12
+ // container service that watches its own files (`continuous`); a kubernetes-service and a
13
+ // task have no such field
14
+ function isWatchMode(work, options) {
13
15
  const continuous = 'continuous' in work.data ? work.data.continuous : false;
14
- const watchMode = options.watch && !options.daemon && !continuous;
16
+ return !!options.watch && !options.daemon && !continuous;
17
+ }
18
+ exports.isWatchMode = isWatchMode;
19
+ // The keys of the execution to share, see getExecutionStateKeys: none in watch mode, where a
20
+ // key is computed again because files changed
21
+ function getSharedStateKeys(work, options) {
22
+ return isWatchMode(work, options) ? undefined : (0, state_key_1.getExecutionStateKeys)(options);
23
+ }
24
+ exports.getSharedStateKeys = getSharedStateKeys;
25
+ async function watchLoop(work, environment, options, factory) {
26
+ const watchMode = isWatchMode(work, options);
15
27
  const currentStats = await (0, enqueue_next_1.checkCacheState)(work, options.cacheDefault, environment, {
16
28
  watch: watchMode,
17
29
  restore: options.restore,
30
+ memo: getSharedStateKeys(work, options),
18
31
  });
19
32
  (0, abort_1.checkForAbort)(environment.abortCtrl.signal);
20
33
  const watchState = watchMode
@@ -39,7 +39,11 @@ function getFileContext(cwd) {
39
39
  resolve({ type: 'directory' });
40
40
  }
41
41
  else if (stats.isFile()) {
42
- resolve({ type: 'file', lastModified: stats.mtimeMs });
42
+ resolve({
43
+ type: 'file',
44
+ lastModified: stats.mtimeMs,
45
+ identity: { size: stats.size, changed: stats.ctimeMs, inode: stats.ino },
46
+ });
43
47
  }
44
48
  else {
45
49
  resolve({ type: 'other' });
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.statBeneath = void 0;
4
+ const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ /**
8
+ * What `path`, inside `root`, is: its device and inode, reached from the root one name at a
9
+ * time without following a link. On Linux each folder is opened with O_NOFOLLOW through the
10
+ * descriptor of the one above (/proc/self/fd/<n>/<name>), and the last name is looked at
11
+ * (lstat) through the descriptor of its folder, so a folder swapped for a link at any moment
12
+ * is either refused or not looked at: the answer is never what a link led to.
13
+ * Elsewhere (a machine of a developer) the names are checked for links, then the path read.
14
+ * Throws when the path leaves the root, goes through a link, or can not be opened.
15
+ */
16
+ async function statBeneath(root, path) {
17
+ const inside = (0, path_1.relative)(root, path);
18
+ if (inside === '..' || inside.startsWith(`..${path_1.sep}`) || (0, path_1.isAbsolute)(inside)) {
19
+ throw new Error(`${path} is outside of ${root}`);
20
+ }
21
+ const parts = inside === '' ? [] : inside.split(path_1.sep);
22
+ if (process.platform !== 'linux') {
23
+ let current = root;
24
+ for (const part of parts) {
25
+ current = (0, path_1.join)(current, part);
26
+ if ((await (0, promises_1.lstat)(current)).isSymbolicLink()) {
27
+ throw new Error(`${path} goes through the symbolic link ${(0, path_1.relative)(root, current)}`);
28
+ }
29
+ }
30
+ return (0, promises_1.stat)(path, { bigint: true });
31
+ }
32
+ let handle = await (0, promises_1.open)(root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
33
+ try {
34
+ if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
35
+ throw new Error(`${path} can not be checked: /proc/self/fd is not readable`);
36
+ }
37
+ // the folders on the way are opened, the last name is only looked at, from the folder
38
+ // above it, which is pinned by its descriptor: so a file the server may not read still
39
+ // has an identity
40
+ for (const [index, part] of parts.entries()) {
41
+ const through = `/proc/self/fd/${handle.fd}/${part}`;
42
+ if (index === parts.length - 1) {
43
+ const stats = await (0, promises_1.lstat)(through, { bigint: true });
44
+ if (stats.isSymbolicLink()) {
45
+ throw new Error(`${path} goes through a symbolic link at ${parts.join('/')}`);
46
+ }
47
+ return stats;
48
+ }
49
+ const next = await (0, promises_1.open)(through, fs_1.constants.O_RDONLY | fs_1.constants.O_NOFOLLOW | fs_1.constants.O_DIRECTORY).catch((e) => {
50
+ const code = e.code;
51
+ if (code === 'ELOOP' || code === 'ENOTDIR') {
52
+ throw new Error(`${path} goes through a symbolic link at ${parts.slice(0, index + 1).join('/')}`);
53
+ }
54
+ throw e;
55
+ });
56
+ await handle.close();
57
+ handle = next;
58
+ }
59
+ return await handle.stat({ bigint: true });
60
+ }
61
+ finally {
62
+ await handle.close();
63
+ }
64
+ }
65
+ exports.statBeneath = statBeneath;
66
+ //# sourceMappingURL=stat-beneath.js.map
@@ -8,7 +8,9 @@ const path_1 = require("path");
8
8
  * checkout, a sandbox), or null when it stays inside. A path may not lead out of the
9
9
  * root, and none of its parts that exist may be a symbolic link, since docker, tar
10
10
  * and the file system would follow it wherever it points. A part that doesn't exist
11
- * yet is fine, it can't be a link until something makes it.
11
+ * yet is fine, it can't be a link until something makes it. A part that can't be looked
12
+ * at (a folder the server may not read) is not: what reads it later, a rootful docker,
13
+ * may well follow a link behind it.
12
14
  */
13
15
  async function findRootEscape(root, path) {
14
16
  const inside = (0, path_1.relative)((0, path_1.resolve)(root), (0, path_1.resolve)(root, path));
@@ -21,9 +23,16 @@ async function findRootEscape(root, path) {
21
23
  let current = (0, path_1.resolve)(root);
22
24
  for (const part of inside.split(path_1.sep)) {
23
25
  current = (0, path_1.join)(current, part);
24
- const stats = await (0, promises_1.lstat)(current).catch(() => undefined);
25
- if (!stats) {
26
- return null;
26
+ let stats;
27
+ try {
28
+ stats = await (0, promises_1.lstat)(current);
29
+ }
30
+ catch (e) {
31
+ const code = e.code;
32
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
33
+ return null;
34
+ }
35
+ return `can not be checked for symbolic links at ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')} (${code ?? e})`;
27
36
  }
28
37
  if (stats.isSymbolicLink()) {
29
38
  return `goes through the symbolic link ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')}`;
@@ -36,12 +36,7 @@ exports.hasShell = hasShell;
36
36
  */
37
37
  async function connectServer(environment, options) {
38
38
  const config = await (0, host_config_1.readHostConfig)(environment);
39
- const name = options.server ?? config.run.on;
40
- if (!name || !(0, host_config_1.hasServer)(config.servers, name)) {
41
- throw new Error(options.server
42
- ? `server ${options.server} is not registered, add it with: hammerkit remote add ${options.server} <url> --issuer <url>`
43
- : 'name a server (HAMMERKIT_SERVER or --server), or set a default with: hammerkit remote use <name>');
44
- }
39
+ const name = (0, host_config_1.chooseServer)(config, options.server || undefined, 'with HAMMERKIT_SERVER or --server');
45
40
  if (!options.build) {
46
41
  throw new Error('name the published version of the build file whose tasks run on the sandbox by its hash (HAMMERKIT_BUILD or --build), as hammerkit remote publish printed it');
47
42
  }
@@ -25,7 +25,7 @@ function registerMcpCommand(remote, environment, input = process.stdin) {
25
25
  remote
26
26
  .command('mcp')
27
27
  .description('serve the files, shell and tasks of a sandbox on a server as MCP tools over stdio (experimental)')
28
- .addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use)').env('HAMMERKIT_SERVER'))
28
+ .addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use, or the only registered server)').env('HAMMERKIT_SERVER'))
29
29
  .addOption(new commander_1.Option('--sandbox <id>', 'a sandbox of yours on the server').env('HAMMERKIT_SANDBOX'))
30
30
  .addOption(new commander_1.Option('--repo <repo>', 'create a sandbox of this repository').env('HAMMERKIT_REPO'))
31
31
  .addOption(new commander_1.Option('--ref <ref>', 'at this branch').env('HAMMERKIT_REF'))
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = void 0;
3
+ exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
4
4
  const path_1 = require("path");
5
5
  const token_source_1 = require("../remote/token-source");
6
6
  // a write carries up to 32 MiB
@@ -9,6 +9,9 @@ const TIMEOUT_MS = 60000;
9
9
  const POLL_WAIT = '1s';
10
10
  // a cancelled run waits this long for the server to take the cancel, before it gives up
11
11
  const CANCEL_WAIT_MS = 10000;
12
+ // what is read of a page of an endpoint: an app can answer with any amount, and only
13
+ // the start of it is shown
14
+ exports.MAX_ENDPOINT_BYTES = 256 * 1024;
12
15
  class SandboxClientError extends Error {
13
16
  constructor(message, status) {
14
17
  super(message);
@@ -213,9 +216,10 @@ class SandboxClient {
213
216
  }
214
217
  /**
215
218
  * A page of an endpoint of a service run, as the caller sees it: only at an address the
216
- * server gave the run, so the token goes to the server and nowhere else.
219
+ * server gave the run, so the token goes to the server and nowhere else. At most
220
+ * `maxBytes` of the body are read, `truncated` tells when there was more.
217
221
  */
218
- async fetchEndpoint(id, path, service, signal) {
222
+ async fetchEndpoint(id, path, service, signal, maxBytes = exports.MAX_ENDPOINT_BYTES) {
219
223
  const run = await this.getRun(id);
220
224
  const endpoint = run.up?.endpoints.find((candidate) => service === undefined || candidate.service === service);
221
225
  if (!endpoint) {
@@ -232,11 +236,13 @@ class SandboxClient {
232
236
  redirect: 'manual',
233
237
  signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]),
234
238
  });
239
+ const { text, truncated } = await readTextUpTo(response, maxBytes);
235
240
  return {
236
241
  url: url.toString(),
237
242
  status: response.status,
238
243
  type: response.headers.get('content-type') ?? '',
239
- body: await response.text(),
244
+ body: text,
245
+ truncated,
240
246
  };
241
247
  }
242
248
  /**
@@ -305,6 +311,35 @@ function oneAtATime() {
305
311
  };
306
312
  }
307
313
  exports.oneAtATime = oneAtATime;
314
+ // The body of an answer as text, read up to `maxBytes` and then cancelled, so a page
315
+ // of any size takes no more memory than that. A character cut at the limit is left out.
316
+ async function readTextUpTo(response, maxBytes) {
317
+ if (!response.body) {
318
+ return { text: '', truncated: false };
319
+ }
320
+ const reader = response.body.getReader();
321
+ const decoder = new TextDecoder();
322
+ let text = '';
323
+ let read = 0;
324
+ try {
325
+ for (;;) {
326
+ const { done, value } = await reader.read();
327
+ if (done) {
328
+ return { text: text + decoder.decode(), truncated: false };
329
+ }
330
+ const room = maxBytes - read;
331
+ if (value.byteLength > room) {
332
+ return { text: text + decoder.decode(value.subarray(0, room), { stream: true }), truncated: true };
333
+ }
334
+ read += value.byteLength;
335
+ text += decoder.decode(value, { stream: true });
336
+ }
337
+ }
338
+ finally {
339
+ await reader.cancel().catch(() => undefined);
340
+ }
341
+ }
342
+ exports.readTextUpTo = readTextUpTo;
308
343
  // a run that is over, its state does not change any more
309
344
  exports.FINAL_RUN_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
310
345
  async function submitRun(connection, request) {
@@ -120,8 +120,8 @@ exports.SERVICE_TOOLS = [
120
120
  required: ['run', 'path'],
121
121
  async call(client, args, signal) {
122
122
  const page = await client.fetchEndpoint(args.run, args.path, args.service || undefined, signal);
123
- const body = page.body.length > MAX_PAGE_CHARS
124
- ? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.body.length} characters, the first ${MAX_PAGE_CHARS} shown)`
123
+ const body = page.truncated || page.body.length > MAX_PAGE_CHARS
124
+ ? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.truncated ? 'more than ' : ''}${page.body.length} characters, the first ${Math.min(MAX_PAGE_CHARS, page.body.length)} shown)`
125
125
  : page.body;
126
126
  return [`GET ${page.url}: ${page.status}${page.type ? ` (${page.type})` : ''}`, '', body].join('\n');
127
127
  },