master-orchestrator 0.0.0-stage → 0.2.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 (50) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/package.json +56 -4
  5. package/src/adapters/agy.ts +285 -0
  6. package/src/adapters/claude.ts +317 -0
  7. package/src/adapters/codex.ts +162 -0
  8. package/src/adapters/common.ts +211 -0
  9. package/src/adapters/dsh.ts +356 -0
  10. package/src/adapters/fake-agent.mjs +50 -0
  11. package/src/adapters/fake.ts +88 -0
  12. package/src/adapters/gemini.ts +239 -0
  13. package/src/adapters/grok.ts +328 -0
  14. package/src/adapters/omp.ts +119 -0
  15. package/src/adapters/opencode.ts +228 -0
  16. package/src/adapters/pi.ts +284 -0
  17. package/src/adapters/registry.ts +27 -0
  18. package/src/adapters/types.ts +201 -0
  19. package/src/config/load.ts +290 -0
  20. package/src/config/profiles.ts +64 -0
  21. package/src/config/schema.ts +158 -0
  22. package/src/config/write.ts +83 -0
  23. package/src/engine/artifacts.ts +145 -0
  24. package/src/engine/baseline.ts +132 -0
  25. package/src/engine/execute.ts +437 -0
  26. package/src/engine/git.ts +32 -0
  27. package/src/engine/hostenv.ts +54 -0
  28. package/src/engine/registry.ts +280 -0
  29. package/src/engine/runner.ts +249 -0
  30. package/src/engine/types.ts +55 -0
  31. package/src/engine/verify.ts +100 -0
  32. package/src/index.ts +602 -0
  33. package/src/prompts/envelope.ts +29 -0
  34. package/src/prompts/templates.ts +389 -0
  35. package/src/ui/configure.ts +174 -0
  36. package/src/ui/dialogs.ts +88 -0
  37. package/src/ui/doctor.ts +120 -0
  38. package/src/ui/format.ts +94 -0
  39. package/src/ui/host.ts +100 -0
  40. package/src/ui/render.ts +86 -0
  41. package/src/ui/widget.ts +70 -0
  42. package/src/workflows/budget.ts +66 -0
  43. package/src/workflows/common.ts +100 -0
  44. package/src/workflows/debate.ts +488 -0
  45. package/src/workflows/host.ts +78 -0
  46. package/src/workflows/plan-exec.ts +807 -0
  47. package/src/workflows/plan.ts +407 -0
  48. package/src/workflows/planfile.ts +380 -0
  49. package/src/workflows/planstate.ts +229 -0
  50. package/src/workflows/verdict.ts +74 -0
@@ -0,0 +1,437 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join, relative, resolve } from "node:path";
3
+ import {
4
+ createParserState,
5
+ FALLBACK_STATUSES,
6
+ type AdapterOutcome,
7
+ type AgentAdapter,
8
+ type Detection,
9
+ type HostEnv,
10
+ type NormalizedEvent,
11
+ type RawRunResult,
12
+ type RunRequest,
13
+ } from "../adapters/types.ts";
14
+ import { resolveProfile, type ResolvedProfile } from "../config/profiles.ts";
15
+ import type { OrchestratorConfig } from "../config/schema.ts";
16
+ import { buildEnvelope } from "../prompts/envelope.ts";
17
+ import type { Templates } from "../prompts/templates.ts";
18
+ import { createRunDir, lockPath, newRunId, readMeta, realWorkspace, runsRoot, writeMeta, type RunMeta } from "./artifacts.ts";
19
+ import { diffBaseline, takeBaseline } from "./baseline.ts";
20
+ import { createHostEnv } from "./hostenv.ts";
21
+ import { acquireWriteLock, type LockHandle, type RunRegistry } from "./registry.ts";
22
+ import { runProcess } from "./runner.ts";
23
+ import type { Assignment, Executor, RunAttempt, RunResult } from "./types.ts";
24
+ import { classifyChanges } from "./verify.ts";
25
+
26
+ export const DEPTH_ENV = "MASTER_ORCHESTRATOR_DEPTH";
27
+
28
+ export interface EngineDeps {
29
+ agentDir: string;
30
+ getConfig(): OrchestratorConfig;
31
+ adapters: ReadonlyMap<string, AgentAdapter>;
32
+ registry: RunRegistry;
33
+ getTemplates(): Templates;
34
+ projectTrusted(): boolean;
35
+ instanceId: string;
36
+ sessionId(): string | undefined;
37
+ /** This process's own depth (0 for the user's pi). */
38
+ depth: number;
39
+ /** Stop-sequence step, 10 s by default; shortened in tests. */
40
+ graceMs?: number;
41
+ /** Milliseconds per configured timeout minute; shortened in tests. */
42
+ msPerTimeoutMinute?: number;
43
+ /** Replaces host lookups in tests. */
44
+ hostEnvFactory?: (bin: string, cwd: string, env: Record<string, string>) => HostEnv;
45
+ }
46
+
47
+ export class Engine implements Executor {
48
+ private readonly deps: EngineDeps;
49
+ private readonly detections = new Map<string, Promise<Detection>>();
50
+ private readonly sessionChains = new Map<string, Promise<unknown>>();
51
+
52
+ constructor(deps: EngineDeps) {
53
+ this.deps = deps;
54
+ }
55
+
56
+ get adapters(): ReadonlyMap<string, AgentAdapter> {
57
+ return this.deps.adapters;
58
+ }
59
+
60
+ hostEnv(agent: string, cwd: string): HostEnv {
61
+ const adapter = this.requireAdapter(agent);
62
+ const settings = this.deps.getConfig().agents[agent] ?? {};
63
+ const bin = settings.bin ?? adapter.binary;
64
+ const factory = this.deps.hostEnvFactory ?? createHostEnv;
65
+ return factory(bin, cwd, settings.env ?? {});
66
+ }
67
+
68
+ /** Detection runs once per agent and extension instance. */
69
+ detect(agent: string, cwd = process.cwd()): Promise<Detection> {
70
+ let pending = this.detections.get(agent);
71
+ if (!pending) {
72
+ const adapter = this.requireAdapter(agent);
73
+ pending = adapter.detect(this.hostEnv(agent, cwd)).catch((error: Error) => ({ available: false, error: error.message }));
74
+ this.detections.set(agent, pending);
75
+ }
76
+ return pending;
77
+ }
78
+
79
+ clearDetections(): void {
80
+ this.detections.clear();
81
+ }
82
+
83
+ resolve(name: string): ResolvedProfile | undefined {
84
+ return resolveProfile(this.deps.getConfig(), this.deps.adapters, name);
85
+ }
86
+
87
+ /** Whether an agent can run now; the reason when it cannot. */
88
+ async availability(agent: string): Promise<{ ok: true; detection: Detection; warnings: string[] } | { ok: false; reason: string }> {
89
+ const adapter = this.deps.adapters.get(agent);
90
+ if (!adapter) return { ok: false, reason: `unknown_agent: no adapter for "${agent}"` };
91
+ const settings = this.deps.getConfig().agents[agent] ?? {};
92
+ if (settings.enabled === false) return { ok: false, reason: `disabled: agents.${agent}.enabled is false` };
93
+ const detection = await this.detect(agent);
94
+ if (!detection.available) return { ok: false, reason: `not_installed: ${detection.error ?? `${adapter.binary} not found`}` };
95
+ const warnings: string[] = [];
96
+ if (detection.inTestedRange === false) {
97
+ const message = `${adapter.displayName} ${detection.version} is outside the tested range ${adapter.testedVersions}`;
98
+ if (settings.allowUntestedVersion === false) return { ok: false, reason: `untested_version: ${message}` };
99
+ warnings.push(message);
100
+ } else if (detection.inTestedRange === undefined) {
101
+ warnings.push(`${adapter.displayName}: version unknown, not checked against ${adapter.testedVersions}`);
102
+ }
103
+ if (adapter.stability === "experimental") warnings.push(`${adapter.displayName} adapter is experimental (verification pass incomplete)`);
104
+ return { ok: true, detection, warnings };
105
+ }
106
+
107
+ /** Finds an earlier run of this workspace by id (for follow-ups). */
108
+ async findRun(workspace: string, runId: string): Promise<RunMeta | undefined> {
109
+ if (!/^[A-Za-z0-9._-]+$/.test(runId)) return undefined;
110
+ return readMeta(join(runsRoot(this.deps.agentDir, workspace), runId));
111
+ }
112
+
113
+ async run(assignment: Assignment): Promise<RunResult> {
114
+ if (assignment.profiles.length === 0) throw new Error("No profile to run the assignment with.");
115
+ if (assignment.followUp && assignment.profiles.length !== 1) throw new Error("A follow-up runs on exactly one profile.");
116
+ const workspace = realWorkspace(resolve(assignment.workspace));
117
+
118
+ // Follow-ups on one session run one after the other.
119
+ const sessionKey = assignment.followUp ? `${assignment.profiles[0]}:${assignment.followUp.sessionId}` : undefined;
120
+ if (sessionKey) {
121
+ const previous = this.sessionChains.get(sessionKey);
122
+ const current = (previous ?? Promise.resolve()).catch(() => undefined).then(() => this.runChain(assignment, workspace));
123
+ this.sessionChains.set(sessionKey, current);
124
+ try {
125
+ return await current;
126
+ } finally {
127
+ if (this.sessionChains.get(sessionKey) === current) this.sessionChains.delete(sessionKey);
128
+ }
129
+ }
130
+ return this.runChain(assignment, workspace);
131
+ }
132
+
133
+ private async runChain(assignment: Assignment, workspace: string): Promise<RunResult> {
134
+ const config = this.deps.getConfig();
135
+ let lock: LockHandle | undefined;
136
+ let releaseSlot: (() => void) | undefined;
137
+ const firstRunId = newRunId(this.resolve(assignment.profiles[0])?.agent ?? "run");
138
+ try {
139
+ if (assignment.mode === "implement" && !assignment.lock) {
140
+ lock = await acquireWriteLock(lockPath(this.deps.agentDir, workspace), {
141
+ instanceId: this.deps.instanceId,
142
+ sessionId: this.deps.sessionId(),
143
+ owner: `run:${firstRunId}`,
144
+ workspace,
145
+ });
146
+ }
147
+ if (assignment.mode === "analyze") releaseSlot = await this.deps.registry.acquireAnalyzeSlot(assignment.signal);
148
+
149
+ const attempts: RunAttempt[] = [];
150
+ let last: RunResult | undefined;
151
+ for (let index = 0; index < assignment.profiles.length; index++) {
152
+ const name = assignment.profiles[index];
153
+ const profile = this.resolve(name);
154
+ if (!profile) {
155
+ attempts.push({ profile: name, agent: "?", status: "unavailable", reason: `unknown_profile: "${name}"` });
156
+ continue;
157
+ }
158
+ const result = await this.attempt(profile, assignment, workspace, index === 0 ? firstRunId : newRunId(profile.agent), config);
159
+ last = { ...result, attempts: [...attempts] };
160
+ const canFallback = FALLBACK_STATUSES.includes(result.status) && index < assignment.profiles.length - 1;
161
+ if (!canFallback || assignment.signal?.aborted) return last;
162
+ attempts.push({ profile: name, agent: profile.agent, status: result.status, reason: result.reason, runId: result.runId });
163
+ }
164
+ if (last) return last;
165
+ const reason = attempts.map((attempt) => `${attempt.profile}: ${attempt.reason}`).join("; ");
166
+ throw new Error(`No profile could run the assignment (${reason}).`);
167
+ } finally {
168
+ releaseSlot?.();
169
+ lock?.release();
170
+ }
171
+ }
172
+
173
+ private async attempt(
174
+ profile: ResolvedProfile,
175
+ assignment: Assignment,
176
+ workspace: string,
177
+ runId: string,
178
+ config: OrchestratorConfig,
179
+ ): Promise<RunResult> {
180
+ const adapter = this.requireAdapter(profile.agent);
181
+ const startedAt = Date.now();
182
+ const runDir = await createRunDir(this.deps.agentDir, workspace, runId);
183
+ const settings = config.agents[profile.agent] ?? {};
184
+ const meta: RunMeta = {
185
+ runId,
186
+ profile: profile.name,
187
+ agent: profile.agent,
188
+ model: profile.model,
189
+ effort: profile.effort,
190
+ mode: assignment.mode,
191
+ workspace,
192
+ startedAt: new Date(startedAt).toISOString(),
193
+ workflowId: assignment.workflowId,
194
+ label: assignment.label,
195
+ };
196
+ const empty = (outcome: AdapterOutcome, warnings: string[] = []): RunResult => ({
197
+ ...outcome,
198
+ runId,
199
+ profile: profile.name,
200
+ agent: profile.agent,
201
+ model: profile.model,
202
+ mode: assignment.mode,
203
+ durationMs: Date.now() - startedAt,
204
+ changedFiles: [],
205
+ unexpectedChanges: [],
206
+ outOfScopeChanges: [],
207
+ gitPolicyDepartures: [],
208
+ artifactsDir: runDir,
209
+ attempts: [],
210
+ warnings,
211
+ overlappingRuns: [],
212
+ changeNote: "The run did not start; nothing changed.",
213
+ resumable: false,
214
+ });
215
+
216
+ const availability = await this.availability(profile.agent);
217
+ if (!availability.ok) {
218
+ const result = empty({ status: "unavailable", reason: availability.reason, deniedActions: [] });
219
+ await this.writeOutcome(runDir, meta, result);
220
+ return result;
221
+ }
222
+ const warnings = [...availability.warnings];
223
+ if (assignment.followUp && !adapter.capabilities.resume) {
224
+ const result = empty({ status: "unavailable", reason: `no_resume: ${adapter.displayName} cannot resume a session`, deniedActions: [] }, warnings);
225
+ await this.writeOutcome(runDir, meta, result);
226
+ return result;
227
+ }
228
+
229
+ const prompt = buildEnvelope(this.deps.getTemplates(), {
230
+ task: assignment.task,
231
+ mode: assignment.mode,
232
+ scope: assignment.scope,
233
+ workspace,
234
+ scratch: join(runDir, "scratch"),
235
+ });
236
+ await writeFile(join(runDir, "prompt.md"), prompt);
237
+
238
+ const request: RunRequest = {
239
+ workspace,
240
+ prompt,
241
+ runDir,
242
+ projectTrusted: this.deps.projectTrusted(),
243
+ model: profile.model,
244
+ effort: profile.effort,
245
+ sessionId: assignment.followUp?.sessionId,
246
+ outputSchema: assignment.outputSchema,
247
+ options: profile.options,
248
+ extraArgs: settings.extraArgs,
249
+ env: settings.env,
250
+ agentConfig: settings as Record<string, unknown>,
251
+ };
252
+ let invocation;
253
+ try {
254
+ invocation = adapter.buildInvocation(request);
255
+ } catch (error) {
256
+ const result = empty({ status: "unavailable", reason: `invalid_invocation: ${(error as Error).message}`, deniedActions: [] }, warnings);
257
+ await this.writeOutcome(runDir, meta, result);
258
+ return result;
259
+ }
260
+ for (const file of invocation.files ?? []) {
261
+ const rel = relative(runDir, file.path);
262
+ if (rel.startsWith("..") || resolve(runDir, rel) !== resolve(file.path)) {
263
+ throw new Error(`Adapter ${adapter.id} tried to write outside the run directory: ${file.path}`);
264
+ }
265
+ await writeFile(file.path, file.content);
266
+ }
267
+
268
+ const env = buildChildEnv(process.env, settings.env, invocation.env, this.deps.depth);
269
+ const baseline = await takeBaseline(workspace);
270
+ const controller = new AbortController();
271
+ const onAbort = () => controller.abort();
272
+ assignment.signal?.addEventListener("abort", onAbort, { once: true });
273
+ if (assignment.signal?.aborted) controller.abort();
274
+
275
+ const active = {
276
+ runId,
277
+ profile: profile.name,
278
+ agent: profile.agent,
279
+ model: profile.model,
280
+ mode: assignment.mode,
281
+ workspace,
282
+ label: assignment.label,
283
+ workflowId: assignment.workflowId,
284
+ startedAt,
285
+ controller,
286
+ overlaps: new Set<string>(),
287
+ };
288
+ this.deps.registry.add(active);
289
+ meta.args = invocation.args;
290
+ await writeMeta(runDir, meta);
291
+
292
+ const state = createParserState();
293
+ const handle = (event: NormalizedEvent) => {
294
+ if (event.type === "activity") this.deps.registry.update(runId, { lastActivity: event.summary });
295
+ else if (event.type === "denied") this.deps.registry.update(runId, { lastActivity: `denied: ${event.action}` });
296
+ else if (event.type === "warning") warnings.push(event.message);
297
+ assignment.onEvent?.(runId, event);
298
+ };
299
+
300
+ const timeoutMinutes = profile.timeoutMinutes ?? config.defaults.timeoutMinutes;
301
+ const detection = availability.detection;
302
+ let stalled: ReturnType<NonNullable<AgentAdapter["watchStderr"]>>;
303
+ let outcomeRaw;
304
+ try {
305
+ outcomeRaw = await runProcess({
306
+ command: detection.path ?? settings.bin ?? adapter.binary,
307
+ args: invocation.args,
308
+ cwd: invocation.cwd,
309
+ env,
310
+ stdin: invocation.stdin,
311
+ timeoutMs: timeoutMinutes * (this.deps.msPerTimeoutMinute ?? 60_000),
312
+ stopSignal: adapter.stopSignal,
313
+ graceMs: this.deps.graceMs,
314
+ signal: controller.signal,
315
+ eventsPath: join(runDir, "events.jsonl"),
316
+ stderrPath: join(runDir, "stderr.log"),
317
+ onLine: (line) => {
318
+ for (const event of adapter.parseEvent(line, state)) handle(event);
319
+ },
320
+ onStderr: adapter.watchStderr
321
+ ? (tail) => {
322
+ if (stalled) return;
323
+ stalled = adapter.watchStderr?.(tail);
324
+ if (stalled) controller.abort();
325
+ }
326
+ : undefined,
327
+ });
328
+ } catch (error) {
329
+ this.deps.registry.remove(runId);
330
+ throw error;
331
+ } finally {
332
+ assignment.signal?.removeEventListener("abort", onAbort);
333
+ }
334
+
335
+ const outputFiles: Record<string, string | undefined> = {};
336
+ for (const [name, path] of Object.entries(invocation.outputFiles ?? {})) {
337
+ try {
338
+ outputFiles[name] = await readFile(path, "utf8");
339
+ } catch {
340
+ outputFiles[name] = undefined;
341
+ }
342
+ }
343
+ const raw: RawRunResult = {
344
+ exitCode: outcomeRaw.exitCode,
345
+ signal: outcomeRaw.signal,
346
+ stderr: outcomeRaw.stderrTail,
347
+ outputFiles,
348
+ timedOut: outcomeRaw.timedOut,
349
+ cancelled: outcomeRaw.cancelled,
350
+ spawnError: outcomeRaw.spawnError,
351
+ };
352
+ let outcome: AdapterOutcome;
353
+ try {
354
+ outcome = adapter.finalize(raw, state);
355
+ } catch (error) {
356
+ outcome = { status: "failed", reason: `adapter_error: ${(error as Error).message}`, deniedActions: [...state.denied] };
357
+ }
358
+ if (stalled) outcome = { ...outcome, status: stalled.status, reason: stalled.reason };
359
+ else if (raw.cancelled) outcome = { ...outcome, status: "cancelled", reason: "cancelled: stopped on request" };
360
+ else if (raw.timedOut) outcome = { ...outcome, status: "timeout", reason: `timeout: no result after ${timeoutMinutes} min` };
361
+ if (outcome.warnings) warnings.push(...outcome.warnings);
362
+ meta.exitCode = raw.exitCode;
363
+ meta.signal = raw.signal;
364
+
365
+ const overlappingRuns = [...active.overlaps];
366
+ this.deps.registry.remove(runId);
367
+ const changes = await diffBaseline(workspace, baseline);
368
+ const classification = classifyChanges(assignment.mode, changes.changed, assignment.scope);
369
+
370
+ const result: RunResult = {
371
+ ...outcome,
372
+ runId,
373
+ profile: profile.name,
374
+ agent: profile.agent,
375
+ model: profile.model,
376
+ mode: assignment.mode,
377
+ durationMs: Date.now() - startedAt,
378
+ changedFiles: changes.changed,
379
+ unexpectedChanges: classification.unexpectedChanges,
380
+ outOfScopeChanges: classification.outOfScopeChanges,
381
+ gitPolicyDepartures: changes.departures,
382
+ artifactsDir: runDir,
383
+ attempts: [],
384
+ warnings: [...new Set(warnings)],
385
+ overlappingRuns,
386
+ changeNote:
387
+ overlappingRuns.length > 0 && changes.git
388
+ ? `${changes.note} Runs ${overlappingRuns.join(", ")} overlapped in this workspace; changes are attributed to the group, not to this run alone.`
389
+ : changes.note,
390
+ resumable: adapter.capabilities.resume && Boolean(outcome.sessionId),
391
+ };
392
+ await this.writeOutcome(runDir, meta, result);
393
+ return result;
394
+ }
395
+
396
+ private async writeOutcome(runDir: string, meta: RunMeta, result: RunResult): Promise<void> {
397
+ const body = result.finalText?.trim() ? result.finalText : `(no final answer: ${result.reason ?? result.status})`;
398
+ await writeFile(join(runDir, "result.md"), `${body.trimEnd()}\n`);
399
+ await writeMeta(runDir, {
400
+ ...meta,
401
+ endedAt: new Date().toISOString(),
402
+ status: result.status,
403
+ reason: result.reason,
404
+ sessionId: result.sessionId,
405
+ });
406
+ }
407
+
408
+ private requireAdapter(agent: string): AgentAdapter {
409
+ const adapter = this.deps.adapters.get(agent);
410
+ if (!adapter) throw new Error(`No adapter for agent "${agent}".`);
411
+ return adapter;
412
+ }
413
+ }
414
+
415
+ /** Parent environment, plus configured and adapter additions, plus the recursion depth. */
416
+ export function buildChildEnv(
417
+ parent: NodeJS.ProcessEnv,
418
+ configured: Record<string, string> | undefined,
419
+ adapterEnv: Record<string, string | null> | undefined,
420
+ depth: number,
421
+ ): Record<string, string> {
422
+ const env: Record<string, string> = {};
423
+ for (const [key, value] of Object.entries(parent)) if (value !== undefined) env[key] = value;
424
+ for (const [key, value] of Object.entries(configured ?? {})) env[key] = value;
425
+ for (const [key, value] of Object.entries(adapterEnv ?? {})) {
426
+ if (value === null) delete env[key];
427
+ else env[key] = value;
428
+ }
429
+ env[DEPTH_ENV] = String(depth + 1);
430
+ return env;
431
+ }
432
+
433
+ /** Depth of the current process: 0 for the user's own pi, 1 or more inside a worker. */
434
+ export function currentDepth(env: NodeJS.ProcessEnv = process.env): number {
435
+ const value = Number.parseInt(env[DEPTH_ENV] ?? "0", 10);
436
+ return Number.isFinite(value) && value > 0 ? value : 0;
437
+ }
@@ -0,0 +1,32 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ export interface GitResult {
4
+ code: number;
5
+ stdout: string;
6
+ stderr: string;
7
+ }
8
+
9
+ /** Runs git without a shell. Never throws for a non-zero exit. */
10
+ export function git(cwd: string, args: string[], options: { timeoutMs?: number } = {}): Promise<GitResult> {
11
+ return new Promise((resolve) => {
12
+ execFile(
13
+ "git",
14
+ args,
15
+ {
16
+ cwd,
17
+ timeout: options.timeoutMs ?? 60_000,
18
+ maxBuffer: 256 * 1024 * 1024,
19
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
20
+ },
21
+ (error, stdout, stderr) => {
22
+ const code = error ? (typeof (error as { code?: unknown }).code === "number" ? ((error as { code: number }).code) : 1) : 0;
23
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
24
+ },
25
+ );
26
+ });
27
+ }
28
+
29
+ export async function gitOk(cwd: string, args: string[]): Promise<string | undefined> {
30
+ const result = await git(cwd, args);
31
+ return result.code === 0 ? result.stdout.trim() : undefined;
32
+ }
@@ -0,0 +1,54 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access, constants } from "node:fs/promises";
3
+ import { delimiter, isAbsolute, join, resolve } from "node:path";
4
+ import type { ExecOptions, ExecResult, HostEnv } from "../adapters/types.ts";
5
+
6
+ /** Finds an executable: a path is checked as is, a bare name is searched on PATH. */
7
+ export async function which(command: string, env: Record<string, string | undefined> = process.env, cwd = process.cwd()): Promise<string | undefined> {
8
+ const candidates = command.includes("/")
9
+ ? [isAbsolute(command) ? command : resolve(cwd, command)]
10
+ : (env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => join(dir, command));
11
+ for (const candidate of candidates) {
12
+ try {
13
+ await access(candidate, constants.X_OK);
14
+ return candidate;
15
+ } catch {
16
+ // Not here.
17
+ }
18
+ }
19
+ return undefined;
20
+ }
21
+
22
+ export function execCommand(command: string, args: string[], options: ExecOptions = {}): Promise<ExecResult> {
23
+ return new Promise((resolvePromise) => {
24
+ execFile(
25
+ command,
26
+ args,
27
+ {
28
+ cwd: options.cwd,
29
+ timeout: options.timeoutMs ?? 30_000,
30
+ maxBuffer: 16 * 1024 * 1024,
31
+ env: { ...process.env, ...options.env } as NodeJS.ProcessEnv,
32
+ },
33
+ (error, stdout, stderr) => {
34
+ if (error && typeof (error as NodeJS.ErrnoException).code === "string") {
35
+ resolvePromise({ code: null, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), error: `${command}: ${(error as NodeJS.ErrnoException).code}` });
36
+ return;
37
+ }
38
+ const code = error ? (((error as { code?: number }).code ?? 1) as number) : 0;
39
+ resolvePromise({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
40
+ },
41
+ );
42
+ });
43
+ }
44
+
45
+ export function createHostEnv(bin: string, cwd: string, extraEnv: Record<string, string> = {}): HostEnv {
46
+ const env = { ...process.env, ...extraEnv };
47
+ return {
48
+ bin,
49
+ cwd,
50
+ env,
51
+ exec: (command, args, options) => execCommand(command, args, { cwd, ...options, env: { ...extraEnv, ...options?.env } }),
52
+ which: (command) => which(command, env, cwd),
53
+ };
54
+ }