@bakers-build/conductor 0.9.1-next.5 → 0.9.1-next.7

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.
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { basename, dirname, join } from 'node:path';
3
- import { killRunProcesses, shellQuote, stemForConfigFile, } from '@bakers-build/core';
3
+ import { killRunProcesses, loadRunClone, protectedProjectPaths, saveRunClone, shellQuote, stemForConfigFile, transferIsolatedCommit, } from '@bakers-build/core';
4
4
  import { CONDUCTOR_TOKEN_ENV, CONDUCTOR_URL_ENV, DEFAULT_ENV_DENY, matchesEnvDeny, } from '../plugins/agent.js';
5
5
  import { homeKey, homePath } from '../plugins/agent-home.js';
6
6
  import { resolveAgent } from '../plugins/plugins.js';
@@ -293,16 +293,18 @@ export class Conductor {
293
293
  */
294
294
  async startTools(endpointFile) {
295
295
  const { siteTools } = this.remote;
296
+ const runtime = await this.runtime();
296
297
  if ((!this.config.tools && !siteTools) || this.toolServer)
297
298
  return;
298
- const hosts = (await (await this.runtime()).toolServerHosts?.()) ?? [];
299
+ const hosts = (await runtime.toolServerHosts?.()) ?? [];
300
+ const registry = this.config.tools ?? (await loadTools([]));
299
301
  // Runs closed while no server ran (`oven once`, a crash) lose their grant here.
300
302
  const openRuns = await this.remote.fetchActiveRuns(this.id).then((runs) => runs.map((r) => r.runUuid), (err) => {
301
303
  this.logger.warn({ err: String(err) }, 'active runs unreadable, keeping every persisted run grant');
302
304
  return undefined;
303
305
  });
304
306
  this.toolServer = await startToolServer({
305
- registry: this.config.tools ?? (await loadTools([])),
307
+ registry,
306
308
  workspaceRoot: this.checkoutRoot,
307
309
  logger: this.logger,
308
310
  ...(endpointFile ? { endpointFile } : {}),
@@ -329,8 +331,9 @@ export class Conductor {
329
331
  /** Tell an open `bakers ui` in the checkout (and the run's worktree) to reload. */
330
332
  signalUi(worktree) {
331
333
  signalUi(this.checkoutRoot);
334
+ // A run clone keeps its own exclude; the host runs no Git in its workspace.
332
335
  if (worktree)
333
- signalUi(worktree);
336
+ signalUi(worktree, !loadRunClone(worktree));
334
337
  }
335
338
  async stopTools() {
336
339
  // Server first, so no new provision_up starts a run after the stop.
@@ -569,6 +572,7 @@ export class Conductor {
569
572
  // The transcript is captured, so killing the PTY is safe (BB-171).
570
573
  if (branch)
571
574
  await this.closeRunTab(branch, r.runUuid, r.runId);
575
+ await this.transferRunCommits(r.worktreePath, r.runUuid);
572
576
  // BB-599: `after_run` fires at run end — after the worker is gone,
573
577
  // before the durable close. A failed close write repeats it next tick,
574
578
  // which is why listeners must be idempotent.
@@ -592,6 +596,25 @@ export class Conductor {
592
596
  this.logger.warn({ run: r.runUuid, err: String(err) }, 'run finalise failed');
593
597
  }
594
598
  }
599
+ /**
600
+ * Bring an isolated run's commits to the ticket branch in the parent
601
+ * repository. Best-effort: a refused transfer is logged and leaves the run's
602
+ * Git directory in place until the next run of the ticket starts.
603
+ */
604
+ async transferRunCommits(worktreePath, runUuid) {
605
+ const clone = worktreePath ? loadRunClone(worktreePath) : undefined;
606
+ if (!clone)
607
+ return;
608
+ try {
609
+ await this.serialGit(async () => {
610
+ const tip = transferIsolatedCommit(clone);
611
+ saveRunClone({ ...clone, expected: tip });
612
+ });
613
+ }
614
+ catch (err) {
615
+ this.logger.warn({ run: runUuid, branch: clone.branch, err: String(err) }, 'run commits not transferred to the ticket branch');
616
+ }
617
+ }
595
618
  /** Read the run's transcript and parse its footprint for the close write. */
596
619
  async captureRun(r) {
597
620
  // Route to the agent that actually ran (BB-144): the persisted
@@ -773,7 +796,8 @@ export class Conductor {
773
796
  });
774
797
  }
775
798
  }
776
- const shell = await this.runHook(name, cwd, { ticket: ticketRef }, shellEnv);
799
+ // Host scripts take the worktree from here: a run clone has no Git to ask.
800
+ const shell = await this.runHook(name, cwd, { ticket: ticketRef }, { ...shellEnv, BAKERS_WORKTREE_PATH: cwd });
777
801
  if (failed.length === 0)
778
802
  return shell;
779
803
  const error = `hook listener failed: ${failed.join(', ')}`;
@@ -962,7 +986,11 @@ export class Conductor {
962
986
  if (!t.baseBranch)
963
987
  throw new Error('ticket has no base branch');
964
988
  // Under the git lock: workspace.ensure fetches the same ref into this repo.
965
- const values = await this.serialGit(() => measureMrChanges(t.worktreePath, t.baseBranch));
989
+ const values = await this.serialGit(() =>
990
+ // A run clone has no Git on the host: measure its branch in the parent.
991
+ loadRunClone(t.worktreePath)
992
+ ? measureMrChanges(this.checkoutRoot, t.baseBranch, t.branchName)
993
+ : measureMrChanges(t.worktreePath, t.baseBranch));
966
994
  await this.remote.replaceTicketMetrics(t.ticketUuid, 'mr_changes.', mrChangesRows(values, Math.floor(Date.now() / 1000)));
967
995
  }
968
996
  catch (err) {
@@ -1144,7 +1172,11 @@ export class Conductor {
1144
1172
  ...(t.identifier ? { BAKERS_TICKET_IDENTIFIER: t.identifier } : {}),
1145
1173
  ...(state ? { BAKERS_STATE: state } : {}),
1146
1174
  ...(runUuid ? { BAKERS_RUN_UUID: runUuid } : {}),
1175
+ // A host script names the worktree's DDEV project after it without asking Git.
1176
+ ...(t.branchName ? { BAKERS_BRANCH_NAME: t.branchName } : {}),
1147
1177
  BAKERS_TUNNEL: (await this.currentTunnel()) ? '1' : '0',
1178
+ // Host scripts skip what an isolated run does in its own container.
1179
+ BAKERS_RUNTIME_ISOLATES: this.config.runtime?.isolates ? '1' : '0',
1148
1180
  WORKSPACE_ROOT: this.checkoutRoot,
1149
1181
  ...(t.issueUrl ? { TICKET_URL: t.issueUrl } : {}),
1150
1182
  ...(t.projectName ? { BAKERS_PROJECT: t.projectName } : {}),
@@ -1277,6 +1309,13 @@ export class Conductor {
1277
1309
  const env = await this.runEnv(t, run.runUuid, run.stateAtStart, chosen.agent);
1278
1310
  const ws = await this.serialGit(() => this.workspace.ensure(t.identifier, t.branchName, baseRef));
1279
1311
  at.worktree = ws.path;
1312
+ // The transfer checks the project's list; the record is the host's alone.
1313
+ if (ws.clone)
1314
+ saveRunClone({
1315
+ ...ws.clone,
1316
+ protectedPaths: this.config.readOnly ?? [],
1317
+ });
1318
+ env.BAKERS_WORKTREE_PATH = ws.path;
1280
1319
  // The backend's own vars (Git config) join the run env; core keys still win.
1281
1320
  for (const [key, value] of Object.entries(ws.env ?? {})) {
1282
1321
  if (!isReservedEnvKey(key))
@@ -1387,7 +1426,7 @@ export class Conductor {
1387
1426
  await this.executor.cleanupRun(t.branchName, run.runId);
1388
1427
  await this.cleanupRuntime(run.runUuid, run.runId);
1389
1428
  const runtime = await this.runtime();
1390
- const prompt = ws.instructions
1429
+ let prompt = ws.instructions
1391
1430
  ? renderPrompt(this.config.prompt, {
1392
1431
  identifier: t.identifier,
1393
1432
  state: t.state || 'qualification',
@@ -1395,6 +1434,13 @@ export class Conductor {
1395
1434
  ticketUuid: t.uuid,
1396
1435
  })
1397
1436
  : '';
1437
+ if (prompt && ws.clone)
1438
+ prompt +=
1439
+ '\n\nRuntime context: this run works in a fresh clone of the ticket branch. ' +
1440
+ 'Commit before you end: uncommitted work is not carried over. ' +
1441
+ 'forge_fetch refreshes the origin refs and forge_push transfers and pushes your commits. ' +
1442
+ `Read-only here: ${['.bakers', ...(this.config.readOnly ?? [])].filter((path, index, all) => all.indexOf(path) === index).join(', ')}. ` +
1443
+ 'If merging the target fails on one of them, report it: a maintainer merges the target outside the run.';
1398
1444
  // BB-473 review round 2 (Critical 1): pinning the run's own UUID
1399
1445
  // unconditionally makes a re-dispatch of the same run — an existing,
1400
1446
  // supported path (see the cleanupRun comment above) — fail to launch,
@@ -1463,7 +1509,14 @@ export class Conductor {
1463
1509
  : undefined;
1464
1510
  if (preparation)
1465
1511
  Object.assign(env, preparation.env);
1466
- const command = chosen.agent.launchCommand(prompt, identity, ws.path, toolsUrl ? { url: toolsUrl } : undefined, env, plugins.args);
1512
+ const isolates = this.config.runtime?.isolates === true;
1513
+ // An isolated run without its own clone would share the parent's Git data.
1514
+ if (isolates && !ws.clone)
1515
+ throw new Error('the runtime isolates runs, but the workspace provides no run clone');
1516
+ const protectedPaths = isolates
1517
+ ? protectedProjectPaths(ws.path, this.config.readOnly ?? [])
1518
+ : [];
1519
+ const command = chosen.agent.launchCommand(prompt, identity, ws.path, toolsUrl ? { url: toolsUrl } : undefined, env, plugins.args, isolates);
1467
1520
  // Read after launchCommand: a warning may depend on what this launch got.
1468
1521
  const warnings = chosen.agent.launchWarnings;
1469
1522
  if (warnings?.length) {
@@ -1490,16 +1543,31 @@ export class Conductor {
1490
1543
  command,
1491
1544
  env: runEnv,
1492
1545
  workspacePath: ws.path,
1546
+ ...(ws.clone
1547
+ ? {
1548
+ gitDir: ws.clone.gitDir,
1549
+ ...(ws.clone.shared
1550
+ ? { sharedObjects: join(ws.clone.parentGitDir, 'objects') }
1551
+ : {}),
1552
+ }
1553
+ : {}),
1493
1554
  run: { uuid: run.runUuid, id: run.runId },
1494
1555
  harness: chosen.agent.id,
1495
1556
  ...agentInfo,
1496
1557
  ...(runtimeContext
1497
1558
  ? {
1498
1559
  homePath: runtimeContext.homePath,
1499
- readPaths: preparation?.readPaths ?? [],
1560
+ readPaths: [
1561
+ ...(preparation?.readPaths ?? []),
1562
+ ...(isolates ? protectedPaths : []),
1563
+ ],
1500
1564
  writePaths: preparation?.writePaths ?? [],
1565
+ ...(preparation?.bindPaths?.length
1566
+ ? { bindPaths: preparation.bindPaths }
1567
+ : {}),
1501
1568
  }
1502
1569
  : {}),
1570
+ ...(isolates && !runtimeContext ? { readPaths: protectedPaths } : {}),
1503
1571
  });
1504
1572
  await this.executor.startRun({
1505
1573
  ticket: {
@@ -14,5 +14,7 @@ export declare function mrChangesRows(v: MrChanges, recorded: number): TicketMet
14
14
  * Measures the ticket branch checked out in `worktreePath` against the merge
15
15
  * base with `origin/<baseBranch>` — the diff the merge request's Changes tab
16
16
  * shows. `HEAD`, not the remote branch: a merge deletes the remote branch.
17
+ * With `branch`, `worktreePath` is the parent repository and the local branch
18
+ * is measured: an isolated run's workspace has no Git on the host.
17
19
  */
18
- export declare function measureMrChanges(worktreePath: string, baseBranch: string): Promise<MrChanges>;
20
+ export declare function measureMrChanges(worktreePath: string, baseBranch: string, branch?: string): Promise<MrChanges>;
@@ -39,11 +39,18 @@ export function mrChangesRows(v, recorded) {
39
39
  * Measures the ticket branch checked out in `worktreePath` against the merge
40
40
  * base with `origin/<baseBranch>` — the diff the merge request's Changes tab
41
41
  * shows. `HEAD`, not the remote branch: a merge deletes the remote branch.
42
+ * With `branch`, `worktreePath` is the parent repository and the local branch
43
+ * is measured: an isolated run's workspace has no Git on the host.
42
44
  */
43
- export async function measureMrChanges(worktreePath, baseBranch) {
45
+ export async function measureMrChanges(worktreePath, baseBranch, branch) {
44
46
  await exec('git', ['fetch', 'origin', '--', baseBranch], {
45
47
  cwd: worktreePath,
46
48
  });
47
- const out = await exec('git', ['diff', '--numstat', '-M', `origin/${baseBranch}...HEAD`], { cwd: worktreePath });
49
+ const out = await exec('git', [
50
+ 'diff',
51
+ '--numstat',
52
+ '-M',
53
+ `origin/${baseBranch}...${branch ? `refs/heads/${branch}` : 'HEAD'}`,
54
+ ], { cwd: worktreePath });
48
55
  return parseNumstat(out);
49
56
  }
@@ -1,2 +1,5 @@
1
- /** Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws. */
2
- export declare function signalUi(dir: string): void;
1
+ /**
2
+ * Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws.
3
+ * `exclude: false` runs no Git in `dir`.
4
+ */
5
+ export declare function signalUi(dir: string, exclude?: boolean): void;
@@ -31,11 +31,15 @@ function ensureExcluded(dir) {
31
31
  // Not a git dir, or unwritable: the file just shows as untracked.
32
32
  }
33
33
  }
34
- /** Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws. */
35
- export function signalUi(dir) {
34
+ /**
35
+ * Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws.
36
+ * `exclude: false` runs no Git in `dir`.
37
+ */
38
+ export function signalUi(dir, exclude = true) {
36
39
  const bakersDir = configHomeOf(dir);
37
40
  if (!existsSync(bakersDir))
38
41
  return;
39
- ensureExcluded(dir);
42
+ if (exclude)
43
+ ensureExcluded(dir);
40
44
  bumpUiRefresh(bakersDir);
41
45
  }
@@ -118,6 +118,13 @@ export interface AgentRunPreparation {
118
118
  env: Record<string, string>;
119
119
  readPaths: string[];
120
120
  writePaths: string[];
121
+ /** Host files mounted read-write over a target inside the run home. */
122
+ bindPaths?: RunBind[];
123
+ }
124
+ /** One host file the run shares, mounted over `target` in the run home. */
125
+ export interface RunBind {
126
+ source: string;
127
+ target: string;
121
128
  }
122
129
  /** Model API facts used by credential relays, independent of an execution backend. */
123
130
  export interface AgentModelApi {
@@ -191,7 +198,9 @@ export interface BbAgent extends AgentRuntimeInfo {
191
198
  */
192
199
  launchCommand(prompt: string, run?: AgentRunIdentity, workspacePath?: string, tools?: {
193
200
  url: string;
194
- }, env?: Readonly<Record<string, string>>, args?: readonly string[]): string;
201
+ }, env?: Readonly<Record<string, string>>, args?: readonly string[],
202
+ /** The workspace is a run clone: grant `<workspace>/.git`, ask Git nothing. */
203
+ isolatedGit?: boolean): string;
195
204
  /**
196
205
  * Locate and read this agent's run transcript for a run that executed in
197
206
  * `worktreePath`. MUST return '' (never throw) when nothing is found.
@@ -0,0 +1,9 @@
1
+ import type { ConductorSettings } from '../types.js';
2
+ /** The script a host command starts: its first word, or the word after `bash`, `sh` or `node`. */
3
+ export declare function hostCommandEntry(command: string): string | undefined;
4
+ /**
5
+ * Throws naming the first hook or provision command whose entry point lies
6
+ * outside `protectedPaths`. Only the entry is checked: what that script calls
7
+ * is the project's responsibility.
8
+ */
9
+ export declare function assertProtectedEntryPoints(hooks: ConductorSettings['hooks'], protectedPaths: readonly string[]): void;
@@ -0,0 +1,35 @@
1
+ // Under an isolating runtime the host runs only code the run cannot write:
2
+ // every project hook and provision command must start in a protected path.
3
+ import { posix } from 'node:path';
4
+ const INTERPRETERS = new Set(['bash', 'sh', 'node']);
5
+ /** The script a host command starts: its first word, or the word after `bash`, `sh` or `node`. */
6
+ export function hostCommandEntry(command) {
7
+ const [first, second] = command
8
+ .trim()
9
+ .split(/[\s;&|]+/)
10
+ .filter(Boolean);
11
+ return first !== undefined && INTERPRETERS.has(first) ? second : first;
12
+ }
13
+ /**
14
+ * Throws naming the first hook or provision command whose entry point lies
15
+ * outside `protectedPaths`. Only the entry is checked: what that script calls
16
+ * is the project's responsibility.
17
+ */
18
+ export function assertProtectedEntryPoints(hooks, protectedPaths) {
19
+ const roots = ['.bakers', ...protectedPaths].map((path) => posix.normalize(path));
20
+ for (const [name, value] of Object.entries(hooks ?? {})) {
21
+ const commands = typeof value === 'string'
22
+ ? [[`hooks.${name}`, value]]
23
+ : Object.entries(value ?? {}).map(([key, command]) => [
24
+ `hooks.${name}.${key}`,
25
+ command,
26
+ ]);
27
+ for (const [label, command] of commands) {
28
+ const entry = hostCommandEntry(command);
29
+ const path = entry === undefined ? undefined : posix.normalize(entry);
30
+ if (path === undefined ||
31
+ !roots.some((root) => path === root || path.startsWith(`${root}/`)))
32
+ throw new Error(`${label}: under an isolating runtime a host command must start with a script in a protected path (${roots.join(', ')}); got ${JSON.stringify(command)}`);
33
+ }
34
+ }
35
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ConductorLogger } from '@bakers-build/core';
2
2
  import type { ConductorFileConfig } from '../types.js';
3
- import type { AgentRuntimeInfo } from './agent.js';
3
+ import type { AgentRuntimeInfo, RunBind } from './agent.js';
4
4
  /** The run a launch belongs to. */
5
5
  export interface RuntimeRun {
6
6
  uuid: string;
@@ -13,11 +13,17 @@ export interface RuntimeLaunch extends AgentRuntimeInfo {
13
13
  env: Record<string, string>;
14
14
  workspacePath: string;
15
15
  run: RuntimeRun;
16
+ /** The run clone's Git directory, mounted as `<workspace>/.git`; absent: the run has no Git. */
17
+ gitDir?: string;
18
+ /** A `shared` clone's parent object store, mounted read-only at its own path. */
19
+ sharedObjects?: string;
16
20
  /** The harness id of the chosen agent (`claude`, `codex`, …). */
17
21
  harness: string;
18
22
  homePath?: string;
19
23
  readPaths?: string[];
20
24
  writePaths?: string[];
25
+ /** Mounted read-write after the home; each target lies inside `homePath`. */
26
+ bindPaths?: RunBind[];
21
27
  }
22
28
  export interface BbRuntime {
23
29
  id: string;
@@ -43,6 +49,8 @@ export interface RuntimePlugin {
43
49
  readonly id: string;
44
50
  /** True when runs are isolated from the host; agent permissions remain unchanged. */
45
51
  readonly isolates: boolean;
52
+ /** Run clones borrow the parent's objects (`git clone --shared`); undefined = the workspace decides. */
53
+ readonly shared?: boolean;
46
54
  readonly requiredModules: string[];
47
55
  createRuntime(config: ConductorFileConfig, deps: {
48
56
  logger: ConductorLogger;
@@ -1,10 +1,25 @@
1
1
  import type { ConductorLogger } from '@bakers-build/core';
2
2
  import { type MessageInput } from '@bakers-build/message';
3
+ import type { ConductorEngineConfig } from '../types.js';
3
4
  import type { Ticket } from './remote.js';
5
+ export type AgentCatalog = Pick<ConductorEngineConfig, 'agents' | 'enabled_agents' | 'disabled_agents' | 'default_agent' | 'routes'>;
6
+ export interface ToolHost {
7
+ agentCatalog(): AgentCatalog;
8
+ }
9
+ /** A message input whose properties may also be lists of strings (argv). */
10
+ export type ToolInput = Omit<MessageInput, 'properties'> & {
11
+ properties: Record<string, MessageInput['properties'][string] | {
12
+ type: 'array';
13
+ items: {
14
+ type: 'string';
15
+ };
16
+ description?: string;
17
+ }>;
18
+ };
4
19
  export interface ToolDefinition {
5
20
  description: string;
6
21
  /** Absent means a parameterless tool. Unknown arguments are refused. */
7
- input?: MessageInput;
22
+ input?: ToolInput;
8
23
  }
9
24
  export interface ToolResult {
10
25
  text: string;
@@ -31,7 +46,7 @@ export interface AddonTools {
31
46
  contract: 1;
32
47
  tools: Record<string, ToolDefinition>;
33
48
  /** Lazy: imported only when the conductor loads the addon. */
34
- handlers: (options?: unknown) => Promise<Record<string, ToolHandler>>;
49
+ handlers: (options?: unknown, host?: ToolHost) => Promise<Record<string, ToolHandler>>;
35
50
  }
36
51
  /** One `tools` export as discovery found it. */
37
52
  export interface DiscoveredTools {
@@ -65,21 +80,29 @@ type ShellResult = {
65
80
  /** Provisioning runs the conductor owns, one per worktree and command. */
66
81
  export interface ProvisionRuns {
67
82
  /** Joins the running command of this worktree, or starts it. */
68
- run(worktreePath: string, command: string): Promise<ShellResult>;
83
+ run(worktreePath: string, command: string, env?: Record<string, string>): Promise<ShellResult>;
69
84
  /** Kills the runs of one worktree, or all; resolves once they closed. */
70
85
  stop(worktreePath?: string): Promise<void>;
71
86
  }
72
87
  export declare function provisionRuns(timeoutMs?: number): ProvisionRuns;
88
+ export interface ProvisionOptions {
89
+ /** `hooks.provision_exec`: commands by key. */
90
+ exec?: Record<string, string>;
91
+ /** Whether the runtime isolates runs; exported to every host command. */
92
+ isolates?: boolean;
93
+ }
73
94
  /**
74
- * The core `provision_up(profile?)` tool, offered only when the hook is set.
75
- * The agent picks when and which configured profile, never the command. The
76
- * command outlives its caller: the call's signal is ignored on purpose.
95
+ * The core `provision_up(profile?)` and `provision_exec(key, args?)` tools,
96
+ * each offered only when its hook is set. The agent picks when, which
97
+ * configured profile or key, and the arguments, never the command. A
98
+ * `provision_up` command outlives its caller: the call's signal is ignored on
99
+ * purpose.
77
100
  */
78
- export declare function provisionTools(hook: ProvisionHook | undefined, runs?: ProvisionRuns): DiscoveredTools[];
101
+ export declare function provisionTools(hook: ProvisionHook | undefined, runs?: ProvisionRuns, options?: ProvisionOptions): DiscoveredTools[];
79
102
  /**
80
103
  * Resolves every addon's handlers and checks that handlers and declared tools
81
104
  * match one to one. A tool name declared by two addons is an error, so the
82
105
  * conductor never starts with an ambiguous tool.
83
106
  */
84
- export declare function loadTools(found: readonly DiscoveredTools[]): Promise<ToolRegistry>;
107
+ export declare function loadTools(found: readonly DiscoveredTools[], host?: ToolHost): Promise<ToolRegistry>;
85
108
  export {};
@@ -10,13 +10,13 @@ const OUTPUT_CAP = 64 * 1024;
10
10
  export function provisionRuns(timeoutMs = PROVISION_TIMEOUT_MS) {
11
11
  const running = new Map();
12
12
  return {
13
- run(worktreePath, command) {
13
+ run(worktreePath, command, env) {
14
14
  const key = JSON.stringify([worktreePath, command]);
15
15
  const current = running.get(key);
16
16
  if (current)
17
17
  return current.done;
18
18
  const abort = new AbortController();
19
- const done = shell(command, worktreePath, abort.signal, timeoutMs);
19
+ const done = shell(command, worktreePath, abort.signal, timeoutMs, env);
20
20
  running.set(key, { worktreePath, abort, done });
21
21
  const forget = () => running.delete(key);
22
22
  done.then(forget, forget);
@@ -31,15 +31,19 @@ export function provisionRuns(timeoutMs = PROVISION_TIMEOUT_MS) {
31
31
  };
32
32
  }
33
33
  /**
34
- * The core `provision_up(profile?)` tool, offered only when the hook is set.
35
- * The agent picks when and which configured profile, never the command. The
36
- * command outlives its caller: the call's signal is ignored on purpose.
34
+ * The core `provision_up(profile?)` and `provision_exec(key, args?)` tools,
35
+ * each offered only when its hook is set. The agent picks when, which
36
+ * configured profile or key, and the arguments, never the command. A
37
+ * `provision_up` command outlives its caller: the call's signal is ignored on
38
+ * purpose.
37
39
  */
38
- export function provisionTools(hook, runs = provisionRuns()) {
39
- if (hook === undefined)
40
+ export function provisionTools(hook, runs = provisionRuns(), options = {}) {
41
+ const exec = options.exec ?? {};
42
+ if (hook === undefined && Object.keys(exec).length === 0)
40
43
  return [];
41
44
  const profiles = typeof hook === 'string' ? undefined : hook;
42
- if (typeof hook !== 'string' &&
45
+ if (hook !== undefined &&
46
+ typeof hook !== 'string' &&
43
47
  (typeof hook !== 'object' ||
44
48
  hook === null ||
45
49
  Object.values(hook).some((cmd) => typeof cmd !== 'string')))
@@ -53,37 +57,53 @@ export function provisionTools(hook, runs = provisionRuns()) {
53
57
  // The input schema's enum has already refused an unknown profile.
54
58
  return profiles[String(profile)];
55
59
  };
60
+ // What a host script needs instead of asking Git in a workspace without one.
61
+ const envFor = (worktreePath) => ({
62
+ BAKERS_WORKTREE_PATH: worktreePath,
63
+ BAKERS_RUNTIME_ISOLATES: options.isolates ? '1' : '0',
64
+ });
65
+ const report = ({ exitCode, output }) => {
66
+ const text = `exit ${exitCode}\n${output}`;
67
+ if (exitCode !== 0)
68
+ throw new Error(text);
69
+ return { text };
70
+ };
71
+ const tools = {};
72
+ const handlers = {};
73
+ if (hook !== undefined) {
74
+ tools.provision_up = {
75
+ description: `Bring this worktree's environment up${profiles ? ` with a configured profile (${keys})` : ''}; the project's command reuses a ready environment. Returns the command's output, including the base URL. The first call on a new worktree can take minutes; the call waits until the command ends, for up to 30 minutes. On a client timeout the command keeps running: call again with the same profile to join it and receive its result, without starting a second one.`,
76
+ input: {
77
+ type: 'object',
78
+ properties: {
79
+ profile: profiles
80
+ ? { type: 'string', enum: Object.keys(profiles) }
81
+ : { type: 'string' },
82
+ },
83
+ },
84
+ };
85
+ // shortcut: inherits the conductor's env, not the run's BAKERS_* env; pass it through the binding once a hook needs it.
86
+ handlers.provision_up = async (req) => report(await runs.run(req.worktreePath, commandFor(req.args.profile), envFor(req.worktreePath)));
87
+ }
88
+ if (Object.keys(exec).length > 0) {
89
+ tools.provision_exec = {
90
+ description: `Run one of the project's configured commands (${Object.keys(exec).join(', ')}) for this worktree, such as a command in its site container. \`args\` reach the command as separate arguments after \`--\`, never through a shell. Returns the exit code and the output tail.`,
91
+ input: {
92
+ type: 'object',
93
+ required: ['key'],
94
+ properties: {
95
+ key: { type: 'string', enum: Object.keys(exec) },
96
+ args: { type: 'array', items: { type: 'string' } },
97
+ },
98
+ },
99
+ };
100
+ handlers.provision_exec = async (req) => report(await shell(`${exec[String(req.args.key)]} -- "$@"`, req.worktreePath, req.signal, PROVISION_TIMEOUT_MS, envFor(req.worktreePath), req.args.args ?? []));
101
+ }
56
102
  return [
57
103
  {
58
104
  name: 'conductor',
59
105
  version: '1',
60
- tools: {
61
- contract: 1,
62
- tools: {
63
- provision_up: {
64
- description: `Bring this worktree's environment up${profiles ? ` with a configured profile (${keys})` : ''}; the project's command reuses a ready environment. Returns the command's output, including the base URL. The first call on a new worktree can take minutes; the call waits until the command ends, for up to 30 minutes. On a client timeout the command keeps running: call again with the same profile to join it and receive its result, without starting a second one.`,
65
- input: {
66
- type: 'object',
67
- properties: {
68
- profile: profiles
69
- ? { type: 'string', enum: Object.keys(profiles) }
70
- : { type: 'string' },
71
- },
72
- },
73
- },
74
- },
75
- handlers: async () => ({
76
- provision_up: async (req) => {
77
- const command = commandFor(req.args.profile);
78
- // shortcut: inherits the conductor's env, not the run's BAKERS_* env; pass it through the binding once a hook needs it.
79
- const { exitCode, output } = await runs.run(req.worktreePath, command);
80
- const text = `exit ${exitCode}\n${output}`;
81
- if (exitCode !== 0)
82
- throw new Error(text);
83
- return { text };
84
- },
85
- }),
86
- },
106
+ tools: { contract: 1, tools, handlers: async () => handlers },
87
107
  },
88
108
  ];
89
109
  }
@@ -91,10 +111,12 @@ export function provisionTools(hook, runs = provisionRuns()) {
91
111
  * `sh -c` with stdout and stderr interleaved, the tail kept. Its own process
92
112
  * group, killed whole at the timeout or abort, so no child outlives it.
93
113
  */
94
- function shell(command, cwd, signal, timeoutMs) {
114
+ function shell(command, cwd, signal, timeoutMs, env = {}, args = []) {
95
115
  return new Promise((done, fail) => {
96
- const child = spawn('sh', ['-c', command], {
116
+ // `args` become "$@": positional parameters, never shell text.
117
+ const child = spawn('sh', ['-c', command, 'sh', ...args], {
97
118
  cwd,
119
+ env: { ...process.env, ...env },
98
120
  detached: true,
99
121
  stdio: ['ignore', 'pipe', 'pipe'],
100
122
  });
@@ -143,13 +165,13 @@ const silent = {
143
165
  * match one to one. A tool name declared by two addons is an error, so the
144
166
  * conductor never starts with an ambiguous tool.
145
167
  */
146
- export async function loadTools(found) {
168
+ export async function loadTools(found, host) {
147
169
  const entries = new Map();
148
170
  for (const addon of found) {
149
171
  const fail = (msg) => new Error(`addon ${addon.name}: ${msg}`);
150
172
  if (addon.tools.contract !== 1)
151
173
  throw fail(`unsupported tools contract ${addon.tools.contract}`);
152
- const handlers = await addon.tools.handlers(addon.options);
174
+ const handlers = await addon.tools.handlers(addon.options, host);
153
175
  for (const [name, def] of Object.entries(addon.tools.tools)) {
154
176
  const handler = handlers[name];
155
177
  if (typeof handler !== 'function')
@@ -1,3 +1,4 @@
1
+ import type { RunClone } from '@bakers-build/core';
1
2
  import type { WorktreeTeardown } from './executor.js';
2
3
  export interface EnsuredWorkspace {
3
4
  path: string;
@@ -20,6 +21,12 @@ export interface EnsuredWorkspace {
20
21
  * keys still win.
21
22
  */
22
23
  env?: Record<string, string>;
24
+ /**
25
+ * Set when the workspace is a fresh clone for an isolated run instead of a
26
+ * linked worktree: its Git directory lies outside `path`, which has no
27
+ * `.git` on the host.
28
+ */
29
+ clone?: RunClone;
23
30
  }
24
31
  export interface BbWorkspace {
25
32
  /**
@@ -70,6 +70,8 @@ export interface ConductorSettings {
70
70
  on_resume?: string;
71
71
  /** Never runs on its own: offered to runs as the `provision_up(profile?)` tool. */
72
72
  provision_up?: ProvisionHook;
73
+ /** Never runs on its own: offered to runs as the `provision_exec(key, args?)` tool. */
74
+ provision_exec?: Record<string, string>;
73
75
  };
74
76
  /** Control-plane site settings used for dropsh and agent env. */
75
77
  site: {
@@ -88,6 +90,17 @@ export interface ConductorSettings {
88
90
  files: string[];
89
91
  dirs: string[];
90
92
  };
93
+ /** Where each slot's plugin came from, for `bakers conductor check`. */
94
+ slot_sources?: Partial<SlotSources>;
95
+ /** The package each slot named with `use`; addon-discovered slots have none. */
96
+ slot_packages?: Partial<Record<keyof SlotSources, string>>;
97
+ }
98
+ /** Where a resolved server, executor or worktree plugin came from. */
99
+ export type SlotSource = 'machine' | 'slot' | 'addons' | 'connection' | 'default';
100
+ export interface SlotSources {
101
+ server: SlotSource;
102
+ executor: SlotSource;
103
+ worktree: SlotSource;
91
104
  }
92
105
  /** Whole project.config.js (dropsh-superset): site + named plugin slots. */
93
106
  export interface ConductorFileConfig extends ConductorSettings {
@@ -106,6 +119,8 @@ export interface ConductorFileConfig extends ConductorSettings {
106
119
  workspace: WorkspacePlugin;
107
120
  /** Where agent processes run (the `runtime` slot); absent means on the host. */
108
121
  runtime?: RuntimePlugin;
122
+ /** The project's `runtime.read_only`: paths an isolated run sees read-only. */
123
+ readOnly?: string[];
109
124
  /** The project's agent plugin marketplaces; empty when it declares none. */
110
125
  marketplaces: MarketplaceDeclaration[];
111
126
  /**
@@ -134,4 +149,7 @@ export interface ConductorFileConfig extends ConductorSettings {
134
149
  * command composes it with the connection (`composeConductorConfig`) into the
135
150
  * full `ConductorFileConfig` the engine consumes.
136
151
  */
137
- export type ConductorEngineConfig = Omit<ConductorFileConfig, 'site' | 'plugins'>;
152
+ export type ConductorEngineConfig = Omit<ConductorFileConfig, 'site' | 'plugins' | 'remote'> & {
153
+ /** Absent when the project names no server; the connection or the default fills it. */
154
+ remote?: RemotePlugin;
155
+ };