@bakers-build/conductor 0.6.1-next.6 → 0.6.1-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,16 +3,41 @@
3
3
  // at launch, binds every call to that run's worktree. The operator token
4
4
  // (endpoint file, 0600) may name a worktree under the workspace root, for
5
5
  // the CLI's plain JSON `POST /call`.
6
- import { randomBytes } from 'node:crypto';
7
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
6
+ //
7
+ // With an endpoint file, the port and the run grants (token hash and binding,
8
+ // never the raw token) persist in `<id>.tools.json` beside it, so a running
9
+ // agent's baked-in URL and token survive a conductor restart.
10
+ import { createHash, randomBytes } from 'node:crypto';
11
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
8
12
  import { createServer, } from 'node:http';
9
13
  import { dirname, relative, resolve } from 'node:path';
10
14
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
11
15
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
12
16
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
13
17
  import { CONDUCTOR_TOOLS_SERVER } from '../plugins/agent.js';
14
- import { SITE_TOOLS, siteToolProxy } from './site-tools.js';
18
+ import { SITE_TOOLS, SITE_WRITE_TOOLS, siteToolProxy } from './site-tools.js';
15
19
  const newToken = () => randomBytes(32).toString('hex');
20
+ const hashOf = (token) => createHash('sha256').update(token).digest('hex');
21
+ function readState(file, logger) {
22
+ if (!file)
23
+ return { runs: {} };
24
+ try {
25
+ const saved = JSON.parse(readFileSync(file, 'utf8'));
26
+ const runs = saved?.runs;
27
+ const port = saved?.port;
28
+ return {
29
+ runs: typeof runs === 'object' && runs
30
+ ? runs
31
+ : {},
32
+ ...(Number.isInteger(port) ? { port: port } : {}),
33
+ };
34
+ }
35
+ catch (err) {
36
+ if (err.code !== 'ENOENT')
37
+ logger?.warn({ err, file }, 'tool server state unreadable, starting empty');
38
+ return { runs: {} };
39
+ }
40
+ }
16
41
  function bearer(req) {
17
42
  const m = /^Bearer (.+)$/.exec(req.headers.authorization ?? '');
18
43
  return m?.[1];
@@ -41,8 +66,24 @@ export async function startToolServer(options) {
41
66
  if (clash)
42
67
  throw new Error(`addon tool ${clash.name} has the name of a bakers site tool`);
43
68
  }
44
- const runs = new Map();
69
+ const stateFile = options.endpointFile?.replace(/(\.json)?$/, '.tools.json');
70
+ const saved = readState(stateFile, logger);
71
+ const runs = new Map(Object.entries(saved.runs).filter(([run]) => !options.openRuns || options.openRuns.includes(run)));
45
72
  const operatorToken = newToken();
73
+ let port = 0;
74
+ const persist = () => {
75
+ if (!stateFile)
76
+ return;
77
+ const state = { port, runs: Object.fromEntries(runs) };
78
+ writeFileSync(`${stateFile}.tmp`, JSON.stringify(state), { mode: 0o600 });
79
+ renameSync(`${stateFile}.tmp`, stateFile);
80
+ };
81
+ const bindingOf = (token) => {
82
+ if (!token)
83
+ return undefined;
84
+ const hash = hashOf(token);
85
+ return [...runs.values()].find((g) => g.hash === hash)?.binding;
86
+ };
46
87
  const mcpServer = (binding) => {
47
88
  const server = new Server({ name: CONDUCTOR_TOOLS_SERVER, version: '1.0.0' }, { capabilities: { tools: {} } });
48
89
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
@@ -54,8 +95,19 @@ export async function startToolServer(options) {
54
95
  }));
55
96
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
56
97
  try {
57
- if (site && SITE_TOOLS.includes(request.params.name))
58
- return await site.call(request.params.name, request.params.arguments ?? {}, binding);
98
+ if (site && SITE_TOOLS.includes(request.params.name)) {
99
+ const result = await site.call(request.params.name, request.params.arguments ?? {}, binding);
100
+ if (SITE_WRITE_TOOLS.includes(request.params.name)) {
101
+ // The write already succeeded: a failing hook must not make the agent retry it.
102
+ try {
103
+ options.onSiteWrite?.(binding);
104
+ }
105
+ catch (err) {
106
+ logger?.warn({ err: String(err) }, 'site write hook failed');
107
+ }
108
+ }
109
+ return result;
110
+ }
59
111
  const result = await registry.call(request.params.name, request.params.arguments, binding, { signal: extra.signal, ...(logger ? { logger } : {}) });
60
112
  return { content: [{ type: 'text', text: result.text }] };
61
113
  }
@@ -96,7 +148,7 @@ export async function startToolServer(options) {
96
148
  const handle = async () => {
97
149
  if (req.method === 'POST' && req.url === '/call')
98
150
  return operatorCall(req, res);
99
- const binding = runs.get(bearer(req) ?? '');
151
+ const binding = bindingOf(bearer(req));
100
152
  if (!binding)
101
153
  return send(res, 401, {
102
154
  error: 'unknown run token — conductor restarted?',
@@ -120,11 +172,28 @@ export async function startToolServer(options) {
120
172
  send(res, 500, { error: 'internal error' });
121
173
  });
122
174
  });
123
- await new Promise((done) => http.listen(0, '127.0.0.1', done));
124
- const { port } = http.address();
175
+ const listen = (at) => new Promise((done, fail) => {
176
+ http.once('error', fail);
177
+ http.listen(at, '127.0.0.1', () => {
178
+ http.off('error', fail);
179
+ done();
180
+ });
181
+ });
182
+ try {
183
+ await listen(saved.port ?? 0);
184
+ }
185
+ catch (err) {
186
+ if (err.code !== 'EADDRINUSE' || !saved.port)
187
+ throw err;
188
+ // shortcut: runs launched before the restart lose their tools until re-dispatched.
189
+ logger?.warn({ port: saved.port }, 'tool server port taken, falling back to a random port');
190
+ await listen(0);
191
+ }
192
+ port = http.address().port;
125
193
  const url = `http://127.0.0.1:${port}`;
126
194
  if (options.endpointFile) {
127
195
  mkdirSync(dirname(options.endpointFile), { recursive: true, mode: 0o700 });
196
+ persist();
128
197
  const endpoint = {
129
198
  url,
130
199
  operatorToken,
@@ -137,18 +206,20 @@ export async function startToolServer(options) {
137
206
  }
138
207
  return {
139
208
  url,
140
- issueRunToken: (binding) => {
209
+ issueRunToken: (runUuid, binding) => {
141
210
  const token = newToken();
142
- runs.set(token, binding);
211
+ runs.set(runUuid, { hash: hashOf(token), binding });
212
+ persist();
143
213
  return token;
144
214
  },
145
- revokeRunToken: (token) => {
146
- runs.delete(token);
215
+ revokeRunToken: (runUuid) => {
216
+ if (runs.delete(runUuid))
217
+ persist();
147
218
  },
148
219
  stop: async () => {
220
+ // The state file stays: the next start serves the same grants.
149
221
  if (options.endpointFile)
150
222
  rmSync(options.endpointFile, { force: true });
151
- runs.clear();
152
223
  http.closeAllConnections();
153
224
  await new Promise((done) => http.close(() => done()));
154
225
  },
@@ -0,0 +1,2 @@
1
+ /** Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws. */
2
+ export declare function signalUi(dir: string): void;
@@ -0,0 +1,41 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { bumpUiRefresh, configHomeOf, UI_REFRESH_FILE, } from '@bakers-build/core';
5
+ // shortcut: root-anchored, so it misses a project in a repo subdirectory; build it from `git rev-parse --show-prefix` when one exists.
6
+ const EXCLUDE_LINE = `/.bakers/${UI_REFRESH_FILE}`;
7
+ /** Repos (by dir) already checked this process, so git runs once per dir. */
8
+ const excluded = new Set();
9
+ /**
10
+ * Keep the signal file out of `git status` in projects that don't ignore it:
11
+ * one line in the repo's local `info/exclude`, never a tracked file.
12
+ */
13
+ function ensureExcluded(dir) {
14
+ if (excluded.has(dir))
15
+ return;
16
+ excluded.add(dir);
17
+ try {
18
+ const common = resolve(dir, execFileSync('git', ['rev-parse', '--git-common-dir'], {
19
+ cwd: dir,
20
+ encoding: 'utf8',
21
+ stdio: ['ignore', 'pipe', 'ignore'],
22
+ }).trim());
23
+ const file = join(common, 'info', 'exclude');
24
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
25
+ if (text.split('\n').includes(EXCLUDE_LINE))
26
+ return;
27
+ mkdirSync(join(common, 'info'), { recursive: true });
28
+ appendFileSync(file, `${text === '' || text.endsWith('\n') ? '' : '\n'}${EXCLUDE_LINE}\n`);
29
+ }
30
+ catch {
31
+ // Not a git dir, or unwritable: the file just shows as untracked.
32
+ }
33
+ }
34
+ /** Touch `<dir>/.bakers/ui-refresh` so a `bakers ui` there reloads. Never throws. */
35
+ export function signalUi(dir) {
36
+ const bakersDir = configHomeOf(dir);
37
+ if (!existsSync(bakersDir))
38
+ return;
39
+ ensureExcluded(dir);
40
+ bumpUiRefresh(bakersDir);
41
+ }
@@ -74,12 +74,12 @@ export interface HookContext {
74
74
  ticket: string;
75
75
  }
76
76
  /**
77
- * What a lifecycle hook invocation DID (BB-237). `runHook` still never throws,
78
- * but it no longer swallows the outcome silently: it reports it, so a caller can
79
- * record a failed provisioning hook against the run it is about to dispatch
80
- * instead of relying on a log line to survive (AC-6). Reporting — rather than
81
- * throwing — keeps the never-wedge property that the never-throw contract exists
82
- * for; boundedness stays with the conductor's circuit breaker.
77
+ * What a lifecycle hook invocation DID (BB-237). The conductor's hook runner
78
+ * never throws, but it does not swallow the outcome silently either: it reports
79
+ * it, so a caller can record a failed provisioning hook against the run it is
80
+ * about to dispatch instead of relying on a log line to survive (AC-6).
81
+ * Reporting — rather than throwing — keeps the never-wedge property; boundedness
82
+ * stays with the conductor's circuit breaker.
83
83
  */
84
84
  export interface HookResult {
85
85
  /** The hook slot that was invoked. */
@@ -108,29 +108,32 @@ export interface HookResult {
108
108
  * `false`.
109
109
  */
110
110
  export type WorktreeTeardown = 'removed' | 'already_absent' | 'unverified';
111
+ /** What {@link BbExecutor.openWorkspace} knows about the fresh worktree. */
112
+ export interface OpenWorkspaceContext {
113
+ identifier: string;
114
+ branch: string;
115
+ title: string;
116
+ }
117
+ /**
118
+ * The executor hosts terminals, nothing else: the workspace owns the worktree
119
+ * and the conductor runs the lifecycle hooks. The two share only the worktree
120
+ * path and branch, so any executor runs on any workspace.
121
+ */
111
122
  export interface BbExecutor {
112
123
  id: string;
124
+ /** `persistent` = the agent lives in a hosted terminal; gates `stopRun`/`cleanupRun` only. */
113
125
  capabilities(): ExecutorCapabilities;
114
126
  /**
115
- * Run the lifecycle hook `name` (command from `config.hooks[name]`) in `cwd`,
116
- * best-effort. This is the SINGLE catch point for all lifecycle hooks:
117
- *
118
- * - MUST NEVER throw. No configured command → silent no-op. A failing command
119
- * → `logger.error({hook,worktree,ticket,err}, 'lifecycle hook failed')` then
120
- * return. So a hook failure never aborts dispatch or wedges a run in
121
- * `claimed`.
122
- * - The underlying shell command still fails honestly (a non-zero exit
123
- * rejects); only the executor catches + logs + continues.
124
- * - MUST report the outcome as a {@link HookResult} (BB-237): never throwing
125
- * is not the same as never telling. The caller decides what a failure means
126
- * for the run it is dispatching; the executor only refuses to abort.
127
+ * Present a freshly created worktree in the tool (panes, tabs, an open
128
+ * layout). Optional: an executor without a UI surface omits it.
127
129
  *
128
- * `env`, when given, is the run's resolved environment (per-ticket env_vars
129
- * merged with the core BB_* vars, BB-99), merged over the hook process's
130
- * inherited env. Values may be sensitive — implementations must never log
131
- * them (log key names only).
130
+ * The conductor calls it after `after_create`, before `before_run`, and ONLY
131
+ * when the workspace reported the worktree as created (BB-237): the layout's
132
+ * startup command may name what `after_create` builds, and re-applying it on
133
+ * reuse would start a duplicate process on every reattach. Best-effort:
134
+ * implementations log and swallow a failure so it never wedges dispatch.
132
135
  */
133
- runHook(name: HookName, cwd: string, ctx: HookContext, env?: Record<string, string>): Promise<HookResult>;
136
+ openWorkspace?(path: string, ctx: OpenWorkspaceContext): Promise<void>;
134
137
  startRun(input: SpawnRunInput): Promise<SpawnedSession>;
135
138
  /**
136
139
  * Signal the run's agent to stop. Called by the conductor's run-finalise pass
@@ -151,32 +154,10 @@ export interface BbExecutor {
151
154
  * and any non-run tab are left untouched. Called as the LAST finalisation step,
152
155
  * strictly after the transcript is captured, and again at dispatch to clear a
153
156
  * reused workspace's leftover tab for the run being (re-)started. No matching
154
- * tab → a quiet no-op. Does NOT touch the branch worktree (that is the
155
- * reap/{@link removeWorktree} lifecycle). Best-effort: a failing tab-close is
157
+ * tab → a quiet no-op. Does NOT touch the branch worktree (that is
158
+ * {@link BbWorkspace.remove}). Best-effort: a failing tab-close is
156
159
  * swallowed and never aborts finalisation or dispatch. A no-op for
157
160
  * non-persistent executors.
158
161
  */
159
162
  cleanupRun(branch: string, runId: number): Promise<void>;
160
- /**
161
- * Tear down the branch's entire worktree (git worktree + hosted workspace),
162
- * reclaiming its disk. Called by the conductor's ticket-cleanup pass once a
163
- * ticket is done. A no-op for non-persistent executors (no hosted workspace);
164
- * the conductor gates the call on `capabilities().persistent`.
165
- *
166
- * `worktreePath` is the stable, identifier-derived worktree path (from the
167
- * ticket's latest run). Prefer it over `branch` to resolve the worktree: the
168
- * checked-out branch is mutable (the coding agent may rename/switch it), the
169
- * path is not.
170
- *
171
- * Reports what the teardown DID as a {@link WorktreeTeardown} (BB-293):
172
- * `removed` when the worktree was present on this host and torn down (or its
173
- * prunable admin entry swept), `already_absent` when there was nothing to
174
- * tear down at all, and `unverified` when nothing matched here and the
175
- * worktree may still be on disk (another conductor's host, or a path that
176
- * could not be resolved). The reaper flags a ticket `cleaned_up` for the
177
- * first two and leaves it on the work list for `unverified`, so it never
178
- * false-teardowns a worktree another host physically holds. A genuine
179
- * failure still throws (surfaced as a teardown miss).
180
- */
181
- removeWorktree(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
182
163
  }
@@ -2,7 +2,6 @@ import type { AddonEntry, BbPreset, DiscoveredContributions } from '@bakers-buil
2
2
  import type { HookListener } from './executor.js';
3
3
  import type { DiscoveredInbox, InboxMessages } from './message.js';
4
4
  import type { AgentCandidate, ExecutorPlugin, RemotePlugin, WorkspacePlugin } from './plugins.js';
5
- import type { HerdrHost } from './process-host.js';
6
5
  import type { Ticket } from './remote.js';
7
6
  import type { AddonTools, DiscoveredTools } from './tools.js';
8
7
  /**
@@ -18,8 +17,6 @@ export interface ConductorContributions {
18
17
  agents: AgentCandidate[];
19
18
  /** Lifecycle hook listeners, in accumulator order (BB-599). */
20
19
  hooks: HookListener[];
21
- /** Conductor process hosts (last wins). */
22
- processHosts: HerdrHost[];
23
20
  /** Addon `inbox` exports with their package name and version (contract 2, BB-661). */
24
21
  addonInbox: DiscoveredInbox[];
25
22
  /** Addon `tools` exports with their package name and version. */
@@ -50,7 +47,6 @@ export interface Preset<O = unknown> extends BbPreset<O> {
50
47
  workspaces?: (acc: WorkspacePlugin[], opts: O) => WorkspacePlugin[] | Promise<WorkspacePlugin[]>;
51
48
  agents?: (acc: AgentCandidate[], opts: O) => AgentCandidate[] | Promise<AgentCandidate[]>;
52
49
  hooks?: (acc: HookListener[], opts: O) => HookListener[] | Promise<HookListener[]>;
53
- processHosts?: (acc: HerdrHost[], opts: O) => HerdrHost[] | Promise<HerdrHost[]>;
54
50
  /** Addon inbox messages: contract 2, BB-661. */
55
51
  inbox?: InboxMessages;
56
52
  /** Agent tools served through the conductor's MCP server. */
@@ -63,4 +59,4 @@ export interface Preset<O = unknown> extends BbPreset<O> {
63
59
  * {@link Preset}, and `resolveConductorSlots` still runs the runtime `.kind`
64
60
  * guard on whatever actually landed in a singleton slot.
65
61
  */
66
- export declare function narrowConductorContributions(discovered: Pick<DiscoveredContributions, 'remotes' | 'executors' | 'workspaces' | 'agents' | 'hooks' | 'processHosts' | 'addonInbox' | 'addonTools'>): ConductorContributions;
62
+ export declare function narrowConductorContributions(discovered: Pick<DiscoveredContributions, 'remotes' | 'executors' | 'workspaces' | 'agents' | 'hooks' | 'addonInbox' | 'addonTools'>): ConductorContributions;
@@ -163,6 +163,12 @@ export interface FinalizableRun {
163
163
  * stays transcript-derived (BB-151). '' / undefined when unset.
164
164
  */
165
165
  startedAt?: string;
166
+ /**
167
+ * The server's current run-log policy for this run (workspace opt-in AND
168
+ * the operator flag), read fresh on every finalize query. Only `true`
169
+ * allows uploading the transcript; absent (an older server) means no.
170
+ */
171
+ runLogStorageAllowed?: boolean;
166
172
  }
167
173
  /**
168
174
  * The attributes the conductor writes in the single PATCH that closes a run:
@@ -1,3 +1,4 @@
1
+ import type { WorktreeTeardown } from './executor.js';
1
2
  export interface EnsuredWorkspace {
2
3
  path: string;
3
4
  instructions: {
@@ -10,8 +11,7 @@ export interface EnsuredWorkspace {
10
11
  * (false). The core runs the `after_create` lifecycle hook on a fresh
11
12
  * worktree, or on a reused one with no recorded successful `after_create`
12
13
  * (BB-663), so it needs to know which happened. Lifecycle hooks themselves
13
- * are no longer a workspace concern (BB-84): the executor owns and runs
14
- * them best-effort.
14
+ * are not a workspace concern: the conductor runs them best-effort.
15
15
  */
16
16
  created: boolean;
17
17
  /**
@@ -36,40 +36,29 @@ export interface BbWorkspace {
36
36
  *
37
37
  * Reports `created` so the caller can decide whether `after_create` needs to
38
38
  * run (fresh worktree, or no recorded success for this one — BB-663).
39
- * Lifecycle-hook invocation is NOT a workspace responsibility
40
- * anymore — the executor owns all hooks (BB-84).
39
+ * Lifecycle-hook invocation is NOT a workspace responsibility — the
40
+ * conductor runs all hooks.
41
41
  */
42
42
  ensure(identifier: string, branch?: string, baseRef?: string): Promise<EnsuredWorkspace>;
43
43
  /**
44
- * Apply the workspace's "open" layout — for a hosted workspace, the startup
45
- * command(s) of the freshly created workspace's initial pane.
44
+ * Tear down the branch's worktree, reclaiming its disk. Called by the
45
+ * conductor's ticket-cleanup pass once a ticket is done, after `after_done`,
46
+ * for every workspace and executor kind.
46
47
  *
47
- * OPTIONAL: a workspace with no layout concept (git, fake) simply omits it and
48
- * the conductor calls it with `?.`.
48
+ * `worktreePath` is the stable, identifier-derived worktree path (from the
49
+ * ticket's latest run). Prefer it over `branch` to resolve the worktree: the
50
+ * checked-out branch is mutable (the coding agent may rename/switch it), the
51
+ * path is not.
49
52
  *
50
- * BB-237 — why this is a SEPARATE call and not part of `ensure()`. The
51
- * layout's startup command typically names the bakers CLI, which the
52
- * `after_create` lifecycle hook builds. Applied inside `ensure()` it
53
- * necessarily ran BEFORE that hook, so in a self-hosting checkout the command
54
- * fired minutes before the binary it names existed. The only remedy available
55
- * to a config author was a cross-process handshake — a sentinel wait loop
56
- * inside the pane command itself. Splitting the call lets the conductor order
57
- * the two correctly (`after_create` → `applyOpenLayout`), which removes the
58
- * need for any handshake.
59
- *
60
- * The conductor calls this ONLY on a freshly created workspace
61
- * ({@link EnsuredWorkspace.created}), because only a fresh create has an
62
- * initial pane to lay out; re-applying on reuse would start a duplicate editor
63
- * process on every reattach. Deliberately a NARROWER gate than the one on
64
- * `after_create`, which runs again on a reuse with no recorded success
65
- * (BB-663), not on every dispatch.
66
- *
67
- * Best-effort by contract: implementations log and swallow a failing layout so
68
- * it can never wedge dispatch.
53
+ * Reports what the teardown DID as a {@link WorktreeTeardown} (BB-293):
54
+ * `removed` when the worktree was present on this host and torn down (or its
55
+ * prunable admin entry swept), `already_absent` when there was nothing to
56
+ * tear down at all, and `unverified` when nothing matched here and the
57
+ * worktree may still be on disk (another conductor's host, or a path that
58
+ * could not be resolved). The reaper flags a ticket `cleaned_up` for the
59
+ * first two and leaves it on the work list for `unverified`, so it never
60
+ * false-teardowns a worktree another host physically holds. A genuine
61
+ * failure still throws (surfaced as a teardown miss).
69
62
  */
70
- applyOpenLayout?(path: string, ctx: {
71
- identifier: string;
72
- branch: string;
73
- title: string;
74
- }): Promise<void>;
63
+ remove(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
75
64
  }
@@ -0,0 +1,20 @@
1
+ export interface DetachedSpawnRequest {
2
+ /** Executable first, then its arguments; no shell, no PATH lookup. */
3
+ argv: string[];
4
+ cwd: string;
5
+ env: NodeJS.ProcessEnv;
6
+ /** Appended to by the child's stdout and stderr. */
7
+ logPath: string;
8
+ }
9
+ export interface DetachedChild {
10
+ pid: number;
11
+ /** Exit code (null on a signal) — settles only if the child ends. */
12
+ exited: Promise<number | null>;
13
+ }
14
+ /**
15
+ * Starts `oven start --foreground` as a detached conductor: its own session
16
+ * (no controlling terminal, untouched by the starting shell's SIGHUP), stdin
17
+ * closed, stdout and stderr appended to the conductor log, and unref'd so the
18
+ * starting process can exit while it runs.
19
+ */
20
+ export declare function spawnDetachedConductor(req: DetachedSpawnRequest): Promise<DetachedChild>;
@@ -0,0 +1,34 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, mkdirSync, openSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ /**
5
+ * Starts `oven start --foreground` as a detached conductor: its own session
6
+ * (no controlling terminal, untouched by the starting shell's SIGHUP), stdin
7
+ * closed, stdout and stderr appended to the conductor log, and unref'd so the
8
+ * starting process can exit while it runs.
9
+ */
10
+ export async function spawnDetachedConductor(req) {
11
+ const [file, ...args] = req.argv;
12
+ if (!file)
13
+ throw new Error('spawnDetachedConductor: empty argv');
14
+ mkdirSync(dirname(req.logPath), { recursive: true });
15
+ const fd = openSync(req.logPath, 'a');
16
+ try {
17
+ const child = spawn(file, args, {
18
+ cwd: req.cwd,
19
+ env: req.env,
20
+ detached: true,
21
+ stdio: ['ignore', fd, fd],
22
+ });
23
+ const exited = new Promise((resolve) => child.once('exit', (code) => resolve(code)));
24
+ await new Promise((resolve, reject) => {
25
+ child.once('spawn', resolve);
26
+ child.once('error', reject);
27
+ });
28
+ child.unref();
29
+ return { pid: child.pid, exited };
30
+ }
31
+ finally {
32
+ closeSync(fd);
33
+ }
34
+ }
@@ -5,7 +5,6 @@ import type { BbProjectSelection } from './cli/project-context.js';
5
5
  import type { HookListener } from './plugins/executor.js';
6
6
  import type { LoadedInbox } from './plugins/message.js';
7
7
  import type { AgentCandidate, ExecutorPlugin, RemotePlugin, ResolvedAgent, WorkspacePlugin } from './plugins/plugins.js';
8
- import type { HerdrHost } from './plugins/process-host.js';
9
8
  import type { Ticket } from './plugins/remote.js';
10
9
  import type { ProvisionHook, ProvisionRuns, ToolRegistry } from './plugins/tools.js';
11
10
  /** Normalized single conductor. */
@@ -47,15 +46,13 @@ export interface ConductorSettings {
47
46
  poll_interval_ms: number;
48
47
  lease_seconds: number;
49
48
  /**
50
- * Whether to upload the agent transcript at finalize. Default true.
49
+ * Local opt-out of transcript upload at finalize. Default true.
51
50
  *
52
- * Turning it off keeps this conductor's runs out of the log store entirely —
53
- * for a machine whose transcripts are large, uninteresting, or subject to a
54
- * local policy. Metrics are unaffected: the footprint is derived from the
55
- * agent's own session files in this process, never from the uploaded log.
56
- *
57
- * Client-side by design. It lets an operator opt out; it is not a policy the
58
- * server enforces, so a conductor running an older build still uploads.
51
+ * The server's per-run policy (`FinalizableRun.runLogStorageAllowed`)
52
+ * decides first; `false` here keeps this conductor's transcripts local even
53
+ * where the server allows storage, and `true` cannot override a denial.
54
+ * Metrics are unaffected: the footprint is derived from the agent's own
55
+ * session files in this process, never from the uploaded log.
59
56
  */
60
57
  capture_logs?: boolean;
61
58
  /** Project shell commands, one per slot; run after the addon listeners. */
@@ -109,12 +106,6 @@ export interface ConductorFileConfig extends ConductorSettings {
109
106
  tools?: ToolRegistry;
110
107
  /** The `provision_up` runs, stopped at ticket end and conductor stop. Absent without the hook. */
111
108
  provisioning?: Pick<ProvisionRuns, 'stop'>;
112
- /**
113
- * Conductor process host from the `processHosts` accumulator (last wins).
114
- * Absent when no addon contributed one — `bakers oven start` then fails
115
- * with the existing no-herdr hint.
116
- */
117
- processHost?: HerdrHost;
118
109
  /** dropsh-layer plugins (auth etc.); separate from the bakers.build slots. */
119
110
  plugins?: DropSHPlugin[];
120
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.6.1-next.6",
3
+ "version": "0.6.1-next.7",
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.6",
36
- "@bakers-build/message": "^0.6.1-next.6",
35
+ "@bakers-build/core": "^0.6.1-next.7",
36
+ "@bakers-build/message": "^0.6.1-next.7",
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": "12b97ff4aa2422d69dab286141f3234609f32351",
42
+ "commit": "b89398b187bf51f4f9ca5bfc1150469f73a879e6",
43
43
  "channel": "next"
44
44
  }
45
45
  }
@@ -1,7 +0,0 @@
1
- /**
2
- * Process host that starts a detached conductor loop. The conductor package
3
- * owns only this contract; `@bakers-build/addon-herdr` implements it.
4
- */
5
- export interface HerdrHost {
6
- spawn(label: string, cwd: string, cmd: string): Promise<void>;
7
- }
@@ -1 +0,0 @@
1
- export {};