@bakers-build/conductor 0.19.1-next.2 → 0.19.1-next.4

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.
@@ -3,7 +3,7 @@ import { mkdirSync } from 'node:fs';
3
3
  import { basename, dirname, join, resolve, sep } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
5
  import { promisify } from 'node:util';
6
- import { CommandRunner, checkForUpdate, configHomeOf, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, envsDir, homeBbDir, loadEnvFiles, loadReadyBbConnection, printVersionLine, readCliVersion, readMachineContext, resolveCliVersion, resolveConfigPath, secretsFilePath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, UNKNOWN_VERSION, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
6
+ import { addonEnvSources, CommandRunner, checkForUpdate, configHomeOf, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, envsDir, homeBbDir, loadEnvFiles, loadReadyBbConnection, printVersionLine, readCliVersion, readMachineContext, resolveCliVersion, resolveConfigPath, secretsFilePath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, UNKNOWN_VERSION, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
7
7
  import { Command } from 'commander';
8
8
  import { authStatus } from 'dropsh';
9
9
  import { resolveBbProjectContext } from '../bakers-project-context.js';
@@ -166,13 +166,17 @@ function logOptsOf(cmd) {
166
166
  * Every bakers env file, or undefined after printing why one was refused and
167
167
  * setting exit 1. The log names each file's keys, never their values.
168
168
  */
169
- function loadSecretsOrFail(logger) {
169
+ function loadSecretsOrFail(logger, config) {
170
170
  try {
171
171
  const files = loadEnvFiles();
172
172
  for (const [path, values] of Object.entries(files)) {
173
173
  const names = Object.keys(values);
174
174
  logger?.info({ path, secrets: names }, `${path}: ${names.join(', ')} set`);
175
175
  }
176
+ const addons = addonEnvSources(config?.addon_env ?? {}, config?.project ?? '', files);
177
+ for (const [addon, sources] of Object.entries(addons))
178
+ for (const [name, source] of Object.entries(sources))
179
+ logger?.info({ addon, name, source }, `${addon}: ${name} from ${source}`);
176
180
  return files;
177
181
  }
178
182
  catch (err) {
@@ -276,7 +280,7 @@ async function cmdPoll(deps, log = {}) {
276
280
  const config = await resolveConfig(deps, undefined, true);
277
281
  const checkoutRoot = await checkoutRootOf(config);
278
282
  const logger = loggerFor(checkoutRoot, log);
279
- const secrets = loadSecretsOrFail(logger);
283
+ const secrets = loadSecretsOrFail(logger, config);
280
284
  if (!secrets)
281
285
  return;
282
286
  if (!(await ensureAuthenticated(config, logger)))
@@ -402,12 +406,25 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
402
406
  // A watched file changed after this instant was not loaded: the watcher restarts on it.
403
407
  // A self-restart hands over when its watcher stopped looking, so a write during its drain counts.
404
408
  const loadedAt = Number(process.env.BAKERS_RESTART_SINCE) || Date.now();
405
- delete process.env.BAKERS_RESTART_SINCE;
406
409
  const config = await resolveConfig(deps, undefined, true);
407
410
  const checkoutRoot = await checkoutRootOf(config);
408
411
  const logger = loggerFor(checkoutRoot, log);
412
+ const execve = deps.execve ?? process.execve?.bind(process);
413
+ const reExec = (env) => execve?.(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)], env);
414
+ // Run cleanup SIGTERMs every process whose environ holds the run's marker.
415
+ const runUuid = process.env.BAKERS_RUN_UUID;
416
+ if (runUuid) {
417
+ logger.warn({ run: runUuid }, `started from run ${runUuid}; dropping the run marker`);
418
+ const { BAKERS_RUN_UUID: _marker, ...env } = process.env;
419
+ // Only a new image clears /proc/<pid>/environ; same pid and log.
420
+ if (execve)
421
+ return reExec(env);
422
+ delete process.env.BAKERS_RUN_UUID;
423
+ logger.warn({ node: process.version }, 'without process.execve (Node >= 22.15) the run cleanup can still end this conductor');
424
+ }
425
+ delete process.env.BAKERS_RESTART_SINCE;
409
426
  // Every start path ends here: detached child, self-restart and update re-exec.
410
- const secrets = loadSecretsOrFail(logger);
427
+ const secrets = loadSecretsOrFail(logger, config);
411
428
  if (!secrets)
412
429
  return;
413
430
  if (!(await ensureAuthenticated(config, logger)))
@@ -437,14 +454,17 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
437
454
  await conductor.startTools(join(homeBbDir(), 'conductors', `${conductor.id}.json`));
438
455
  const controller = new AbortController();
439
456
  let restart = false;
457
+ let reason = 'serve ended';
440
458
  // A stop wins over a restart already decided: `oven stop` must stay a stop.
441
- const onSignal = () => {
459
+ const onSignal = (signal) => {
442
460
  restart = false;
461
+ reason = signal;
462
+ logger.info({ signal }, `stopping on ${signal}`);
443
463
  controller.abort();
444
464
  };
445
- process.once('SIGINT', onSignal);
446
- process.once('SIGTERM', onSignal);
447
- const execve = deps.execve ?? process.execve?.bind(process);
465
+ const signalHandlers = ['SIGINT', 'SIGTERM', 'SIGHUP'].map((signal) => [signal, () => onSignal(signal)]);
466
+ for (const [signal, handler] of signalHandlers)
467
+ process.once(signal, handler);
448
468
  let watcher;
449
469
  const check = deps.checkConfig ?? defaultCheckConfig;
450
470
  // The restart re-runs loadSecretsOrFail, which exits on a bad file: check first.
@@ -462,6 +482,7 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
462
482
  const heldBack = new Set();
463
483
  const restartNow = (since = Date.now()) => {
464
484
  restart = true;
485
+ reason = 'restart';
465
486
  process.env.BAKERS_RESTART_SINCE = String(since);
466
487
  watcher?.close();
467
488
  clearInterval(versionTimer);
@@ -626,12 +647,17 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
626
647
  try {
627
648
  await conductor.serve(controller.signal);
628
649
  }
650
+ catch (err) {
651
+ reason = 'error';
652
+ logger.error({ err: String(err) }, `conductor failed: ${err}`);
653
+ throw err;
654
+ }
629
655
  finally {
630
656
  watcher?.close();
631
657
  clearInterval(versionTimer);
632
658
  await conductor.stopTools();
633
- process.removeListener('SIGINT', onSignal);
634
- process.removeListener('SIGTERM', onSignal);
659
+ for (const [signal, handler] of signalHandlers)
660
+ process.removeListener(signal, handler);
635
661
  // The exiting process writes its own `offline`. It has to be this process:
636
662
  // a heartbeat sets `online` unconditionally (ConductorRegistrar), so an
637
663
  // offline written by anyone else is erased by the next tick — the status
@@ -647,10 +673,11 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
647
673
  logger.warn({ conductorId: conductor.id, err: String(err) }, 'could not write offline status on shutdown; the lease reaper will');
648
674
  }
649
675
  }
676
+ logger.info({ reason }, 'conductor stopped');
650
677
  }
651
678
  // Same pid and log.
652
- if (restart && execve)
653
- execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)], process.env);
679
+ if (restart)
680
+ reExec(process.env);
654
681
  }
655
682
  async function defaultAskUpdate(question) {
656
683
  const rl = createInterface({
@@ -1,7 +1,7 @@
1
1
  import { readdirSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
- import { addonOptionKeys, assertSchemaVersion, assertValidConfig, discoverAddons, discoverScoped, findDefaultExportObject, loadAddonPreset, loadRunClone, machineContextPath, matchDelimiter, normalizeEntry, readMachineContext, resolveConductorSlots, resolveModuleEslintStyle, scanTopLevelProperties, scopeAddons, secretsFilePath, slotKeys, slotOptions, stemForConfigFile, } from '@bakers-build/core';
4
+ import { addonEnv, addonOptionKeys, assertSchemaVersion, assertValidConfig, discoverAddons, discoverScoped, envOptionNames, findDefaultExportObject, loadAddonPreset, loadEnvFiles, loadRunClone, machineContextPath, matchDelimiter, normalizeEntry, readMachineContext, resolveConductorSlots, resolveModuleEslintStyle, scanTopLevelProperties, scopeAddons, secretsFilePath, slotKeys, slotOptions, stemForConfigFile, } from '@bakers-build/core';
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';
@@ -600,8 +600,13 @@ export async function loadConductorConfig(configFile) {
600
600
  throw new Error('agent catalog is not resolved yet');
601
601
  return agentCatalog;
602
602
  },
603
+ // Read at call time: a bad env file fails the call, not every config load.
604
+ addonEnv: (names) => addonEnv(names, project, loadEnvFiles()),
603
605
  })
604
606
  : undefined;
607
+ const addonEnvNames = Object.fromEntries(discovered.addonTools
608
+ .map((addon) => [addon.name, envOptionNames(addon.options)])
609
+ .filter(([, names]) => names.length > 0));
605
610
  const inboxAddons = await loadInboxAddons(discovered.addonInbox, new Set(tools?.list().map((t) => t.name)));
606
611
  // No server here is fine: composeConductorConfig takes the connection's or the default.
607
612
  const remote = config.server !== undefined
@@ -757,6 +762,7 @@ export async function loadConductorConfig(configFile) {
757
762
  slot_sources: slotSources,
758
763
  slot_packages: slotPackages,
759
764
  slot_options: slotReport.values,
765
+ addon_env: addonEnvNames,
760
766
  ...(slotReport.rejected.length > 0
761
767
  ? { slot_options_rejected: slotReport.rejected }
762
768
  : {}),
@@ -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, AgentCatalog, ToolBinding, ToolDefinition, ToolHandler, ToolHost, ToolRequest, ToolResult, } from './plugins/tools.js';
15
+ export type { AddonToolHost, 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';
@@ -1,10 +1,16 @@
1
- import type { ConductorLogger } from '@bakers-build/core';
1
+ import { type AddonEnv, type ConductorLogger } from '@bakers-build/core';
2
2
  import { type MessageInput } from '@bakers-build/message';
3
3
  import type { ConductorEngineConfig, ProvisionExecCommand } from '../types.js';
4
4
  import type { Ticket } from './remote.js';
5
5
  export type AgentCatalog = Pick<ConductorEngineConfig, 'agents' | 'enabled_agents' | 'disabled_agents' | 'default_agent' | 'routes'>;
6
6
  export interface ToolHost {
7
7
  agentCatalog(): AgentCatalog;
8
+ /** Resolves `*_env` names from the shell and the env files; never writes `process.env`. */
9
+ addonEnv?(names: readonly string[]): AddonEnv;
10
+ }
11
+ /** The host one addon's handlers get: `env()` resolves only the names its own options give. */
12
+ export interface AddonToolHost extends ToolHost {
13
+ env(): AddonEnv;
8
14
  }
9
15
  /** A message input whose properties may also be lists of strings (argv). */
10
16
  export type ToolInput = Omit<MessageInput, 'properties'> & {
@@ -50,7 +56,7 @@ export interface AddonTools {
50
56
  contract: 1;
51
57
  tools: Record<string, ToolDefinition>;
52
58
  /** Lazy: imported only when the conductor loads the addon. */
53
- handlers: (options?: unknown, host?: ToolHost) => Promise<Record<string, ToolHandler>>;
59
+ handlers: (options?: unknown, host?: AddonToolHost) => Promise<Record<string, ToolHandler>>;
54
60
  }
55
61
  /** One `tools` export as discovery found it. */
56
62
  export interface DiscoveredTools {
@@ -4,6 +4,7 @@
4
4
  // server, and addons call each other's tools through the same registry.
5
5
  // Every call is bound to one worktree by the caller, never by an argument.
6
6
  import { spawn } from 'node:child_process';
7
+ import { envOptionNames, } from '@bakers-build/core';
7
8
  import { payloadSchema, validateArgs, } from '@bakers-build/message';
8
9
  export const PROVISION_TIMEOUT_MS = 30 * 60_000;
9
10
  const OUTPUT_CAP = 64 * 1024;
@@ -198,7 +199,18 @@ export async function loadTools(found, host) {
198
199
  const fail = (msg) => new Error(`addon ${addon.name}: ${msg}`);
199
200
  if (addon.tools.contract !== 1)
200
201
  throw fail(`unsupported tools contract ${addon.tools.contract}`);
201
- const handlers = await addon.tools.handlers(addon.options, host);
202
+ const names = envOptionNames(addon.options);
203
+ // The addon gets no resolver of its own: it can never ask for another name.
204
+ const { addonEnv: resolveEnv, ...shared } = host ?? {};
205
+ const handlers = await addon.tools.handlers(addon.options, host && {
206
+ ...shared,
207
+ // No names, no file read: a bad env file must not break an addon that names none.
208
+ env: () => (names.length ? resolveEnv?.(names) : undefined) ?? {
209
+ values: {},
210
+ sources: {},
211
+ searched: [],
212
+ },
213
+ });
202
214
  for (const [name, def] of Object.entries(addon.tools.tools)) {
203
215
  const handler = handlers[name];
204
216
  if (typeof handler !== 'function')
@@ -103,6 +103,8 @@ export interface ConductorSettings {
103
103
  key: string;
104
104
  value: unknown;
105
105
  }[];
106
+ /** Per tool addon, the variables its `*_env` options name; addons without any are left out. */
107
+ addon_env?: Record<string, string[]>;
106
108
  }
107
109
  export type OptionSlot = 'agent' | 'runtime';
108
110
  export interface SlotKeyReport {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.19.1-next.2",
3
+ "version": "0.19.1-next.4",
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.19.1-next.2",
36
- "@bakers-build/message": "^0.19.1-next.2",
35
+ "@bakers-build/core": "^0.19.1-next.4",
36
+ "@bakers-build/message": "^0.19.1-next.4",
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": "e30620a66141c1a790cc993de7cdc7379bcc6720",
42
+ "commit": "682730a11f21199f6bccc581bce98fead5655458",
43
43
  "channel": "next"
44
44
  }
45
45
  }