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

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,9 @@
1
- import { type ConfigInventoryOptions, type ConfigReport } from '@bakers-build/core';
1
+ import { type AddonCapabilities, type ConfigInventoryOptions, type ConfigReport } from '@bakers-build/core';
2
2
  import { type ConnectionAuthType } from './config-templates.js';
3
+ export { DEFAULT_SLOT_ADDON } from './config-templates.js';
3
4
  export interface ConfigPlanOptions extends ConfigInventoryOptions {
5
+ capabilities?: AddonCapabilities;
6
+ slots?: Partial<Record<'server' | 'executor' | 'worktree', string>>;
4
7
  inputs?: {
5
8
  /** Machine display label; the machine UUID is always generated. */
6
9
  label?: string;
@@ -6,8 +6,10 @@ import { dirname } from 'node:path';
6
6
  import { configRecheckCommand, finalizeConfigReport, inspectConfigSource, inventoryConfig, shellQuote, } from '@bakers-build/core';
7
7
  import { applyMigrations, BB_CONFIG_SCHEMA_VERSION } from './config-schema.js';
8
8
  import { ConfigSourceEditor, redactConfigSource, } from './config-source-edit.js';
9
- import { renderCommittedConfig, renderGlobalConnection, renderHostMachine, } from './config-templates.js';
9
+ import { DEFAULT_SLOT_ADDON, renderCommittedConfig, renderGlobalConnection, renderHostMachine, } from './config-templates.js';
10
10
  import { validateConfigSources } from './config-validation.js';
11
+ // The host reads this addon's capabilities before a fresh project file exists.
12
+ export { DEFAULT_SLOT_ADDON } from './config-templates.js';
11
13
  // Every config file is at schema v1; no migration step exists yet.
12
14
  const CURRENT = {
13
15
  machine: 1,
@@ -30,6 +32,21 @@ function readFingerprint(path) {
30
32
  }
31
33
  /** Inventory, transform in memory, validate the complete proposed installation. */
32
34
  export function planConfig(options = {}) {
35
+ const capabilities = options.capabilities ?? {};
36
+ const selectedSlots = Object.entries(options.slots ?? {});
37
+ if (selectedSlots.length &&
38
+ (options.operation !== 'init' ||
39
+ !['project', 'all'].includes(options.scope ?? '')))
40
+ throw new Error('Slot flags require config init --scope project (or all).');
41
+ for (const [slot, spec] of selectedSlots) {
42
+ const capability = capabilities[spec];
43
+ if (!capability)
44
+ throw new Error(`--${slot}: cannot resolve addon '${spec}'.`);
45
+ if (!capability.scopes.includes('project'))
46
+ throw new Error(`--${slot}: '${spec}' does not allow project scope.`);
47
+ if (!capability.slots.includes(slot))
48
+ throw new Error(`--${slot}: '${spec}' contributes no ${slot}.`);
49
+ }
33
50
  // `conductor` is a bakers.build-specific sub-scope of `project`: it selects the same
34
51
  // files but communicates to the planner that only conductor-config changes are
35
52
  // requested. We map it to `project` for the inventory, which uses a strict
@@ -59,7 +76,7 @@ export function planConfig(options = {}) {
59
76
  const machine = files.find((f) => f.kind === 'machine');
60
77
  const connection = files.find((f) => f.kind === 'connection');
61
78
  if (options.operation === 'check') {
62
- const validated = validateConfigSources(inventoryOptions, new Map(original), files);
79
+ const validated = validateConfigSources(inventoryOptions, new Map(original), files, options.capabilities);
63
80
  return {
64
81
  report: finalizeConfigReport(validated),
65
82
  writes: [],
@@ -448,9 +465,8 @@ export function planConfig(options = {}) {
448
465
  editor(file).stamp(1);
449
466
  }
450
467
  if (file.kind === 'project') {
451
- if ((!e || e.text.trim() === 'export default {};') &&
452
- file.required &&
453
- options.project) {
468
+ const fresh = !e || e.text.trim() === 'export default {};';
469
+ if (fresh && file.required && options.project) {
454
470
  e = new ConfigSourceEditor(renderCommittedConfig({
455
471
  project: options.project,
456
472
  ...(options.inputs?.hooks ? { hooks: options.inputs.hooks } : {}),
@@ -458,6 +474,19 @@ export function planConfig(options = {}) {
458
474
  ? { bakersWorkspace: options.inputs.workspace }
459
475
  : {}),
460
476
  }));
477
+ if (selectedSlots.length) {
478
+ const contributed = new Set(selectedSlots.flatMap(([, spec]) => capabilities[spec]?.slots ?? []));
479
+ if (options.slots?.executor) {
480
+ const entries = Array.from({ length: e.property('addons')?.arrayLength ?? 0 }, (_, index) => `addons[${index}]`);
481
+ e.set('addons', `[${entries
482
+ .filter((key) => (e?.property(`${key}.use`)?.value ??
483
+ e?.property(key)?.value) !== DEFAULT_SLOT_ADDON)
484
+ .map((key) => e?.expression(key))
485
+ .join(', ')}]`);
486
+ }
487
+ for (const slot of contributed)
488
+ e.remove(slot);
489
+ }
461
490
  editors.set(file.path, e);
462
491
  }
463
492
  if (!e)
@@ -465,30 +494,49 @@ export function planConfig(options = {}) {
465
494
  {
466
495
  e = editor(file);
467
496
  fill(file, 'project.name', options.project);
468
- const canonical = new ConfigSourceEditor(renderCommittedConfig({
469
- project: options.project ?? 'project',
470
- }));
471
497
  const addonPackages = new Set([...e.source.properties]
472
498
  .filter(([key]) => /^addons\[\d+\](?:\.use)?$/.test(key))
473
499
  .map(([, property]) => property.value)
474
500
  .filter((value) => typeof value === 'string'));
475
- const providers = {
476
- server: [
477
- '@bakers-build/addon-remote-drupal',
478
- '@bakers-build/addon-fake',
479
- ],
480
- executor: ['@bakers-build/addon-herdr', '@bakers-build/addon-fake'],
481
- worktree: [
482
- '@bakers-build/addon-herdr',
483
- '@bakers-build/addon-fake',
484
- '@bakers-build/addon-workspace-git',
485
- ],
501
+ const existingPackages = [...addonPackages];
502
+ // Text is spliced into addons, so only a literal array can take it.
503
+ const literalAddons = () => {
504
+ const addons = e?.property('addons');
505
+ if (!addons || addons.nodeType === 'ArrayExpression')
506
+ return true;
507
+ problem(file, 'unsupported_source_shape', 'addons', 'A literal addons array is required to add a slot provider.');
508
+ return false;
486
509
  };
487
- for (const slot of ['server', 'executor', 'worktree']) {
510
+ for (const [slot, spec] of selectedSlots) {
488
511
  if (e.property(slot) ||
489
- providers[slot]?.some((provider) => addonPackages.has(provider)))
512
+ existingPackages.some((pkg) => capabilities[pkg]?.slots.includes(slot)))
513
+ continue;
514
+ if (!literalAddons())
515
+ continue;
516
+ if (!addonPackages.has(spec)) {
517
+ const expression = e.expression('addons') ?? '[]';
518
+ const before = expression.slice(0, -1).trimEnd();
519
+ e.set('addons', `${before}${before.endsWith('[') || before.endsWith(',') ? '' : ','} { use: ${JSON.stringify(spec)} }]`);
520
+ addonPackages.add(spec);
521
+ }
522
+ }
523
+ const supplied = (slot) => e?.property(slot) ||
524
+ [...addonPackages].some((pkg) => capabilities[pkg]?.slots.includes(slot) ??
525
+ pkg === DEFAULT_SLOT_ADDON);
526
+ if (options.slots?.executor && !supplied('worktree'))
527
+ problem(file, 'missing_required_key', 'worktree', 'The selected executor supplies no worktree; pass --worktree <package>.');
528
+ // The server comes from the connection; herdr fills a missing executor or worktree.
529
+ for (const slot of ['executor', 'worktree']) {
530
+ if (supplied(slot))
531
+ continue;
532
+ if (slot === 'worktree' && options.slots?.executor)
490
533
  continue;
491
- e.set(slot, canonical.expression(slot));
534
+ if (!literalAddons())
535
+ break;
536
+ const expression = e.expression('addons') ?? '[]';
537
+ const before = expression.slice(0, -1).trimEnd();
538
+ e.set('addons', `${before}${before.endsWith('[') || before.endsWith(',') ? '' : ','} '${DEFAULT_SLOT_ADDON}']`);
539
+ addonPackages.add(DEFAULT_SLOT_ADDON);
492
540
  }
493
541
  if (options.operation === 'init' &&
494
542
  options.inputs?.workspace &&
@@ -550,11 +598,13 @@ export function planConfig(options = {}) {
550
598
  for (const [path] of original)
551
599
  if (!editors.has(path))
552
600
  overlay.set(path, null);
553
- const proposed = validateConfigSources(inventoryOptions, overlay, files);
601
+ const proposed = validateConfigSources(inventoryOptions, overlay, files, options.capabilities);
554
602
  report.findings = [
555
603
  ...errors,
556
604
  ...proposed.findings.filter((f) => !errors.some((e) => e.path === f.path && e.code === f.code && e.key === f.key)),
557
605
  ];
606
+ if (proposed.slot_sources)
607
+ report.slot_sources = proposed.slot_sources;
558
608
  report.verification.skipped = proposed.verification.skipped;
559
609
  const writes = [];
560
610
  for (const file of files.filter((f) => f.selected)) {
@@ -1,4 +1,6 @@
1
- export declare const DEFAULT_CONDUCTOR_AGENT_ADDONS = "[{ use: '@bakers-build/addon-herdr' }, { use: '@bakers-build/addon-claude', alias: 'opus' }]";
1
+ /** Supplies the executor and the worktree slot through its preset. */
2
+ export declare const DEFAULT_SLOT_ADDON = "@bakers-build/addon-herdr";
3
+ export declare const DEFAULT_CONDUCTOR_AGENT_ADDONS = "['@bakers-build/addon-herdr']";
2
4
  export type ConnectionAuthType = 'oauth2_client_credentials' | 'oauth2_device_code';
3
5
  /** Current connection template inputs never come from machine context. */
4
6
  export interface ConnectionInputs {
@@ -1,4 +1,6 @@
1
- export const DEFAULT_CONDUCTOR_AGENT_ADDONS = "[{ use: '@bakers-build/addon-herdr' }, { use: '@bakers-build/addon-claude', alias: 'opus' }]";
1
+ /** Supplies the executor and the worktree slot through its preset. */
2
+ export const DEFAULT_SLOT_ADDON = '@bakers-build/addon-herdr';
3
+ export const DEFAULT_CONDUCTOR_AGENT_ADDONS = `['${DEFAULT_SLOT_ADDON}']`;
2
4
  export function renderGlobalConnection(inputs) {
3
5
  // The device-code grant has no client_secret in @dropsh/plugin-oauth2's
4
6
  // config union, so the key is omitted rather than rendered undefined
@@ -50,10 +52,9 @@ export function renderCommittedConfig(inputs) {
50
52
  // everyone. A conductor is this machine (machine.config.js) + this project +
51
53
  // the variant (project.<name>.config.js). Connections are private files.
52
54
  //
53
- // The slots are \`{ use, export?, with? }\` descriptors naming the published
54
- // package; the loader resolves each name (config dir → cwd → CLI install).
55
- // \`@bakers-build/addon-herdr\` default-exports the executor, so the worktree
56
- // slot names \`export: 'herdrWorkspace'\`.
55
+ // Each addon in \`addons\` fills its slots through its preset: herdr supplies
56
+ // the executor and the worktree. The server comes from the connection,
57
+ // by default @bakers-build/addon-remote-drupal.
57
58
 
58
59
  /** @type {import('@bakers-build/core').ProjectConfig} */
59
60
  export default {
@@ -76,10 +77,7 @@ ${inputs.hooks?.after_create || inputs.hooks?.after_done
76
77
  ]
77
78
  .filter(Boolean)
78
79
  .join(', ')} },\n`
79
- : ''} server: { use: '@bakers-build/addon-remote-drupal' },
80
- executor: { use: '@bakers-build/addon-herdr' },
81
- addons: ${DEFAULT_CONDUCTOR_AGENT_ADDONS},
82
- worktree: { use: '@bakers-build/addon-herdr', export: 'herdrWorkspace' },
80
+ : ''} addons: ${DEFAULT_CONDUCTOR_AGENT_ADDONS},
83
81
  };
84
82
  `;
85
83
  }
@@ -1,12 +1,3 @@
1
- import { type ConfigFileReport, type ConfigInventoryOptions, type ConfigReport } from '@bakers-build/core';
2
- /**
3
- * Known addons and the CONDUCTOR slots each fills. An empty list means "known
4
- * addon, fills no conductor slot" — a UI-only addon (BB-562) belongs in a
5
- * conductor `addons[]` but contributes a cockpit tab, not a slot. Listing it is
6
- * not cosmetic: an UNKNOWN specifier sets `addonsAreOpaque` below, which
7
- * downgrades a genuinely missing server/executor/worktree from
8
- * `missing_required_key` to `unknown_value`.
9
- */
10
- export declare const CONDUCTOR_ADDON_SLOTS: Record<string, string[]>;
1
+ import { type AddonCapabilities, type ConfigFileReport, type ConfigInventoryOptions, type ConfigReport } from '@bakers-build/core';
11
2
  /** Resolve only documented generated wiring and primitive const bindings. Never execute code. */
12
- export declare function validateConfigSources(options: ConfigInventoryOptions, texts: Map<string, string | null>, files: ConfigFileReport[]): ConfigReport;
3
+ export declare function validateConfigSources(options: ConfigInventoryOptions, texts: Map<string, string | null>, files: ConfigFileReport[], capabilities?: AddonCapabilities): ConfigReport;
@@ -1,50 +1,6 @@
1
1
  import { configRecheckCommand, inventoryConfig, shellQuote, } from '@bakers-build/core';
2
2
  import { ConfigSourceEditor } from './config-source-edit.js';
3
- /**
4
- * Known addons and the CONDUCTOR slots each fills. An empty list means "known
5
- * addon, fills no conductor slot" — a UI-only addon (BB-562) belongs in a
6
- * conductor `addons[]` but contributes a cockpit tab, not a slot. Listing it is
7
- * not cosmetic: an UNKNOWN specifier sets `addonsAreOpaque` below, which
8
- * downgrades a genuinely missing server/executor/worktree from
9
- * `missing_required_key` to `unknown_value`.
10
- */
11
- export const CONDUCTOR_ADDON_SLOTS = {
12
- '@bakers-build/addon-remote-drupal': ['server'],
13
- '@bakers-build/addon-herdr': ['executor', 'worktree'],
14
- '@bakers-build/addon-orca': ['executor', 'worktree'],
15
- '@bakers-build/addon-herdr-core': ['executor'],
16
- '@bakers-build/addon-fake': ['server', 'executor', 'worktree'],
17
- '@bakers-build/addon-workspace-git': ['worktree'],
18
- '@bakers-build/addon-claude': ['agent'],
19
- '@bakers-build/addon-codex': ['agent'],
20
- '@bakers-build/addon-grok': ['agent'],
21
- '@bakers-build/addon-kimi': ['agent'],
22
- '@bakers-build/addon-opencode': ['agent'],
23
- '@bakers-build/addon-pi': ['agent'],
24
- '@bakers-build/addon-runtime-docker': ['runtime'],
25
- '@bakers-build/addon-runtime-bwrap': ['runtime'],
26
- '@bakers-build/addon-ports': [],
27
- '@bakers-build/addon-ports-cloudflare': [],
28
- '@bakers-build/addon-ports-cloudflare-quick': [],
29
- '@bakers-build/addon-ports-frp': [],
30
- '@bakers-build/addon-forge': [],
31
- '@bakers-build/addon-forge-github': [],
32
- '@bakers-build/addon-forge-gitlab': [],
33
- '@bakers-build/addon-bakers-ui': [],
34
- '@bakers-build/addon-bakers-ui-artifacts': [],
35
- '@bakers-build/addon-agents': [],
36
- '@bakers-build/addon-auth-basic': [],
37
- '@bakers-build/addon-ddev': [],
38
- '@bakers-build/addon-deployment': [],
39
- '@bakers-build/addon-docker-compose': [],
40
- '@bakers-build/addon-dropsh': [],
41
- '@bakers-build/addon-essentials': [],
42
- '@bakers-build/addon-info': [],
43
- '@bakers-build/addon-name-refs': [],
44
- '@bakers-build/addon-track': [],
45
- '@bakers-build/addon-workspace': [],
46
- };
47
- function validateConductorSources(options, editors, report) {
3
+ function validateConductorSources(options, editors, report, capabilities) {
48
4
  const recheck = configRecheckCommand((options.scope ?? 'all'), report.roots.project);
49
5
  for (const file of report.files.filter((candidate) => candidate.selected && candidate.kind === 'project')) {
50
6
  const editor = editors.get(file.path);
@@ -73,6 +29,7 @@ function validateConductorSources(options, editors, report) {
73
29
  };
74
30
  const addon = editor.property('addons');
75
31
  const addonSlots = new Set();
32
+ const origins = {};
76
33
  let addonsAreOpaque = false;
77
34
  if (addon) {
78
35
  if (addon.nodeType !== 'ArrayExpression')
@@ -85,16 +42,28 @@ function validateConductorSources(options, editors, report) {
85
42
  if (typeof specifier !== 'string')
86
43
  addonsAreOpaque = true;
87
44
  else {
88
- const contributions = CONDUCTOR_ADDON_SLOTS[specifier];
45
+ const contributions = capabilities[specifier]?.slots;
89
46
  if (!contributions)
90
47
  addonsAreOpaque = true;
91
- else
48
+ else {
92
49
  for (const slot of contributions)
93
50
  addonSlots.add(slot);
51
+ for (const contribution of capabilities[specifier]
52
+ ?.contributions ?? [])
53
+ origins[contribution.slot] =
54
+ `${contribution.spec}${contribution.via ? ` (via ${contribution.via})` : ''}`;
55
+ }
94
56
  }
95
57
  }
96
58
  }
59
+ report.slot_sources = origins;
97
60
  for (const slot of ['server', 'executor', 'worktree']) {
61
+ const explicit = editor.property(`${slot}.use`)?.value;
62
+ if (typeof explicit === 'string')
63
+ origins[slot] = explicit;
64
+ // Without one here, the conductor takes the connection's server or the default.
65
+ if (slot === 'server')
66
+ continue;
98
67
  if (editor.property(slot) || addonSlots.has(slot))
99
68
  continue;
100
69
  add(addon && addonsAreOpaque ? 'unknown_value' : 'missing_required_key', slot, `A ${slot} supplied by an explicit slot or a listed addon.`);
@@ -107,7 +76,7 @@ function validateConductorSources(options, editors, report) {
107
76
  }
108
77
  }
109
78
  /** Resolve only documented generated wiring and primitive const bindings. Never execute code. */
110
- export function validateConfigSources(options, texts, files) {
79
+ export function validateConfigSources(options, texts, files, capabilities = {}) {
111
80
  const editors = new Map([...texts]
112
81
  .filter((entry) => entry[1] !== null)
113
82
  .map(([path, text]) => [path, new ConfigSourceEditor(text)]));
@@ -200,7 +169,7 @@ export function validateConfigSources(options, texts, files) {
200
169
  for (const [path, e] of editors)
201
170
  overlay.set(path, e.text);
202
171
  const report = inventoryConfig({ ...options, sourceTexts: overlay }).report;
203
- validateConductorSources(options, editors, report);
172
+ validateConductorSources(options, editors, report, capabilities);
204
173
  // Literal values resolved from generated wiring are not secrets stored in the committed file.
205
174
  report.findings = report.findings.filter((f) => !(f.code === 'misplaced_key' &&
206
175
  f.key?.endsWith('client_secret') &&
@@ -83,7 +83,7 @@ async function resolveConfig(deps, configPathOverride, resolveProject = false) {
83
83
  ? { workspaceSelector: engine.bakers.workspace }
84
84
  : {}),
85
85
  });
86
- return composeConductorConfig(engine, connection);
86
+ return await composeConductorConfig(engine, connection);
87
87
  }
88
88
  const unscoped = await loadReadyBbConnection(host, {
89
89
  workspaceIdOverride: '',
@@ -95,7 +95,7 @@ async function resolveConfig(deps, configPathOverride, resolveProject = false) {
95
95
  workspaceSelector: context.workspaceId,
96
96
  });
97
97
  return {
98
- ...composeConductorConfig(engine, connection),
98
+ ...(await composeConductorConfig(engine, connection)),
99
99
  resolved_bakers: context,
100
100
  };
101
101
  }
@@ -249,6 +249,16 @@ async function cmdPoll(deps, log = {}) {
249
249
  /** `bakers conductor check`: whether each enabled agent can start its sandbox. */
250
250
  async function cmdCheck(deps) {
251
251
  const config = await resolveConfig(deps);
252
+ const sources = config.slot_sources ?? {};
253
+ const packages = config.slot_packages ?? {};
254
+ for (const [slot, plugin] of [
255
+ ['server', config.remote],
256
+ ['executor', config.executor],
257
+ ['worktree', config.workspace],
258
+ ]) {
259
+ const source = sources[slot];
260
+ console.log(`${slot}: ${packages[slot] ?? plugin.id}${source ? ` (${source})` : ''}`);
261
+ }
252
262
  const warning = runtimeSandboxWarning(config.runtime?.id);
253
263
  if (warning)
254
264
  console.warn(`warning: ${warning}`);
@@ -763,14 +773,20 @@ async function cmdStartBody(deps, log, force = false, choice = {}) {
763
773
  // is what tells a genuine new heartbeat apart from the killed conductor's
764
774
  // stale-but-still-in-window one.
765
775
  const priorLastSeen = existing?.lastSeen;
766
- if (existing && classify(existing) === 'online') {
776
+ const probe = deps.procProbe ?? defaultProcProbe();
777
+ // A record online by heartbeat whose pid is provably gone or recycled on
778
+ // this host (same proof as `ls`) is offline: its offline write was lost.
779
+ const recordOnline = existing !== undefined && classify(existing) === 'online';
780
+ if (recordOnline && classify(existing, thisHostKey, probe) !== 'online') {
781
+ console.log(`conductor ${id}: recorded pid ${existing.lastPid} is not running here; starting`);
782
+ }
783
+ else if (recordOnline) {
767
784
  if (!force) {
768
785
  const age = heartbeatAgeSeconds(existing);
769
786
  console.log(`conductor ${id} already running (pid ${existing.lastPid ?? 'unknown'}, ` +
770
787
  `heartbeat ${age === undefined ? 'age unknown' : `${age}s old`})`);
771
788
  return;
772
789
  }
773
- const probe = deps.procProbe ?? defaultProcProbe();
774
790
  const stopOutcome = signalVerifiedProcess({
775
791
  pid: existing.lastPid,
776
792
  hostKey: existing.hostKey,
@@ -80,7 +80,9 @@ export declare function loadConductorConfig(configFile: string): Promise<Conduct
80
80
  * `selectRemote` read them exactly as before — the fields just arrive from
81
81
  * connection file now.
82
82
  */
83
- export declare function composeConductorConfig(engine: ConductorEngineConfig, connection: Pick<BbConnectionConfig, 'site' | 'plugins'>): ConductorFileConfig;
83
+ export declare function composeConductorConfig(engine: ConductorEngineConfig, connection: Pick<BbConnectionConfig, 'site' | 'plugins' | 'config_path'> & Partial<Pick<BbConnectionConfig, 'server'>>): Promise<ConductorFileConfig>;
84
+ /** The server a connection gets when neither it nor the project names one. */
85
+ export declare const DEFAULT_SERVER_ADDON = "@bakers-build/addon-remote-drupal";
84
86
  /**
85
87
  * The conductor variants in a `.bakers/` dir (`conductor` for
86
88
  * `project.config.js`), by the loader's own naming rule.
@@ -5,9 +5,10 @@ import { assertSchemaVersion, assertValidConfig, discoverAddons, discoverScoped,
5
5
  import { readBbProjectSelection } from './cli/project-context.js';
6
6
  import { SHARED_SECURITY_KEY, validateSharedSecurity, } from './plugins/agent-args.js';
7
7
  import { validateMarketplaces } from './plugins/agent-home.js';
8
+ import { assertProtectedEntryPoints } from './plugins/host-commands.js';
8
9
  import { loadInbox } from './plugins/message.js';
9
10
  import { narrowConductorContributions, } from './plugins/preset.js';
10
- import { loadTools, provisionRuns, provisionTools } from './plugins/tools.js';
11
+ import { loadTools, provisionRuns, provisionTools, } from './plugins/tools.js';
11
12
  // BB-201: the `.bakers/` walk-up + connection resolution moved to `@bakers-build/core`
12
13
  // (`resolveConfigPath` / `resolveBbConfigPath` / `findBbDir`). Re-export the
13
14
  // engine resolver here so existing conductor callers/tests keep importing it
@@ -172,6 +173,10 @@ function requirePlugin(value, kind) {
172
173
  * "unknown command dropsh" breakage after the @bakers → @bakers-ai scope rename).
173
174
  * Mirror of dropsh 0.4.1 `loadNamedPlugin` / `resolveSlot`.
174
175
  */
176
+ /** The `use` package of each slot value that is a descriptor. */
177
+ function packagesOf(slots) {
178
+ return Object.fromEntries(Object.entries(slots).flatMap(([slot, value]) => isPluginDescriptor(value) ? [[slot, value.use]] : []));
179
+ }
175
180
  function isPluginDescriptor(entry) {
176
181
  return isRecord(entry) && typeof entry.use === 'string';
177
182
  }
@@ -371,22 +376,62 @@ export async function loadConductorConfig(configFile) {
371
376
  ]);
372
377
  const discovered = narrowConductorContributions(await discoverScoped(effectiveAddons, 'conductor', { agentGlobals }));
373
378
  const wired = resolveConductorSlots(discovered);
379
+ // The schema has checked the shape; the list is the project's alone.
380
+ const readOnly = config.runtime
381
+ ?.read_only;
382
+ const isolates = wired.runtime?.isolates === true;
383
+ if (isolates) {
384
+ try {
385
+ assertProtectedEntryPoints(config.hooks, readOnly ?? []);
386
+ }
387
+ catch (error) {
388
+ throw new Error(`${configPath}: ${error.message}`);
389
+ }
390
+ }
374
391
  const hookListeners = validateHookListeners(discovered.hooks);
375
392
  // Unlike the inbox, a broken or ambiguous tool set stops the conductor.
376
393
  // Tools load first so inbox bindings can be checked against them.
377
394
  const provisioning = provisionRuns();
378
395
  const toolSets = [
379
396
  ...discovered.addonTools,
380
- ...provisionTools(config.hooks?.provision_up, provisioning),
397
+ ...provisionTools(config.hooks?.provision_up, provisioning, {
398
+ ...(config.hooks?.provision_exec
399
+ ? { exec: config.hooks.provision_exec }
400
+ : {}),
401
+ isolates,
402
+ }),
381
403
  ];
382
- const tools = toolSets.length > 0 ? await loadTools(toolSets) : undefined;
404
+ let agentCatalog;
405
+ const tools = toolSets.length > 0
406
+ ? await loadTools(toolSets, {
407
+ agentCatalog: () => {
408
+ if (!agentCatalog)
409
+ throw new Error('agent catalog is not resolved yet');
410
+ return agentCatalog;
411
+ },
412
+ })
413
+ : undefined;
383
414
  const inboxAddons = await loadInboxAddons(discovered.addonInbox, new Set(tools?.list().map((t) => t.name)));
415
+ // No server here is fine: composeConductorConfig takes the connection's or the default.
384
416
  const remote = config.server !== undefined
385
417
  ? await resolveSlot(config.server, 'server', configPath)
386
418
  : wired.remote;
387
- if (!remote) {
388
- throw new Error('project config resolves no server — name a server addon in addons[] or set the server slot');
389
- }
419
+ const slotSources = {
420
+ ...(remote
421
+ ? { server: config.server !== undefined ? 'slot' : 'addons' }
422
+ : {}),
423
+ executor: machineCtx.executor !== undefined
424
+ ? 'machine'
425
+ : config.executor !== undefined
426
+ ? 'slot'
427
+ : 'addons',
428
+ worktree: config.worktree !== undefined ? 'slot' : 'addons',
429
+ };
430
+ const slotPackages = packagesOf({
431
+ server: config.server,
432
+ executor: machineCtx.executor ?? config.executor,
433
+ worktree: config.worktree,
434
+ });
390
435
  // The machine may run its own installed tool: its explicit executor wins
391
436
  // over the project's, which wins over the one discovered from addons[].
392
437
  const executor = machineCtx.executor !== undefined
@@ -505,8 +550,17 @@ export async function loadConductorConfig(configFile) {
505
550
  throw new Error(`agents.routes.default names unavailable alias '${defaultAgent}'`);
506
551
  if (!routes.default)
507
552
  routes.default = { '*': defaultAgent };
553
+ agentCatalog = {
554
+ agents: candidates,
555
+ enabled_agents: enabledAgents,
556
+ disabled_agents: disabled,
557
+ default_agent: defaultAgent,
558
+ routes,
559
+ };
508
560
  return {
509
- remote,
561
+ ...(remote ? { remote } : {}),
562
+ slot_sources: slotSources,
563
+ slot_packages: slotPackages,
510
564
  executor,
511
565
  agents: candidates,
512
566
  enabled_agents: enabledAgents,
@@ -520,6 +574,7 @@ export async function loadConductorConfig(configFile) {
520
574
  : {}),
521
575
  workspace,
522
576
  ...(wired.runtime ? { runtime: wired.runtime } : {}),
577
+ ...(readOnly ? { readOnly } : {}),
523
578
  marketplaces,
524
579
  hookListeners,
525
580
  ...(inboxAddons.length > 0 ? { inboxAddons } : {}),
@@ -563,13 +618,36 @@ export async function loadConductorConfig(configFile) {
563
618
  * `selectRemote` read them exactly as before — the fields just arrive from
564
619
  * connection file now.
565
620
  */
566
- export function composeConductorConfig(engine, connection) {
621
+ export async function composeConductorConfig(engine, connection) {
622
+ // The project's server wins, then the connection's, then the Drupal default.
623
+ const descriptor = engine.remote
624
+ ? undefined
625
+ : (connection.server ?? { use: DEFAULT_SERVER_ADDON });
626
+ const [remote, server] = engine.remote
627
+ ? [engine.remote, engine.slot_sources?.server ?? 'slot']
628
+ : connection.server !== undefined
629
+ ? [
630
+ await resolveSlot(connection.server, 'server', connection.config_path),
631
+ 'connection',
632
+ ]
633
+ : [
634
+ await resolveSlot({ use: DEFAULT_SERVER_ADDON }, 'server', engine.config_path),
635
+ 'default',
636
+ ];
567
637
  return {
568
638
  ...engine,
639
+ remote,
640
+ slot_sources: { ...engine.slot_sources, server },
641
+ slot_packages: {
642
+ ...engine.slot_packages,
643
+ ...packagesOf({ server: descriptor }),
644
+ },
569
645
  site: connection.site,
570
646
  ...(connection.plugins.length > 0 ? { plugins: connection.plugins } : {}),
571
647
  };
572
648
  }
649
+ /** The server a connection gets when neither it nor the project names one. */
650
+ export const DEFAULT_SERVER_ADDON = '@bakers-build/addon-remote-drupal';
573
651
  /**
574
652
  * The conductor variants in a `.bakers/` dir (`conductor` for
575
653
  * `project.config.js`), by the loader's own naming rule.
@@ -1,5 +1,5 @@
1
1
  export { AmbiguousProjectNameError, type ResolvedBbProjectContext, resolveBbProjectContext, } from './bakers-project-context.js';
2
- export { type AgentFootprint, type AgentModelApi, type AgentRunContext, type AgentRunIdentity, type AgentRunPreparation, type AgentRuntimeInfo, type BbAgent, CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOL_TIMEOUT_MS, CONDUCTOR_TOOLS_SERVER, CONDUCTOR_URL_ENV, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, type PluginLaunch, type RunEnvPolicy, } from './plugins/agent.js';
2
+ export { type AgentFootprint, type AgentModelApi, type AgentRunContext, type AgentRunIdentity, type AgentRunPreparation, type AgentRuntimeInfo, type BbAgent, CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOL_TIMEOUT_MS, CONDUCTOR_TOOLS_SERVER, CONDUCTOR_URL_ENV, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, type PluginLaunch, type RunBind, type RunEnvPolicy, } from './plugins/agent.js';
3
3
  export { detectKnownOverrides, type KnownOptionSpec, type KnownOverrides, type KnownScalarKind, type ResolvedSecurity, resolveAgentCliOptions, resolveSecurityOptions, type SandboxOptions, SECURITY_MODES, type SecurityMode, type SecurityOptions, type SecurityReport, SHARED_SECURITY_KEY, type SharedListKey, type SharedSecurity, validateAgentArgs, validateOptionalBoolean, validateOptionalString, validateSharedSecurity, } from './plugins/agent-args.js';
4
4
  export { ensureHome, homeKey, homePath, type MarketplaceDeclaration, validateMarketplaces, } from './plugins/agent-home.js';
5
5
  export type { BbExecutor, ConductorStartContext, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, MachineRegistrationData, OpenWorkspaceContext, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
@@ -12,6 +12,6 @@ export type { ActiveRun, AddonDefinitionV2, AddonRegistration, BbRemote, Claimed
12
12
  export { ConductorTakeoverRequired } from './plugins/remote.js';
13
13
  export { type BbRuntime, hostRuntime, type RuntimeLaunch, type RuntimePlugin, type RuntimeRun, } from './plugins/runtime.js';
14
14
  export { installCommand, lastLine, type SandboxHost, type SandboxPreflight, sandboxFailures, systemSandboxHost, } from './plugins/sandbox-preflight.js';
15
- export type { AddonTools, ToolBinding, ToolDefinition, ToolHandler, ToolRequest, ToolResult, } from './plugins/tools.js';
15
+ export type { AddonTools, AgentCatalog, ToolBinding, ToolDefinition, ToolHandler, ToolHost, ToolRequest, ToolResult, } from './plugins/tools.js';
16
16
  export type { BbWorkspace, EnsuredWorkspace, } from './plugins/workspace.js';
17
17
  export type { ConductorEngineConfig, ConductorFileConfig, ConductorSettings, } from './types.js';
@@ -127,6 +127,12 @@ export declare class Conductor {
127
127
  private enqueueFinalize;
128
128
  /** Finalises one run; a failure is logged and retried next tick. */
129
129
  private finalizeOne;
130
+ /**
131
+ * Bring an isolated run's commits to the ticket branch in the parent
132
+ * repository. Best-effort: a refused transfer is logged and leaves the run's
133
+ * Git directory in place until the next run of the ticket starts.
134
+ */
135
+ private transferRunCommits;
130
136
  /** Read the run's transcript and parse its footprint for the close write. */
131
137
  private captureRun;
132
138
  /**
@@ -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;
@@ -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
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.9.1-next.5",
3
+ "version": "0.9.1-next.6",
4
4
  "description": "bakers.build conductor engine + CLI: registers, claims tickets via JSON:API, dispatches agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,14 +32,14 @@
32
32
  "dependencies": {
33
33
  "@dropsh/plugin-jsonapi-schema": "^0.8.2",
34
34
  "@dropsh/plugin-oauth2": "^0.8.2",
35
- "@bakers-build/core": "^0.9.1-next.5",
36
- "@bakers-build/message": "^0.9.1-next.5",
35
+ "@bakers-build/core": "^0.9.1-next.6",
36
+ "@bakers-build/message": "^0.9.1-next.6",
37
37
  "@modelcontextprotocol/sdk": "1.32.1",
38
38
  "commander": "^12.1.0",
39
39
  "dropsh": "^0.8.2"
40
40
  },
41
41
  "bakersBuild": {
42
- "commit": "d9242cad6cabee1faf010b5d46ac1bac33f6e0a1",
42
+ "commit": "e7d9921d51d5c045f29ca7e35d1e6a348e6ddf08",
43
43
  "channel": "next"
44
44
  }
45
45
  }