pi-roundtable-coding 0.40.0 → 0.43.0

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.
@@ -1,175 +1,55 @@
1
- import {
2
- type ChannelKey,
3
- type ConversationModes,
4
- type HeldCall,
5
- type InterimTextMode,
6
- type Logger,
7
- type OwnerPrompts,
8
- SYSTEM_PRINCIPAL,
9
- type ThinkingLevel,
10
- type Tier,
11
- } from "pi-roundtable";
1
+ import type { ChannelKey, HeldCall } from "pi-roundtable";
12
2
  import {
13
3
  AgentError,
14
4
  approvalCard,
15
5
  approvalDetails,
16
- type DispatchThread,
17
- type DispatchThreads,
18
6
  InterimPoster,
19
- type PromptSlot,
20
7
  promptSlot,
21
- workTimeout,
22
- YOLO_CARDED_SHELL_CLASSES,
23
8
  } from "pi-roundtable/kit";
24
- import { checkCount, checkMaxWorkers, checkTime } from "./limits.ts";
9
+ import { codingReport } from "./coding-report.ts";
10
+ import { DeskModes } from "./desk-modes.ts";
25
11
  import type {
26
- Integration,
27
- RepoShelf,
28
- RepoState,
29
- WorkerTree,
30
- } from "./repo-shelf.ts";
12
+ CodingDeskOptions,
13
+ CodingJob,
14
+ CodingResult,
15
+ CodingStart,
16
+ HeldCallAnswer,
17
+ } from "./desk-types.ts";
18
+ import { checkCount, checkMaxWorkers } from "./limits.ts";
19
+ import { RepoGate } from "./repo-gate.ts";
20
+ import type { Integration, RepoState, WorkerTree } from "./repo-shelf.ts";
21
+ import {
22
+ type CancelResult,
23
+ type CodingTask,
24
+ cancelledText,
25
+ droppedText,
26
+ hostStopping,
27
+ interruptedText,
28
+ notMergedReason,
29
+ notStartedText,
30
+ stoppedOutsideText,
31
+ within,
32
+ } from "./task-control.ts";
31
33
  import { CodingWorkerFailure } from "./worker-failure.ts";
32
34
 
35
+ export { codingReport, integrationText } from "./coding-report.ts";
36
+ export type {
37
+ CodingAutonomy,
38
+ CodingDeskOptions,
39
+ CodingJob,
40
+ CodingLimits,
41
+ CodingModes,
42
+ CodingProgress,
43
+ CodingResult,
44
+ CodingSpeaker,
45
+ CodingStart,
46
+ CodingStarter,
47
+ CodingThreadText,
48
+ CodingWorker,
49
+ HeldCallAnswer,
50
+ } from "./desk-types.ts";
33
51
  export { checkLimit } from "./limits.ts";
34
52
 
35
- export type HeldCallAnswer = "approved" | "declined" | "held";
36
- /** Who spoke the turn that started a job, as yolo and long-running modes need to know. */
37
- export interface CodingSpeaker {
38
- id: string;
39
- principalId: string;
40
- name?: string;
41
- tier?: Tier;
42
- }
43
- /** The conversation whose turn started a job, whose modes the worker follows live. */
44
- export interface CodingStarter {
45
- channel: ChannelKey;
46
- speaker: CodingSpeaker;
47
- }
48
- export interface CodingJob {
49
- id: number;
50
- repo: string;
51
- task: string;
52
- channel: ChannelKey;
53
- /** The calling turn's channel, where a progress thread opens. */
54
- origin?: ChannelKey;
55
- /** The conversation that started it; its yolo and long-running modes apply while it works. */
56
- starter?: CodingStarter;
57
- /** Host-resolved names of the skills carried to this run. */
58
- skillNames?: string[];
59
- /** Progress thread, when the surface supports one. */
60
- thread?: DispatchThread;
61
- model: string;
62
- thinking: ThinkingLevel;
63
- skillFiles: string[];
64
- /** When it was asked for; a queued job starts later. */
65
- queuedAt?: Date;
66
- /** When its worker started. */
67
- startedAt: Date;
68
- startHead: string;
69
- /** The worker's own branch, in its own worktree, once it has started. */
70
- branch?: string;
71
- }
72
- /** A started or queued job, as `CodingDesk.start` answers. */
73
- export type CodingStart = CodingJob & {
74
- /** Its place in the queue, from 1, when every worker slot is taken; absent when it started. */
75
- queuePosition?: number;
76
- };
77
- /** What the worker writes and runs as it goes, for its thread's progress posts. */
78
- export interface CodingProgress {
79
- /** A finished message of the worker's session: its role, stop reason, and text. */
80
- messageEnd(message: {
81
- role: string;
82
- content?: unknown;
83
- stopReason?: string;
84
- }): void;
85
- /** A tool the worker started. */
86
- toolStart(name: string): void;
87
- }
88
- export interface CodingWorker {
89
- /** `progress`, when given, hears the session's messages and tools as the worker goes. */
90
- run(
91
- job: CodingJob & { dir: string },
92
- signal: AbortSignal,
93
- review: (call: HeldCall) => Promise<HeldCallAnswer>,
94
- progress?: CodingProgress,
95
- ): Promise<string>;
96
- }
97
- export interface CodingResult {
98
- job: CodingJob;
99
- outcome: { ok: true; report: string } | { ok: false; error: string };
100
- held: string[];
101
- /** Held calls the starter's yolo mode approved without a card. */
102
- autoApproved?: string[];
103
- state?: RepoState;
104
- commits: string[];
105
- /** How the worker's branch came back into the clone; absent when no worktree was made. */
106
- integration?: Integration;
107
- }
108
- /** The conversations' modes, read live for each held call and at each work-time limit. */
109
- export type CodingModes = Pick<ConversationModes, "peek"> &
110
- Partial<Pick<ConversationModes, "autoApproved">>;
111
- /**
112
- * The host's autonomy limits, as its `autonomy` config resolves them: what yolo may approve, and
113
- * how long a long-running run works in all.
114
- */
115
- export interface CodingAutonomy {
116
- yolo?: { allow?: readonly string[]; card?: readonly string[] };
117
- /** Default four hours; at most 2147483647. */
118
- longRunningMaxMs?: number;
119
- }
120
- export interface CodingThreadText {
121
- initial?(job: CodingJob): string;
122
- held?(entry: string, job: CodingJob): string;
123
- approvalTitle?(job: CodingJob): string;
124
- report?(result: CodingResult): string;
125
- }
126
- export interface CodingDeskOptions {
127
- shelf: Pick<
128
- RepoShelf,
129
- | "dirOf"
130
- | "state"
131
- | "addWorktree"
132
- | "integrate"
133
- | "treeState"
134
- | "treeCommits"
135
- >;
136
- worker: CodingWorker;
137
- prompts?(channel: ChannelKey): OwnerPrompts | undefined;
138
- /** When configured, approval cards stay in the job's thread; no thread means held. */
139
- threads?: Pick<DispatchThreads, "open">;
140
- threadText?: CodingThreadText;
141
- deliver(result: CodingResult): Promise<void>;
142
- logger: Logger;
143
- timeoutMs?: number;
144
- limits?: CodingLimits;
145
- /**
146
- * Whether the worker posts the text it writes before its report into its thread as it goes,
147
- * as the host's turns do; "on" by default. A thread whose host cannot edit its posts gets none.
148
- */
149
- interimText?: InterimTextMode;
150
- /** Length from which an intermediate text is posted as its own message; default 400. */
151
- interimPrimaryChars?: number;
152
- /** Workers running at once on the host, across repositories and channels; default 4. */
153
- maxWorkers?: number;
154
- /** Tasks waiting for a worker slot, first in first out; one more is refused. Default 16. */
155
- maxQueued?: number;
156
- /**
157
- * The conversations' modes: with them a worker follows the yolo and long-running modes of the
158
- * conversation that started it, read live, when an owner other than the host spoke that turn.
159
- */
160
- modes?: CodingModes;
161
- /** The host's autonomy limits for those modes; pass the same values its `autonomy` config sets. */
162
- autonomy?: CodingAutonomy;
163
- }
164
- /** What a coding report keeps of a long run; each is a count of characters or entries, or `Infinity` for no bound. */
165
- export interface CodingLimits {
166
- /** Longest worker report, and longest thread report; default 20,000 characters. */
167
- reportChars?: number;
168
- /** Held actions listed in the report, the rest counted; default 10. */
169
- heldEntries?: number;
170
- /** Longest held-action entry; default 1,000 characters. */
171
- heldChars?: number;
172
- }
173
53
  export const MAX_CODING_TASK_CHARS = 8_000;
174
54
  const MAX_REPORT_CHARS = 20_000;
175
55
  const MAX_HELD_ENTRIES = 10;
@@ -181,24 +61,23 @@ function bounded(text: string, max: number): string {
181
61
  : text;
182
62
  }
183
63
 
184
- const DEFAULT_TIMEOUT_MS = 3_600_000;
185
- /** The core's default long-running ceiling, four hours. */
186
- const DEFAULT_LONG_RUNNING_MS = 4 * 60 * 60_000;
187
- /** How often a run past its own limit looks again at the starter's long-running mode. */
188
- const LONG_RUNNING_STEP_MS = 60_000;
189
64
  const DEFAULT_MAX_WORKERS = 4;
190
65
  const DEFAULT_MAX_QUEUED = 16;
191
-
192
- /** The rule a class belongs to: the part before its first dot, or a rule's bare name. */
193
- function ruleOf(id: string): string {
194
- const dot = id.indexOf(".");
195
- return dot === -1 ? id : id.slice(0, dot);
196
- }
66
+ const DEFAULT_STOP_WAIT_MS = 15_000;
197
67
 
198
68
  interface Running {
199
69
  job: CodingJob;
200
70
  controller: AbortController;
201
71
  done?: Promise<void>;
72
+ /** Who cancelled it; its branch is then kept, not merged. */
73
+ cancelledBy?: string;
74
+ /** The host's shutdown told it to stop; its branch is then kept, not merged. */
75
+ interrupted?: boolean;
76
+ /** Resolves with its kept commits once the worker settles. */
77
+ settled?: Promise<string[]>;
78
+ settle?: (commits: string[]) => void;
79
+ /** Its worktree, once made. */
80
+ dir?: string;
202
81
  }
203
82
 
204
83
  /**
@@ -210,42 +89,28 @@ export class CodingDesk {
210
89
  readonly #options: CodingDeskOptions;
211
90
  #maxWorkers: number;
212
91
  readonly #maxQueued: number;
213
- readonly #longRunningMs: number;
214
- readonly #yoloApproves: (id: string) => boolean;
92
+ readonly #modes: DeskModes;
215
93
  /** Every run until its report is delivered, for idle(). */
216
94
  readonly #pending = new Set<Promise<void>>();
217
95
  readonly #running = new Map<number, Running>();
218
96
  readonly #queue: CodingJob[] = [];
219
- /** The last integration asked for in each repository, which the next waits for. */
220
- readonly #integrations = new Map<string, Promise<unknown>>();
221
- /** Repositories whose clone an integration is changing now. */
222
- readonly #integrating = new Set<string>();
223
- /** Reports and pushes in progress, by repository. */
224
- readonly #shipping = new Map<string, Promise<unknown>>();
97
+ readonly #gate: RepoGate;
98
+ /** The channels of reports being delivered, one entry each, until `deliver` settles. */
99
+ readonly #delivering: ChannelKey[] = [];
225
100
  #nextId = 1;
226
101
  #stopped = false;
102
+ /** The host's shutdown is waiting for work: nothing new starts. */
103
+ #draining = false;
227
104
  constructor(options: CodingDeskOptions) {
228
- checkTime("timeoutMs", options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
229
- const longRunning =
230
- options.autonomy?.longRunningMaxMs ?? DEFAULT_LONG_RUNNING_MS;
231
- checkTime("autonomy.longRunningMaxMs", longRunning);
105
+ this.#modes = new DeskModes(options);
232
106
  this.#maxWorkers = options.maxWorkers ?? DEFAULT_MAX_WORKERS;
233
107
  this.#maxQueued = options.maxQueued ?? DEFAULT_MAX_QUEUED;
234
108
  checkMaxWorkers(this.#maxWorkers);
235
109
  checkCount("maxQueued", this.#maxQueued, 0);
236
- this.#longRunningMs = longRunning;
237
- const allow = new Set(options.autonomy?.yolo?.allow ?? []);
238
- const card = new Set(options.autonomy?.yolo?.card ?? []);
239
- const carded = new Set<string>(YOLO_CARDED_SHELL_CLASSES);
240
- // The core's yolo rules: a carded class or rule never, an unclassed call only by its rule's name.
241
- this.#yoloApproves = (id) => {
242
- if (card.has(id) || card.has(ruleOf(id))) return false;
243
- if (!id.includes(".")) return allow.has(id);
244
- return !carded.has(id) || allow.has(id);
245
- };
246
110
  this.#options = options;
111
+ this.#gate = new RepoGate(options.shelf);
247
112
  }
248
- /** The channels of running workers, which a shutdown waits for; queued tasks are not among them. */
113
+ /** The channels of running workers. */
249
114
  runningChannels(): ChannelKey[] {
250
115
  return [...this.#running.values()].map(({ job }) => job.channel);
251
116
  }
@@ -253,15 +118,20 @@ export class CodingDesk {
253
118
  queuedChannels(): ChannelKey[] {
254
119
  return this.#queue.map((job) => job.channel);
255
120
  }
121
+ /**
122
+ * The channels of work a shutdown waits for: running tasks, and the reports of finished or
123
+ * dropped ones still being delivered, which a stop must not cut off. Queued tasks are not
124
+ * among them: `beginDrain` drops them.
125
+ */
126
+ busyChannels(): ChannelKey[] {
127
+ return [...this.runningChannels(), ...this.#delivering];
128
+ }
256
129
  /** Workers allowed at once, and how many run and wait now. */
257
130
  workers(): { max: number; running: number; queued: number } {
258
131
  const { size: running } = this.#running;
259
132
  return { max: this.#maxWorkers, running, queued: this.#queue.length };
260
133
  }
261
- /**
262
- * Changes how many workers run at once, 1 to 64. A higher limit starts queued tasks now, in
263
- * order; a lower one stops no running worker, and new tasks queue until fewer run.
264
- */
134
+ /** Sets the workers run at once, 1 to 64: a higher limit starts queued tasks now; a lower one stops none. */
265
135
  setMaxWorkers(max: number): void {
266
136
  checkMaxWorkers(max);
267
137
  this.#maxWorkers = max;
@@ -280,51 +150,122 @@ export class CodingDesk {
280
150
  }
281
151
  /** Refuses while a worker's branch is being merged into the clone; running workers do not count. */
282
152
  checkIdle(repo: string): void {
283
- if (this.#integrating.has(repo))
284
- throw new AgentError(
285
- `A coding worker's commits are being merged into ${repo}; try again in a moment.`,
286
- );
153
+ this.#gate.checkIdle(repo);
287
154
  }
288
155
  /** Whether a report or push is in progress for the repository. */
289
156
  shipping(repo: string): boolean {
290
- return this.#shipping.has(repo);
157
+ return this.#gate.shipping(repo);
291
158
  }
292
- /**
293
- * Runs a report or push of the repository, one at a time; refuses during an integration, and
294
- * an integration that comes due waits for it.
295
- */
296
- async ship<T>(repo: string, operation: () => Promise<T>): Promise<T> {
297
- this.checkIdle(repo);
298
- if (this.#shipping.has(repo))
299
- throw new AgentError(
300
- "A report or push is already in progress for this repository.",
301
- );
302
- const done = operation();
303
- this.#shipping.set(
304
- repo,
305
- done.catch(() => {}),
306
- );
307
- try {
308
- return await done;
309
- } finally {
310
- this.#shipping.delete(repo);
311
- }
159
+ /** Runs a report or push of the repository, one at a time; see `RepoGate.ship`. */
160
+ ship<T>(repo: string, operation: () => Promise<T>): Promise<T> {
161
+ return this.#gate.ship(repo, operation);
312
162
  }
313
163
  async idle(): Promise<void> {
314
164
  // A run that ends starts the next queued one before it settles, so look again.
315
165
  while (this.#pending.size) await Promise.all(this.#pending);
316
166
  }
317
- /** Stops the running workers and drops the queued tasks, telling each that it never ran. */
167
+ /** The running tasks, then the queued ones in queue order. */
168
+ tasks(): CodingTask[] {
169
+ return [
170
+ ...[...this.#running.values()].map(({ job }) => ({
171
+ job,
172
+ status: "running" as const,
173
+ })),
174
+ ...this.#queue.map((job, index) => ({
175
+ job,
176
+ status: "queued" as const,
177
+ queuePosition: index + 1,
178
+ })),
179
+ ];
180
+ }
181
+ /**
182
+ * Cancels a task: a queued one never starts; a running one is stopped as a timeout stops it,
183
+ * and its commits stay on its branch and worktree, not merged. Waits up to `waitMs` for the
184
+ * worker to settle; the report reaches `deliver` as for any run.
185
+ */
186
+ async cancel(id: number, by: string, waitMs = 30_000): Promise<CancelResult> {
187
+ const queued = this.#queue.findIndex((job) => job.id === id);
188
+ if (queued !== -1) {
189
+ const [job] = this.#queue.splice(queued, 1);
190
+ if (!job) throw new Error("unreachable");
191
+ this.#track(this.#drop(job, droppedText(by)));
192
+ return { status: "dropped", job };
193
+ }
194
+ const run = this.#running.get(id);
195
+ if (!run || run.cancelledBy !== undefined)
196
+ return {
197
+ status: "refused",
198
+ reason: `No running or queued coding task #${id}; it may have finished already.`,
199
+ };
200
+ run.cancelledBy = by;
201
+ run.controller.abort();
202
+ const commits = run.settled && (await within(run.settled, waitMs));
203
+ const { job } = run;
204
+ return {
205
+ status: "stopped",
206
+ job,
207
+ ...(job.branch ? { branch: job.branch } : {}),
208
+ ...(run.dir ? { dir: run.dir } : {}),
209
+ commits: commits ?? [],
210
+ settled: commits !== undefined,
211
+ };
212
+ }
213
+ /**
214
+ * The host's shutdown began waiting for work: no queued task starts and `start` refuses, so the
215
+ * drain waits for the running workers only. Each queued task gets a report at once that it did
216
+ * not start, with the time left to deliver it before the queue is sealed.
217
+ */
218
+ beginDrain(): void {
219
+ this.#draining = true;
220
+ for (const job of this.#queue.splice(0))
221
+ this.#track(this.#drop(job, notStartedText));
222
+ }
223
+ /**
224
+ * The host's drain ran out of time: tells each running worker to stop, as a cancel does, so its
225
+ * commits stay on its branch and its report names the worktree, and drops the queued tasks with
226
+ * a report that they never ran. Starts nothing more. Whether any task was told.
227
+ */
228
+ interrupt(): boolean {
229
+ this.#stopped = true;
230
+ const queued = this.#queue.splice(0);
231
+ for (const job of queued) this.#track(this.#drop(job));
232
+ let told = queued.length > 0;
233
+ for (const run of this.#running.values()) {
234
+ if (run.interrupted) continue;
235
+ run.interrupted = true;
236
+ run.controller.abort(hostStopping);
237
+ told = true;
238
+ }
239
+ return told;
240
+ }
241
+ /**
242
+ * Stops the running workers as a host shutdown does and drops the queued tasks, telling each
243
+ * that it never ran. Waits at most `stopWaitMs` for the reports: a report turn that is still
244
+ * going then is left behind, not waited for.
245
+ */
318
246
  async stop(): Promise<void> {
319
247
  this.#stopped = true;
320
248
  for (const job of this.#queue.splice(0)) this.#track(this.#drop(job));
321
- for (const run of this.#running.values()) run.controller.abort();
322
- await this.idle();
249
+ for (const run of this.#running.values()) {
250
+ run.interrupted = true;
251
+ run.controller.abort(hostStopping);
252
+ }
253
+ const waited = this.#options.stopWaitMs ?? DEFAULT_STOP_WAIT_MS;
254
+ const ended = await within(
255
+ this.idle().then(() => true),
256
+ waited,
257
+ );
258
+ if (!ended)
259
+ this.#options.logger.warn(
260
+ { waitedMs: waited },
261
+ "Coding reports still going out; not waiting for them.",
262
+ );
323
263
  }
324
264
  async start(
325
265
  request: Omit<CodingJob, "id" | "startedAt" | "startHead" | "thread">,
326
266
  ): Promise<CodingStart> {
327
267
  if (this.#stopped) throw new AgentError("The coding desk is stopped.");
268
+ if (this.#draining) throw new AgentError(notStartedText);
328
269
  const task = request.task.trim();
329
270
  if (!task) throw new AgentError("The task is required.");
330
271
  if (task.length > MAX_CODING_TASK_CHARS)
@@ -361,15 +302,21 @@ export class CodingDesk {
361
302
  #launch(job: CodingJob): void {
362
303
  job.startedAt = new Date();
363
304
  const run: Running = { job, controller: new AbortController() };
305
+ run.settled = new Promise((resolve) => {
306
+ run.settle = resolve;
307
+ });
364
308
  this.#running.set(job.id, run);
365
- run.done = this.#run(job, run.controller)
309
+ run.done = this.#run(job, run)
366
310
  .catch(() => {
367
311
  this.#options.logger.error(
368
312
  { job: job.id },
369
313
  "Coding report delivery failed.",
370
314
  );
371
315
  })
372
- .finally(() => this.#free(job));
316
+ .finally(() => {
317
+ run.settle?.([]);
318
+ this.#free(job);
319
+ });
373
320
  this.#track(run.done);
374
321
  }
375
322
  /** Frees the job's slot and starts the next queued tasks. */
@@ -380,6 +327,7 @@ export class CodingDesk {
380
327
  #fill(): void {
381
328
  while (
382
329
  !this.#stopped &&
330
+ !this.#draining &&
383
331
  this.#running.size < this.#maxWorkers &&
384
332
  this.#queue.length
385
333
  ) {
@@ -387,15 +335,14 @@ export class CodingDesk {
387
335
  if (next) this.#launch(next);
388
336
  }
389
337
  }
390
- async #drop(job: CodingJob): Promise<void> {
338
+ async #drop(
339
+ job: CodingJob,
340
+ error = "the host stopped before this queued task started; nothing ran, so start it again",
341
+ ): Promise<void> {
391
342
  try {
392
- await this.#options.deliver({
343
+ await this.#deliver({
393
344
  job,
394
- outcome: {
395
- ok: false,
396
- error:
397
- "the host stopped before this queued task started; nothing ran, so start it again",
398
- },
345
+ outcome: { ok: false, error },
399
346
  held: [],
400
347
  commits: [],
401
348
  });
@@ -406,96 +353,18 @@ export class CodingDesk {
406
353
  );
407
354
  }
408
355
  }
409
- /** Whether the starter's modes may act: only for an owner other than the host's own principal. */
410
- #modeOf(job: CodingJob): { yolo: boolean; longRunning: boolean } {
411
- const { modes } = this.#options;
412
- const speaker = job.starter?.speaker;
413
- if (
414
- !modes ||
415
- !job.starter ||
416
- speaker?.tier !== "owner" ||
417
- speaker.principalId === SYSTEM_PRINCIPAL
418
- )
419
- return { yolo: false, longRunning: false };
420
- const mode = modes.peek(job.starter.channel);
421
- return { yolo: mode.yolo === true, longRunning: mode.longRunning === true };
422
- }
423
- /** Whether the starter's yolo mode approves the call now, as it would in that conversation. */
424
- #yolo(job: CodingJob, call: HeldCall): boolean {
425
- if (!this.#modeOf(job).yolo || call.approverIds !== undefined) return false;
426
- const classes = call.holdClasses;
427
- if (!classes?.length || !classes.every(this.#yoloApproves)) return false;
428
- const { starter } = job;
429
- if (!starter) return false;
356
+ /** Delivers a report, which a shutdown waits for meanwhile. */
357
+ async #deliver(result: CodingResult): Promise<void> {
358
+ this.#delivering.push(result.job.channel);
430
359
  try {
431
- this.#options.modes?.autoApproved?.({
432
- channel: starter.channel,
433
- tool: call.tool,
434
- action: `coding #${job.id} in ${job.repo}: ${call.action}`,
435
- classes: [...classes],
436
- principalId: starter.speaker.principalId,
437
- at: new Date(),
438
- });
439
- } catch {
440
- this.#options.logger.warn(
441
- { job: job.id },
442
- "Recording a yolo approval failed.",
443
- );
444
- }
445
- return true;
446
- }
447
- /**
448
- * The worker's work-time budget: `timeoutMs`, then, while the starter's long-running mode is
449
- * on, further steps up to `autonomy.longRunningMaxMs` in all. Card waits never count.
450
- */
451
- #budget(
452
- job: CodingJob,
453
- slot: PromptSlot,
454
- expire: (workedMs: number) => void,
455
- ): () => void {
456
- const base = this.#options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
457
- let worked = 0;
458
- let cancel = () => {};
459
- const phase = (ms: number) => {
460
- cancel = workTimeout(ms, slot, () => {
461
- worked += ms;
462
- if (this.#modeOf(job).longRunning && worked < this.#longRunningMs)
463
- phase(Math.min(LONG_RUNNING_STEP_MS, this.#longRunningMs - worked));
464
- else expire(worked);
465
- });
466
- };
467
- phase(base);
468
- return () => cancel();
469
- }
470
- /** Integrations of one clone run one after another, and never during its report or push. */
471
- async #integrate(tree: WorkerTree): Promise<Integration> {
472
- const { repo } = tree;
473
- const previous = this.#integrations.get(repo) ?? Promise.resolve();
474
- const mine = previous
475
- .catch(() => {})
476
- .then(async () => {
477
- for (let ship = this.#shipping.get(repo); ship; ) {
478
- await ship;
479
- ship = this.#shipping.get(repo);
480
- }
481
- this.#integrating.add(repo);
482
- try {
483
- return await this.#options.shelf.integrate(tree);
484
- } finally {
485
- this.#integrating.delete(repo);
486
- }
487
- });
488
- this.#integrations.set(repo, mine);
489
- try {
490
- return await mine;
360
+ await this.#options.deliver(result);
491
361
  } finally {
492
- if (this.#integrations.get(repo) === mine)
493
- this.#integrations.delete(repo);
362
+ this.#delivering.splice(this.#delivering.indexOf(result.job.channel), 1);
494
363
  }
495
364
  }
496
- async #run(job: CodingJob, controller: AbortController): Promise<void> {
497
- const { shelf, worker, prompts, threads, threadText, deliver } =
498
- this.#options;
365
+ async #run(job: CodingJob, run: Running): Promise<void> {
366
+ const { controller } = run;
367
+ const { shelf, worker, prompts, threads, threadText } = this.#options;
499
368
  const slot = promptSlot();
500
369
  const held: string[] = [];
501
370
  const autoApproved: string[] = [];
@@ -508,12 +377,14 @@ export class CodingDesk {
508
377
  let cancel = () => {};
509
378
  let interim: InterimPoster | undefined;
510
379
  let timedOut: number | undefined;
380
+ let stoppedOutside = false;
511
381
  let tree: WorkerTree | undefined;
512
382
  let outcome: CodingResult["outcome"];
513
383
  try {
514
384
  tree = await shelf.addWorktree(job.repo, job.id);
515
385
  job.startHead = tree.base.slice(0, 12);
516
386
  job.branch = tree.branch;
387
+ run.dir = tree.dir;
517
388
  if (controller.signal.aborted)
518
389
  throw new AgentError("the worker was stopped");
519
390
  if (threads) {
@@ -550,13 +421,13 @@ export class CodingDesk {
550
421
  `Coding worker #${job.id}`,
551
422
  poster ? () => poster.flush() : undefined,
552
423
  );
553
- cancel = this.#budget(job, slot, (worked) => {
424
+ cancel = this.#modes.budget(job, slot, (worked) => {
554
425
  timedOut = worked;
555
426
  controller.abort();
556
427
  });
557
428
  const review = async (call: HeldCall): Promise<HeldCallAnswer> => {
558
429
  // The starter's yolo mode answers for a call it may approve, read at the time of the call.
559
- if (!controller.signal.aborted && this.#yolo(job, call)) {
430
+ if (!controller.signal.aborted && this.#modes.yolo(job, call)) {
560
431
  if (autoApproved.length < maxHeldEntries)
561
432
  autoApproved.push(
562
433
  bounded(
@@ -618,14 +489,20 @@ export class CodingDesk {
618
489
  "The worker failed; inspect the clone and worker configuration on the host.";
619
490
  if (error instanceof AgentError) message = error.message;
620
491
  if (error instanceof CodingWorkerFailure) {
492
+ if (error.category === "stopped" && !controller.signal.aborted)
493
+ stoppedOutside = true;
621
494
  this.#options.logger.warn(
622
495
  { job: job.id, category: error.category, exitCode: error.exitCode },
623
496
  "Coding worker failed.",
624
497
  );
625
498
  }
626
499
  if (controller.signal.aborted) message = "the worker was stopped";
500
+ if (stoppedOutside) message = stoppedOutsideText;
501
+ if (run.interrupted) message = interruptedText;
627
502
  if (timedOut !== undefined)
628
503
  message = `the worker ran out of time (${Math.round(timedOut / 60_000)} minutes)`;
504
+ if (run.cancelledBy !== undefined)
505
+ message = cancelledText(run.cancelledBy);
629
506
  outcome = { ok: false, error: message };
630
507
  } finally {
631
508
  cancel();
@@ -634,9 +511,20 @@ export class CodingDesk {
634
511
  await interim?.flush();
635
512
  }
636
513
  let integration: Integration | undefined;
637
- if (tree)
514
+ // An aborted worker's commits stay on its branch for the owner to inspect, merge or delete.
515
+ if (
516
+ tree &&
517
+ (controller.signal.aborted || run.interrupted || stoppedOutside)
518
+ )
519
+ integration = {
520
+ status: "refused",
521
+ branch: tree.branch,
522
+ dir: tree.dir,
523
+ reason: notMergedReason({ ...run, timedOut, stoppedOutside }),
524
+ };
525
+ else if (tree)
638
526
  try {
639
- integration = await this.#integrate(tree);
527
+ integration = await this.#gate.integrate(tree);
640
528
  } catch (error) {
641
529
  integration = {
642
530
  status: "refused",
@@ -693,51 +581,9 @@ export class CodingDesk {
693
581
  } catch {
694
582
  this.#options.logger.warn({ job: job.id }, "Coding thread close failed.");
695
583
  }
584
+ run.settle?.(commits);
696
585
  // The work is over: free the slot and the repository before the report turn, so that turn can ship it.
697
586
  this.#free(job);
698
- await deliver(result);
587
+ await this.#deliver(result);
699
588
  }
700
589
  }
701
-
702
- /** What became of the worker's branch, for the report. */
703
- export function integrationText(
704
- integration: Integration | undefined,
705
- branch: string | undefined,
706
- ): string | undefined {
707
- switch (integration?.status) {
708
- case "merged":
709
- return `Merged ${integration.branch}: rebased onto the clone's branch and fast-forwarded it.`;
710
- case "nothing":
711
- return `${branch ?? "The worker's branch"} added no commits; its worktree is removed.`;
712
- case "conflict":
713
- return `Rebasing ${integration.branch} onto the clone's branch conflicted in:\n${integration.files.join("\n") || "(files not listed)"}\nThe rebase was aborted and the clone is unchanged; the branch ${integration.branch} and its worktree ${integration.dir} are kept to resolve.`;
714
- case "refused":
715
- return `Not merged: ${integration.reason}\nThe branch ${integration.branch} and its worktree ${integration.dir} are kept.`;
716
- default:
717
- return undefined;
718
- }
719
- }
720
-
721
- export function codingReport(result: CodingResult, started: string): string {
722
- const { job, outcome, state, commits, held, autoApproved, integration } =
723
- result;
724
- const merge = integrationText(integration, job.branch);
725
- return [
726
- `## Coding task #${job.id}: ${job.repo}`,
727
- `Started: ${started}`,
728
- outcome.ok ? outcome.report : outcome.error,
729
- "### Held",
730
- held.length ? held.join("\n") : "None.",
731
- ...(autoApproved?.length
732
- ? ["### Approved by yolo mode", autoApproved.join("\n")]
733
- : []),
734
- "### Repository",
735
- [
736
- ...(merge ? [merge] : []),
737
- state
738
- ? `Branch ${state.branch}, HEAD ${state.head} (was ${job.startHead}).\nNew commits:\n${commits.join("\n") || "None."}\nUncommitted:\n${state.uncommitted.join("\n") || "None."}`
739
- : "Unreadable.",
740
- ].join("\n"),
741
- "Review the changes and checks, then use repo_change_report before repo_push.",
742
- ].join("\n\n");
743
- }