dsh-hive-runner 0.1.0 → 0.6.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.
- package/CHANGELOG.md +45 -0
- package/LICENSE +21 -0
- package/README.md +274 -10
- package/README.zh-CN.md +206 -0
- package/SPEC.md +209 -0
- package/cordis.patch.yml +80 -2
- package/docs/DESIGN.md +181 -0
- package/index.js +182 -64
- package/lib/commands.js +261 -0
- package/lib/config.js +264 -0
- package/lib/discover.js +96 -0
- package/lib/hooks.js +92 -0
- package/lib/http.js +120 -0
- package/lib/limits.js +184 -0
- package/lib/queue.js +156 -0
- package/lib/round.js +362 -0
- package/lib/shell.js +72 -0
- package/lib/supervisor.js +574 -0
- package/package.json +45 -10
package/lib/round.js
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One Hive round for one repository: fetch every ready card and run one card
|
|
3
|
+
* end to end.
|
|
4
|
+
*
|
|
5
|
+
* The default policy is one subagent per ready card (the number of workers
|
|
6
|
+
* equals the current ready-task count). `roleConcurrency` is only an optional
|
|
7
|
+
* operations cap; the real ceiling is DSH's `subagent.maxActiveSubagents` and
|
|
8
|
+
* the model provider's rate limits. Capacity rejections are turned into
|
|
9
|
+
* queueable work items by `lib/queue.js` instead of failing the round.
|
|
10
|
+
*
|
|
11
|
+
* All Hive/git commands go through the allowlisted `lib/commands.js` layer,
|
|
12
|
+
* hence through `ctx.shell`. Card workers are DSH subagents, not processes.
|
|
13
|
+
*
|
|
14
|
+
* Merge-on-commit is mandatory: a drain preflights `<repo>/.git/hooks/pre-commit`
|
|
15
|
+
* (missing hook = deferrable environment error, run `hive init`) and a card is
|
|
16
|
+
* only recorded done when HEAD moved through that hook-equipped commit path.
|
|
17
|
+
*/
|
|
18
|
+
import { roleLimitForRepo } from './config.js';
|
|
19
|
+
import { HiveCommandError, tail } from './commands.js';
|
|
20
|
+
import { assertMergeOnCommitHook } from './hooks.js';
|
|
21
|
+
import { isCapacityError } from './queue.js';
|
|
22
|
+
|
|
23
|
+
/** A round-level failure. `hive/capacity` is retried from the queue. */
|
|
24
|
+
export class RoundError extends Error {
|
|
25
|
+
constructor(code, message, options = {}) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'RoundError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.deferrable = options.deferrable === true;
|
|
30
|
+
if (options.capacity === true) this.capacity = true;
|
|
31
|
+
if (options.cause !== undefined) this.cause = options.cause;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Render the worker prompt for one card.
|
|
37
|
+
* @param {object} card Hive task card
|
|
38
|
+
* @param {Array<{ text: string, status?: string, scope?: string }>} [lessons] recalled hive lessons
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
export function renderPrompt(card, lessons = []) {
|
|
42
|
+
const lines = [
|
|
43
|
+
'# Task ' + card.id + ': ' + card.title,
|
|
44
|
+
'',
|
|
45
|
+
'You are working as: ' + (card.role || 'worker') + '.',
|
|
46
|
+
'',
|
|
47
|
+
];
|
|
48
|
+
if (card.goal) lines.push('## Goal', card.goal, '');
|
|
49
|
+
if (card.scope && card.scope.length) {
|
|
50
|
+
lines.push('## Scope (edit only these paths)');
|
|
51
|
+
for (const entry of card.scope) lines.push('- ' + entry);
|
|
52
|
+
lines.push('');
|
|
53
|
+
}
|
|
54
|
+
if (card.acceptance) lines.push('## Acceptance (the runner will run this)', ' ' + card.acceptance, '');
|
|
55
|
+
if (card.reason) lines.push('## Previous attempt failed with', card.reason, '');
|
|
56
|
+
lines.push('## Hive consensus rules (mandatory)');
|
|
57
|
+
lines.push('1. At the start, run `hive guard <path...>` for every entry in the card scope (including `resource:` entries, which are leases, not files). It co-signs your leases and marks the board working.');
|
|
58
|
+
lines.push('2. If `hive guard` exits 2, stop immediately and report the holder information (stderr) as the failure reason. NEVER bypass it: do not edit files outside the scope, do not `git checkout` files owned by someone else, and do not delete lease refs.');
|
|
59
|
+
lines.push('3. Your claim already marks the board working with this task id; guard keeps it current.');
|
|
60
|
+
lines.push('4. Before finishing, release your own leases (`hive release <scope...>`); done/fail normally release them, but verify nothing is left behind.');
|
|
61
|
+
if (lessons.length > 0) {
|
|
62
|
+
lines.push('5. The runner already ran `hive recall <scope>` for this card; the relevant experience is injected below. Only if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
|
|
63
|
+
} else {
|
|
64
|
+
lines.push('5. The runner already ran `hive recall <scope>`; if you discover genuinely new knowledge, record it with `hive lesson add` (the `hive learn` path); do not write a lesson just to write one.');
|
|
65
|
+
}
|
|
66
|
+
lines.push('');
|
|
67
|
+
lines.push('## Commit rules (mandatory)');
|
|
68
|
+
lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc) and performs a three-way merge automatically.');
|
|
69
|
+
lines.push('2. NEVER bypass the hook: do not use `git commit --no-verify`, do not use `git commit --amend` to skip it, and do not use `git update-ref` or `git reset` to rewrite history that others already committed.');
|
|
70
|
+
lines.push('3. If the hook reports merge conflicts, resolve them in place using the conflict markers, then commit again. Never discard the other side\'s changes.');
|
|
71
|
+
lines.push('');
|
|
72
|
+
if (lessons.length > 0) {
|
|
73
|
+
lines.push('## Recalled experience (hive recall)');
|
|
74
|
+
for (const lesson of lessons) {
|
|
75
|
+
const status = lesson.status ? '[' + lesson.status + '] ' : '';
|
|
76
|
+
lines.push('- ' + status + String(lesson.text ?? '').trim());
|
|
77
|
+
}
|
|
78
|
+
lines.push('');
|
|
79
|
+
}
|
|
80
|
+
lines.push('## How to finish');
|
|
81
|
+
lines.push('1. Edit only the scope paths.');
|
|
82
|
+
lines.push('2. Commit before you exit: the runner checks that HEAD moved through the hook.');
|
|
83
|
+
lines.push('3. Do not run hive-tasks done; the runner records it.');
|
|
84
|
+
return lines.join('\n');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function messageOf(error) {
|
|
88
|
+
return error instanceof Error ? error.message : String(error);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Bind the Hive round helpers to the DSH runtime and the Hive command layer.
|
|
93
|
+
* @param {{ ctx: object, config: object, commands: object }} options
|
|
94
|
+
*/
|
|
95
|
+
export function createRoundRunner({ ctx, config, commands, limitFor, checkHook = assertMergeOnCommitHook }) {
|
|
96
|
+
if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
|
|
97
|
+
throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
|
|
98
|
+
}
|
|
99
|
+
if (commands === undefined || commands === null) throw new TypeError('createRoundRunner: commands are required');
|
|
100
|
+
/** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
|
|
101
|
+
const capFor = typeof limitFor === 'function'
|
|
102
|
+
? limitFor
|
|
103
|
+
: (repo, role) => roleLimitForRepo(config, repo, role);
|
|
104
|
+
|
|
105
|
+
function subagents() {
|
|
106
|
+
const service = ctx.get('subagents');
|
|
107
|
+
if (service === undefined || service === null) {
|
|
108
|
+
throw new RoundError('hive/no-subagents', 'ctx.subagents is unavailable; the Hive supervisor cannot start card subagents');
|
|
109
|
+
}
|
|
110
|
+
return service;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Resolve the Agent that owns subagent runs. Prefer the caller's agent (tool
|
|
115
|
+
* calls); otherwise the explicitly pinned session, then any live agent.
|
|
116
|
+
*/
|
|
117
|
+
function resolveParent(explicit) {
|
|
118
|
+
if (explicit !== undefined && explicit !== null) return explicit;
|
|
119
|
+
const agents = ctx.get('agents');
|
|
120
|
+
if (config.parentSession) {
|
|
121
|
+
const pinned = typeof agents?.get === 'function' ? agents.get(config.parentSession) : undefined;
|
|
122
|
+
if (pinned !== undefined) return pinned;
|
|
123
|
+
throw new RoundError(
|
|
124
|
+
'hive/no-parent-agent',
|
|
125
|
+
'parentSession ' + JSON.stringify(config.parentSession) + ' is not live; open that session or remove parentSession',
|
|
126
|
+
{ deferrable: true },
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
const live = typeof agents?.list === 'function' ? agents.list() : [];
|
|
130
|
+
if (live.length > 0) return live[0];
|
|
131
|
+
throw new RoundError(
|
|
132
|
+
'hive/no-parent-agent',
|
|
133
|
+
'no live DSH agent to parent Hive subagent runs; open a session or set parentSession (deferred, not counted as a failure)',
|
|
134
|
+
{ deferrable: true },
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function assertProvider(providerName) {
|
|
139
|
+
const service = subagents();
|
|
140
|
+
const provider = typeof service.getProvider === 'function' ? service.getProvider(providerName) : undefined;
|
|
141
|
+
if (provider === undefined) {
|
|
142
|
+
throw new RoundError('hive/no-provider', 'no subagent provider named ' + JSON.stringify(providerName) + ' is registered');
|
|
143
|
+
}
|
|
144
|
+
return service;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function verify({ repo, before, card, signal, session }) {
|
|
148
|
+
const head = await commands.head(repo, { signal, session });
|
|
149
|
+
if (head === before) return { ok: false, reason: 'no commit produced' };
|
|
150
|
+
// The commit must have landed through the merge-on-commit path: if the hook
|
|
151
|
+
// vanished the commit may have bypassed it, so this is an environment error.
|
|
152
|
+
checkHook(repo);
|
|
153
|
+
if (card.acceptance) {
|
|
154
|
+
const result = await commands.acceptance(repo, card.acceptance, { signal, session });
|
|
155
|
+
if (result.exitCode !== 0) {
|
|
156
|
+
const detail = result.stderr.trim() !== '' ? result.stderr : result.stdout;
|
|
157
|
+
return { ok: false, reason: 'acceptance failed: ' + tail(detail) };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return { ok: true, head };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Scope entries of one card (files and `resource:` lease keys alike). */
|
|
164
|
+
function scopeOf(card) {
|
|
165
|
+
return Array.isArray(card.scope)
|
|
166
|
+
? card.scope.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
|
|
167
|
+
: [];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Recall lessons for the card scope. Best effort: a recall failure never
|
|
172
|
+
* blocks the card (the runner already has the environment churn signal).
|
|
173
|
+
*/
|
|
174
|
+
async function recallLessons(repo, scope, { signal, session }) {
|
|
175
|
+
const seen = new Map();
|
|
176
|
+
for (const query of scope.slice(0, 3)) {
|
|
177
|
+
try {
|
|
178
|
+
const items = await commands.recall(repo, query, { signal, session });
|
|
179
|
+
for (const item of items) {
|
|
180
|
+
if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
|
|
181
|
+
seen.set(item.id ?? item.text, item);
|
|
182
|
+
}
|
|
183
|
+
} catch {
|
|
184
|
+
// Lessons are advisory; continue without them.
|
|
185
|
+
}
|
|
186
|
+
if (seen.size >= 5) break;
|
|
187
|
+
}
|
|
188
|
+
return [...seen.values()].slice(0, 5);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Best-effort release of the leases we own for this card scope. */
|
|
192
|
+
async function releaseScope(repo, scope, { signal, session }) {
|
|
193
|
+
if (scope.length === 0) return;
|
|
194
|
+
try {
|
|
195
|
+
await commands.release(repo, scope, { signal, session });
|
|
196
|
+
} catch {
|
|
197
|
+
// done/fail already release leases; this is only orphan cleanup.
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Best-effort release of a claim when the worker could not run at all. */
|
|
202
|
+
async function releaseClaim(repo, id, error, signal, session) {
|
|
203
|
+
await commands.fail(repo, id, {
|
|
204
|
+
reason: 'runner error: ' + tail(messageOf(error)),
|
|
205
|
+
signal,
|
|
206
|
+
session,
|
|
207
|
+
}).catch(() => {});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function executeCard({ repo, card, before, owner, signal, session }) {
|
|
211
|
+
const id = card.id;
|
|
212
|
+
const service = assertProvider(config.provider);
|
|
213
|
+
const scope = scopeOf(card);
|
|
214
|
+
let activation;
|
|
215
|
+
try {
|
|
216
|
+
// hive-consensus: co-sign the card's leases (guard) before the worker
|
|
217
|
+
// starts. Exit 2 means someone else holds the scope: the card fails with
|
|
218
|
+
// the holder information and no work/commit happens.
|
|
219
|
+
if (scope.length > 0) {
|
|
220
|
+
const guard = await commands.guard(repo, scope, {
|
|
221
|
+
taskId: id,
|
|
222
|
+
ttl: config.ttl,
|
|
223
|
+
signal,
|
|
224
|
+
session,
|
|
225
|
+
});
|
|
226
|
+
if (guard.exitCode === 2) {
|
|
227
|
+
const reason = 'guard denied: ' + tail(guard.stderr || guard.stdout || 'scope held by another agent');
|
|
228
|
+
await commands.fail(repo, id, { reason, signal, session });
|
|
229
|
+
await releaseScope(repo, scope, { signal, session });
|
|
230
|
+
return { id, state: 'failed', reason };
|
|
231
|
+
}
|
|
232
|
+
if (guard.exitCode !== 0) {
|
|
233
|
+
throw new RoundError(
|
|
234
|
+
'hive/guard-failed',
|
|
235
|
+
'hive guard exited ' + String(guard.exitCode) + ': ' + tail(guard.stderr || guard.stdout),
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const lessons = scope.length > 0 ? await recallLessons(repo, scope, { signal, session }) : [];
|
|
240
|
+
activation = await service.startActivation({
|
|
241
|
+
provider: config.provider,
|
|
242
|
+
label: 'hive:' + id,
|
|
243
|
+
prompt: [{ type: 'text', text: renderPrompt(card, lessons) }],
|
|
244
|
+
cwd: repo,
|
|
245
|
+
parent: owner,
|
|
246
|
+
signal,
|
|
247
|
+
delivery: 'caller',
|
|
248
|
+
});
|
|
249
|
+
const outcome = await activation.result;
|
|
250
|
+
if (outcome.stopReason !== 'completed') {
|
|
251
|
+
const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
|
|
252
|
+
const reason = 'subagent stopped: ' + outcome.stopReason + detail;
|
|
253
|
+
await commands.fail(repo, id, { reason, signal, session });
|
|
254
|
+
await releaseScope(repo, scope, { signal, session });
|
|
255
|
+
return { id, state: 'failed', reason };
|
|
256
|
+
}
|
|
257
|
+
const verdict = await verify({ repo, before, card, signal, session });
|
|
258
|
+
if (verdict.ok) {
|
|
259
|
+
await commands.done(repo, id, { sha: verdict.head, verdict: 'pass', signal, session });
|
|
260
|
+
await releaseScope(repo, scope, { signal, session });
|
|
261
|
+
return { id, state: 'done', sha: verdict.head };
|
|
262
|
+
}
|
|
263
|
+
await commands.fail(repo, id, { reason: verdict.reason, signal, session });
|
|
264
|
+
await releaseScope(repo, scope, { signal, session });
|
|
265
|
+
return { id, state: 'failed', reason: verdict.reason };
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (isCapacityError(error)) {
|
|
268
|
+
// Capacity is a scheduling concern, not this card's failure: keep the
|
|
269
|
+
// claimed item and let the dispatcher retry it.
|
|
270
|
+
const capacity = new RoundError('hive/capacity', messageOf(error), { capacity: true });
|
|
271
|
+
capacity.item = { role: card.role, card, claimed: true };
|
|
272
|
+
throw capacity;
|
|
273
|
+
}
|
|
274
|
+
// Deferrable environment errors (missing merge-on-commit hook, no live
|
|
275
|
+
// parent agent) are not the card's failure: leave the claim to expire /
|
|
276
|
+
// retry later instead of recording a card failure.
|
|
277
|
+
const environment = error?.deferrable === true
|
|
278
|
+
|| (typeof error?.code === 'string' && error.code.startsWith('hive/no-'));
|
|
279
|
+
if (!environment) await releaseClaim(repo, id, error, signal, session);
|
|
280
|
+
await releaseScope(repo, scope, { signal, session });
|
|
281
|
+
throw error instanceof RoundError
|
|
282
|
+
? error
|
|
283
|
+
: environment
|
|
284
|
+
? error
|
|
285
|
+
: new RoundError('hive/round-failed', messageOf(error), { cause: error });
|
|
286
|
+
} finally {
|
|
287
|
+
if (activation !== undefined) {
|
|
288
|
+
await Promise.resolve(activation.dispose?.()).catch(() => {});
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
resolveParent,
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Round-start environment check: the repository must be Hive-initialised
|
|
298
|
+
* with the merge-on-commit pre-commit hook. Throws a deferrable error.
|
|
299
|
+
* @param {string} repo
|
|
300
|
+
*/
|
|
301
|
+
preflight(repo) {
|
|
302
|
+
checkHook(repo);
|
|
303
|
+
},
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* All ready cards in one repository. Roles configured with a 0 cap are
|
|
307
|
+
* filtered out; otherwise every card becomes one work item.
|
|
308
|
+
* @returns {Promise<object[]>}
|
|
309
|
+
*/
|
|
310
|
+
async listReady(repo, { signal, session } = {}) {
|
|
311
|
+
const cards = await commands.ready(repo, { signal, session });
|
|
312
|
+
return cards.filter((card) => capFor(repo, card?.role) > 0);
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Run one card end to end. Fresh items are claimed here; retried items
|
|
317
|
+
* arrive with `claimed: true` and reuse the claim if it survived the wait.
|
|
318
|
+
* @param {{ repo: string, card: object, claimed?: boolean, signal?: AbortSignal, parent?: object, session?: object, agent?: string, ttl?: string }} request
|
|
319
|
+
* @returns {Promise<object>} card result
|
|
320
|
+
*/
|
|
321
|
+
async runCard({ repo, card, claimed = false, signal, parent, session, agent, ttl }) {
|
|
322
|
+
if (typeof repo !== 'string' || repo === '') throw new TypeError('runCard: repo is required');
|
|
323
|
+
if (card === null || typeof card !== 'object' || typeof card.id !== 'string' || card.id === '') {
|
|
324
|
+
return { id: String(card?.id), state: 'skipped', reason: 'card has no id' };
|
|
325
|
+
}
|
|
326
|
+
const id = card.id;
|
|
327
|
+
const owner = resolveParent(parent);
|
|
328
|
+
let fresh = card;
|
|
329
|
+
try {
|
|
330
|
+
const shown = await commands.show(repo, id, { signal, session });
|
|
331
|
+
if (shown !== null && typeof shown === 'object') fresh = shown;
|
|
332
|
+
} catch {
|
|
333
|
+
// The ready snapshot is enough to render the prompt.
|
|
334
|
+
}
|
|
335
|
+
const agentId = agent ?? config.agent;
|
|
336
|
+
const claimedUntil = fresh.claimedUntil === undefined || fresh.claimedUntil === null
|
|
337
|
+
? Infinity
|
|
338
|
+
: Date.parse(fresh.claimedUntil);
|
|
339
|
+
const claimValid = fresh.state === 'claimed'
|
|
340
|
+
&& fresh.owner === agentId
|
|
341
|
+
&& (Number.isNaN(claimedUntil) || claimedUntil > Date.now());
|
|
342
|
+
const alreadyClaimed = claimed === true && claimValid;
|
|
343
|
+
if (claimed === true && !alreadyClaimed && fresh.state === 'claimed' && fresh.owner !== agentId) {
|
|
344
|
+
return { id, state: 'skipped', reason: 'claim held by ' + String(fresh.owner) };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (!alreadyClaimed) {
|
|
348
|
+
const before = await commands.head(repo, { signal, session });
|
|
349
|
+
const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
|
|
350
|
+
if (claim.exitCode !== 0) {
|
|
351
|
+
return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
|
|
352
|
+
}
|
|
353
|
+
return await executeCard({ repo, card: fresh, before, owner, signal, session });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const before = await commands.head(repo, { signal, session });
|
|
357
|
+
return await executeCard({ repo, card: fresh, before, owner, signal, session });
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export { HiveCommandError };
|
package/lib/shell.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One thin adapter over DSH's shell seam (`ctx.shell.resolve` + `execute`).
|
|
3
|
+
*
|
|
4
|
+
* The shell seam is the only execution path this plugin uses. Deliberately no
|
|
5
|
+
* `node:child_process`: spawning directly would bypass the sandbox, the session
|
|
6
|
+
* sandbox policy, credential scrubbing, output caps and cancellation (see
|
|
7
|
+
* dsh-hive-panel/docs/RESEARCH.md §1).
|
|
8
|
+
*
|
|
9
|
+
* Agent-triggered calls (a tool run) pass the calling `session` so the session's
|
|
10
|
+
* resolved sandbox policy applies. Agentless calls from the supervisor have no
|
|
11
|
+
* session; the deployment default mode is kept, but the resolved policy's
|
|
12
|
+
* workspace root is pinned to the repository being driven, otherwise
|
|
13
|
+
* `workspace-write` would only allow writes under the DSH host cwd.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Trusted in-process caller: parse a complete `--json` document, not a tool-sized tail. */
|
|
17
|
+
export const DEFAULT_STDOUT_MAX_BYTES = 4 * 1024 * 1024;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {{ ctx: object, config: { cliTimeoutMs?: number } }} options
|
|
21
|
+
* @returns {(command: string, options?: object) => Promise<object>}
|
|
22
|
+
*/
|
|
23
|
+
export function createShellRunner({ ctx, config = {} }) {
|
|
24
|
+
if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
|
|
25
|
+
throw new TypeError('createShellRunner: ctx with ctx.get() is required');
|
|
26
|
+
}
|
|
27
|
+
const shell = ctx.get('shell');
|
|
28
|
+
if (shell === undefined || shell === null) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
'hive-runner: ctx.shell is unavailable; mount a bash executor (dsh-bash-sandbox / dsh-bash-local). '
|
|
31
|
+
+ 'Refusing to fall back to child_process because that bypasses the sandbox.',
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
const sandboxPolicy = ctx.get('sandboxPolicy');
|
|
35
|
+
const defaultTimeoutMs = config.cliTimeoutMs ?? 120_000;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Run one already-allowlisted command through the shell seam.
|
|
39
|
+
* @param {string} command shell command string (the seam executes it with bash -c)
|
|
40
|
+
* @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number }} [options]
|
|
41
|
+
* @returns {Promise<{ command: string, exitCode: number | null, signal: string | null, timedOut: boolean, aborted: boolean, stdout: string, stderr: string, sandbox?: object }>}
|
|
42
|
+
*/
|
|
43
|
+
return async function run(command, options = {}) {
|
|
44
|
+
const { workdir, session, signal } = options;
|
|
45
|
+
const request = {
|
|
46
|
+
command,
|
|
47
|
+
timeoutMs: options.timeoutMs ?? defaultTimeoutMs,
|
|
48
|
+
stdoutMaxBytes: options.stdoutMaxBytes ?? DEFAULT_STDOUT_MAX_BYTES,
|
|
49
|
+
};
|
|
50
|
+
if (workdir !== undefined) request.workdir = workdir;
|
|
51
|
+
if (signal !== undefined) request.signal = signal;
|
|
52
|
+
if (sandboxPolicy !== undefined && sandboxPolicy !== null) {
|
|
53
|
+
const base = sandboxPolicy.resolve(session === undefined ? {} : { session });
|
|
54
|
+
request.sandboxPolicy = session === undefined && workdir !== undefined
|
|
55
|
+
? { ...base, workspaceRoot: workdir }
|
|
56
|
+
: base;
|
|
57
|
+
}
|
|
58
|
+
const spec = shell.resolve(request);
|
|
59
|
+
const execution = await shell.execute(spec);
|
|
60
|
+
const result = await execution.result();
|
|
61
|
+
return {
|
|
62
|
+
command: spec.command,
|
|
63
|
+
exitCode: result.exitCode,
|
|
64
|
+
signal: result.signal,
|
|
65
|
+
timedOut: result.timedOut,
|
|
66
|
+
aborted: result.aborted,
|
|
67
|
+
stdout: result.stdout?.text ?? '',
|
|
68
|
+
stderr: result.stderr?.text ?? '',
|
|
69
|
+
sandbox: result.sandbox,
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
}
|