@bakers-build/conductor 0.6.1-next.4 → 0.6.1-next.5

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.
@@ -5,7 +5,7 @@ import { assertSchemaVersion1, discoverAddons, discoverScoped, findDefaultExport
5
5
  import { readBbProjectSelection } from './cli/project-context.js';
6
6
  import { loadInbox } from './plugins/message.js';
7
7
  import { narrowConductorContributions, } from './plugins/preset.js';
8
- import { loadTools, provisionTools } from './plugins/tools.js';
8
+ import { loadTools, provisionRuns, provisionTools } from './plugins/tools.js';
9
9
  // BB-201: the `.bakers/` walk-up + connection resolution moved to `@bakers-build/core`
10
10
  // (`resolveConfigPath` / `resolveBbConfigPath` / `findBbDir`). Re-export the
11
11
  // engine resolver here so existing conductor callers/tests keep importing it
@@ -365,9 +365,10 @@ export async function loadConductorConfig(configFile) {
365
365
  const hookListeners = validateHookListeners(discovered.hooks);
366
366
  // Unlike the inbox, a broken or ambiguous tool set stops the conductor.
367
367
  // Tools load first so inbox bindings can be checked against them.
368
+ const provisioning = provisionRuns();
368
369
  const toolSets = [
369
370
  ...discovered.addonTools,
370
- ...provisionTools(config.hooks?.provision_up),
371
+ ...provisionTools(config.hooks?.provision_up, provisioning),
371
372
  ];
372
373
  const tools = toolSets.length > 0 ? await loadTools(toolSets) : undefined;
373
374
  const inboxAddons = await loadInboxAddons(discovered.addonInbox, new Set(tools?.list().map((t) => t.name)));
@@ -542,6 +543,7 @@ export async function loadConductorConfig(configFile) {
542
543
  hookListeners,
543
544
  ...(inboxAddons.length > 0 ? { inboxAddons } : {}),
544
545
  ...(tools !== undefined ? { tools } : {}),
546
+ ...(config.hooks?.provision_up !== undefined ? { provisioning } : {}),
545
547
  ...(processHost !== undefined ? { processHost } : {}),
546
548
  bakers,
547
549
  ...identityOf(machineCtx, project, variant),
@@ -283,7 +283,9 @@ export class Conductor {
283
283
  this.logger.info({ conductorId: this.config.conductor_id, url: this.toolServer.url }, 'tool server started');
284
284
  }
285
285
  async stopTools() {
286
+ // Server first, so no new provision_up starts a run after the stop.
286
287
  await this.toolServer?.stop();
288
+ await this.config.provisioning?.stop();
287
289
  this.toolServer = undefined;
288
290
  this.runTokens.clear();
289
291
  }
@@ -909,6 +911,8 @@ export class Conductor {
909
911
  // workspace just created MUST exist, and silencing a hook there would
910
912
  // hide a real provisioning failure.
911
913
  if (t.worktreePath) {
914
+ // A provisioning outlives its run, never its ticket: end it before teardown.
915
+ await this.config.provisioning?.stop(t.worktreePath);
912
916
  if (existsSync(t.worktreePath)) {
913
917
  await this.recordMrChanges(t);
914
918
  // BB-599: listeners get the ticket's current context; the shell
@@ -57,14 +57,28 @@ export interface ToolRegistry {
57
57
  }
58
58
  /** `hooks.provision_up`: one command, or a command per profile. */
59
59
  export type ProvisionHook = string | Record<string, string>;
60
+ type ShellResult = {
61
+ exitCode: number;
62
+ output: string;
63
+ };
64
+ /** Provisioning runs the conductor owns, one per worktree and command. */
65
+ export interface ProvisionRuns {
66
+ /** Joins the running command of this worktree, or starts it. */
67
+ run(worktreePath: string, command: string): Promise<ShellResult>;
68
+ /** Kills the runs of one worktree, or all; resolves once they closed. */
69
+ stop(worktreePath?: string): Promise<void>;
70
+ }
71
+ export declare function provisionRuns(timeoutMs?: number): ProvisionRuns;
60
72
  /**
61
73
  * The core `provision_up(profile?)` tool, offered only when the hook is set.
62
- * The agent picks when and which configured profile, never the command.
74
+ * The agent picks when and which configured profile, never the command. The
75
+ * command outlives its caller: the call's signal is ignored on purpose.
63
76
  */
64
- export declare function provisionTools(hook: ProvisionHook | undefined): DiscoveredTools[];
77
+ export declare function provisionTools(hook: ProvisionHook | undefined, runs?: ProvisionRuns): DiscoveredTools[];
65
78
  /**
66
79
  * Resolves every addon's handlers and checks that handlers and declared tools
67
80
  * match one to one. A tool name declared by two addons is an error, so the
68
81
  * conductor never starts with an ambiguous tool.
69
82
  */
70
83
  export declare function loadTools(found: readonly DiscoveredTools[]): Promise<ToolRegistry>;
84
+ export {};
@@ -7,11 +7,35 @@ import { spawn } from 'node:child_process';
7
7
  import { payloadSchema, validateArgs, } from '@bakers-build/message';
8
8
  const PROVISION_TIMEOUT_MS = 30 * 60_000;
9
9
  const OUTPUT_CAP = 64 * 1024;
10
+ export function provisionRuns(timeoutMs = PROVISION_TIMEOUT_MS) {
11
+ const running = new Map();
12
+ return {
13
+ run(worktreePath, command) {
14
+ const key = JSON.stringify([worktreePath, command]);
15
+ const current = running.get(key);
16
+ if (current)
17
+ return current.done;
18
+ const abort = new AbortController();
19
+ const done = shell(command, worktreePath, abort.signal, timeoutMs);
20
+ running.set(key, { worktreePath, abort, done });
21
+ const forget = () => running.delete(key);
22
+ done.then(forget, forget);
23
+ return done;
24
+ },
25
+ async stop(worktreePath) {
26
+ const ending = [...running.values()].filter((r) => worktreePath === undefined || r.worktreePath === worktreePath);
27
+ for (const r of ending)
28
+ r.abort.abort();
29
+ await Promise.allSettled(ending.map((r) => r.done));
30
+ },
31
+ };
32
+ }
10
33
  /**
11
34
  * The core `provision_up(profile?)` tool, offered only when the hook is set.
12
- * The agent picks when and which configured profile, never the command.
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.
13
37
  */
14
- export function provisionTools(hook) {
38
+ export function provisionTools(hook, runs = provisionRuns()) {
15
39
  if (hook === undefined)
16
40
  return [];
17
41
  const profiles = typeof hook === 'string' ? undefined : hook;
@@ -52,7 +76,7 @@ export function provisionTools(hook) {
52
76
  provision_up: async (req) => {
53
77
  const command = commandFor(req.args.profile);
54
78
  // shortcut: inherits the conductor's env, not the run's BB_* env; pass it through the binding once a hook needs it.
55
- const { exitCode, output } = await shell(command, req.worktreePath, req.signal);
79
+ const { exitCode, output } = await runs.run(req.worktreePath, command);
56
80
  const text = `exit ${exitCode}\n${output}`;
57
81
  if (exitCode !== 0)
58
82
  throw new Error(text);
@@ -63,26 +87,49 @@ export function provisionTools(hook) {
63
87
  },
64
88
  ];
65
89
  }
66
- /** `sh -c` with stdout and stderr interleaved, the tail kept, killed at the timeout. */
67
- function shell(command, cwd, signal) {
90
+ /**
91
+ * `sh -c` with stdout and stderr interleaved, the tail kept. Its own process
92
+ * group, killed whole at the timeout or abort, so no child outlives it.
93
+ */
94
+ function shell(command, cwd, signal, timeoutMs) {
68
95
  return new Promise((done, fail) => {
69
96
  const child = spawn('sh', ['-c', command], {
70
97
  cwd,
71
- signal,
72
- timeout: PROVISION_TIMEOUT_MS,
98
+ detached: true,
73
99
  stdio: ['ignore', 'pipe', 'pipe'],
74
100
  });
101
+ let killed = false;
102
+ const kill = () => {
103
+ try {
104
+ if (child.pid)
105
+ process.kill(-child.pid, 'SIGTERM');
106
+ killed = true;
107
+ }
108
+ catch {
109
+ // The group is already gone.
110
+ }
111
+ };
112
+ // Armed until 'close', not 'exit': a child of sh can hold the output open after sh exits.
113
+ const timer = setTimeout(kill, timeoutMs);
114
+ signal.addEventListener('abort', kill, { once: true });
75
115
  let output = '';
76
116
  const collect = (chunk) => {
77
117
  output = (output + chunk.toString('utf8')).slice(-OUTPUT_CAP);
78
118
  };
79
119
  child.stdout.on('data', collect);
80
120
  child.stderr.on('data', collect);
81
- child.on('error', fail);
82
- child.on('close', (code, sig) => done({
83
- exitCode: code ?? 124,
84
- output: sig ? `${output}\n(killed: ${sig})` : output,
85
- }));
121
+ child.on('error', (err) => {
122
+ clearTimeout(timer);
123
+ fail(err);
124
+ });
125
+ child.on('close', (code, sig) => {
126
+ clearTimeout(timer);
127
+ const by = sig ?? (killed ? 'SIGTERM' : null);
128
+ done({
129
+ exitCode: by ? 124 : (code ?? 124),
130
+ output: by ? `${output}\n(killed: ${by})` : output,
131
+ });
132
+ });
86
133
  });
87
134
  }
88
135
  const silent = {
@@ -7,7 +7,7 @@ import type { LoadedInbox } from './plugins/message.js';
7
7
  import type { AgentCandidate, ExecutorPlugin, RemotePlugin, ResolvedAgent, WorkspacePlugin } from './plugins/plugins.js';
8
8
  import type { HerdrHost } from './plugins/process-host.js';
9
9
  import type { Ticket } from './plugins/remote.js';
10
- import type { ProvisionHook, ToolRegistry } from './plugins/tools.js';
10
+ import type { ProvisionHook, ProvisionRuns, ToolRegistry } from './plugins/tools.js';
11
11
  /** Normalized single conductor. */
12
12
  export interface ConductorSettings {
13
13
  /** Display label, sent once at registration: `<machine label> · <project>[/<variant>]`. */
@@ -107,6 +107,8 @@ export interface ConductorFileConfig extends ConductorSettings {
107
107
  inboxAddons?: LoadedInbox[];
108
108
  /** Agent tools from the conductor `addons[]` `tools` exports. Absent means none. */
109
109
  tools?: ToolRegistry;
110
+ /** The `provision_up` runs, stopped at ticket end and conductor stop. Absent without the hook. */
111
+ provisioning?: Pick<ProvisionRuns, 'stop'>;
110
112
  /**
111
113
  * Conductor process host from the `processHosts` accumulator (last wins).
112
114
  * Absent when no addon contributed one — `bakers oven start` then fails
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.6.1-next.4",
3
+ "version": "0.6.1-next.5",
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.6.1-next.4",
36
- "@bakers-build/message": "^0.6.1-next.4",
35
+ "@bakers-build/core": "^0.6.1-next.5",
36
+ "@bakers-build/message": "^0.6.1-next.5",
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": "f9ce4e2980c83b80ba5f007fe2d8e534797cf66c",
42
+ "commit": "314f28982940df736bea55293a81435d37864b31",
43
43
  "channel": "next"
44
44
  }
45
45
  }