dsh-hive-runner 0.1.0 → 0.6.1

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.
package/lib/config.js ADDED
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Configuration for the resident Hive supervisor and the shared Hive commands.
3
+ *
4
+ * The plugin accepts plain Cordis plugin config (cordis.patch.yml -> config).
5
+ * Everything is defaulted and validated here so `apply()` never has to branch on
6
+ * partially-shaped input, and so the state machine can be unit-tested without
7
+ * the DSH runtime.
8
+ */
9
+ import path from 'node:path';
10
+
11
+ /** Default tick period: how often the supervisor looks for due repositories. */
12
+ export const DEFAULT_INTERVAL_MS = 30_000;
13
+ /** Default idle backoff: when a repository has no ready cards it is skipped this long. */
14
+ export const DEFAULT_IDLE_BACKOFF_MS = 120_000;
15
+ /** How many repositories may run a round at the same time (one round per repo). */
16
+ export const DEFAULT_MAX_CONCURRENT_REPOS = 2;
17
+ /** Consecutive round exceptions before the repository is auto-paused. */
18
+ export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
19
+ /** Default capacity retry delay when DSH's subagent capacity is exhausted. */
20
+ export const DEFAULT_CAPACITY_RETRY_MS = 2_000;
21
+ /** Default role -> concurrent live-worker cap, per repository. */
22
+ export const DEFAULT_ROLE_CONCURRENCY = Object.freeze({ coder: 5, tester: 5 });
23
+ /** Fallback cap for roles not listed in `roleConcurrency` (also finite). */
24
+ export const DEFAULT_DEFAULT_ROLE_CONCURRENCY = 5;
25
+ /** Safe role name accepted as a `roleConcurrency` key / `hive-tasks --role` value. */
26
+ export const ROLE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
27
+
28
+ const DEFAULTS = Object.freeze({
29
+ repos: [],
30
+ autoDiscover: false,
31
+ discoverRoots: [],
32
+ discoverDepth: 3,
33
+ discoverIntervalMs: 10 * 60_000,
34
+ intervalMs: DEFAULT_INTERVAL_MS,
35
+ idleBackoffMs: DEFAULT_IDLE_BACKOFF_MS,
36
+ maxConcurrentRepos: DEFAULT_MAX_CONCURRENT_REPOS,
37
+ maxConsecutiveFailures: DEFAULT_MAX_CONSECUTIVE_FAILURES,
38
+ paused: [],
39
+ agent: 'dsh',
40
+ ttl: '5m',
41
+ // Finite, user-set default: five live workers per role per repository
42
+ // (repo-level .hive/limits.json overrides this at runtime). Repository
43
+ // overrides use absolute-path keys with a role-cap object, e.g.
44
+ // { "/abs/repo": { coder: 5 } }.
45
+ roleConcurrency: DEFAULT_ROLE_CONCURRENCY,
46
+ // Fallback cap for roles not listed in roleConcurrency (also finite).
47
+ defaultRoleConcurrency: DEFAULT_DEFAULT_ROLE_CONCURRENCY,
48
+ capacityRetryMs: DEFAULT_CAPACITY_RETRY_MS,
49
+ provider: 'spawn',
50
+ parentSession: null,
51
+ cwd: null,
52
+ tasksBin: null,
53
+ hiveBin: null,
54
+ gitBin: 'git',
55
+ cliTimeoutMs: 120_000,
56
+ headTimeoutMs: 30_000,
57
+ acceptanceTimeoutMs: 15 * 60_000,
58
+ debug: false,
59
+ });
60
+
61
+ function fail(message) {
62
+ throw new TypeError('[hive-runner] config: ' + message);
63
+ }
64
+
65
+ function isPlainObject(value) {
66
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
67
+ }
68
+
69
+ function absolutePath(value, name) {
70
+ if (typeof value !== 'string' || value.trim() === '') fail(name + ' must be a non-empty absolute path');
71
+ if (!path.isAbsolute(value)) fail(name + ' must be absolute, got ' + JSON.stringify(value));
72
+ return path.normalize(value);
73
+ }
74
+
75
+ function absolutePathList(value, name) {
76
+ if (value === undefined || value === null) return [];
77
+ if (!Array.isArray(value)) fail(name + ' must be an array of absolute paths');
78
+ return [...new Set(value.map((entry, index) => absolutePath(entry, name + '[' + index + ']')))];
79
+ }
80
+
81
+ function positiveNumber(value, name) {
82
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) fail(name + ' must be a positive number');
83
+ return value;
84
+ }
85
+
86
+ function positiveInteger(value, name, max) {
87
+ if (!Number.isInteger(value) || value <= 0) fail(name + ' must be a positive integer');
88
+ if (max !== undefined && value > max) fail(name + ' must be <= ' + max);
89
+ return value;
90
+ }
91
+
92
+ function nonEmptyString(value, name) {
93
+ if (typeof value !== 'string' || value.trim() === '') fail(name + ' must be a non-empty string');
94
+ return value.trim();
95
+ }
96
+
97
+ function boolean(value, name) {
98
+ if (typeof value !== 'boolean') fail(name + ' must be a boolean');
99
+ return value;
100
+ }
101
+
102
+ function roleLimit(value, label) {
103
+ if (!Number.isInteger(value) || value < 0 || value > 999) {
104
+ fail(label + ' must be an integer in 0..999 (0 pauses the role)');
105
+ }
106
+ return value;
107
+ }
108
+
109
+ function roleCapObject(value, label) {
110
+ if (!isPlainObject(value)) fail(label + ' must be an object of role -> non-negative integer');
111
+ const caps = {};
112
+ for (const [role, limit] of Object.entries(value)) {
113
+ if (!ROLE_RE.test(role)) fail(label + ' role ' + JSON.stringify(role) + ' must match ' + ROLE_RE);
114
+ caps[role] = roleLimit(limit, label + '.' + role);
115
+ }
116
+ return caps;
117
+ }
118
+
119
+ /**
120
+ * Parse `roleConcurrency`, which may mix two kinds of keys:
121
+ * - a role name -> global per-repository cap for that role, e.g. `coder: 2`;
122
+ * - an absolute repository path -> a role-cap object overriding the global
123
+ * caps for that repository, e.g. `"/abs/repo": { coder: 5 }`.
124
+ * Package defaults (`{ coder: 2, tester: 2 }`) are merged with the global
125
+ * entries; 0 pauses a role. Unlisted roles fall back to
126
+ * `defaultRoleConcurrency`.
127
+ * @param {unknown} value
128
+ * @returns {{ roleConcurrency: Record<string, number>, repoRoleConcurrency: Record<string, Record<string, number>> }}
129
+ */
130
+ function resolveRoleConfiguration(value) {
131
+ const roleConcurrency = { ...DEFAULT_ROLE_CONCURRENCY };
132
+ const repoRoleConcurrency = {};
133
+ if (value === undefined || value === null) return { roleConcurrency, repoRoleConcurrency };
134
+ if (!isPlainObject(value)) {
135
+ fail('roleConcurrency must be an object of role -> cap and/or absolute repo path -> role caps');
136
+ }
137
+ for (const [key, entry] of Object.entries(value)) {
138
+ if (path.isAbsolute(key)) {
139
+ repoRoleConcurrency[path.normalize(key)] = roleCapObject(entry, 'roleConcurrency[' + JSON.stringify(key) + ']');
140
+ } else if (ROLE_RE.test(key)) {
141
+ roleConcurrency[key] = roleLimit(entry, 'roleConcurrency.' + key);
142
+ } else {
143
+ fail('roleConcurrency key ' + JSON.stringify(key) + ' must be a role name or an absolute repository path');
144
+ }
145
+ }
146
+ return { roleConcurrency, repoRoleConcurrency };
147
+ }
148
+
149
+ /**
150
+ * Effective per-role live-worker cap for one repository.
151
+ * Repository override -> global role map -> `defaultRoleConcurrency`.
152
+ * @param {object} config resolved config (or an object with the three fields)
153
+ * @param {string} repo normalized absolute repository path
154
+ * @param {string} role
155
+ * @returns {number}
156
+ */
157
+ export function roleLimitForRepo(config, repo, role) {
158
+ const overrides = config.repoRoleConcurrency?.[repo];
159
+ if (overrides !== undefined && Object.hasOwn(overrides, role)) return overrides[role];
160
+ if (Object.hasOwn(config.roleConcurrency ?? {}, role)) return config.roleConcurrency[role];
161
+ return config.defaultRoleConcurrency ?? DEFAULT_DEFAULT_ROLE_CONCURRENCY;
162
+ }
163
+
164
+ /**
165
+ * Roles known for one repository: global role keys, repo-override keys and any
166
+ * additional roles observed in the current ready queue.
167
+ * @param {object} config
168
+ * @param {string} repo
169
+ * @param {string[]} [extra]
170
+ * @returns {string[]}
171
+ */
172
+ export function roleNamesForRepo(config, repo, extra = []) {
173
+ const names = new Set([
174
+ ...Object.keys(config.roleConcurrency ?? {}),
175
+ ...Object.keys(config.repoRoleConcurrency?.[repo] ?? {}),
176
+ ...extra.filter((role) => typeof role === 'string' && role !== ''),
177
+ ]);
178
+ return [...names];
179
+ }
180
+
181
+ /**
182
+ * Per-role status seeded with the configured limits (`live`/`queued` at 0).
183
+ * @param {object} config
184
+ * @param {string} repo
185
+ * @param {string[]} [extra]
186
+ * @returns {Record<string, { limit: number, live: number, queued: number }>}
187
+ */
188
+ export function initialRoleStatus(config, repo, extra = []) {
189
+ const status = {};
190
+ for (const role of roleNamesForRepo(config, repo, extra)) {
191
+ status[role] = { limit: roleLimitForRepo(config, repo, role), live: 0, queued: 0 };
192
+ }
193
+ return status;
194
+ }
195
+
196
+ function bin(value, name, env, fallback) {
197
+ if (value === undefined || value === null || value === '') {
198
+ const fromEnv = process.env[env];
199
+ return typeof fromEnv === 'string' && fromEnv.trim() !== '' ? fromEnv : fallback;
200
+ }
201
+ return nonEmptyString(value, name);
202
+ }
203
+
204
+ /**
205
+ * Normalize one repository key. Configuration requires absolute paths; HTTP and
206
+ * tool callers may send any string, resolved against the host working directory.
207
+ * @param {string} repo
208
+ * @returns {string}
209
+ */
210
+ export function normalizeRepoKey(repo) {
211
+ if (typeof repo !== 'string' || repo.trim() === '') throw new TypeError('repo must be a non-empty string');
212
+ return path.normalize(path.resolve(repo));
213
+ }
214
+
215
+ /**
216
+ * Apply defaults and validate the plugin config.
217
+ * @param {Record<string, unknown>} [config]
218
+ * @returns {object}
219
+ */
220
+ export function resolveConfig(config = {}) {
221
+ if (config === undefined || config === null) config = {};
222
+ if (!isPlainObject(config)) fail('config must be an object');
223
+
224
+ const cfg = { ...DEFAULTS, ...config };
225
+ cfg.debug = boolean(cfg.debug, 'debug');
226
+ cfg.repos = absolutePathList(cfg.repos, 'repos');
227
+ cfg.paused = absolutePathList(cfg.paused, 'paused');
228
+ cfg.autoDiscover = boolean(cfg.autoDiscover, 'autoDiscover');
229
+ cfg.discoverRoots = absolutePathList(cfg.discoverRoots, 'discoverRoots');
230
+ cfg.discoverDepth = positiveInteger(cfg.discoverDepth, 'discoverDepth', 8);
231
+ cfg.discoverIntervalMs = positiveNumber(cfg.discoverIntervalMs, 'discoverIntervalMs');
232
+ cfg.intervalMs = positiveNumber(cfg.intervalMs, 'intervalMs');
233
+ cfg.idleBackoffMs = positiveNumber(cfg.idleBackoffMs, 'idleBackoffMs');
234
+ cfg.maxConcurrentRepos = positiveInteger(cfg.maxConcurrentRepos, 'maxConcurrentRepos');
235
+ cfg.maxConsecutiveFailures = positiveInteger(cfg.maxConsecutiveFailures, 'maxConsecutiveFailures');
236
+ const roleConfiguration = resolveRoleConfiguration(cfg.roleConcurrency);
237
+ cfg.roleConcurrency = roleConfiguration.roleConcurrency;
238
+ cfg.repoRoleConcurrency = roleConfiguration.repoRoleConcurrency;
239
+ if (!Number.isInteger(cfg.defaultRoleConcurrency) || cfg.defaultRoleConcurrency < 0 || cfg.defaultRoleConcurrency > 999) {
240
+ fail('defaultRoleConcurrency must be an integer in 0..999 (0 pauses unlisted roles)');
241
+ }
242
+ cfg.capacityRetryMs = positiveNumber(cfg.capacityRetryMs, 'capacityRetryMs');
243
+ cfg.cliTimeoutMs = positiveNumber(cfg.cliTimeoutMs, 'cliTimeoutMs');
244
+ cfg.headTimeoutMs = positiveNumber(cfg.headTimeoutMs, 'headTimeoutMs');
245
+ cfg.acceptanceTimeoutMs = positiveNumber(cfg.acceptanceTimeoutMs, 'acceptanceTimeoutMs');
246
+ cfg.agent = nonEmptyString(cfg.agent, 'agent');
247
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(cfg.agent)) fail('agent must be a safe identity (letters, digits, . _ -)');
248
+ cfg.ttl = nonEmptyString(cfg.ttl, 'ttl');
249
+ if (!/^\d{1,4}[smhd]$/.test(cfg.ttl)) fail('ttl must look like 5m, 30s, 2h or 1d');
250
+ cfg.provider = nonEmptyString(cfg.provider, 'provider');
251
+ if (cfg.parentSession !== null && cfg.parentSession !== undefined) cfg.parentSession = nonEmptyString(cfg.parentSession, 'parentSession');
252
+ else cfg.parentSession = null;
253
+ cfg.cwd = cfg.cwd === null || cfg.cwd === undefined ? process.cwd() : absolutePath(cfg.cwd, 'cwd');
254
+ cfg.tasksBin = bin(cfg.tasksBin, 'tasksBin', 'HIVE_TASKS_BIN', 'hive-tasks');
255
+ cfg.hiveBin = bin(cfg.hiveBin, 'hiveBin', 'HIVE_BIN', 'hive');
256
+ cfg.gitBin = bin(cfg.gitBin, 'gitBin', 'HIVE_GIT_BIN', 'git');
257
+
258
+ // Auto-discovery without explicit roots scans the parent of each configured
259
+ // repository: the "configured root" in the common one-off deployment.
260
+ if (cfg.autoDiscover && cfg.discoverRoots.length === 0) {
261
+ cfg.discoverRoots = [...new Set(cfg.repos.map((repo) => path.dirname(repo)))];
262
+ }
263
+ return cfg;
264
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Automatic repository discovery.
3
+ *
4
+ * A repository is discovered when its git directory has a `refs/hive/v1`
5
+ * namespace (loose ref directory or packed refs): the same hard fact the Hive
6
+ * tools use to decide that a repository was initialised. The scan is bounded by
7
+ * depth and skips `node_modules` and `.git` directories; a discovered
8
+ * repository's own tree is not descended into.
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ const SKIP_DIRS = new Set(['node_modules', '.git']);
14
+
15
+ function refsExist(gitDir) {
16
+ try {
17
+ if (fs.existsSync(path.join(gitDir, 'refs', 'hive', 'v1'))) return true;
18
+ } catch {
19
+ // fall through to packed-refs
20
+ }
21
+ try {
22
+ const packed = fs.readFileSync(path.join(gitDir, 'packed-refs'), 'utf8');
23
+ return /(?:^|\n)[0-9a-f]{40,64} refs\/hive\/v1\//.test(packed);
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Whether this directory is a git worktree whose git dir carries
31
+ * `refs/hive/v1` (loose or packed). Supports worktrees where `.git` is a file.
32
+ * @param {string} repoPath
33
+ * @returns {boolean}
34
+ */
35
+ export function hasHiveRef(repoPath) {
36
+ try {
37
+ const dotGit = path.join(repoPath, '.git');
38
+ const stat = fs.statSync(dotGit);
39
+ let gitDir;
40
+ if (stat.isDirectory()) {
41
+ gitDir = dotGit;
42
+ } else if (stat.isFile()) {
43
+ const match = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dotGit, 'utf8'));
44
+ if (match === null) return false;
45
+ gitDir = path.resolve(repoPath, match[1].trim());
46
+ } else {
47
+ return false;
48
+ }
49
+ let commonDir = gitDir;
50
+ try {
51
+ const common = fs.readFileSync(path.join(gitDir, 'commondir'), 'utf8').trim();
52
+ if (common !== '') commonDir = path.resolve(gitDir, common);
53
+ } catch {
54
+ // no commondir: plain repository
55
+ }
56
+ return refsExist(gitDir) || refsExist(commonDir);
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Scan configured roots for Hive-initialised repositories.
64
+ * @param {{ roots?: string[], depth?: number, maxRepos?: number }} [options]
65
+ * @returns {string[]} sorted absolute repository paths
66
+ */
67
+ export function discoverRepos({ roots = [], depth = 3, maxRepos = 500 } = {}) {
68
+ const found = new Set();
69
+ const visited = new Set();
70
+
71
+ function walk(directory, level) {
72
+ if (found.size >= maxRepos || visited.has(directory)) return;
73
+ visited.add(directory);
74
+ if (hasHiveRef(directory)) {
75
+ found.add(directory);
76
+ return; // do not descend into a repository we already registered
77
+ }
78
+ if (level >= depth) return;
79
+ let entries;
80
+ try {
81
+ entries = fs.readdirSync(directory, { withFileTypes: true });
82
+ } catch {
83
+ return;
84
+ }
85
+ for (const entry of entries) {
86
+ if (!entry.isDirectory()) continue;
87
+ if (SKIP_DIRS.has(entry.name)) continue;
88
+ walk(path.join(directory, entry.name), level + 1);
89
+ }
90
+ }
91
+
92
+ for (const root of roots) {
93
+ walk(path.resolve(root), 0);
94
+ }
95
+ return [...found].sort();
96
+ }
package/lib/hooks.js ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * merge-on-commit guard for Hive card workers.
3
+ *
4
+ * Hive's `hive init` installs a `.git/hooks/pre-commit` hook that performs a
5
+ * three-way merge (merge-on-commit / moc) before every commit. Card workers
6
+ * must land their work through that ordinary `git commit` path; bypassing the
7
+ * hook (`--no-verify`, amend, update-ref/reset) would lose the other side's
8
+ * changes.
9
+ *
10
+ * The supervisor checks the hook before every drain (a missing hook is an
11
+ * environment error: retry later, do not fail the card, do not auto-pause) and
12
+ * once more before marking a card done.
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ /** Coded, deferrable environment error: the repository is not ready for runs. */
18
+ export const PRE_COMMIT_HOOK_ERROR_CODE = 'hive/no-pre-commit-hook';
19
+
20
+ export class MergeOnCommitHookError extends Error {
21
+ constructor(repo, detail) {
22
+ super(
23
+ 'merge-on-commit pre-commit hook is not ready in ' + JSON.stringify(repo) + ': ' + detail
24
+ + '. Run `hive init` first (先跑 hive init), then retry.',
25
+ );
26
+ this.name = 'MergeOnCommitHookError';
27
+ this.code = PRE_COMMIT_HOOK_ERROR_CODE;
28
+ this.deferrable = true;
29
+ this.repo = repo;
30
+ }
31
+ }
32
+
33
+ /** Resolve the repository's git directory, supporting worktrees where .git is a file. */
34
+ export function gitDirOf(repo) {
35
+ const dotGit = path.join(repo, '.git');
36
+ const stat = fs.statSync(dotGit);
37
+ if (stat.isDirectory()) return dotGit;
38
+ if (stat.isFile()) {
39
+ const match = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dotGit, 'utf8'));
40
+ if (match === null) throw new Error('.git file in ' + repo + ' has no gitdir line');
41
+ return path.resolve(repo, match[1].trim());
42
+ }
43
+ throw new Error('.git in ' + repo + ' is neither a directory nor a file');
44
+ }
45
+
46
+ /** Absolute path of the repository's pre-commit hook. */
47
+ export function preCommitHookPath(repo) {
48
+ return path.join(gitDirOf(repo), 'hooks', 'pre-commit');
49
+ }
50
+
51
+ /**
52
+ * Read the hook content, or null when it does not exist.
53
+ * @param {string} repo
54
+ * @returns {string | null}
55
+ */
56
+ export function readPreCommitHook(repo) {
57
+ try {
58
+ return fs.readFileSync(preCommitHookPath(repo), 'utf8');
59
+ } catch (error) {
60
+ if (error?.code === 'ENOENT') return null;
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ /** Whether the hook script mentions merge-on-commit / moc. */
66
+ export function isMergeOnCommitHook(content) {
67
+ return typeof content === 'string' && /(merge[-_ ]?on[-_ ]?commit|\bmoc\b)/i.test(content);
68
+ }
69
+
70
+ /**
71
+ * Throw a deferrable environment error unless the repository has a
72
+ * merge-on-commit pre-commit hook installed.
73
+ * @param {string} repo
74
+ * @returns {{ path: string, content: string }}
75
+ */
76
+ export function assertMergeOnCommitHook(repo) {
77
+ let hookPath;
78
+ let content;
79
+ try {
80
+ hookPath = preCommitHookPath(repo);
81
+ content = readPreCommitHook(repo);
82
+ } catch (error) {
83
+ throw new MergeOnCommitHookError(repo, 'cannot read .git/hooks/pre-commit (' + String(error?.message ?? error) + ')');
84
+ }
85
+ if (content === null) {
86
+ throw new MergeOnCommitHookError(repo, 'missing .git/hooks/pre-commit');
87
+ }
88
+ if (!isMergeOnCommitHook(content)) {
89
+ throw new MergeOnCommitHookError(repo, hookPath + ' does not reference merge-on-commit/moc');
90
+ }
91
+ return { path: hookPath, content };
92
+ }
package/lib/http.js ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Same-origin observability/control route for the supervisor.
3
+ *
4
+ * Registered through Connection's exact Fetch route, so it shares the DSH web
5
+ * server's cookie authentication and needs no extra port or HTTP server
6
+ * (RESEARCH.md §3.2). JSON in, JSON out.
7
+ *
8
+ * GET /api/hive-runner?op=status
9
+ * POST /api/hive-runner?op=pause { repo }
10
+ * POST /api/hive-runner?op=resume { repo }
11
+ * POST /api/hive-runner?op=limits { repo, roleLimits: { role: number } }
12
+ */
13
+ import { normalizeRepoKey } from './config.js';
14
+ import { UnknownRepoError } from './supervisor.js';
15
+
16
+ /** Exact same-origin path owned by this plugin. */
17
+ export const HIVE_RUNNER_PATH = '/api/hive-runner';
18
+
19
+ function json(value, status = 200) {
20
+ return Response.json(value, { status });
21
+ }
22
+
23
+ function failure(op, code, message, status) {
24
+ return json({ ok: false, op, error: { code, message } }, status);
25
+ }
26
+
27
+ async function readPayload(request) {
28
+ if (request.method !== 'POST' && request.method !== 'PUT' && request.method !== 'PATCH') return {};
29
+ try {
30
+ const text = await request.text();
31
+ if (text.trim() === '') return {};
32
+ const value = JSON.parse(text);
33
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
34
+ } catch {
35
+ return {};
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Handle one request against a supervisor instance.
41
+ * @param {Request} request
42
+ * @param {import('./supervisor.js').HiveSupervisor} supervisor
43
+ * @returns {Promise<Response>}
44
+ */
45
+ export async function handleHiveRunnerRequest(request, supervisor) {
46
+ const url = new URL(request.url);
47
+ const payload = await readPayload(request);
48
+ const op = url.searchParams.get('op') ?? (typeof payload.op === 'string' ? payload.op : null);
49
+ const repo = typeof payload.repo === 'string' ? payload.repo : url.searchParams.get('repo');
50
+
51
+ if (op === 'status') {
52
+ return json({ ok: true, op: 'status', ...supervisor.status() });
53
+ }
54
+ if (op === 'pause' || op === 'resume') {
55
+ if (typeof repo !== 'string' || repo.trim() === '') {
56
+ return failure(op, 'hive/missing-repo', 'repo is required (query parameter or JSON body field)', 400);
57
+ }
58
+ let key;
59
+ try {
60
+ key = normalizeRepoKey(repo);
61
+ } catch {
62
+ return failure(op, 'hive/invalid-repo', 'repo must be a non-empty path', 400);
63
+ }
64
+ if (!supervisor.hasRepo(key)) {
65
+ return failure(op, 'hive/unknown-repo', 'unknown repository ' + JSON.stringify(key), 404);
66
+ }
67
+ try {
68
+ const snapshot = op === 'pause' ? supervisor.pause(key) : supervisor.resume(key);
69
+ return json({ ok: true, op, repo: snapshot });
70
+ } catch (error) {
71
+ if (error instanceof UnknownRepoError) {
72
+ return failure(op, error.code, error.message, 404);
73
+ }
74
+ return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
75
+ }
76
+ }
77
+ if (op === 'limits') {
78
+ if (request.method !== 'POST') {
79
+ return failure(op, 'hive/method-not-allowed', 'op=limits requires POST', 405);
80
+ }
81
+ if (typeof repo !== 'string' || repo.trim() === '') {
82
+ return failure(op, 'hive/missing-repo', 'repo is required (JSON body field)', 400);
83
+ }
84
+ const roleLimits = payload.roleLimits;
85
+ if (roleLimits === null || typeof roleLimits !== 'object' || Array.isArray(roleLimits)) {
86
+ return failure(op, 'hive/invalid-role-limits', 'roleLimits must be an object of role -> integer in 0..999', 400);
87
+ }
88
+ let key;
89
+ try {
90
+ key = normalizeRepoKey(repo);
91
+ } catch {
92
+ return failure(op, 'hive/invalid-repo', 'repo must be a non-empty path', 400);
93
+ }
94
+ if (!supervisor.hasRepo(key)) {
95
+ return failure(op, 'hive/unknown-repo', 'unknown repository ' + JSON.stringify(key), 404);
96
+ }
97
+ try {
98
+ const snapshot = supervisor.setRoleLimits(key, roleLimits);
99
+ return json({ ok: true, op, repo: snapshot });
100
+ } catch (error) {
101
+ if (error instanceof UnknownRepoError) return failure(op, error.code, error.message, 404);
102
+ if (error instanceof TypeError) return failure(op, 'hive/invalid-role-limits', error.message, 400);
103
+ return failure(op, 'hive/internal', error instanceof Error ? error.message : String(error), 500);
104
+ }
105
+ }
106
+ return failure(op, 'hive/unknown-op', 'unknown op ' + JSON.stringify(op) + '; use status, pause, resume or limits', 400);
107
+ }
108
+
109
+ /**
110
+ * Build the Connection Fetch route descriptor.
111
+ * @param {import('./supervisor.js').HiveSupervisor} supervisor
112
+ */
113
+ export function createHiveRunnerRoute(supervisor) {
114
+ return {
115
+ path: HIVE_RUNNER_PATH,
116
+ methods: ['GET', 'POST'],
117
+ requestBody: 'buffered',
118
+ fetch: (request) => handleHiveRunnerRequest(request, supervisor),
119
+ };
120
+ }