@bakers-build/conductor 0.5.1-next.855 → 0.5.1-next.856
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.
- package/dist/src/commands/conductor.js +4 -1
- package/dist/src/config.js +6 -0
- package/dist/src/contract.d.ts +2 -1
- package/dist/src/contract.js +1 -1
- package/dist/src/core/conductor.d.ts +13 -0
- package/dist/src/core/conductor.js +50 -3
- package/dist/src/core/inbox-runtime.d.ts +3 -1
- package/dist/src/core/inbox-runtime.js +8 -1
- package/dist/src/core/tool-server.d.ts +25 -0
- package/dist/src/core/tool-server.js +145 -0
- package/dist/src/plugins/agent.d.ts +11 -1
- package/dist/src/plugins/agent.js +4 -0
- package/dist/src/plugins/message.d.ts +3 -0
- package/dist/src/plugins/preset.d.ts +6 -1
- package/dist/src/plugins/tools.d.ts +63 -0
- package/dist/src/plugins/tools.js +63 -0
- package/dist/src/types.d.ts +3 -0
- package/package.json +5 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
2
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
3
3
|
import { createInterface } from 'node:readline';
|
|
4
|
-
import { CommandRunner, checkForUpdate, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, loadReadyBbConnection, printVersionLine, resolveConfigPath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
|
|
4
|
+
import { CommandRunner, checkForUpdate, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, homeBbDir, loadReadyBbConnection, printVersionLine, resolveConfigPath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
|
|
5
5
|
import { Command } from 'commander';
|
|
6
6
|
import { authStatus } from 'dropsh';
|
|
7
7
|
import { resolveBbProjectContext } from '../bakers-project-context.js';
|
|
@@ -316,6 +316,8 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
|
|
|
316
316
|
// Conductor too but never claim, so they cannot overwrite this pid.
|
|
317
317
|
conductor.claimServeProcess();
|
|
318
318
|
await conductor.start();
|
|
319
|
+
// The endpoint file is how `bakers ports` and other CLI calls reach the tools.
|
|
320
|
+
await conductor.startTools(join(homeBbDir(), 'conductors', `${conductor.id}.json`));
|
|
319
321
|
const controller = new AbortController();
|
|
320
322
|
const onSignal = () => controller.abort();
|
|
321
323
|
process.once('SIGINT', onSignal);
|
|
@@ -326,6 +328,7 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
|
|
|
326
328
|
finally {
|
|
327
329
|
process.removeListener('SIGINT', onSignal);
|
|
328
330
|
process.removeListener('SIGTERM', onSignal);
|
|
331
|
+
await conductor.stopTools();
|
|
329
332
|
// The exiting process writes its own `offline`. It has to be this process:
|
|
330
333
|
// a heartbeat sets `online` unconditionally (ConductorRegistrar), so an
|
|
331
334
|
// offline written by anyone else is erased by the next tick — the status
|
package/dist/src/config.js
CHANGED
|
@@ -5,6 +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 } from './plugins/tools.js';
|
|
8
9
|
// BB-201: the `.bakers/` walk-up + connection resolution moved to `@bakers-build/core`
|
|
9
10
|
// (`resolveConfigPath` / `resolveBbConfigPath` / `findBbDir`). Re-export the
|
|
10
11
|
// engine resolver here so existing conductor callers/tests keep importing it
|
|
@@ -363,6 +364,10 @@ export async function loadConductorConfig(configFile) {
|
|
|
363
364
|
const wired = resolveConductorSlots(discovered);
|
|
364
365
|
const hookListeners = validateHookListeners(discovered.hooks);
|
|
365
366
|
const inboxAddons = await loadInboxAddons(discovered.addonInbox);
|
|
367
|
+
// Unlike the inbox, a broken or ambiguous tool set stops the conductor.
|
|
368
|
+
const tools = discovered.addonTools.length > 0
|
|
369
|
+
? await loadTools(discovered.addonTools)
|
|
370
|
+
: undefined;
|
|
366
371
|
// Explicit executor/workspace descriptors still load those slots, but they
|
|
367
372
|
// skip addons[] discovery — so a pre-BB-215 config never contributes a
|
|
368
373
|
// process host unless we load that package's processHosts accumulator too.
|
|
@@ -533,6 +538,7 @@ export async function loadConductorConfig(configFile) {
|
|
|
533
538
|
workspace,
|
|
534
539
|
hookListeners,
|
|
535
540
|
...(inboxAddons.length > 0 ? { inboxAddons } : {}),
|
|
541
|
+
...(tools !== undefined ? { tools } : {}),
|
|
536
542
|
...(processHost !== undefined ? { processHost } : {}),
|
|
537
543
|
bakers,
|
|
538
544
|
...identityOf(machineCtx, project, variant),
|
package/dist/src/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { AmbiguousProjectNameError, type ResolvedBbProjectContext, resolveBbProjectContext, } from './bakers-project-context.js';
|
|
2
|
-
export { type AgentFootprint, type AgentRunIdentity, type BbAgent, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, type RunEnvPolicy, } from './plugins/agent.js';
|
|
2
|
+
export { type AgentFootprint, type AgentRunIdentity, type BbAgent, CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, 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, validateAgentArgs, validateOptionalBoolean, validateOptionalString, } from './plugins/agent-args.js';
|
|
4
4
|
export type { BbExecutor, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
|
|
5
5
|
export type { DiscoveredInbox, InboxMessageHandler, InboxMessageRequest, InboxMessages, LoadedInbox, } from './plugins/message.js';
|
|
@@ -11,5 +11,6 @@ export type { HerdrHost } from './plugins/process-host.js';
|
|
|
11
11
|
export type { ActiveRun, AddonDefinitionV2, AddonRegistration, BbRemote, ClaimedRun, ClaimOptions, ClaimWithheld, ConductorRegistration, ConductorStatus, FinalizableRun, FrozenTicket, InboxMessage, InboxSnapshot, RunMetrics, RunWriteAttributes, Ticket, TicketMetric, UncleanTicket, } from './plugins/remote.js';
|
|
12
12
|
export { ConductorTakeoverRequired } from './plugins/remote.js';
|
|
13
13
|
export { installCommand, lastLine, type SandboxHost, type SandboxPreflight, sandboxFailures, systemSandboxHost, } from './plugins/sandbox-preflight.js';
|
|
14
|
+
export type { AddonTools, ToolBinding, ToolDefinition, ToolHandler, ToolRequest, ToolResult, } from './plugins/tools.js';
|
|
14
15
|
export type { BbWorkspace, EnsuredWorkspace, } from './plugins/workspace.js';
|
|
15
16
|
export type { ConductorEngineConfig, ConductorFileConfig, ConductorSettings, } from './types.js';
|
package/dist/src/contract.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// The package main re-exports everything here too, so `import type { BbRemote }
|
|
13
13
|
// from '@bakers-build/conductor'` keeps working for type-only consumers.
|
|
14
14
|
export { AmbiguousProjectNameError, resolveBbProjectContext, } from './bakers-project-context.js';
|
|
15
|
-
export { DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, } from './plugins/agent.js';
|
|
15
|
+
export { CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, } from './plugins/agent.js';
|
|
16
16
|
export { detectKnownOverrides, resolveAgentCliOptions, resolveSecurityOptions, SECURITY_MODES, validateAgentArgs, validateOptionalBoolean, validateOptionalString, } from './plugins/agent-args.js';
|
|
17
17
|
export { loadInbox, validateRequestPayload, } from './plugins/message.js';
|
|
18
18
|
export { resolveAgent, selectAgent, selectAgents, selectExecutor, selectRemote, selectWorkspace, } from './plugins/plugins.js';
|
|
@@ -46,6 +46,10 @@ export declare class Conductor {
|
|
|
46
46
|
private readonly inboxAddons;
|
|
47
47
|
/** The per-item work each tick enqueues. */
|
|
48
48
|
private readonly queue;
|
|
49
|
+
/** The local MCP server for addon tools; only the serve process runs one. */
|
|
50
|
+
private toolServer;
|
|
51
|
+
/** The live run token per run UUID, revoked when the run is finalised. */
|
|
52
|
+
private readonly runTokens;
|
|
49
53
|
/** Serializes git worktree add/remove: parallel ones fight over git locks. */
|
|
50
54
|
private gitLock;
|
|
51
55
|
constructor(config: ConductorFileConfig, remote: BbRemote, executor: BbExecutor, workspace: BbWorkspace, agents: ResolvedAgent[], logger: ConductorLogger, checkoutRoot?: string, frozenStateFile?: string | undefined);
|
|
@@ -78,6 +82,15 @@ export declare class Conductor {
|
|
|
78
82
|
claimServeProcess(): void;
|
|
79
83
|
/** This conductor's registration payload, built from config. */
|
|
80
84
|
private registration;
|
|
85
|
+
/**
|
|
86
|
+
* Starts the tool server when an addon declares tools. Only the serve
|
|
87
|
+
* process calls this; `endpointFile` publishes it to the CLI.
|
|
88
|
+
*/
|
|
89
|
+
startTools(endpointFile?: string): Promise<void>;
|
|
90
|
+
stopTools(): Promise<void>;
|
|
91
|
+
/** A fresh token for this run's worktree; a re-dispatch replaces the old one. */
|
|
92
|
+
private issueRunTools;
|
|
93
|
+
private revokeRunTools;
|
|
81
94
|
start(): Promise<void>;
|
|
82
95
|
/** One tick that also waits for its actions: `bakers oven once`, tests. */
|
|
83
96
|
tick(): Promise<void>;
|
|
@@ -8,6 +8,7 @@ import { ActionQueue } from './action-queue.js';
|
|
|
8
8
|
import { attemptFamily } from './attempt.js';
|
|
9
9
|
import { InboxRuntime, runInbox } from './inbox-runtime.js';
|
|
10
10
|
import { measureMrChanges, mrChangesRows } from './mr-changes.js';
|
|
11
|
+
import { startToolServer } from './tool-server.js';
|
|
11
12
|
function sleep(ms, signal) {
|
|
12
13
|
return new Promise((resolve) => {
|
|
13
14
|
if (signal?.aborted) {
|
|
@@ -196,6 +197,10 @@ export class Conductor {
|
|
|
196
197
|
inboxAddons;
|
|
197
198
|
/** The per-item work each tick enqueues. */
|
|
198
199
|
queue;
|
|
200
|
+
/** The local MCP server for addon tools; only the serve process runs one. */
|
|
201
|
+
toolServer;
|
|
202
|
+
/** The live run token per run UUID, revoked when the run is finalised. */
|
|
203
|
+
runTokens = new Map();
|
|
199
204
|
/** Serializes git worktree add/remove: parallel ones fight over git locks. */
|
|
200
205
|
gitLock = Promise.resolve();
|
|
201
206
|
constructor(config, remote, executor, workspace, agents, logger, checkoutRoot = process.cwd(), frozenStateFile) {
|
|
@@ -207,7 +212,7 @@ export class Conductor {
|
|
|
207
212
|
this.logger = logger;
|
|
208
213
|
this.checkoutRoot = checkoutRoot;
|
|
209
214
|
this.frozenStateFile = frozenStateFile;
|
|
210
|
-
this.inboxAddons = new InboxRuntime(config.inboxAddons ?? [], remote, logger, (ticket) => this.runEnv(ticket, undefined, ticket.state));
|
|
215
|
+
this.inboxAddons = new InboxRuntime(config.inboxAddons ?? [], remote, logger, (ticket) => this.runEnv(ticket, undefined, ticket.state), config.tools);
|
|
211
216
|
this.queue = new ActionQueue(logger);
|
|
212
217
|
}
|
|
213
218
|
serialGit(fn) {
|
|
@@ -262,6 +267,41 @@ export class Conductor {
|
|
|
262
267
|
// overwrite the running conductor's.
|
|
263
268
|
return this.ownsServeProcess ? { ...base, last_pid: process.pid } : base;
|
|
264
269
|
}
|
|
270
|
+
/**
|
|
271
|
+
* Starts the tool server when an addon declares tools. Only the serve
|
|
272
|
+
* process calls this; `endpointFile` publishes it to the CLI.
|
|
273
|
+
*/
|
|
274
|
+
async startTools(endpointFile) {
|
|
275
|
+
if (!this.config.tools || this.toolServer)
|
|
276
|
+
return;
|
|
277
|
+
this.toolServer = await startToolServer({
|
|
278
|
+
registry: this.config.tools,
|
|
279
|
+
workspaceRoot: this.checkoutRoot,
|
|
280
|
+
logger: this.logger,
|
|
281
|
+
...(endpointFile ? { endpointFile } : {}),
|
|
282
|
+
});
|
|
283
|
+
this.logger.info({ conductorId: this.config.conductor_id, url: this.toolServer.url }, 'tool server started');
|
|
284
|
+
}
|
|
285
|
+
async stopTools() {
|
|
286
|
+
await this.toolServer?.stop();
|
|
287
|
+
this.toolServer = undefined;
|
|
288
|
+
this.runTokens.clear();
|
|
289
|
+
}
|
|
290
|
+
/** A fresh token for this run's worktree; a re-dispatch replaces the old one. */
|
|
291
|
+
issueRunTools(runUuid, binding) {
|
|
292
|
+
if (!this.toolServer)
|
|
293
|
+
return undefined;
|
|
294
|
+
this.revokeRunTools(runUuid);
|
|
295
|
+
const token = this.toolServer.issueRunToken(binding);
|
|
296
|
+
this.runTokens.set(runUuid, token);
|
|
297
|
+
return { url: this.toolServer.url, token };
|
|
298
|
+
}
|
|
299
|
+
revokeRunTools(runUuid) {
|
|
300
|
+
const token = this.runTokens.get(runUuid);
|
|
301
|
+
if (token)
|
|
302
|
+
this.toolServer?.revokeRunToken(token);
|
|
303
|
+
this.runTokens.delete(runUuid);
|
|
304
|
+
}
|
|
265
305
|
async start() {
|
|
266
306
|
this.uuid = await this.remote.registerConductor(this.registration());
|
|
267
307
|
this.logger.info({ conductorId: this.id, uuid: this.uuid, project: this.config.project }, 'conductor started');
|
|
@@ -448,6 +488,7 @@ export class Conductor {
|
|
|
448
488
|
// server change is needed and no empty log is written.
|
|
449
489
|
const uploadedLog = (this.config.capture_logs ?? true) ? captured.log : '';
|
|
450
490
|
await this.remote.finalizeRun(r.runUuid, uploadedLog, captured.metrics);
|
|
491
|
+
this.revokeRunTools(r.runUuid);
|
|
451
492
|
this.logger.info({ run: r.runUuid, state: r.state, footprint: captured.metrics }, 'run finalised');
|
|
452
493
|
}
|
|
453
494
|
catch (err) {
|
|
@@ -1221,7 +1262,11 @@ export class Conductor {
|
|
|
1221
1262
|
}, `${chosen.agent.id}/${alias}: ${warning}`);
|
|
1222
1263
|
}
|
|
1223
1264
|
}
|
|
1224
|
-
const
|
|
1265
|
+
const tools = this.issueRunTools(run.runUuid, {
|
|
1266
|
+
worktreePath: ws.path,
|
|
1267
|
+
ticket: t,
|
|
1268
|
+
});
|
|
1269
|
+
const command = chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined);
|
|
1225
1270
|
await this.executor.startRun({
|
|
1226
1271
|
ticket: {
|
|
1227
1272
|
uuid: t.uuid,
|
|
@@ -1235,7 +1280,8 @@ export class Conductor {
|
|
|
1235
1280
|
workspacePath: ws.path,
|
|
1236
1281
|
instructions: ws.instructions,
|
|
1237
1282
|
command,
|
|
1238
|
-
env,
|
|
1283
|
+
// The token travels in the env, never in argv or the launch log.
|
|
1284
|
+
env: tools ? { ...env, BB_CONDUCTOR_TOKEN: tools.token } : env,
|
|
1239
1285
|
});
|
|
1240
1286
|
launch.started = true;
|
|
1241
1287
|
this.logger.info({
|
|
@@ -1267,6 +1313,7 @@ export class Conductor {
|
|
|
1267
1313
|
*/
|
|
1268
1314
|
async unwindDispatch(ctx, launched) {
|
|
1269
1315
|
const runUuid = ctx.run?.uuid ?? '';
|
|
1316
|
+
this.revokeRunTools(runUuid);
|
|
1270
1317
|
try {
|
|
1271
1318
|
if (launched && this.executor.capabilities().persistent) {
|
|
1272
1319
|
try {
|
|
@@ -2,6 +2,7 @@ import type { ConductorLogger } from '@bakers-build/core';
|
|
|
2
2
|
import { type MessageResult } from '@bakers-build/message';
|
|
3
3
|
import type { LoadedInbox } from '../plugins/message.js';
|
|
4
4
|
import type { BbRemote, InboxMessage, Ticket } from '../plugins/remote.js';
|
|
5
|
+
import type { ToolRegistry } from '../plugins/tools.js';
|
|
5
6
|
import type { ActionQueue } from './action-queue.js';
|
|
6
7
|
/** Per-handler timeout; the request's `signal` aborts after it. */
|
|
7
8
|
export declare const HANDLER_TIMEOUT_MS = 60000;
|
|
@@ -17,9 +18,10 @@ export declare class InboxRuntime {
|
|
|
17
18
|
private readonly remote;
|
|
18
19
|
private readonly logger;
|
|
19
20
|
private readonly env;
|
|
21
|
+
private readonly tools?;
|
|
20
22
|
private readonly ids;
|
|
21
23
|
private registeredOk;
|
|
22
|
-
constructor(addons: LoadedInbox[], remote: BbRemote, logger: ConductorLogger, env: (ticket: Ticket) => Promise<Record<string, string
|
|
24
|
+
constructor(addons: LoadedInbox[], remote: BbRemote, logger: ConductorLogger, env: (ticket: Ticket) => Promise<Record<string, string>>, tools?: ToolRegistry | undefined);
|
|
23
25
|
/** Whether this conductor runs no contract-2 addon. */
|
|
24
26
|
get empty(): boolean;
|
|
25
27
|
/** Whether the last registration reached the server. */
|
|
@@ -15,13 +15,15 @@ export class InboxRuntime {
|
|
|
15
15
|
remote;
|
|
16
16
|
logger;
|
|
17
17
|
env;
|
|
18
|
+
tools;
|
|
18
19
|
ids = new Map();
|
|
19
20
|
registeredOk = false;
|
|
20
|
-
constructor(addons, remote, logger, env) {
|
|
21
|
+
constructor(addons, remote, logger, env, tools) {
|
|
21
22
|
this.addons = addons;
|
|
22
23
|
this.remote = remote;
|
|
23
24
|
this.logger = logger;
|
|
24
25
|
this.env = env;
|
|
26
|
+
this.tools = tools;
|
|
25
27
|
}
|
|
26
28
|
/** Whether this conductor runs no contract-2 addon. */
|
|
27
29
|
get empty() {
|
|
@@ -108,6 +110,11 @@ export class InboxRuntime {
|
|
|
108
110
|
env: await this.env(ticket),
|
|
109
111
|
logger: this.logger,
|
|
110
112
|
signal: controller.signal,
|
|
113
|
+
...(this.tools
|
|
114
|
+
? {
|
|
115
|
+
callTool: (name, args) => this.tools.call(name, args, { worktreePath, ticket }, { signal: controller.signal, logger: this.logger }),
|
|
116
|
+
}
|
|
117
|
+
: {}),
|
|
111
118
|
}),
|
|
112
119
|
timeout,
|
|
113
120
|
]);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ConductorLogger } from '@bakers-build/core';
|
|
2
|
+
import type { ToolBinding, ToolRegistry } from '../plugins/tools.js';
|
|
3
|
+
export interface ToolServer {
|
|
4
|
+
/** The MCP endpoint. */
|
|
5
|
+
url: string;
|
|
6
|
+
issueRunToken(binding: ToolBinding): string;
|
|
7
|
+
revokeRunToken(token: string): void;
|
|
8
|
+
stop(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
/** What the conductor publishes for the CLI in the endpoint file. */
|
|
11
|
+
export interface ToolServerEndpoint {
|
|
12
|
+
url: string;
|
|
13
|
+
operatorToken: string;
|
|
14
|
+
workspaceRoot: string;
|
|
15
|
+
pid: number;
|
|
16
|
+
}
|
|
17
|
+
export interface ToolServerOptions {
|
|
18
|
+
registry: ToolRegistry;
|
|
19
|
+
/** `<BB_HOME>/conductors/<conductor_id>.json`; absent: no operator access. */
|
|
20
|
+
endpointFile?: string;
|
|
21
|
+
/** The operator may only name worktrees below this directory. */
|
|
22
|
+
workspaceRoot?: string;
|
|
23
|
+
logger?: ConductorLogger;
|
|
24
|
+
}
|
|
25
|
+
export declare function startToolServer(options: ToolServerOptions): Promise<ToolServer>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// The conductor's local MCP server, `bakers-conductor`: serves the addon
|
|
2
|
+
// tools to agent runs over Streamable HTTP on 127.0.0.1. A run token, issued
|
|
3
|
+
// at launch, binds every call to that run's worktree. The operator token
|
|
4
|
+
// (endpoint file, 0600) may name a worktree under the workspace root, for
|
|
5
|
+
// the CLI's plain JSON `POST /call`.
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { createServer, } from 'node:http';
|
|
9
|
+
import { dirname, relative, resolve } from 'node:path';
|
|
10
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
11
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
12
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
13
|
+
import { CONDUCTOR_TOOLS_SERVER } from '../plugins/agent.js';
|
|
14
|
+
const newToken = () => randomBytes(32).toString('hex');
|
|
15
|
+
function bearer(req) {
|
|
16
|
+
const m = /^Bearer (.+)$/.exec(req.headers.authorization ?? '');
|
|
17
|
+
return m?.[1];
|
|
18
|
+
}
|
|
19
|
+
function send(res, status, body) {
|
|
20
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
21
|
+
res.end(JSON.stringify(body));
|
|
22
|
+
}
|
|
23
|
+
async function readJson(req) {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
for await (const chunk of req)
|
|
26
|
+
chunks.push(chunk);
|
|
27
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
28
|
+
}
|
|
29
|
+
function isInside(root, path) {
|
|
30
|
+
const rel = relative(resolve(root), resolve(path));
|
|
31
|
+
return !rel.startsWith('..') && !rel.startsWith('/');
|
|
32
|
+
}
|
|
33
|
+
export async function startToolServer(options) {
|
|
34
|
+
const { registry, logger } = options;
|
|
35
|
+
const runs = new Map();
|
|
36
|
+
const operatorToken = newToken();
|
|
37
|
+
const mcpServer = (binding) => {
|
|
38
|
+
const server = new Server({ name: CONDUCTOR_TOOLS_SERVER, version: '1.0.0' }, { capabilities: { tools: {} } });
|
|
39
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
40
|
+
tools: registry.list().map((t) => ({
|
|
41
|
+
name: t.name,
|
|
42
|
+
description: t.description,
|
|
43
|
+
inputSchema: t.inputSchema,
|
|
44
|
+
})),
|
|
45
|
+
}));
|
|
46
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
47
|
+
try {
|
|
48
|
+
const result = await registry.call(request.params.name, request.params.arguments, binding, { signal: extra.signal, ...(logger ? { logger } : {}) });
|
|
49
|
+
return { content: [{ type: 'text', text: result.text }] };
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
53
|
+
return { isError: true, content: [{ type: 'text', text }] };
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return server;
|
|
57
|
+
};
|
|
58
|
+
const operatorCall = async (req, res) => {
|
|
59
|
+
if (bearer(req) !== operatorToken)
|
|
60
|
+
return send(res, 401, { error: 'operator token required' });
|
|
61
|
+
const body = (await readJson(req));
|
|
62
|
+
if (typeof body.tool !== 'string' || typeof body.worktree !== 'string')
|
|
63
|
+
return send(res, 400, { error: 'tool and worktree are required' });
|
|
64
|
+
if (!options.workspaceRoot ||
|
|
65
|
+
!isInside(options.workspaceRoot, body.worktree))
|
|
66
|
+
return send(res, 403, {
|
|
67
|
+
error: `${body.worktree} is not under the conductor's workspace root ${options.workspaceRoot ?? '(none)'}`,
|
|
68
|
+
});
|
|
69
|
+
try {
|
|
70
|
+
const result = await registry.call(body.tool, body.args, {
|
|
71
|
+
worktreePath: resolve(body.worktree),
|
|
72
|
+
...(typeof body.ticket === 'string'
|
|
73
|
+
? { ticket: { identifier: body.ticket } }
|
|
74
|
+
: {}),
|
|
75
|
+
}, logger ? { logger } : {});
|
|
76
|
+
send(res, 200, result);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
send(res, 422, {
|
|
80
|
+
error: err instanceof Error ? err.message : String(err),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const http = createServer((req, res) => {
|
|
85
|
+
const handle = async () => {
|
|
86
|
+
if (req.method === 'POST' && req.url === '/call')
|
|
87
|
+
return operatorCall(req, res);
|
|
88
|
+
const binding = runs.get(bearer(req) ?? '');
|
|
89
|
+
if (!binding)
|
|
90
|
+
return send(res, 401, {
|
|
91
|
+
error: 'unknown run token — conductor restarted?',
|
|
92
|
+
});
|
|
93
|
+
// Stateless (no session id generator): one server and transport per request.
|
|
94
|
+
const server = mcpServer(binding);
|
|
95
|
+
const transport = new StreamableHTTPServerTransport({
|
|
96
|
+
enableJsonResponse: true,
|
|
97
|
+
});
|
|
98
|
+
res.on('close', () => {
|
|
99
|
+
void transport.close();
|
|
100
|
+
void server.close();
|
|
101
|
+
});
|
|
102
|
+
// The SDK's own types disagree under exactOptionalPropertyTypes.
|
|
103
|
+
await server.connect(transport);
|
|
104
|
+
await transport.handleRequest(req, res);
|
|
105
|
+
};
|
|
106
|
+
handle().catch((err) => {
|
|
107
|
+
logger?.error({ err }, 'tool server request failed');
|
|
108
|
+
if (!res.headersSent)
|
|
109
|
+
send(res, 500, { error: 'internal error' });
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
await new Promise((done) => http.listen(0, '127.0.0.1', done));
|
|
113
|
+
const { port } = http.address();
|
|
114
|
+
const url = `http://127.0.0.1:${port}`;
|
|
115
|
+
if (options.endpointFile) {
|
|
116
|
+
mkdirSync(dirname(options.endpointFile), { recursive: true, mode: 0o700 });
|
|
117
|
+
const endpoint = {
|
|
118
|
+
url,
|
|
119
|
+
operatorToken,
|
|
120
|
+
workspaceRoot: options.workspaceRoot ?? '',
|
|
121
|
+
pid: process.pid,
|
|
122
|
+
};
|
|
123
|
+
writeFileSync(options.endpointFile, JSON.stringify(endpoint), {
|
|
124
|
+
mode: 0o600,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
url,
|
|
129
|
+
issueRunToken: (binding) => {
|
|
130
|
+
const token = newToken();
|
|
131
|
+
runs.set(token, binding);
|
|
132
|
+
return token;
|
|
133
|
+
},
|
|
134
|
+
revokeRunToken: (token) => {
|
|
135
|
+
runs.delete(token);
|
|
136
|
+
},
|
|
137
|
+
stop: async () => {
|
|
138
|
+
if (options.endpointFile)
|
|
139
|
+
rmSync(options.endpointFile, { force: true });
|
|
140
|
+
runs.clear();
|
|
141
|
+
http.closeAllConnections();
|
|
142
|
+
await new Promise((done) => http.close(() => done()));
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -80,6 +80,10 @@ export interface AgentRunIdentity {
|
|
|
80
80
|
*/
|
|
81
81
|
attemptFamily?: string[];
|
|
82
82
|
}
|
|
83
|
+
/** The MCP server name agents see for the conductor's addon tools. */
|
|
84
|
+
export declare const CONDUCTOR_TOOLS_SERVER = "bakers-conductor";
|
|
85
|
+
/** The run env var holding the run's bearer token for that server. */
|
|
86
|
+
export declare const CONDUCTOR_TOKEN_ENV = "BB_CONDUCTOR_TOKEN";
|
|
83
87
|
export interface BbAgent {
|
|
84
88
|
/** Stable id, e.g. 'claude'. */
|
|
85
89
|
readonly id: string;
|
|
@@ -106,8 +110,14 @@ export interface BbAgent {
|
|
|
106
110
|
* a resumed/re-dispatched/reused worktree finalise a FOREIGN transcript.
|
|
107
111
|
* `workspacePath` is the dispatch workspace, for harness permissions that need
|
|
108
112
|
* its Git metadata paths rather than the conductor's own working directory.
|
|
113
|
+
*
|
|
114
|
+
* `tools`, when given, is the conductor's MCP server for this run
|
|
115
|
+
* ({@link CONDUCTOR_TOOLS_SERVER}); its bearer token is in the run env as
|
|
116
|
+
* {@link CONDUCTOR_TOKEN_ENV}. An agent that cannot add an MCP server ignores it.
|
|
109
117
|
*/
|
|
110
|
-
launchCommand(prompt: string, run?: AgentRunIdentity, workspacePath?: string
|
|
118
|
+
launchCommand(prompt: string, run?: AgentRunIdentity, workspacePath?: string, tools?: {
|
|
119
|
+
url: string;
|
|
120
|
+
}): string;
|
|
111
121
|
/**
|
|
112
122
|
* Locate and read this agent's run transcript for a run that executed in
|
|
113
123
|
* `worktreePath`. MUST return '' (never throw) when nothing is found.
|
|
@@ -37,3 +37,7 @@ export function matchesEnvDeny(name, patterns) {
|
|
|
37
37
|
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
38
38
|
.join('.*')}$`).test(name));
|
|
39
39
|
}
|
|
40
|
+
/** The MCP server name agents see for the conductor's addon tools. */
|
|
41
|
+
export const CONDUCTOR_TOOLS_SERVER = 'bakers-conductor';
|
|
42
|
+
/** The run env var holding the run's bearer token for that server. */
|
|
43
|
+
export const CONDUCTOR_TOKEN_ENV = 'BB_CONDUCTOR_TOKEN';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ConductorLogger } from '@bakers-build/core';
|
|
2
2
|
import { type MessageDefinition, type MessageResult } from '@bakers-build/message';
|
|
3
3
|
import type { Ticket } from './remote.js';
|
|
4
|
+
import type { ToolResult } from './tools.js';
|
|
4
5
|
/** What a handler gets: its own request identity plus the ticket's worktree. */
|
|
5
6
|
export interface InboxMessageRequest {
|
|
6
7
|
/** The bb_inbox_message entity UUID; the request's own identity, never the message type. */
|
|
@@ -16,6 +17,8 @@ export interface InboxMessageRequest {
|
|
|
16
17
|
logger: ConductorLogger;
|
|
17
18
|
/** Aborts when the handler runs past its timeout. */
|
|
18
19
|
signal: AbortSignal;
|
|
20
|
+
/** Call an addon tool on this worktree; absent when no addon declares tools. */
|
|
21
|
+
callTool?: (name: string, args?: Record<string, unknown>) => Promise<ToolResult>;
|
|
19
22
|
}
|
|
20
23
|
export type InboxMessageHandler = (request: InboxMessageRequest) => Promise<MessageResult>;
|
|
21
24
|
/** An addon preset's `inbox` export. */
|
|
@@ -4,6 +4,7 @@ import type { DiscoveredInbox, InboxMessages } from './message.js';
|
|
|
4
4
|
import type { AgentCandidate, ExecutorPlugin, RemotePlugin, WorkspacePlugin } from './plugins.js';
|
|
5
5
|
import type { HerdrHost } from './process-host.js';
|
|
6
6
|
import type { Ticket } from './remote.js';
|
|
7
|
+
import type { AddonTools, DiscoveredTools } from './tools.js';
|
|
7
8
|
/**
|
|
8
9
|
* The conductor surface's concrete contributions — the strongly-typed view of
|
|
9
10
|
* the conductor accumulators `discoverAddons(entries, 'conductor', …)`
|
|
@@ -21,6 +22,8 @@ export interface ConductorContributions {
|
|
|
21
22
|
processHosts: HerdrHost[];
|
|
22
23
|
/** Addon `inbox` exports with their package name and version (contract 2, BB-661). */
|
|
23
24
|
addonInbox: DiscoveredInbox[];
|
|
25
|
+
/** Addon `tools` exports with their package name and version. */
|
|
26
|
+
addonTools: DiscoveredTools[];
|
|
24
27
|
}
|
|
25
28
|
/**
|
|
26
29
|
* One `addons[]` entry on the conductor surface: core's surface-agnostic
|
|
@@ -50,6 +53,8 @@ export interface Preset<O = unknown> extends BbPreset<O> {
|
|
|
50
53
|
processHosts?: (acc: HerdrHost[], opts: O) => HerdrHost[] | Promise<HerdrHost[]>;
|
|
51
54
|
/** Addon inbox messages: contract 2, BB-661. */
|
|
52
55
|
inbox?: InboxMessages;
|
|
56
|
+
/** Agent tools served through the conductor's MCP server. */
|
|
57
|
+
tools?: AddonTools;
|
|
53
58
|
}
|
|
54
59
|
/**
|
|
55
60
|
* The single, reviewed narrowing at the engine's discovery seam: reinterpret
|
|
@@ -58,4 +63,4 @@ export interface Preset<O = unknown> extends BbPreset<O> {
|
|
|
58
63
|
* {@link Preset}, and `resolveConductorSlots` still runs the runtime `.kind`
|
|
59
64
|
* guard on whatever actually landed in a singleton slot.
|
|
60
65
|
*/
|
|
61
|
-
export declare function narrowConductorContributions(discovered: Pick<DiscoveredContributions, 'remotes' | 'executors' | 'workspaces' | 'agents' | 'hooks' | 'processHosts' | 'addonInbox'>): ConductorContributions;
|
|
66
|
+
export declare function narrowConductorContributions(discovered: Pick<DiscoveredContributions, 'remotes' | 'executors' | 'workspaces' | 'agents' | 'hooks' | 'processHosts' | 'addonInbox' | 'addonTools'>): ConductorContributions;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { ConductorLogger } from '@bakers-build/core';
|
|
2
|
+
import { type MessageInput } from '@bakers-build/message';
|
|
3
|
+
import type { Ticket } from './remote.js';
|
|
4
|
+
export interface ToolDefinition {
|
|
5
|
+
description: string;
|
|
6
|
+
/** Absent means a parameterless tool. Unknown arguments are refused. */
|
|
7
|
+
input?: MessageInput;
|
|
8
|
+
}
|
|
9
|
+
export interface ToolResult {
|
|
10
|
+
text: string;
|
|
11
|
+
}
|
|
12
|
+
/** The worktree a call acts on — fixed by the session, never by the tool. */
|
|
13
|
+
export interface ToolBinding {
|
|
14
|
+
worktreePath: string;
|
|
15
|
+
/** The run's ticket; an operator call may know only its identifier. */
|
|
16
|
+
ticket?: Partial<Ticket> & {
|
|
17
|
+
identifier: string;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export interface ToolRequest extends ToolBinding {
|
|
21
|
+
args: Record<string, unknown>;
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
logger: ConductorLogger;
|
|
24
|
+
/** Call another registered tool on the same worktree. */
|
|
25
|
+
callTool(name: string, args?: Record<string, unknown>): Promise<ToolResult>;
|
|
26
|
+
}
|
|
27
|
+
/** Throw to report a tool error; the message reaches the caller. */
|
|
28
|
+
export type ToolHandler = (request: ToolRequest) => Promise<ToolResult>;
|
|
29
|
+
/** An addon preset's `tools` export. */
|
|
30
|
+
export interface AddonTools {
|
|
31
|
+
contract: 1;
|
|
32
|
+
tools: Record<string, ToolDefinition>;
|
|
33
|
+
/** Lazy: imported only when the conductor loads the addon. */
|
|
34
|
+
handlers: (options?: unknown) => Promise<Record<string, ToolHandler>>;
|
|
35
|
+
}
|
|
36
|
+
/** One `tools` export as discovery found it. */
|
|
37
|
+
export interface DiscoveredTools {
|
|
38
|
+
name: string;
|
|
39
|
+
version: string;
|
|
40
|
+
tools: AddonTools;
|
|
41
|
+
/** The addon entry's `with` options, handed to `tools.handlers`. */
|
|
42
|
+
options?: unknown;
|
|
43
|
+
}
|
|
44
|
+
export interface ListedTool {
|
|
45
|
+
name: string;
|
|
46
|
+
addon: string;
|
|
47
|
+
description: string;
|
|
48
|
+
/** JSON schema of the arguments. */
|
|
49
|
+
inputSchema: object;
|
|
50
|
+
}
|
|
51
|
+
export interface ToolRegistry {
|
|
52
|
+
list(): ListedTool[];
|
|
53
|
+
call(name: string, args: Record<string, unknown> | undefined, binding: ToolBinding, options?: {
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
logger?: ConductorLogger;
|
|
56
|
+
}): Promise<ToolResult>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolves every addon's handlers and checks that handlers and declared tools
|
|
60
|
+
* match one to one. A tool name declared by two addons is an error, so the
|
|
61
|
+
* conductor never starts with an ambiguous tool.
|
|
62
|
+
*/
|
|
63
|
+
export declare function loadTools(found: readonly DiscoveredTools[]): Promise<ToolRegistry>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The agent-tool contract on the conductor surface: an addon's preset may
|
|
2
|
+
// export `tools` — tool definitions plus LAZY handlers, shaped like the
|
|
3
|
+
// inbox contract. The conductor serves them to agent runs through its MCP
|
|
4
|
+
// server, and addons call each other's tools through the same registry.
|
|
5
|
+
// Every call is bound to one worktree by the caller, never by an argument.
|
|
6
|
+
import { payloadSchema, validateArgs, } from '@bakers-build/message';
|
|
7
|
+
const silent = {
|
|
8
|
+
debug: () => { },
|
|
9
|
+
info: () => { },
|
|
10
|
+
warn: () => { },
|
|
11
|
+
error: () => { },
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Resolves every addon's handlers and checks that handlers and declared tools
|
|
15
|
+
* match one to one. A tool name declared by two addons is an error, so the
|
|
16
|
+
* conductor never starts with an ambiguous tool.
|
|
17
|
+
*/
|
|
18
|
+
export async function loadTools(found) {
|
|
19
|
+
const entries = new Map();
|
|
20
|
+
for (const addon of found) {
|
|
21
|
+
const fail = (msg) => new Error(`addon ${addon.name}: ${msg}`);
|
|
22
|
+
if (addon.tools.contract !== 1)
|
|
23
|
+
throw fail(`unsupported tools contract ${addon.tools.contract}`);
|
|
24
|
+
const handlers = await addon.tools.handlers(addon.options);
|
|
25
|
+
for (const [name, def] of Object.entries(addon.tools.tools)) {
|
|
26
|
+
const handler = handlers[name];
|
|
27
|
+
if (typeof handler !== 'function')
|
|
28
|
+
throw fail(`no handler for tool ${name}`);
|
|
29
|
+
const taken = entries.get(name);
|
|
30
|
+
if (taken)
|
|
31
|
+
throw new Error(`tool ${name} is declared by both ${taken.addon} and ${addon.name}`);
|
|
32
|
+
entries.set(name, { addon: addon.name, def, handler });
|
|
33
|
+
}
|
|
34
|
+
for (const name of Object.keys(handlers))
|
|
35
|
+
if (!(name in addon.tools.tools))
|
|
36
|
+
throw fail(`handler ${name} is not declared`);
|
|
37
|
+
}
|
|
38
|
+
const registry = {
|
|
39
|
+
list: () => [...entries].map(([name, { addon, def }]) => ({
|
|
40
|
+
name,
|
|
41
|
+
addon,
|
|
42
|
+
description: def.description,
|
|
43
|
+
inputSchema: payloadSchema(def.input),
|
|
44
|
+
})),
|
|
45
|
+
call: async (name, args, binding, options = {}) => {
|
|
46
|
+
const entry = entries.get(name);
|
|
47
|
+
if (!entry)
|
|
48
|
+
throw new Error(`unknown tool ${name}`);
|
|
49
|
+
const valid = validateArgs(entry.def.input, args);
|
|
50
|
+
if (!valid.ok)
|
|
51
|
+
throw new Error(`${name}: invalid arguments: ${valid.errors.join('; ')}`);
|
|
52
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
53
|
+
return entry.handler({
|
|
54
|
+
...binding,
|
|
55
|
+
args: args ?? {},
|
|
56
|
+
signal,
|
|
57
|
+
logger: options.logger ?? silent,
|
|
58
|
+
callTool: (next, nextArgs) => registry.call(next, nextArgs, binding, { ...options, signal }),
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
return registry;
|
|
63
|
+
}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -7,6 +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 { ToolRegistry } from './plugins/tools.js';
|
|
10
11
|
/** Normalized single conductor. */
|
|
11
12
|
export interface ConductorSettings {
|
|
12
13
|
/** Display label, sent once at registration: `<machine label> · <project>[/<variant>]`. */
|
|
@@ -102,6 +103,8 @@ export interface ConductorFileConfig extends ConductorSettings {
|
|
|
102
103
|
* validated at load (BB-661). Absent means none.
|
|
103
104
|
*/
|
|
104
105
|
inboxAddons?: LoadedInbox[];
|
|
106
|
+
/** Agent tools from the conductor `addons[]` `tools` exports. Absent means none. */
|
|
107
|
+
tools?: ToolRegistry;
|
|
105
108
|
/**
|
|
106
109
|
* Conductor process host from the `processHosts` accumulator (last wins).
|
|
107
110
|
* 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.5.1-next.
|
|
3
|
+
"version": "0.5.1-next.856",
|
|
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,13 +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.5.1-next.
|
|
36
|
-
"@bakers-build/message": "^0.5.1-next.
|
|
35
|
+
"@bakers-build/core": "^0.5.1-next.856",
|
|
36
|
+
"@bakers-build/message": "^0.5.1-next.856",
|
|
37
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
37
38
|
"commander": "^12.1.0",
|
|
38
39
|
"dropsh": "^0.8.2"
|
|
39
40
|
},
|
|
40
41
|
"bakersBuild": {
|
|
41
|
-
"commit": "
|
|
42
|
+
"commit": "756501eea816e36604ee443b4b3dc8a9e6c89692",
|
|
42
43
|
"channel": "next"
|
|
43
44
|
}
|
|
44
45
|
}
|