@bakers-build/conductor 0.8.1-next.1 → 0.8.1-next.2

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.
@@ -25,6 +25,9 @@ export const CONDUCTOR_ADDON_SLOTS = {
25
25
  '@bakers-build/addon-ports-cloudflare': [],
26
26
  '@bakers-build/addon-ports-cloudflare-quick': [],
27
27
  '@bakers-build/addon-ports-frp': [],
28
+ '@bakers-build/addon-forge': [],
29
+ '@bakers-build/addon-forge-github': [],
30
+ '@bakers-build/addon-forge-gitlab': [],
28
31
  '@bakers-build/addon-bakers-ui': [],
29
32
  '@bakers-build/addon-bakers-ui-artifacts': [],
30
33
  '@bakers-build/addon-agents': [],
@@ -39,6 +39,8 @@ 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?;
42
44
  /**
43
45
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
44
46
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -116,6 +118,25 @@ export declare class Conductor {
116
118
  * the heartbeat or the claims.
117
119
  */
118
120
  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;
119
140
  /**
120
141
  * One-shot finalisation: for each of this conductor's runs that is state in
121
142
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -262,13 +283,18 @@ export declare class Conductor {
262
283
  * one `plugins` entry. A failed install throws, failing the run start.
263
284
  */
264
285
  private installPlugins;
265
- /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
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
+ */
266
290
  private dispatch;
267
291
  /**
268
292
  * The part of a dispatch that can leave a sidecar or a worker behind
269
293
  * (BB-599): its caller unwinds it through `after_run` on any failure.
270
294
  */
271
295
  private launch;
296
+ /** The run's newest agent session, or why it cannot be resumed. */
297
+ private resumableSession;
272
298
  /**
273
299
  * Stop what a failed dispatch started (BB-599): the worker if it was
274
300
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -159,6 +159,30 @@ function recordAfterCreateOutcome(file, worktreePath, ok) {
159
159
  // best-effort: a later dispatch simply re-runs after_create.
160
160
  }
161
161
  }
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
+ }
162
186
  function renderPrompt(template, values) {
163
187
  return template
164
188
  .replaceAll('{identifier}', values.identifier)
@@ -199,6 +223,8 @@ export class Conductor {
199
223
  runHook;
200
224
  readMachine;
201
225
  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;
202
228
  /**
203
229
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
204
230
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -413,6 +439,7 @@ export class Conductor {
413
439
  }
414
440
  // A hung action blocks only its ticket's lane; make it visible.
415
441
  this.queue.warnOverdue(this.config.lease_seconds * 1000);
442
+ await this.step('lost', () => this.enqueueLostRuns());
416
443
  await this.step('finalize', () => this.enqueueFinalize());
417
444
  await this.step('reap', () => this.enqueueReap());
418
445
  await this.step('freeze', () => this.observeFreezes());
@@ -468,6 +495,122 @@ export class Conductor {
468
495
  : 'idle, nothing to claim');
469
496
  }
470
497
  }
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
+ }
471
614
  /**
472
615
  * One-shot finalisation: for each of this conductor's runs that is state in
473
616
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -1316,8 +1459,11 @@ export class Conductor {
1316
1459
  log();
1317
1460
  return { env: launch.env, args: launch.args };
1318
1461
  }
1319
- /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
1320
- async dispatch(run, at = {}) {
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) {
1321
1467
  const t = await this.remote.getTicket(run.ticketUuid);
1322
1468
  // Resolve the ticket alias and machine defaults, or the project selection hook.
1323
1469
  // Persist the package id below so finalize can choose its transcript parser.
@@ -1363,7 +1509,7 @@ export class Conductor {
1363
1509
  };
1364
1510
  const launch = { started: false };
1365
1511
  try {
1366
- await this.launch(run, t, chosen, ws, ctx, launch);
1512
+ await this.launch(run, t, chosen, ws, ctx, launch, resume);
1367
1513
  }
1368
1514
  catch (err) {
1369
1515
  await this.unwindDispatch(ctx, launch.started);
@@ -1374,8 +1520,11 @@ export class Conductor {
1374
1520
  * The part of a dispatch that can leave a sidecar or a worker behind
1375
1521
  * (BB-599): its caller unwinds it through `after_run` on any failure.
1376
1522
  */
1377
- async launch(run, t, chosen, ws, ctx, launch) {
1523
+ async launch(run, t, chosen, ws, ctx, launch, resume = false) {
1378
1524
  const env = ctx.env;
1525
+ const resumeSession = resume
1526
+ ? await this.resumableSession(chosen, ws.path, run.runUuid)
1527
+ : undefined;
1379
1528
  // Lifecycle hooks are conductor-owned + best-effort (BB-84): runHook never
1380
1529
  // throws, so neither call can abort dispatch or wedge a run in `claimed`.
1381
1530
  // `runSlot` runs the addon listeners first under the same rule (BB-599).
@@ -1494,12 +1643,19 @@ export class Conductor {
1494
1643
  // field's accepted formats and the PATCH would be rejected (review round
1495
1644
  // 4, Critical 1).
1496
1645
  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();
1497
1649
  const tools = chosen.agent.withoutConductorTools
1498
1650
  ? undefined
1499
1651
  : this.issueRunTools(run.runUuid, { worktreePath: ws.path, ticket: t });
1500
1652
  const plugins = await this.installPlugins(chosen, t, run, ws.path);
1501
1653
  Object.assign(env, plugins.env);
1502
- const command = chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args);
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`);
1503
1659
  // Read after launchCommand: a warning may depend on what this launch got.
1504
1660
  const warnings = chosen.agent.launchWarnings;
1505
1661
  if (warnings?.length) {
@@ -1559,6 +1715,20 @@ export class Conductor {
1559
1715
  });
1560
1716
  this.signalUi(ws.path);
1561
1717
  }
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
+ }
1562
1732
  /**
1563
1733
  * Stop what a failed dispatch started (BB-599): the worker if it was
1564
1734
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -155,6 +155,16 @@ 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;
158
168
  /**
159
169
  * Locate and read this agent's run transcript for a run that executed in
160
170
  * `worktreePath`. MUST return '' (never throw) when nothing is found.
@@ -160,4 +160,11 @@ export interface BbExecutor {
160
160
  * non-persistent executors.
161
161
  */
162
162
  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>;
163
170
  }
@@ -104,6 +104,8 @@ export interface Ticket {
104
104
  }
105
105
  export interface ActiveRun {
106
106
  runUuid: string;
107
+ /** Numeric run id (drupal_internal__id); names the run's terminal. */
108
+ runId: number;
107
109
  ticketUuid: string;
108
110
  ticketIdentifier: string;
109
111
  branchName: string;
@@ -395,6 +397,8 @@ export interface BbRemote {
395
397
  * failure is visible immediately and its cause is recorded.
396
398
  */
397
399
  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>;
398
402
  /**
399
403
  * Cancel a live run (`cancel`: claimed/running → cancelled). Finalisation
400
404
  * then captures its transcript and stops its agent, as for an operator's cancel.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.8.1-next.1",
3
+ "version": "0.8.1-next.2",
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.1",
36
- "@bakers-build/message": "^0.8.1-next.1",
35
+ "@bakers-build/core": "^0.8.1-next.2",
36
+ "@bakers-build/message": "^0.8.1-next.2",
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": "c4a887bee37bb2fed14bb9ba15ad0aacf0e26f7e",
42
+ "commit": "0177880667693d1c36c65ffced82d2f3a17cbf2a",
43
43
  "channel": "next"
44
44
  }
45
45
  }