@bakers-build/conductor 0.8.1-next.3 → 0.8.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.
@@ -144,7 +144,7 @@ function validateHookListeners(value) {
144
144
  for (const [index, listener] of value.entries()) {
145
145
  if (!isRecord(listener))
146
146
  throw new Error(`hooks[${index}] must be a listener object`);
147
- for (const slot of HOOK_SLOTS) {
147
+ for (const slot of [...HOOK_SLOTS, 'before_conductor_start']) {
148
148
  if (listener[slot] !== undefined && typeof listener[slot] !== 'function')
149
149
  throw new Error(`hooks[${index}].${slot} must be a function`);
150
150
  }
@@ -520,6 +520,9 @@ export async function loadConductorConfig(configFile) {
520
520
  ...(config.hooks?.provision_up !== undefined ? { provisioning } : {}),
521
521
  bakers,
522
522
  ...identityOf(machineCtx, project, variant),
523
+ ...(machineCtx.connection_url !== undefined
524
+ ? { connection_url: machineCtx.connection_url }
525
+ : {}),
523
526
  variant,
524
527
  project,
525
528
  states,
@@ -2,7 +2,7 @@ export { AmbiguousProjectNameError, type ResolvedBbProjectContext, resolveBbProj
2
2
  export { type AgentFootprint, type AgentRunIdentity, type BbAgent, CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, CONDUCTOR_URL_ENV, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, type PluginLaunch, type RunEnvPolicy, } from './plugins/agent.js';
3
3
  export { detectKnownOverrides, type KnownOptionSpec, type KnownOverrides, type KnownScalarKind, type ResolvedSecurity, resolveAgentCliOptions, resolveSecurityOptions, type SandboxOptions, SECURITY_MODES, type SecurityMode, type SecurityOptions, type SecurityReport, SHARED_SECURITY_KEY, type SharedListKey, type SharedSecurity, validateAgentArgs, validateOptionalBoolean, validateOptionalString, validateSharedSecurity, } from './plugins/agent-args.js';
4
4
  export { ensureHome, homeKey, homePath, type MarketplaceDeclaration, validateMarketplaces, } from './plugins/agent-home.js';
5
- export type { BbExecutor, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, OpenWorkspaceContext, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
5
+ export type { BbExecutor, ConductorStartContext, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, MachineRegistrationData, OpenWorkspaceContext, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
6
6
  export type { DiscoveredInbox, InboxBinding, InboxMessageHandler, InboxMessageRequest, InboxMessages, LoadedInbox, } from './plugins/message.js';
7
7
  export { loadInbox, validateRequestPayload, } from './plugins/message.js';
8
8
  export type { AgentCandidate, AgentPlugin, ExecutorDeps, ExecutorPlugin, RemotePlugin, ResolvedAgent, WorkspacePlugin, } from './plugins/plugins.js';
@@ -39,8 +39,6 @@ export declare class Conductor {
39
39
  /** Re-reads machine.config.js per run; absent, `config.tunnel` stays. */
40
40
  private readonly readMachine?;
41
41
  private uuid;
42
- /** Runs running at this process's first lost-run check whose pane lookup has not answered yet: resumed, not failed. */
43
- private recovering?;
44
42
  /**
45
43
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
46
44
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -48,10 +46,6 @@ export declare class Conductor {
48
46
  * restart does not repeat `on_freeze`; loaded on the first observation.
49
47
  */
50
48
  private frozenSeen;
51
- /** Transcript mtime each active run was last checked for denials at. */
52
- private readonly stallChecked;
53
- /** Active runs already reported as blocked; never reported twice. */
54
- private readonly stallReported;
55
49
  /** The addons with contract-2 inbox messages this conductor runs. */
56
50
  private readonly inboxAddons;
57
51
  /** The per-item work each tick enqueues. */
@@ -118,25 +112,6 @@ export declare class Conductor {
118
112
  * the heartbeat or the claims.
119
113
  */
120
114
  produce(): Promise<void>;
121
- /**
122
- * Fails every running run whose terminal is gone: nobody executes it, and
123
- * the server never expires a `running` run. Keyed off the durable active-run
124
- * query, so a restarted conductor checks adopted runs on its first tick.
125
- */
126
- private enqueueLostRuns;
127
- /**
128
- * Fails and reports one run when its terminal is gone; a failed lookup
129
- * changes nothing. On a run's first answering lookup after a restart it
130
- * resumes the run instead, when its agent and session allow.
131
- */
132
- private lostOne;
133
- private stillRunning;
134
- private lostComment;
135
- /**
136
- * Relaunches a lost run in its worktree with its agent's session resume.
137
- * Returns undefined when resumed, else why it was not: the caller fails it.
138
- */
139
- private resumeLost;
140
115
  /**
141
116
  * One-shot finalisation: for each of this conductor's runs that is state in
142
117
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -145,26 +120,8 @@ export declare class Conductor {
145
120
  * conductor still finalises any unclosed run on its next tick.
146
121
  */
147
122
  private enqueueFinalize;
148
- /**
149
- * A run a permission rule denied cannot ask anyone on an unattended box,
150
- * so it stops. Once its transcript has been quiet for {@link STALL_QUIET_MS}
151
- * and holds a denial, report it once. One stat per running run per tick;
152
- * the transcript is read once per modification.
153
- */
154
- private observeStalls;
155
- /**
156
- * The technical-problem note, then the error: the PM bot relays the newest
157
- * comment of a frozen, labelled ticket. Cancelling lets finalisation stop
158
- * the agent and keep its transcript.
159
- */
160
- private reportBlocked;
161
123
  /** Finalises one run; a failure is logged and retried next tick. */
162
124
  private finalizeOne;
163
- /**
164
- * The agent that actually ran: the persisted run.agent id, falling back to
165
- * the first candidate for a run written before the field existed (empty id).
166
- */
167
- private agentFor;
168
125
  /** Read the run's transcript and parse its footprint for the close write. */
169
126
  private captureRun;
170
127
  /**
@@ -283,18 +240,13 @@ export declare class Conductor {
283
240
  * one `plugins` entry. A failed install throws, failing the run start.
284
241
  */
285
242
  private installPlugins;
286
- /**
287
- * `at.worktree` is set once the workspace exists, so a failure can signal it.
288
- * `resume`: continue the run's newest agent session instead of prompting afresh.
289
- */
243
+ /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
290
244
  private dispatch;
291
245
  /**
292
246
  * The part of a dispatch that can leave a sidecar or a worker behind
293
247
  * (BB-599): its caller unwinds it through `after_run` on any failure.
294
248
  */
295
249
  private launch;
296
- /** The run's newest agent session, or why it cannot be resumed. */
297
- private resumableSession;
298
250
  /**
299
251
  * Stop what a failed dispatch started (BB-599): the worker if it was
300
252
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -12,6 +12,7 @@ import { shellHookRunner } from './hook-runner.js';
12
12
  import { InboxRuntime, runInbox } from './inbox-runtime.js';
13
13
  import { measureMrChanges, mrChangesRows } from './mr-changes.js';
14
14
  import { checkRequiredSkills } from './required-skills.js';
15
+ import { runStartHooks } from './start-hooks.js';
15
16
  import { startToolServer } from './tool-server.js';
16
17
  import { signalUi } from './ui-signal.js';
17
18
  function sleep(ms, signal) {
@@ -45,8 +46,6 @@ function isReservedEnvKey(key) {
45
46
  }
46
47
  /** A portable environment variable name. */
47
48
  const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
48
- /** How long a run's transcript stays unchanged before its permission denials are reported. */
49
- const STALL_QUIET_MS = 5 * 60_000;
50
49
  /**
51
50
  * What a failed listener is logged as: the error's class name, never its
52
51
  * message — listener text may carry an env value (BB-599).
@@ -159,30 +158,6 @@ function recordAfterCreateOutcome(file, worktreePath, ok) {
159
158
  // best-effort: a later dispatch simply re-runs after_create.
160
159
  }
161
160
  }
162
- /**
163
- * Run UUIDs this conductor resumed after a restart, beside its config file so
164
- * a second restart fails a run instead of resuming it again.
165
- * shortcut: entries are never pruned (a UUID per resumed run); prune on finalize if it ever grows.
166
- */
167
- function resumedStateFileOf(config) {
168
- const file = config.config_path;
169
- return join(dirname(file), `${basename(file, '.js')}.resumed.json`);
170
- }
171
- function loadResumed(file) {
172
- try {
173
- const v = JSON.parse(readFileSync(file, 'utf8'));
174
- return Array.isArray(v) ? v : [];
175
- }
176
- catch {
177
- return [];
178
- }
179
- }
180
- /** A lost run the restart recovery fails instead of resuming; the message is the reason. */
181
- class ResumeRefused extends Error {
182
- }
183
- /** A resume met a run that is no longer `running`: nothing to launch or fail. */
184
- class RunClosed extends Error {
185
- }
186
161
  function renderPrompt(template, values) {
187
162
  return template
188
163
  .replaceAll('{identifier}', values.identifier)
@@ -223,8 +198,6 @@ export class Conductor {
223
198
  runHook;
224
199
  readMachine;
225
200
  uuid = null;
226
- /** Runs running at this process's first lost-run check whose pane lookup has not answered yet: resumed, not failed. */
227
- recovering;
228
201
  /**
229
202
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
230
203
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -232,10 +205,6 @@ export class Conductor {
232
205
  * restart does not repeat `on_freeze`; loaded on the first observation.
233
206
  */
234
207
  frozenSeen = null;
235
- /** Transcript mtime each active run was last checked for denials at. */
236
- stallChecked = new Map();
237
- /** Active runs already reported as blocked; never reported twice. */
238
- stallReported = new Set();
239
208
  /** The addons with contract-2 inbox messages this conductor runs. */
240
209
  inboxAddons;
241
210
  /** The per-item work each tick enqueues. */
@@ -370,7 +339,44 @@ export class Conductor {
370
339
  }
371
340
  }
372
341
  async start() {
373
- this.uuid = await this.remote.registerConductor(this.registration());
342
+ const registration = this.registration();
343
+ const machine = this.ownsServeProcess
344
+ ? await runStartHooks(this.config.hookListeners ?? [], {
345
+ ...(registration.host_key !== undefined
346
+ ? { host_key: registration.host_key }
347
+ : {}),
348
+ ...(registration.machine_label !== undefined
349
+ ? { machine_label: registration.machine_label }
350
+ : {}),
351
+ ...(this.config.connection_url !== undefined
352
+ ? { connection_url: this.config.connection_url }
353
+ : {}),
354
+ }, {
355
+ id: registration.id,
356
+ project: registration.project,
357
+ variant: registration.conductor_name ?? this.config.variant,
358
+ }, (reason) => this.logger.warn({ conductorId: this.id }, reason))
359
+ : {};
360
+ try {
361
+ this.uuid = await this.remote.registerConductor({
362
+ ...registration,
363
+ ...machine,
364
+ });
365
+ }
366
+ catch (err) {
367
+ if (typeof machine.connection_url !== 'string')
368
+ throw err;
369
+ // A server that refuses the address must not stop the start; without
370
+ // the field the stored address stays unchanged.
371
+ // Value-free: the error may quote the address.
372
+ this.logger.warn({ conductorId: this.id }, 'registration failed with the connection URL; retrying without it');
373
+ const rest = { ...machine };
374
+ delete rest.connection_url;
375
+ this.uuid = await this.remote.registerConductor({
376
+ ...registration,
377
+ ...rest,
378
+ });
379
+ }
374
380
  this.logger.info({ conductorId: this.id, uuid: this.uuid, project: this.config.project }, 'conductor started');
375
381
  try {
376
382
  await this.inboxAddons.register(this.id);
@@ -439,11 +445,9 @@ export class Conductor {
439
445
  }
440
446
  // A hung action blocks only its ticket's lane; make it visible.
441
447
  this.queue.warnOverdue(this.config.lease_seconds * 1000);
442
- await this.step('lost', () => this.enqueueLostRuns());
443
448
  await this.step('finalize', () => this.enqueueFinalize());
444
449
  await this.step('reap', () => this.enqueueReap());
445
450
  await this.step('freeze', () => this.observeFreezes());
446
- await this.step('stalls', () => this.observeStalls());
447
451
  await runInbox(this.remote, this.inboxAddons, this.id, this.logger, this.queue);
448
452
  // A run that cannot start its sandbox would only fail and count against
449
453
  // the retry cap; claim nothing until every enabled agent can start.
@@ -495,122 +499,6 @@ export class Conductor {
495
499
  : 'idle, nothing to claim');
496
500
  }
497
501
  }
498
- /**
499
- * Fails every running run whose terminal is gone: nobody executes it, and
500
- * the server never expires a `running` run. Keyed off the durable active-run
501
- * query, so a restarted conductor checks adopted runs on its first tick.
502
- */
503
- async enqueueLostRuns() {
504
- if (!this.executor.runAlive)
505
- return;
506
- const runs = (await this.remote.fetchActiveRuns(this.id)).filter((r) => r.state === 'running');
507
- this.recovering ??= new Set(runs.map((r) => r.runUuid));
508
- for (const r of runs) {
509
- this.queue.enqueue({
510
- key: `lost:${r.runUuid}`,
511
- lane: r.ticketUuid || r.runUuid,
512
- run: () => this.lostOne(r),
513
- });
514
- }
515
- }
516
- /**
517
- * Fails and reports one run when its terminal is gone; a failed lookup
518
- * changes nothing. On a run's first answering lookup after a restart it
519
- * resumes the run instead, when its agent and session allow.
520
- */
521
- async lostOne(r) {
522
- let alive;
523
- try {
524
- alive = (await this.executor.runAlive?.(r.branchName, r.runId)) ?? true;
525
- }
526
- catch (err) {
527
- this.logger.warn({ run: r.runUuid, err: String(err) }, 'pane lookup failed; run left active');
528
- return;
529
- }
530
- const recovery = this.recovering?.delete(r.runUuid) ?? false;
531
- if (alive)
532
- return;
533
- let refused;
534
- try {
535
- // The run may have ended normally since the snapshot.
536
- if (!(await this.stillRunning(r.runUuid)))
537
- return;
538
- if (recovery) {
539
- refused = await this.resumeLost(r);
540
- if (refused === undefined)
541
- return;
542
- }
543
- const gone = `herdr pane gone: ${this.executor.id} found no live terminal for run #${r.runId} (branch ${r.branchName})`;
544
- const cause = refused ? `conductor restart: ${refused}; ${gone}` : gone;
545
- // herdr may have restored the tab and restarted an agent in it; a fresh run would share the worktree.
546
- await this.executor
547
- .cleanupRun(r.branchName, r.runId)
548
- .catch((err) => {
549
- this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run tab not closed');
550
- });
551
- await this.remote.markFailed(r.runUuid, cause);
552
- this.revokeRunTools(r.runUuid);
553
- this.signalUi(r.worktreePath);
554
- this.logger.warn({ run: r.runUuid }, cause);
555
- }
556
- catch (err) {
557
- // A transient remote error must not cost the retry its resume or its restart reason.
558
- if (recovery)
559
- this.recovering?.add(r.runUuid);
560
- this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run not marked failed; retried next tick');
561
- return;
562
- }
563
- // Not retried: the run is no longer active, so a retry could only duplicate.
564
- await this.lostComment(r, `was marked \`failed\`: its terminal pane is gone (\`${this.executor.id}\` found no live terminal on branch \`${r.branchName}\`), so nobody was executing it any more.${refused ? ` It could not be resumed after the conductor restart: ${refused}. The ticket gets a fresh run.` : ''}`);
565
- }
566
- async stillRunning(runUuid) {
567
- return (await this.remote.fetchActiveRuns(this.id)).some((a) => a.runUuid === runUuid && a.state === 'running');
568
- }
569
- async lostComment(r, what) {
570
- await this.remote
571
- .publishTicketComment(r.ticketUuid, `Run #${r.runId} (\`${r.runUuid}\`) in state \`${r.stateAtStart}\` ${what}\n`)
572
- .catch((err) => {
573
- this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run comment failed');
574
- });
575
- }
576
- /**
577
- * Relaunches a lost run in its worktree with its agent's session resume.
578
- * Returns undefined when resumed, else why it was not: the caller fails it.
579
- */
580
- async resumeLost(r) {
581
- const file = resumedStateFileOf(this.config);
582
- const resumed = loadResumed(file);
583
- if (resumed.includes(r.runUuid))
584
- return 'the run was already resumed once';
585
- if (!r.worktreePath || !existsSync(r.worktreePath))
586
- return `its worktree ${r.worktreePath || '(unrecorded)'} is gone`;
587
- try {
588
- // Recorded first: a resume that dies half-way must not be tried again.
589
- mkdirSync(dirname(file), { recursive: true });
590
- writeFileSync(file, `${JSON.stringify([...resumed, r.runUuid])}\n`);
591
- await this.dispatch({
592
- runUuid: r.runUuid,
593
- runId: r.runId,
594
- ticketUuid: r.ticketUuid,
595
- stateAtStart: r.stateAtStart,
596
- handler: r.stateAtStart,
597
- }, {}, true);
598
- }
599
- catch (err) {
600
- // A cancel during the launch makes the server reject it; that run is closed, not failed.
601
- if (err instanceof RunClosed ||
602
- !(await this.stillRunning(r.runUuid).catch(() => true))) {
603
- this.logger.info({ run: r.runUuid }, 'lost run closed during its resume');
604
- return undefined;
605
- }
606
- return err instanceof ResumeRefused
607
- ? err.message
608
- : `the resume launch failed: ${err instanceof Error ? err.message : String(err)}`;
609
- }
610
- this.logger.info({ run: r.runUuid }, 'lost run resumed after restart');
611
- await this.lostComment(r, `was resumed after a conductor restart: its terminal pane was gone, so the agent continues its session in \`${r.worktreePath}\`.`);
612
- return undefined;
613
- }
614
502
  /**
615
503
  * One-shot finalisation: for each of this conductor's runs that is state in
616
504
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -628,107 +516,6 @@ export class Conductor {
628
516
  });
629
517
  }
630
518
  }
631
- /**
632
- * A run a permission rule denied cannot ask anyone on an unattended box,
633
- * so it stops. Once its transcript has been quiet for {@link STALL_QUIET_MS}
634
- * and holds a denial, report it once. One stat per running run per tick;
635
- * the transcript is read once per modification.
636
- */
637
- async observeStalls() {
638
- const runs = await this.remote.fetchActiveRuns(this.id);
639
- const live = new Set(runs.map((r) => r.runUuid));
640
- for (const seen of [this.stallChecked, this.stallReported])
641
- for (const id of seen.keys())
642
- if (!live.has(id))
643
- seen.delete(id);
644
- for (const r of runs) {
645
- if (r.state !== 'running' || !r.worktreePath)
646
- continue;
647
- if (this.stallReported.has(r.runUuid))
648
- continue;
649
- const agent = this.agentFor(r)?.agent;
650
- if (!agent?.permissionDenials || !agent.runLogModified)
651
- continue;
652
- const identity = {
653
- sessionId: r.runUuid,
654
- attemptFamily: attemptFamily(r.runUuid),
655
- };
656
- let denied;
657
- try {
658
- const modified = await agent.runLogModified(r.worktreePath, identity);
659
- if (modified === undefined ||
660
- Date.now() - modified < STALL_QUIET_MS ||
661
- this.stallChecked.get(r.runUuid) === modified)
662
- continue;
663
- denied = agent.permissionDenials(await agent.getRunLog(r.worktreePath, identity));
664
- // Only a successful read counts: a stuck transcript never changes again.
665
- this.stallChecked.set(r.runUuid, modified);
666
- }
667
- catch (err) {
668
- this.logger.warn({ conductorId: this.id, run: r.runUuid, err }, 'could not read the run transcript for permission denials');
669
- continue;
670
- }
671
- if (denied.length === 0)
672
- continue;
673
- this.stallReported.add(r.runUuid);
674
- this.queue.enqueue({
675
- key: `stall:${r.runUuid}`,
676
- lane: r.ticketUuid || r.runUuid,
677
- run: () => this.reportBlocked(r, denied),
678
- });
679
- }
680
- }
681
- /**
682
- * The technical-problem note, then the error: the PM bot relays the newest
683
- * comment of a frozen, labelled ticket. Cancelling lets finalisation stop
684
- * the agent and keep its transcript.
685
- */
686
- async reportBlocked(r, denied) {
687
- const site = this.remote.siteTools;
688
- // Without site tools nothing reaches the ticket; a silent cancel would hide the run.
689
- // Unmarked, the next tick with site tools reports it.
690
- if (!site) {
691
- this.stallReported.delete(r.runUuid);
692
- this.stallChecked.delete(r.runUuid);
693
- throw new Error('no site tools to report the blocked run');
694
- }
695
- this.logger.warn({ conductorId: this.id, run: r.runUuid, denied }, 'run blocked on a permission denial; reporting and cancelling it');
696
- const call = async (name, args) => {
697
- const result = await site.call(`tool_api__${name}`, args);
698
- if (result?.isError)
699
- throw new Error(`${name}: ${JSON.stringify(result?.content)}`);
700
- };
701
- const comment = (body) => call('bakers_comment_publish', {
702
- ticket: r.ticketUuid,
703
- type: 'comment',
704
- body,
705
- });
706
- try {
707
- await comment('# Technical problem\n\nPlease contact the developers.\n');
708
- await comment([
709
- '# Error',
710
- '',
711
- `The sandboxed run stopped: a permission rule denied an action it needed, and its transcript has not changed for ${STALL_QUIET_MS / 60_000} minutes. An allow rule for the action is missing from the agent's \`permissions\` settings. Add it, then unfreeze the ticket.`,
712
- '',
713
- 'Denied actions:',
714
- '',
715
- ...denied.map((action) => `- \`${action}\``),
716
- '',
717
- ].join('\n'));
718
- await call('bakers_ticket_update', {
719
- ticket: r.ticketUuid,
720
- labels_add: ['technical problem'],
721
- frozen: true,
722
- });
723
- }
724
- finally {
725
- // A stuck run is cancelled even when the report fails; the warning names the actions.
726
- // shortcut: the reported mark lives in memory, so if this cancel fails a restarted
727
- // conductor reports the run again; persist the mark if duplicates show up.
728
- await this.remote.cancelRun(r.runUuid);
729
- }
730
- this.signalUi();
731
- }
732
519
  /** Finalises one run; a failure is logged and retried next tick. */
733
520
  async finalizeOne(r) {
734
521
  try {
@@ -785,16 +572,12 @@ export class Conductor {
785
572
  this.logger.warn({ run: r.runUuid, err: String(err) }, 'run finalise failed');
786
573
  }
787
574
  }
788
- /**
789
- * The agent that actually ran: the persisted run.agent id, falling back to
790
- * the first candidate for a run written before the field existed (empty id).
791
- */
792
- agentFor(r) {
793
- return this.agents.find((a) => a.id === r.agent) ?? this.agents[0];
794
- }
795
575
  /** Read the run's transcript and parse its footprint for the close write. */
796
576
  async captureRun(r) {
797
- const resolved = this.agentFor(r);
577
+ // Route to the agent that actually ran (BB-144): the persisted
578
+ // run.agent id, falling back to the first candidate for a run written
579
+ // before the field existed (empty id).
580
+ const resolved = this.agents.find((a) => a.id === r.agent) ?? this.agents[0];
798
581
  if (!resolved) {
799
582
  throw new Error('no agent candidates configured for finalize');
800
583
  }
@@ -1459,11 +1242,8 @@ export class Conductor {
1459
1242
  log();
1460
1243
  return { env: launch.env, args: launch.args };
1461
1244
  }
1462
- /**
1463
- * `at.worktree` is set once the workspace exists, so a failure can signal it.
1464
- * `resume`: continue the run's newest agent session instead of prompting afresh.
1465
- */
1466
- async dispatch(run, at = {}, resume = false) {
1245
+ /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
1246
+ async dispatch(run, at = {}) {
1467
1247
  const t = await this.remote.getTicket(run.ticketUuid);
1468
1248
  // Resolve the ticket alias and machine defaults, or the project selection hook.
1469
1249
  // Persist the package id below so finalize can choose its transcript parser.
@@ -1509,7 +1289,7 @@ export class Conductor {
1509
1289
  };
1510
1290
  const launch = { started: false };
1511
1291
  try {
1512
- await this.launch(run, t, chosen, ws, ctx, launch, resume);
1292
+ await this.launch(run, t, chosen, ws, ctx, launch);
1513
1293
  }
1514
1294
  catch (err) {
1515
1295
  await this.unwindDispatch(ctx, launch.started);
@@ -1520,11 +1300,8 @@ export class Conductor {
1520
1300
  * The part of a dispatch that can leave a sidecar or a worker behind
1521
1301
  * (BB-599): its caller unwinds it through `after_run` on any failure.
1522
1302
  */
1523
- async launch(run, t, chosen, ws, ctx, launch, resume = false) {
1303
+ async launch(run, t, chosen, ws, ctx, launch) {
1524
1304
  const env = ctx.env;
1525
- const resumeSession = resume
1526
- ? await this.resumableSession(chosen, ws.path, run.runUuid)
1527
- : undefined;
1528
1305
  // Lifecycle hooks are conductor-owned + best-effort (BB-84): runHook never
1529
1306
  // throws, so neither call can abort dispatch or wedge a run in `claimed`.
1530
1307
  // `runSlot` runs the addon listeners first under the same rule (BB-599).
@@ -1643,19 +1420,12 @@ export class Conductor {
1643
1420
  // field's accepted formats and the PATCH would be rejected (review round
1644
1421
  // 4, Critical 1).
1645
1422
  const dispatchedAt = Math.floor(Date.now() / 1000);
1646
- // A resumed run already is `running`; one closed meanwhile (cancelled) is not relaunched.
1647
- if (resume && !(await this.stillRunning(run.runUuid)))
1648
- throw new RunClosed();
1649
1423
  const tools = chosen.agent.withoutConductorTools
1650
1424
  ? undefined
1651
1425
  : this.issueRunTools(run.runUuid, { worktreePath: ws.path, ticket: t });
1652
1426
  const plugins = await this.installPlugins(chosen, t, run, ws.path);
1653
1427
  Object.assign(env, plugins.env);
1654
- const command = resumeSession === undefined
1655
- ? chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args)
1656
- : chosen.agent.resumeCommand?.(resumeSession, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args);
1657
- if (command === undefined)
1658
- throw new ResumeRefused(`agent ${chosen.id} cannot resume a session in this configuration`);
1428
+ const command = chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args);
1659
1429
  // Read after launchCommand: a warning may depend on what this launch got.
1660
1430
  const warnings = chosen.agent.launchWarnings;
1661
1431
  if (warnings?.length) {
@@ -1715,20 +1485,6 @@ export class Conductor {
1715
1485
  });
1716
1486
  this.signalUi(ws.path);
1717
1487
  }
1718
- /** The run's newest agent session, or why it cannot be resumed. */
1719
- async resumableSession(chosen, worktree, runUuid) {
1720
- if (!chosen.agent.resumeCommand || !chosen.agent.sessionExists)
1721
- throw new ResumeRefused(`agent ${chosen.id} has no session resume`);
1722
- let newest;
1723
- for (const id of attemptFamily(runUuid)) {
1724
- if (!(await chosen.agent.sessionExists(worktree, id)))
1725
- break;
1726
- newest = id;
1727
- }
1728
- if (newest === undefined)
1729
- throw new ResumeRefused(`no agent session of the run in ${worktree}`);
1730
- return newest;
1731
- }
1732
1488
  /**
1733
1489
  * Stop what a failed dispatch started (BB-599): the worker if it was
1734
1490
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -41,7 +41,9 @@ export function mrChangesRows(v, recorded) {
41
41
  * shows. `HEAD`, not the remote branch: a merge deletes the remote branch.
42
42
  */
43
43
  export async function measureMrChanges(worktreePath, baseBranch) {
44
- await exec('git', ['fetch', 'origin', baseBranch], { cwd: worktreePath });
44
+ await exec('git', ['fetch', 'origin', '--', baseBranch], {
45
+ cwd: worktreePath,
46
+ });
45
47
  const out = await exec('git', ['diff', '--numstat', '-M', `origin/${baseBranch}...HEAD`], { cwd: worktreePath });
46
48
  return parseNumstat(out);
47
49
  }
@@ -0,0 +1,3 @@
1
+ import type { ConductorStartContext, HookListener, MachineRegistrationData } from '../plugins/executor.js';
2
+ /** Dispatch atomically: failures retain the validated baseline, never partial data. */
3
+ export declare function runStartHooks(listeners: readonly HookListener[], machine: MachineRegistrationData, conductor: Readonly<ConductorStartContext>, warn: (reason: string) => void): Promise<MachineRegistrationData>;
@@ -0,0 +1,58 @@
1
+ import { isValidMachineConnectionUrl } from '@bakers-build/core';
2
+ /** Dispatch atomically: failures retain the validated baseline, never partial data. */
3
+ export async function runStartHooks(listeners, machine, conductor, warn) {
4
+ const baseline = { ...machine };
5
+ if (baseline.connection_url !== undefined &&
6
+ baseline.connection_url !== null &&
7
+ !isValidMachineConnectionUrl(baseline.connection_url)) {
8
+ delete baseline.connection_url;
9
+ warn('invalid manual connection URL; start hooks skipped');
10
+ return baseline;
11
+ }
12
+ const shared = { ...baseline };
13
+ const context = Object.freeze({ ...conductor });
14
+ let closed = false;
15
+ let timer;
16
+ const validate = () => {
17
+ if (Reflect.ownKeys(shared).some((key) => !['host_key', 'machine_label', 'connection_url'].includes(String(key))) ||
18
+ shared.host_key !== baseline.host_key ||
19
+ (shared.machine_label !== undefined &&
20
+ (typeof shared.machine_label !== 'string' ||
21
+ !shared.machine_label.trim() ||
22
+ shared.machine_label.length > 255)) ||
23
+ (shared.connection_url !== undefined &&
24
+ shared.connection_url !== null &&
25
+ !isValidMachineConnectionUrl(shared.connection_url)) ||
26
+ (baseline.connection_url !== undefined &&
27
+ shared.connection_url !== baseline.connection_url))
28
+ throw new Error('invalid start hook data');
29
+ };
30
+ try {
31
+ return await Promise.race([
32
+ (async () => {
33
+ for (const listener of listeners) {
34
+ await listener.before_conductor_start?.(shared, context);
35
+ if (closed)
36
+ return baseline;
37
+ validate();
38
+ }
39
+ validate();
40
+ return { ...shared };
41
+ })(),
42
+ new Promise((_, reject) => {
43
+ timer = setTimeout(() => {
44
+ closed = true;
45
+ reject(new Error('deadline'));
46
+ }, 5000);
47
+ }),
48
+ ]);
49
+ }
50
+ catch {
51
+ warn('start hooks discarded after failure, invalid data or timeout');
52
+ return baseline;
53
+ }
54
+ finally {
55
+ closed = true;
56
+ clearTimeout(timer);
57
+ }
58
+ }
@@ -155,16 +155,6 @@ export interface BbAgent {
155
155
  launchCommand(prompt: string, run?: AgentRunIdentity, workspacePath?: string, tools?: {
156
156
  url: string;
157
157
  }, env?: Readonly<Record<string, string>>, args?: readonly string[]): string;
158
- /**
159
- * The command that continues session `sessionId` in `workspacePath`, with
160
- * the launch's own flags (see {@link launchCommand} for the other
161
- * arguments). The conductor uses it after a restart, for a run whose pane
162
- * is gone. Optional: an agent without it, or one returning undefined for
163
- * this configuration, has its lost runs failed and retried instead.
164
- */
165
- resumeCommand?(sessionId: string, workspacePath?: string, tools?: {
166
- url: string;
167
- }, env?: Readonly<Record<string, string>>, args?: readonly string[]): string | undefined;
168
158
  /**
169
159
  * Locate and read this agent's run transcript for a run that executed in
170
160
  * `worktreePath`. MUST return '' (never throw) when nothing is found.
@@ -188,11 +178,6 @@ export interface BbAgent {
188
178
  * `pi`) declares none, and the conductor always pins for it.
189
179
  */
190
180
  sessionExists?(worktreePath: string, sessionId: string): Promise<boolean>;
191
- /**
192
- * When the run's transcript was last written (epoch ms), from a stat alone;
193
- * undefined when it has none yet. Optional, like {@link permissionDenials}.
194
- */
195
- runLogModified?(worktreePath: string, run: AgentRunIdentity): Promise<number | undefined>;
196
181
  /**
197
182
  * Parse this agent's run transcript (as returned by {@link getRunLog}) into
198
183
  * a footprint of effort metrics (BB-132). The transcript format is
@@ -208,11 +193,4 @@ export interface BbAgent {
208
193
  * agent without it is never checked.
209
194
  */
210
195
  sandboxPreflight?(host?: SandboxHost): Promise<SandboxPreflight>;
211
- /**
212
- * The actions a permission rule denied in this run's transcript, each as
213
- * `Tool(argument)`, in order, but only when the run stopped on one: the agent
214
- * ended its turn after a denial with no call outstanding; [] otherwise. Never
215
- * throws. Optional: a run of an agent without it is never reported as blocked.
216
- */
217
- permissionDenials?(log: string): string[];
218
196
  }
@@ -57,6 +57,16 @@ export interface HookListenerContext {
57
57
  }
58
58
  /** A listener's callback for one slot. Awaited; a failure is logged, never fatal. */
59
59
  export type HookListenerFn = (ctx: HookListenerContext) => void | Promise<void>;
60
+ export interface MachineRegistrationData {
61
+ host_key?: string;
62
+ machine_label?: string;
63
+ connection_url?: string | null;
64
+ }
65
+ export interface ConductorStartContext {
66
+ id: string;
67
+ project: string;
68
+ variant: string;
69
+ }
60
70
  /**
61
71
  * One addon contribution to the conductor `hooks` accumulator (BB-599): an
62
72
  * object with an optional function per lifecycle slot. Listeners run in
@@ -65,6 +75,7 @@ export type HookListenerFn = (ctx: HookListenerContext) => void | Promise<void>;
65
75
  export type HookListener = {
66
76
  [K in HookName]?: HookListenerFn;
67
77
  } & {
78
+ before_conductor_start?: (machine: MachineRegistrationData, conductor: Readonly<ConductorStartContext>) => void | Promise<void>;
68
79
  /** Names the listener in conductor logs. */
69
80
  id?: string;
70
81
  };
@@ -160,11 +171,4 @@ export interface BbExecutor {
160
171
  * non-persistent executors.
161
172
  */
162
173
  cleanupRun(branch: string, runId: number): Promise<void>;
163
- /**
164
- * Whether ONE run's hosted terminal still lives. `false` only when the
165
- * executor knows none does (gone, or its process exited); throws when it
166
- * cannot tell, so the conductor leaves the run alone. Optional: without it
167
- * the conductor never checks a running run's terminal.
168
- */
169
- runAlive?(branch: string, runId: number): Promise<boolean>;
170
174
  }
@@ -15,6 +15,7 @@ export interface ConductorRegistration {
15
15
  host_key?: string;
16
16
  /** This machine's display label; names a newly created bb_machine. */
17
17
  machine_label?: string;
18
+ connection_url?: string | null;
18
19
  project: string;
19
20
  /** Empty = serve all claimable states in the project (BB-207). */
20
21
  states: string[];
@@ -104,8 +105,6 @@ export interface Ticket {
104
105
  }
105
106
  export interface ActiveRun {
106
107
  runUuid: string;
107
- /** Numeric run id (drupal_internal__id); names the run's terminal. */
108
- runId: number;
109
108
  ticketUuid: string;
110
109
  ticketIdentifier: string;
111
110
  branchName: string;
@@ -113,8 +112,6 @@ export interface ActiveRun {
113
112
  stateAtStart: string;
114
113
  /** Absolute path of the per-run git worktree, or '' when unset. */
115
114
  worktreePath: string;
116
- /** Id of the agent the run was dispatched to, '' / undefined when unset. */
117
- agent?: string;
118
115
  }
119
116
  export interface ConductorStatus {
120
117
  id: string;
@@ -397,13 +394,6 @@ export interface BbRemote {
397
394
  * failure is visible immediately and its cause is recorded.
398
395
  */
399
396
  markFailed(runUuid: string, errorLog: string): Promise<void>;
400
- /** Publishes one Markdown comment (type `comment`) on the ticket. */
401
- publishTicketComment(ticketUuid: string, body: string): Promise<void>;
402
- /**
403
- * Cancel a live run (`cancel`: claimed/running → cancelled). Finalisation
404
- * then captures its transcript and stops its agent, as for an operator's cancel.
405
- */
406
- cancelRun(runUuid: string): Promise<void>;
407
397
  /**
408
398
  * Runs this conductor owns that are state in (done, cancelled) but not yet
409
399
  * closed — the conductor's one-shot finalisation work list. Cancelled runs
@@ -22,6 +22,7 @@ export interface ConductorSettings {
22
22
  variant: string;
23
23
  /** This machine's display label (`machine.config.js` label). */
24
24
  machine_label?: string;
25
+ connection_url?: string | null;
25
26
  /** Project name (bb_project.name); resolved at registration. */
26
27
  project: string;
27
28
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.8.1-next.3",
3
+ "version": "0.8.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.8.1-next.3",
36
- "@bakers-build/message": "^0.8.1-next.3",
35
+ "@bakers-build/core": "^0.8.1-next.5",
36
+ "@bakers-build/message": "^0.8.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": "808f07a3ab9eb6ca6005894ba725623817e79c30",
42
+ "commit": "0a852637a4317a2ba18e831a2dcee4be2e67d060",
43
43
  "channel": "next"
44
44
  }
45
45
  }