pi-roundtable-coding 0.42.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.43.0] - 2026-11-09
6
+
7
+ ### Added
8
+
9
+ - `pi-roundtable-coding` exports `DEFAULT_TOOL_TEXT`, the shipped description and argument text of every repository tool, so a host sets `toolText` for only the wording that differs and sees what an upgrade changed. The `presentation` hooks `list`, `changeReport`, `taskStarted` and `taskQueued` now receive the package's own text as a last argument, so a host can append to it instead of replacing it.
10
+ - `pi-roundtable-drawing` takes a `toolText` option, the same for its five tools, and exports `DEFAULT_DRAWING_TOOL_TEXT`; unset text keeps the package wording, and a tool or argument the plugin does not have stops the start.
11
+
12
+ ### Fixed
13
+
14
+ - A deploy no longer cuts a coding worker short without a word. The shutdown drain (`drainSeconds`, now up to 14,400) waits for the desk's running workers and for reports still being delivered. A service can now tell the drain began (`Service.beginDrain()`): the coding desk then starts no queued task, reports each as "not started: host restarting, dispatch again after restart", and refuses `repo_task` with the same message. At the limit the drain calls the new `Service.abort()` before `stop()`, and the desk stops each worker with SIGTERM (the worker saves its tracked changes in a `wip:` commit, `stopGraceMs` of 5 seconds before SIGKILL), keeps its branch and worktree unmerged, and reports where they are.
15
+ - A coding worker that is cancelled or runs out of time is killed at once and its branch is never merged into the clone, even when its worktree is clean; the report names the kept branch and worktree. Only a host shutdown saves a `wip:` commit. `CodingDesk.stop()` stops workers the same way and waits at most `stopWaitMs` (15 seconds) for reports.
16
+ - New `QueuePort.finishing(task)` (absent on an older host): a queue task started inside it, and what it awaits, is admitted although the host is shutting down, until the drain ends. The coding plugin delivers every report through it, so the report of a worker that ends during the drain is no longer refused with "the host is shutting down". After the abort grace the host tells the turns still running in the queue to stop once more, so a report turn begun during the grace cannot run past the drain.
17
+ - A coding worker that gets SIGTERM from outside the desk (a `systemctl kill`, a cgroup-wide stop, a manual `kill`) still saves its `wip:` commit but now reports a `stopped` failure; the desk refuses to merge that run, keeps its branch and worktree, and says so in the report. A run that already timed out is reported as timed out even when `interrupt()` or `stop()` lands afterwards.
18
+
5
19
  ## [0.42.0] - 2026-11-08
6
20
 
7
21
  ### Added
package/README.md CHANGED
@@ -7,7 +7,7 @@ This package is a reference for the plugin guide's [Helpers for a Pi session of
7
7
  ## Requirements
8
8
 
9
9
  - Bun 1.4.4 or newer on a POSIX host (Linux or macOS).
10
- - pi-roundtable `>=0.42.0 <0.43.0` as a peer dependency; this package uses only its public main, kit and testing entries.
10
+ - pi-roundtable `>=0.43.0 <0.44.0` as a peer dependency; this package uses only its public main, kit and testing entries.
11
11
  - Pi `>=1.0.0 <2`, shared with the host's core dependencies.
12
12
  A core-only host still pinned to Pi 0.99.x must update its Pi dependencies before adding coding, so cross-package extension and session types resolve to one Pi version.
13
13
  - Git, plus GitHub CLI (`gh`) for the default clone implementation.
@@ -130,7 +130,7 @@ Cancelling frees the slot, so the next queued task starts; an unknown or finishe
130
130
  The Settings page `coding-workers` lists the running and queued tasks, each with a Cancel action that asks first; only an owner may use it.
131
131
  `desk.cancel(id, by)` does the same in code and answers a `CancelResult`: `dropped`, `stopped` (with `branch`, `dir`, `commits` and whether the worker `settled`), or `refused` with a reason; `desk.tasks()` lists the tasks.
132
132
 
133
- On host stop queued tasks are dropped and each gets a report saying it never ran; the shutdown drain waits only for running workers.
133
+ On host stop queued tasks are dropped and each gets a report saying it never ran. When the shutdown drain begins, the desk starts no queued task: each is reported at once as "not started: host restarting, dispatch again after restart", and `repo_task` is refused with that message until the restart. The drain waits for the running workers and for reports still being delivered; at the drain limit the desk stops each worker gently (SIGTERM, a `wip:` commit of its tracked changes, `stopGraceMs` before SIGKILL), keeps its branch and worktree unmerged, and reports where they are; untracked files are not committed and are listed under Uncommitted. Only a host shutdown saves a `wip:` commit: a cancelled or timed-out worker is killed at once, and its branch is likewise kept, never merged. Reports go out through the host queue's `finishing` lane, so they get through while the host is stopping. `desk.stop()` waits at most `stopWaitMs` (15 seconds by default) for workers and reports, so a report turn still running then does not hold up the shutdown.
134
134
  The worker's report includes its final answer, declined or unanswered actions, calls approved by yolo mode, what became of its branch, branch, HEAD, new commits and uncommitted files.
135
135
  Failures and timeouts also report the final Git state when it can be read.
136
136
  By default reports are sent to the caller's surface; `onResult(result)` can instead enqueue a background conversation turn through your host integration.
@@ -184,8 +184,8 @@ A worker failure carries its exit category and numeric code; git and gh stderr a
184
184
  Card expiration is determined by the host's surface implementation, not this package.
185
185
 
186
186
  The worker runs in a fresh Bun child process with an unsaved Pi session and uses the public `runWorkerTask` helper.
187
- Timeout and shutdown kill its POSIX process group and wait for exit; normal completion also removes shell descendants left in that group.
188
- The service advertises running jobs through `busy()` so the host can drain them before shutdown; queued tasks are not among them.
187
+ A timeout or cancel kills its POSIX process group; a host shutdown sends SIGTERM first, then `stopGraceMs` (5 seconds) before SIGKILL; both wait for exit; normal completion also removes shell descendants left in that group.
188
+ The service advertises running jobs and unsent reports through `busy()` so the host can drain them before shutdown, stops queued tasks from starting through `beginDrain()`, and stops running workers through `abort()` at the drain limit.
189
189
  `CodingDesk.busy()` lists running and queued jobs, marking each queued one with its position, and `queuedChannels()` names the channels of queued tasks.
190
190
  Jobs are in memory; they do not resume after a crash.
191
191
  The injectable `worker` runner must observe aborts and settle its run; this is a trusted test/integration seam.
@@ -225,8 +225,8 @@ The `CODING` service exposes `shelf: RepoShelf` and `desk: CodingDesk` for trust
225
225
  | `adoptClones` | `[]` | Startup `{ from, repo }` moves of standalone clones; existing shelf destinations are never replaced. |
226
226
  | `resolveRun` | configured model/thinking, caller channel | Per-caller model, thinking, report channel and optional thread origin. |
227
227
  | `postChangeReport` | caller surface reply | Post the record using the calling identity and channel. |
228
- | `presentation` | English package text | Separate change-report post/result text, task-start/omitted-skill wording, queued-task wording (`taskQueued(job, position, skipped)`), and the `repo_list` result (`list(repos, { shelfDir, fetched })`). |
229
- | `toolText` | package wording | Trusted description and argument descriptions for each repository tool, as `{ repo_task: { description, parameters: { task: "…" } } }`; it never changes a tool's arguments or approval rules. |
228
+ | `presentation` | English package text | Separate change-report post/result text, task-start/omitted-skill wording, queued-task wording (`taskQueued(job, position, skipped, defaultText)`), and the `repo_list` result (`list(repos, { shelfDir, fetched }, defaultText)`). Each hook is also given the package's own text (`taskStarted(job, skipped, defaultText)`, `changeReport(report, direct, { post, result })`), so a host can append to it, such as the clause that `repo_task_cancel` cancels the task, instead of copying it. |
229
+ | `toolText` | package wording | Trusted description and argument descriptions for each repository tool, as `{ repo_task: { description, parameters: { task: "…" } } }`; it never changes a tool's arguments or approval rules. A host words only what differs: `DEFAULT_TOOL_TEXT`, exported by the package, holds the shipped wording of every tool, to compose on (`{ ...DEFAULT_TOOL_TEXT.repo_task, description: \`${DEFAULT_TOOL_TEXT.repo_task.description} …\` }`) or to compare against after an upgrade. Unset text follows the package. |
230
230
  | `threads` | none | Public `DispatchThreads`-compatible progress and approval thread port. |
231
231
  | `threadText` | English package text | Thread introduction, held-action notice, approval title and final report. |
232
232
  | `interimText` | `"on"` | `"off"` keeps the worker's progress out of its thread; pass the host config's `interimText` to follow it. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable-coding",
3
- "version": "0.42.0",
3
+ "version": "0.43.0",
4
4
  "description": "Repository shelves and owner-approved Pi coding workers for pi-roundtable",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,13 +38,13 @@
38
38
  "typebox": "1.3.37"
39
39
  },
40
40
  "peerDependencies": {
41
- "pi-roundtable": ">=0.42.0 <0.43.0"
41
+ "pi-roundtable": ">=0.43.0 <0.44.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@earendil-works/pi-ai": ">=1.0.0 <2",
45
45
  "@biomejs/biome": "2.5.15",
46
46
  "@types/bun": "1.4.3",
47
- "pi-roundtable": "0.42.0",
47
+ "pi-roundtable": "0.43.0",
48
48
  "typescript": "7.0.2"
49
49
  }
50
50
  }
@@ -1,20 +1,13 @@
1
- import {
2
- type ChannelKey,
3
- type HeldCall,
4
- SYSTEM_PRINCIPAL,
5
- } from "pi-roundtable";
1
+ import type { ChannelKey, HeldCall } from "pi-roundtable";
6
2
  import {
7
3
  AgentError,
8
4
  approvalCard,
9
5
  approvalDetails,
10
6
  InterimPoster,
11
- type PromptSlot,
12
7
  promptSlot,
13
- workTimeout,
14
- YOLO_CARDED_SHELL_CLASSES,
15
- YOLO_NEVER_CLASS,
16
8
  } from "pi-roundtable/kit";
17
9
  import { codingReport } from "./coding-report.ts";
10
+ import { DeskModes } from "./desk-modes.ts";
18
11
  import type {
19
12
  CodingDeskOptions,
20
13
  CodingJob,
@@ -22,13 +15,19 @@ import type {
22
15
  CodingStart,
23
16
  HeldCallAnswer,
24
17
  } from "./desk-types.ts";
25
- import { checkCount, checkMaxWorkers, checkTime } from "./limits.ts";
18
+ import { checkCount, checkMaxWorkers } from "./limits.ts";
19
+ import { RepoGate } from "./repo-gate.ts";
26
20
  import type { Integration, RepoState, WorkerTree } from "./repo-shelf.ts";
27
21
  import {
28
22
  type CancelResult,
29
23
  type CodingTask,
30
24
  cancelledText,
31
25
  droppedText,
26
+ hostStopping,
27
+ interruptedText,
28
+ notMergedReason,
29
+ notStartedText,
30
+ stoppedOutsideText,
32
31
  within,
33
32
  } from "./task-control.ts";
34
33
  import { CodingWorkerFailure } from "./worker-failure.ts";
@@ -62,19 +61,9 @@ function bounded(text: string, max: number): string {
62
61
  : text;
63
62
  }
64
63
 
65
- const DEFAULT_TIMEOUT_MS = 3_600_000;
66
- /** The core's default long-running ceiling, four hours. */
67
- const DEFAULT_LONG_RUNNING_MS = 4 * 60 * 60_000;
68
- /** How often a run past its own limit looks again at the starter's long-running mode. */
69
- const LONG_RUNNING_STEP_MS = 60_000;
70
64
  const DEFAULT_MAX_WORKERS = 4;
71
65
  const DEFAULT_MAX_QUEUED = 16;
72
-
73
- /** The rule a class belongs to: the part before its first dot, or a rule's bare name. */
74
- function ruleOf(id: string): string {
75
- const dot = id.indexOf(".");
76
- return dot === -1 ? id : id.slice(0, dot);
77
- }
66
+ const DEFAULT_STOP_WAIT_MS = 15_000;
78
67
 
79
68
  interface Running {
80
69
  job: CodingJob;
@@ -82,6 +71,8 @@ interface Running {
82
71
  done?: Promise<void>;
83
72
  /** Who cancelled it; its branch is then kept, not merged. */
84
73
  cancelledBy?: string;
74
+ /** The host's shutdown told it to stop; its branch is then kept, not merged. */
75
+ interrupted?: boolean;
85
76
  /** Resolves with its kept commits once the worker settles. */
86
77
  settled?: Promise<string[]>;
87
78
  settle?: (commits: string[]) => void;
@@ -98,43 +89,28 @@ export class CodingDesk {
98
89
  readonly #options: CodingDeskOptions;
99
90
  #maxWorkers: number;
100
91
  readonly #maxQueued: number;
101
- readonly #longRunningMs: number;
102
- readonly #yoloApproves: (id: string) => boolean;
92
+ readonly #modes: DeskModes;
103
93
  /** Every run until its report is delivered, for idle(). */
104
94
  readonly #pending = new Set<Promise<void>>();
105
95
  readonly #running = new Map<number, Running>();
106
96
  readonly #queue: CodingJob[] = [];
107
- /** The last integration asked for in each repository, which the next waits for. */
108
- readonly #integrations = new Map<string, Promise<unknown>>();
109
- /** Repositories whose clone an integration is changing now. */
110
- readonly #integrating = new Set<string>();
111
- /** Reports and pushes in progress, by repository. */
112
- 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[] = [];
113
100
  #nextId = 1;
114
101
  #stopped = false;
102
+ /** The host's shutdown is waiting for work: nothing new starts. */
103
+ #draining = false;
115
104
  constructor(options: CodingDeskOptions) {
116
- checkTime("timeoutMs", options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
117
- const longRunning =
118
- options.autonomy?.longRunningMaxMs ?? DEFAULT_LONG_RUNNING_MS;
119
- checkTime("autonomy.longRunningMaxMs", longRunning);
105
+ this.#modes = new DeskModes(options);
120
106
  this.#maxWorkers = options.maxWorkers ?? DEFAULT_MAX_WORKERS;
121
107
  this.#maxQueued = options.maxQueued ?? DEFAULT_MAX_QUEUED;
122
108
  checkMaxWorkers(this.#maxWorkers);
123
109
  checkCount("maxQueued", this.#maxQueued, 0);
124
- this.#longRunningMs = longRunning;
125
- const allow = new Set(options.autonomy?.yolo?.allow ?? []);
126
- const card = new Set(options.autonomy?.yolo?.card ?? []);
127
- const carded = new Set<string>(YOLO_CARDED_SHELL_CLASSES);
128
- // The core's yolo rules: a carded class or rule never, an unclassed call only by its rule's name.
129
- this.#yoloApproves = (id) => {
130
- if (id.endsWith(`.${YOLO_NEVER_CLASS}`)) return false;
131
- if (card.has(id) || card.has(ruleOf(id))) return false;
132
- if (!id.includes(".")) return allow.has(id);
133
- return !carded.has(id) || allow.has(id);
134
- };
135
110
  this.#options = options;
111
+ this.#gate = new RepoGate(options.shelf);
136
112
  }
137
- /** The channels of running workers, which a shutdown waits for; queued tasks are not among them. */
113
+ /** The channels of running workers. */
138
114
  runningChannels(): ChannelKey[] {
139
115
  return [...this.#running.values()].map(({ job }) => job.channel);
140
116
  }
@@ -142,6 +118,14 @@ export class CodingDesk {
142
118
  queuedChannels(): ChannelKey[] {
143
119
  return this.#queue.map((job) => job.channel);
144
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
+ }
145
129
  /** Workers allowed at once, and how many run and wait now. */
146
130
  workers(): { max: number; running: number; queued: number } {
147
131
  const { size: running } = this.#running;
@@ -166,35 +150,15 @@ export class CodingDesk {
166
150
  }
167
151
  /** Refuses while a worker's branch is being merged into the clone; running workers do not count. */
168
152
  checkIdle(repo: string): void {
169
- if (this.#integrating.has(repo))
170
- throw new AgentError(
171
- `A coding worker's commits are being merged into ${repo}; try again in a moment.`,
172
- );
153
+ this.#gate.checkIdle(repo);
173
154
  }
174
155
  /** Whether a report or push is in progress for the repository. */
175
156
  shipping(repo: string): boolean {
176
- return this.#shipping.has(repo);
157
+ return this.#gate.shipping(repo);
177
158
  }
178
- /**
179
- * Runs a report or push of the repository, one at a time; refuses during an integration, and
180
- * an integration that comes due waits for it.
181
- */
182
- async ship<T>(repo: string, operation: () => Promise<T>): Promise<T> {
183
- this.checkIdle(repo);
184
- if (this.#shipping.has(repo))
185
- throw new AgentError(
186
- "A report or push is already in progress for this repository.",
187
- );
188
- const done = operation();
189
- this.#shipping.set(
190
- repo,
191
- done.catch(() => {}),
192
- );
193
- try {
194
- return await done;
195
- } finally {
196
- this.#shipping.delete(repo);
197
- }
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);
198
162
  }
199
163
  async idle(): Promise<void> {
200
164
  // A run that ends starts the next queued one before it settles, so look again.
@@ -246,17 +210,62 @@ export class CodingDesk {
246
210
  settled: commits !== undefined,
247
211
  };
248
212
  }
249
- /** Stops the running workers and drops the queued tasks, telling each that it never ran. */
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
+ */
250
246
  async stop(): Promise<void> {
251
247
  this.#stopped = true;
252
248
  for (const job of this.#queue.splice(0)) this.#track(this.#drop(job));
253
- for (const run of this.#running.values()) run.controller.abort();
254
- 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
+ );
255
263
  }
256
264
  async start(
257
265
  request: Omit<CodingJob, "id" | "startedAt" | "startHead" | "thread">,
258
266
  ): Promise<CodingStart> {
259
267
  if (this.#stopped) throw new AgentError("The coding desk is stopped.");
268
+ if (this.#draining) throw new AgentError(notStartedText);
260
269
  const task = request.task.trim();
261
270
  if (!task) throw new AgentError("The task is required.");
262
271
  if (task.length > MAX_CODING_TASK_CHARS)
@@ -318,6 +327,7 @@ export class CodingDesk {
318
327
  #fill(): void {
319
328
  while (
320
329
  !this.#stopped &&
330
+ !this.#draining &&
321
331
  this.#running.size < this.#maxWorkers &&
322
332
  this.#queue.length
323
333
  ) {
@@ -330,7 +340,7 @@ export class CodingDesk {
330
340
  error = "the host stopped before this queued task started; nothing ran, so start it again",
331
341
  ): Promise<void> {
332
342
  try {
333
- await this.#options.deliver({
343
+ await this.#deliver({
334
344
  job,
335
345
  outcome: { ok: false, error },
336
346
  held: [],
@@ -343,97 +353,18 @@ export class CodingDesk {
343
353
  );
344
354
  }
345
355
  }
346
- /** Whether the starter's modes may act: only for an owner other than the host's own principal. */
347
- #modeOf(job: CodingJob): { yolo: boolean; longRunning: boolean } {
348
- const { modes } = this.#options;
349
- const speaker = job.starter?.speaker;
350
- if (
351
- !modes ||
352
- !job.starter ||
353
- speaker?.tier !== "owner" ||
354
- speaker.principalId === SYSTEM_PRINCIPAL
355
- )
356
- return { yolo: false, longRunning: false };
357
- const mode = modes.peek(job.starter.channel);
358
- return { yolo: mode.yolo === true, longRunning: mode.longRunning === true };
359
- }
360
- /** Whether the starter's yolo mode approves the call now, as it would in that conversation. */
361
- #yolo(job: CodingJob, call: HeldCall): boolean {
362
- if (!this.#modeOf(job).yolo || call.approverIds !== undefined) return false;
363
- const classes = call.holdClasses;
364
- if (!classes?.length || !classes.every(this.#yoloApproves)) return false;
365
- const { starter } = job;
366
- 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);
367
359
  try {
368
- this.#options.modes?.autoApproved?.({
369
- channel: starter.channel,
370
- tool: call.tool,
371
- action: `coding #${job.id} in ${job.repo}: ${call.action}`,
372
- classes: [...classes],
373
- principalId: starter.speaker.principalId,
374
- at: new Date(),
375
- });
376
- } catch {
377
- this.#options.logger.warn(
378
- { job: job.id },
379
- "Recording a yolo approval failed.",
380
- );
381
- }
382
- return true;
383
- }
384
- /**
385
- * The worker's work-time budget: `timeoutMs`, then, while the starter's long-running mode is
386
- * on, further steps up to `autonomy.longRunningMaxMs` in all. Card waits never count.
387
- */
388
- #budget(
389
- job: CodingJob,
390
- slot: PromptSlot,
391
- expire: (workedMs: number) => void,
392
- ): () => void {
393
- const base = this.#options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
394
- let worked = 0;
395
- let cancel = () => {};
396
- const phase = (ms: number) => {
397
- cancel = workTimeout(ms, slot, () => {
398
- worked += ms;
399
- if (this.#modeOf(job).longRunning && worked < this.#longRunningMs)
400
- phase(Math.min(LONG_RUNNING_STEP_MS, this.#longRunningMs - worked));
401
- else expire(worked);
402
- });
403
- };
404
- phase(base);
405
- return () => cancel();
406
- }
407
- /** Integrations of one clone run one after another, and never during its report or push. */
408
- async #integrate(tree: WorkerTree): Promise<Integration> {
409
- const { repo } = tree;
410
- const previous = this.#integrations.get(repo) ?? Promise.resolve();
411
- const mine = previous
412
- .catch(() => {})
413
- .then(async () => {
414
- for (let ship = this.#shipping.get(repo); ship; ) {
415
- await ship;
416
- ship = this.#shipping.get(repo);
417
- }
418
- this.#integrating.add(repo);
419
- try {
420
- return await this.#options.shelf.integrate(tree);
421
- } finally {
422
- this.#integrating.delete(repo);
423
- }
424
- });
425
- this.#integrations.set(repo, mine);
426
- try {
427
- return await mine;
360
+ await this.#options.deliver(result);
428
361
  } finally {
429
- if (this.#integrations.get(repo) === mine)
430
- this.#integrations.delete(repo);
362
+ this.#delivering.splice(this.#delivering.indexOf(result.job.channel), 1);
431
363
  }
432
364
  }
433
365
  async #run(job: CodingJob, run: Running): Promise<void> {
434
366
  const { controller } = run;
435
- const { shelf, worker, prompts, threads, threadText, deliver } =
436
- this.#options;
367
+ const { shelf, worker, prompts, threads, threadText } = this.#options;
437
368
  const slot = promptSlot();
438
369
  const held: string[] = [];
439
370
  const autoApproved: string[] = [];
@@ -446,6 +377,7 @@ export class CodingDesk {
446
377
  let cancel = () => {};
447
378
  let interim: InterimPoster | undefined;
448
379
  let timedOut: number | undefined;
380
+ let stoppedOutside = false;
449
381
  let tree: WorkerTree | undefined;
450
382
  let outcome: CodingResult["outcome"];
451
383
  try {
@@ -489,13 +421,13 @@ export class CodingDesk {
489
421
  `Coding worker #${job.id}`,
490
422
  poster ? () => poster.flush() : undefined,
491
423
  );
492
- cancel = this.#budget(job, slot, (worked) => {
424
+ cancel = this.#modes.budget(job, slot, (worked) => {
493
425
  timedOut = worked;
494
426
  controller.abort();
495
427
  });
496
428
  const review = async (call: HeldCall): Promise<HeldCallAnswer> => {
497
429
  // The starter's yolo mode answers for a call it may approve, read at the time of the call.
498
- if (!controller.signal.aborted && this.#yolo(job, call)) {
430
+ if (!controller.signal.aborted && this.#modes.yolo(job, call)) {
499
431
  if (autoApproved.length < maxHeldEntries)
500
432
  autoApproved.push(
501
433
  bounded(
@@ -557,12 +489,16 @@ export class CodingDesk {
557
489
  "The worker failed; inspect the clone and worker configuration on the host.";
558
490
  if (error instanceof AgentError) message = error.message;
559
491
  if (error instanceof CodingWorkerFailure) {
492
+ if (error.category === "stopped" && !controller.signal.aborted)
493
+ stoppedOutside = true;
560
494
  this.#options.logger.warn(
561
495
  { job: job.id, category: error.category, exitCode: error.exitCode },
562
496
  "Coding worker failed.",
563
497
  );
564
498
  }
565
499
  if (controller.signal.aborted) message = "the worker was stopped";
500
+ if (stoppedOutside) message = stoppedOutsideText;
501
+ if (run.interrupted) message = interruptedText;
566
502
  if (timedOut !== undefined)
567
503
  message = `the worker ran out of time (${Math.round(timedOut / 60_000)} minutes)`;
568
504
  if (run.cancelledBy !== undefined)
@@ -575,17 +511,20 @@ export class CodingDesk {
575
511
  await interim?.flush();
576
512
  }
577
513
  let integration: Integration | undefined;
578
- // A cancelled worker's commits stay on its branch for the owner to inspect, merge or delete.
579
- if (tree && run.cancelledBy !== undefined)
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
+ )
580
519
  integration = {
581
520
  status: "refused",
582
521
  branch: tree.branch,
583
522
  dir: tree.dir,
584
- reason: `the task was cancelled by ${run.cancelledBy}`,
523
+ reason: notMergedReason({ ...run, timedOut, stoppedOutside }),
585
524
  };
586
525
  else if (tree)
587
526
  try {
588
- integration = await this.#integrate(tree);
527
+ integration = await this.#gate.integrate(tree);
589
528
  } catch (error) {
590
529
  integration = {
591
530
  status: "refused",
@@ -645,6 +584,6 @@ export class CodingDesk {
645
584
  run.settle?.(commits);
646
585
  // The work is over: free the slot and the repository before the report turn, so that turn can ship it.
647
586
  this.#free(job);
648
- await deliver(result);
587
+ await this.#deliver(result);
649
588
  }
650
589
  }
@@ -44,27 +44,44 @@ export interface CodingToolText {
44
44
  parameters?: Record<string, string>;
45
45
  }
46
46
  export interface CodingPresentation {
47
- /** The repo_list result; unset: the managed clones as JSON. */
47
+ /**
48
+ * The repo_list result; unset: the managed clones as JSON. `defaultText` is that default, so a
49
+ * hook can append to it.
50
+ */
48
51
  list?(
49
52
  repos: (RepoSummary & { skills: string[] })[],
50
53
  context: { shelfDir: string; fetched: boolean },
54
+ defaultText: string,
51
55
  ): string;
52
- /** Separate the owner's posted record from the model's shipping instructions. */
56
+ /**
57
+ * Separate the owner's posted record from the model's shipping instructions. `defaults` is the
58
+ * package's own pair, so a hook can append to either.
59
+ */
53
60
  changeReport?(
54
61
  report: ChangeReport,
55
62
  direct: boolean,
63
+ defaults: { post: string; result: string },
56
64
  ): { post: string; result: string };
57
- taskStarted?(job: CodingJob, skippedSkills: string[]): string;
58
- /** The repo_task result for a task waiting for a worker slot, at `position` (from 1) in the queue. */
65
+ /** The repo_task result for a started task; `defaultText` is the package's, which names `repo_task_cancel`. */
66
+ taskStarted?(
67
+ job: CodingJob,
68
+ skippedSkills: string[],
69
+ defaultText: string,
70
+ ): string;
59
71
  /**
60
72
  * Wording of the Settings page, keyed by its English text, such as
61
73
  * `{ "Coding workers": "..." }`; it wins over the built-in zh-TW wording, key by key.
62
74
  */
63
75
  messages?: Readonly<Record<string, string>>;
76
+ /**
77
+ * The repo_task result for a task waiting for a worker slot, at `position` (from 1) in the
78
+ * queue; `defaultText` is the package's.
79
+ */
64
80
  taskQueued?(
65
81
  job: CodingJob,
66
82
  position: number,
67
83
  skippedSkills: string[],
84
+ defaultText: string,
68
85
  ): string;
69
86
  }
70
87
  export interface CodingOptions {
@@ -30,10 +30,12 @@ import {
30
30
  memorySettings,
31
31
  registerSettingsPage,
32
32
  } from "./coding-settings.ts";
33
+ import type { CodingResult } from "./desk-types.ts";
33
34
  import { checkCount, checkMaxWorkers } from "./limits.ts";
34
35
  import { PiCodingWorker } from "./pi-coding-worker.ts";
35
36
  import { RepoShelf, reportPost } from "./repo-shelf.ts";
36
37
  import { taskTools } from "./task-tools.ts";
38
+ import { DEFAULT_TOOL_TEXT } from "./tool-text.ts";
37
39
  import { workerHolds } from "./worker-holds.ts";
38
40
 
39
41
  export type {
@@ -126,6 +128,18 @@ export function coding(options: CodingOptions) {
126
128
  diagnosticChars: options.diagnosticChars,
127
129
  holds: workerHolds(options.holds, () => context.sessions().holds),
128
130
  });
131
+ const deliverReport =
132
+ options.onResult ??
133
+ (async (result: CodingResult) => {
134
+ await context.surfaces.sendReply(result.job.channel, {
135
+ chunks: [
136
+ codingReport(
137
+ result,
138
+ zonedStamp(result.job.startedAt, context.env.timeZone),
139
+ ),
140
+ ],
141
+ });
142
+ });
129
143
  const desk = new CodingDesk({
130
144
  shelf,
131
145
  worker,
@@ -147,18 +161,13 @@ export function coding(options: CodingOptions) {
147
161
  ? { interimPrimaryChars: options.interimPrimaryChars }
148
162
  : {}),
149
163
  prompts: (channel) => context.surfaces.prompts(channel),
150
- deliver:
151
- options.onResult ??
152
- (async (result) => {
153
- await context.surfaces.sendReply(result.job.channel, {
154
- chunks: [
155
- codingReport(
156
- result,
157
- zonedStamp(result.job.startedAt, context.env.timeZone),
158
- ),
159
- ],
160
- });
161
- }),
164
+ // A report of work that ends while the host drains still gets through the closed queue.
165
+ deliver: (result) => {
166
+ const report = () => deliverReport(result);
167
+ return context.queue.finishing
168
+ ? context.queue.finishing(report)
169
+ : report();
170
+ },
162
171
  });
163
172
  const ship = <T>(repo: string, operation: () => Promise<T>) =>
164
173
  desk.ship(repo, operation);
@@ -190,22 +199,29 @@ export function coding(options: CodingOptions) {
190
199
  }
191
200
  };
192
201
  const textOf = (tool: RepoToolName) => options.toolText?.[tool];
193
- const describe = (tool: RepoToolName, fallback: string) =>
194
- textOf(tool)?.description ?? fallback;
195
- const about = (tool: RepoToolName, name: string, fallback?: string) => {
196
- const description = textOf(tool)?.parameters?.[name] ?? fallback;
202
+ const describe = (tool: RepoToolName) =>
203
+ textOf(tool)?.description ?? DEFAULT_TOOL_TEXT[tool].description;
204
+ const about = (tool: RepoToolName, name: string) => {
205
+ const description =
206
+ textOf(tool)?.parameters?.[name] ??
207
+ DEFAULT_TOOL_TEXT[tool].parameters[name];
197
208
  return description ? { description } : {};
198
209
  };
199
210
  const repoSchema = (tool: RepoToolName) =>
200
- Type.String(about(tool, "repo", "A managed repository, owner/repo."));
211
+ Type.String(about(tool, "repo"));
201
212
  return {
202
213
  services: [
203
214
  {
204
215
  name: "coding-desk",
205
216
  // The stored limit is read at start: setup must not query the database.
206
217
  start: () => applyStoredLimit(store, desk, context.logger),
207
- // The host names the channels whose work a shutdown waits for or aborts.
208
- busy: () => desk.runningChannels(),
218
+ // The shutdown starts no queued task and refuses new ones; queued tasks are reported at once.
219
+ beginDrain: () => desk.beginDrain(),
220
+ // The host names the channels whose work a shutdown waits for or aborts: running tasks
221
+ // and reports still going out.
222
+ busy: () => desk.busyChannels(),
223
+ // At the drain limit workers are told to stop, and their reports go out, before stop.
224
+ abort: () => desk.interrupt(),
209
225
  stop: () => desk.stop(),
210
226
  },
211
227
  ],
@@ -265,10 +281,7 @@ export function coding(options: CodingOptions) {
265
281
  defineTool({
266
282
  name: "repo_list",
267
283
  minTier: "owner",
268
- description: describe(
269
- "repo_list",
270
- "List managed clones, branch, upstream counts, dirty files, last commit, summary, CI hints and linked skills. Fetch first only when requested.",
271
- ),
284
+ description: describe("repo_list"),
272
285
  parameters: Type.Object({
273
286
  fetch: Type.Optional(Type.Boolean(about("repo_list", "fetch"))),
274
287
  }),
@@ -280,23 +293,22 @@ export function coding(options: CodingOptions) {
280
293
  skills: skills?.linkedFrom(repo.repo) ?? [],
281
294
  }),
282
295
  );
283
- if (options.presentation?.list)
284
- return options.presentation.list(repos, {
285
- shelfDir: shelf.dir,
286
- fetched: fetch === true,
287
- });
288
- return repos.length
296
+ const text = repos.length
289
297
  ? JSON.stringify(repos, null, 2)
290
298
  : `No managed repositories in ${shelf.dir}; use repo_add.`;
299
+ return (
300
+ options.presentation?.list?.(
301
+ repos,
302
+ { shelfDir: shelf.dir, fetched: fetch === true },
303
+ text,
304
+ ) ?? text
305
+ );
291
306
  }),
292
307
  }),
293
308
  defineTool({
294
309
  name: "repo_add",
295
310
  minTier: "owner",
296
- description: describe(
297
- "repo_add",
298
- "Clone owner/repo into the shelf using the host's Git login (GitHub CLI by default).",
299
- ),
311
+ description: describe("repo_add"),
300
312
  parameters: Type.Object({ repo: repoSchema("repo_add") }),
301
313
  run: ({ repo }) =>
302
314
  refusal(
@@ -306,10 +318,7 @@ export function coding(options: CodingOptions) {
306
318
  defineTool({
307
319
  name: "repo_change_report",
308
320
  minTier: "owner",
309
- description: describe(
310
- "repo_change_report",
311
- "Fetch and report commits and changed files for the default branch. Requires a clean, ahead-only clone. Review checks before requesting this report.",
312
- ),
321
+ description: describe("repo_change_report"),
313
322
  parameters: Type.Object({
314
323
  repo: repoSchema("repo_change_report"),
315
324
  }),
@@ -318,13 +327,16 @@ export function coding(options: CodingOptions) {
318
327
  ship(repo, async () => {
319
328
  const report = await shelf.report(repo);
320
329
  const direct = ownerOwned(repo);
321
- const text = options.presentation?.changeReport?.(
322
- report,
323
- direct,
324
- ) ?? {
330
+ const standard = {
325
331
  post: reportPost(report, direct),
326
332
  result: reportPost(report, direct),
327
333
  };
334
+ const text =
335
+ options.presentation?.changeReport?.(
336
+ report,
337
+ direct,
338
+ standard,
339
+ ) ?? standard;
328
340
  if (options.postChangeReport)
329
341
  await options.postChangeReport(turn, text.post);
330
342
  else
@@ -338,10 +350,7 @@ export function coding(options: CodingOptions) {
338
350
  defineTool({
339
351
  name: "repo_push",
340
352
  minTier: "owner",
341
- description: describe(
342
- "repo_push",
343
- "Push the SHA from the latest change report to its default branch, without force. Held for owner approval unless the trusted host policy explicitly marks the clone owner-owned.",
344
- ),
353
+ description: describe("repo_push"),
345
354
  parameters: Type.Object({
346
355
  repo: repoSchema("repo_push"),
347
356
  sha: Type.String({
@@ -366,10 +375,7 @@ export function coding(options: CodingOptions) {
366
375
  defineTool({
367
376
  name: "repo_task",
368
377
  minTier: "owner",
369
- description: describe(
370
- "repo_task",
371
- "Start a background Pi coding worker on a clone. Each worker has its own worktree and branch, so several may work on one repository; when it finishes, its commits are rebased onto the clone and fast-forwarded, and a conflict keeps the branch and is reported. When every worker slot is taken the task waits in a queue. The worker reads repository instructions, edits, checks and commits; shipping uses a separate report and approval. Report returns to this channel.",
372
- ),
378
+ description: describe("repo_task"),
373
379
  parameters: Type.Object({
374
380
  repo: repoSchema("repo_task"),
375
381
  task: Type.String({
@@ -444,18 +450,21 @@ export function coding(options: CodingOptions) {
444
450
  const skippedText = skipped.length
445
451
  ? ` Unavailable implicit skills skipped: ${skipped.join(", ")}.`
446
452
  : "";
447
- if (job.queuePosition !== undefined)
453
+ if (job.queuePosition !== undefined) {
454
+ const queued = `Queued coding task #${job.id} in ${repo} at position ${job.queuePosition}: every worker slot is taken, and it starts on ${job.model} when one frees. Its report returns to ${job.channel}; repo_task_cancel cancels it.${skippedText}`;
448
455
  return (
449
456
  options.presentation?.taskQueued?.(
450
457
  job,
451
458
  job.queuePosition,
452
459
  skipped,
453
- ) ??
454
- `Queued coding task #${job.id} in ${repo} at position ${job.queuePosition}: every worker slot is taken, and it starts on ${job.model} when one frees. Its report returns to ${job.channel}; repo_task_cancel cancels it.${skippedText}`
460
+ queued,
461
+ ) ?? queued
455
462
  );
463
+ }
464
+ const started = `Started coding task #${job.id} in ${repo} on ${job.model}; its report returns to ${job.channel}, and repo_task_cancel cancels it.${skippedText}`;
456
465
  return (
457
- options.presentation?.taskStarted?.(job, skipped) ??
458
- `Started coding task #${job.id} in ${repo} on ${job.model}; its report returns to ${job.channel}, and repo_task_cancel cancels it.${skippedText}`
466
+ options.presentation?.taskStarted?.(job, skipped, started) ??
467
+ started
459
468
  );
460
469
  }),
461
470
  }),
@@ -0,0 +1,107 @@
1
+ import { type HeldCall, SYSTEM_PRINCIPAL } from "pi-roundtable";
2
+ import {
3
+ type PromptSlot,
4
+ workTimeout,
5
+ YOLO_CARDED_SHELL_CLASSES,
6
+ YOLO_NEVER_CLASS,
7
+ } from "pi-roundtable/kit";
8
+ import type { CodingDeskOptions, CodingJob } from "./desk-types.ts";
9
+ import { checkTime } from "./limits.ts";
10
+
11
+ const DEFAULT_TIMEOUT_MS = 3_600_000;
12
+ /** The core's default long-running ceiling, four hours. */
13
+ const DEFAULT_LONG_RUNNING_MS = 4 * 60 * 60_000;
14
+ /** How often a run past its own limit looks again at the starter's long-running mode. */
15
+ const LONG_RUNNING_STEP_MS = 60_000;
16
+
17
+ /** The rule a class belongs to: the part before its first dot, or a rule's bare name. */
18
+ function ruleOf(id: string): string {
19
+ const dot = id.indexOf(".");
20
+ return dot === -1 ? id : id.slice(0, dot);
21
+ }
22
+
23
+ /** What a job's starter's yolo and long-running modes allow its worker, read live. */
24
+ export class DeskModes {
25
+ readonly #options: CodingDeskOptions;
26
+ readonly #longRunningMs: number;
27
+ readonly #yoloApproves: (id: string) => boolean;
28
+ constructor(options: CodingDeskOptions) {
29
+ checkTime("timeoutMs", options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
30
+ const longRunning =
31
+ options.autonomy?.longRunningMaxMs ?? DEFAULT_LONG_RUNNING_MS;
32
+ checkTime("autonomy.longRunningMaxMs", longRunning);
33
+ this.#longRunningMs = longRunning;
34
+ const allow = new Set(options.autonomy?.yolo?.allow ?? []);
35
+ const card = new Set(options.autonomy?.yolo?.card ?? []);
36
+ const carded = new Set<string>(YOLO_CARDED_SHELL_CLASSES);
37
+ // The core's yolo rules: a carded class or rule never, an unclassed call only by its rule's name.
38
+ this.#yoloApproves = (id) => {
39
+ if (id.endsWith(`.${YOLO_NEVER_CLASS}`)) return false;
40
+ if (card.has(id) || card.has(ruleOf(id))) return false;
41
+ if (!id.includes(".")) return allow.has(id);
42
+ return !carded.has(id) || allow.has(id);
43
+ };
44
+ this.#options = options;
45
+ }
46
+ /** Whether the starter's modes may act: only for an owner other than the host's own principal. */
47
+ #modeOf(job: CodingJob): { yolo: boolean; longRunning: boolean } {
48
+ const { modes } = this.#options;
49
+ const speaker = job.starter?.speaker;
50
+ if (
51
+ !modes ||
52
+ !job.starter ||
53
+ speaker?.tier !== "owner" ||
54
+ speaker.principalId === SYSTEM_PRINCIPAL
55
+ )
56
+ return { yolo: false, longRunning: false };
57
+ const mode = modes.peek(job.starter.channel);
58
+ return { yolo: mode.yolo === true, longRunning: mode.longRunning === true };
59
+ }
60
+ /** Whether the starter's yolo mode approves the call now, as it would in that conversation. */
61
+ yolo(job: CodingJob, call: HeldCall): boolean {
62
+ if (!this.#modeOf(job).yolo || call.approverIds !== undefined) return false;
63
+ const classes = call.holdClasses;
64
+ if (!classes?.length || !classes.every(this.#yoloApproves)) return false;
65
+ const { starter } = job;
66
+ if (!starter) return false;
67
+ try {
68
+ this.#options.modes?.autoApproved?.({
69
+ channel: starter.channel,
70
+ tool: call.tool,
71
+ action: `coding #${job.id} in ${job.repo}: ${call.action}`,
72
+ classes: [...classes],
73
+ principalId: starter.speaker.principalId,
74
+ at: new Date(),
75
+ });
76
+ } catch {
77
+ this.#options.logger.warn(
78
+ { job: job.id },
79
+ "Recording a yolo approval failed.",
80
+ );
81
+ }
82
+ return true;
83
+ }
84
+ /**
85
+ * The worker's work-time budget: `timeoutMs`, then, while the starter's long-running mode is
86
+ * on, further steps up to `autonomy.longRunningMaxMs` in all. Card waits never count.
87
+ */
88
+ budget(
89
+ job: CodingJob,
90
+ slot: PromptSlot,
91
+ expire: (workedMs: number) => void,
92
+ ): () => void {
93
+ const base = this.#options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
94
+ let worked = 0;
95
+ let cancel = () => {};
96
+ const phase = (ms: number) => {
97
+ cancel = workTimeout(ms, slot, () => {
98
+ worked += ms;
99
+ if (this.#modeOf(job).longRunning && worked < this.#longRunningMs)
100
+ phase(Math.min(LONG_RUNNING_STEP_MS, this.#longRunningMs - worked));
101
+ else expire(worked);
102
+ });
103
+ };
104
+ phase(base);
105
+ return () => cancel();
106
+ }
107
+ }
package/src/desk-types.ts CHANGED
@@ -134,6 +134,11 @@ export interface CodingDeskOptions {
134
134
  maxWorkers?: number;
135
135
  /** Tasks waiting for a worker slot, first in first out; one more is refused. Default 16. */
136
136
  maxQueued?: number;
137
+ /**
138
+ * The most `stop()` waits for workers to end and their reports to go out; a report still going
139
+ * then is left behind. Default 15 seconds.
140
+ */
141
+ stopWaitMs?: number;
137
142
  /**
138
143
  * The conversations' modes: with them a worker follows the yolo and long-running modes of the
139
144
  * conversation that started it, read live, when an owner other than the host spoke that turn.
package/src/index.ts CHANGED
@@ -43,4 +43,5 @@ export {
43
43
  } from "./repo-shelf.ts";
44
44
  export { REPO_TOOLS } from "./repo-tools.ts";
45
45
  export type { CancelResult, CodingTask } from "./task-control.ts";
46
+ export { DEFAULT_TOOL_TEXT } from "./tool-text.ts";
46
47
  export { CodingWorkerFailure } from "./worker-failure.ts";
@@ -16,6 +16,7 @@ import type {
16
16
  CodingWorker,
17
17
  HeldCallAnswer,
18
18
  } from "./coding-desk.ts";
19
+ import { hostStopping } from "./task-control.ts";
19
20
  import { CodingWorkerFailure } from "./worker-failure.ts";
20
21
 
21
22
  export interface PiCodingWorkerOptions {
@@ -49,6 +50,11 @@ export interface PiCodingWorkerOptions {
49
50
  workerEnv?: WorkerEnv;
50
51
  /** What the worker's shell gets besides `SHELL_ENV_NAMES`, as the agents' shell; default the host's `env.shellEnv`. */
51
52
  shellEnv?: ShellEnv;
53
+ /**
54
+ * How long a stopped worker gets to save its work and exit after SIGTERM before its process
55
+ * group is killed; default 5,000. 0 kills it at once.
56
+ */
57
+ stopGraceMs?: number;
52
58
  }
53
59
 
54
60
  /** Host variables a coding worker's process gets for its model and Pi runtime, by name. */
@@ -104,6 +110,7 @@ interface WorkerMessage {
104
110
  stopReason?: string;
105
111
  text?: string;
106
112
  name?: string;
113
+ stopped?: boolean;
107
114
  }
108
115
  function isMessage(value: unknown): value is WorkerMessage {
109
116
  return (
@@ -154,6 +161,7 @@ export class PiCodingWorker implements CodingWorker {
154
161
  const prompt = this.#options.prompt?.(job.dir);
155
162
  let report: string | undefined;
156
163
  let failure: string | undefined;
164
+ let windedDown = false;
157
165
  const child = Bun.spawn(
158
166
  [
159
167
  process.execPath,
@@ -212,6 +220,7 @@ export class PiCodingWorker implements CodingWorker {
212
220
  value.type === "failure" &&
213
221
  typeof value.message === "string"
214
222
  ) {
223
+ if (value.stopped === true) windedDown = true;
215
224
  failure = value.message.slice(
216
225
  0,
217
226
  this.#options.diagnosticChars === undefined
@@ -281,11 +290,25 @@ export class PiCodingWorker implements CodingWorker {
281
290
  /* The group has already exited. */
282
291
  }
283
292
  };
284
- signal.addEventListener("abort", kill, { once: true });
293
+ // A host shutdown sends SIGTERM first, so the worker saves what it has; the group is killed when it ends
294
+ // or the grace runs out. A cancel or a timeout kills at once: that work is not saved or merged.
295
+ const stop = () => {
296
+ const grace = this.#options.stopGraceMs ?? 5_000;
297
+ if (grace <= 0 || signal.reason !== hostStopping) return kill();
298
+ try {
299
+ process.kill(child.pid, "SIGTERM");
300
+ } catch {
301
+ /* The worker has already exited. */
302
+ }
303
+ const timer = setTimeout(kill, grace);
304
+ void child.exited.then(() => clearTimeout(timer));
305
+ };
306
+ signal.addEventListener("abort", stop, { once: true });
285
307
  try {
286
- if (signal.aborted) kill();
308
+ if (signal.aborted) stop();
287
309
  const code = await child.exited;
288
310
  if (signal.aborted) throw new CodingWorkerFailure("stopped");
311
+ if (windedDown) throw new CodingWorkerFailure("stopped");
289
312
  if (code !== 0)
290
313
  throw new CodingWorkerFailure(
291
314
  "exit",
@@ -296,7 +319,7 @@ export class PiCodingWorker implements CodingWorker {
296
319
  if (!report?.trim()) throw new CodingWorkerFailure("missing-report");
297
320
  return report;
298
321
  } finally {
299
- signal.removeEventListener("abort", kill);
322
+ signal.removeEventListener("abort", stop);
300
323
  kill(); // Also remove shell descendants the task left running.
301
324
  }
302
325
  }
@@ -0,0 +1,77 @@
1
+ import { AgentError } from "pi-roundtable/kit";
2
+ import type { Integration, RepoShelf, WorkerTree } from "./repo-shelf.ts";
3
+
4
+ /**
5
+ * Orders the changes to one clone: integrations of its worker branches run one after another, and
6
+ * never during its report or push.
7
+ */
8
+ export class RepoGate {
9
+ readonly #shelf: Pick<RepoShelf, "integrate">;
10
+ /** The last integration asked for in each repository, which the next waits for. */
11
+ readonly #integrations = new Map<string, Promise<unknown>>();
12
+ /** Repositories whose clone an integration is changing now. */
13
+ readonly #integrating = new Set<string>();
14
+ /** Reports and pushes in progress, by repository. */
15
+ readonly #shipping = new Map<string, Promise<unknown>>();
16
+ constructor(shelf: Pick<RepoShelf, "integrate">) {
17
+ this.#shelf = shelf;
18
+ }
19
+ /** Refuses while a worker's branch is being merged into the clone; running workers do not count. */
20
+ checkIdle(repo: string): void {
21
+ if (this.#integrating.has(repo))
22
+ throw new AgentError(
23
+ `A coding worker's commits are being merged into ${repo}; try again in a moment.`,
24
+ );
25
+ }
26
+ /** Whether a report or push is in progress for the repository. */
27
+ shipping(repo: string): boolean {
28
+ return this.#shipping.has(repo);
29
+ }
30
+ /**
31
+ * Runs a report or push of the repository, one at a time; refuses during an integration, and
32
+ * an integration that comes due waits for it.
33
+ */
34
+ async ship<T>(repo: string, operation: () => Promise<T>): Promise<T> {
35
+ this.checkIdle(repo);
36
+ if (this.#shipping.has(repo))
37
+ throw new AgentError(
38
+ "A report or push is already in progress for this repository.",
39
+ );
40
+ const done = operation();
41
+ this.#shipping.set(
42
+ repo,
43
+ done.catch(() => {}),
44
+ );
45
+ try {
46
+ return await done;
47
+ } finally {
48
+ this.#shipping.delete(repo);
49
+ }
50
+ }
51
+ /** Integrations of one clone run one after another, and never during its report or push. */
52
+ async integrate(tree: WorkerTree): Promise<Integration> {
53
+ const { repo } = tree;
54
+ const previous = this.#integrations.get(repo) ?? Promise.resolve();
55
+ const mine = previous
56
+ .catch(() => {})
57
+ .then(async () => {
58
+ for (let ship = this.#shipping.get(repo); ship; ) {
59
+ await ship;
60
+ ship = this.#shipping.get(repo);
61
+ }
62
+ this.#integrating.add(repo);
63
+ try {
64
+ return await this.#shelf.integrate(tree);
65
+ } finally {
66
+ this.#integrating.delete(repo);
67
+ }
68
+ });
69
+ this.#integrations.set(repo, mine);
70
+ try {
71
+ return await mine;
72
+ } finally {
73
+ if (this.#integrations.get(repo) === mine)
74
+ this.#integrations.delete(repo);
75
+ }
76
+ }
77
+ }
@@ -89,3 +89,34 @@ export async function within<T>(
89
89
  clearTimeout(timer);
90
90
  }
91
91
  }
92
+
93
+ /** What a report says in place of the worker's own when the host's shutdown stopped it. */
94
+ export const interruptedText =
95
+ "the host shut down while the worker ran, so the worker was stopped; its commits were not merged into the clone";
96
+ export const stoppedOutsideText =
97
+ "the worker was stopped by a signal from outside the desk; its commits were not merged into the clone";
98
+ export const stoppedOutsideReason =
99
+ "the worker was stopped from outside the desk (a signal to its process); its tracked changes were saved in a wip: commit, untracked files were not, and the work stays on its branch and worktree";
100
+ export const interruptedReason =
101
+ "the host shut down while the task ran; its tracked changes were saved in a wip: commit, untracked files were not, and the work stays on its branch and worktree";
102
+ /**
103
+ * The abort reason of a host shutdown. A worker stopped with it is asked to wind down and save a
104
+ * wip commit; one stopped for any other reason (a cancel, its time) is killed and leaves nothing.
105
+ */
106
+ export const hostStopping = "the host is stopping";
107
+ /** Said when a task could not start because the host is draining before a restart. */
108
+ export const notStartedText =
109
+ "not started: host restarting, dispatch again after restart";
110
+ /** Why an aborted worker's branch is not merged. */
111
+ export function notMergedReason(run: {
112
+ cancelledBy?: string | undefined;
113
+ interrupted?: boolean | undefined;
114
+ timedOut?: number | undefined;
115
+ stoppedOutside?: boolean | undefined;
116
+ }): string {
117
+ if (run.cancelledBy !== undefined)
118
+ return `the task was cancelled by ${run.cancelledBy}`;
119
+ if (run.timedOut === undefined && run.interrupted) return interruptedReason;
120
+ if (run.stoppedOutside) return stoppedOutsideReason;
121
+ return `the worker was stopped${run.timedOut === undefined ? "" : ` after ${Math.round(run.timedOut / 60_000)} minutes without finishing`}; its work stays on its branch and worktree`;
122
+ }
package/src/task-tools.ts CHANGED
@@ -68,52 +68,34 @@ export async function cancelTask(
68
68
  export function taskTools(
69
69
  desk: CodingDesk,
70
70
  refusal: <T>(operation: () => Promise<T>) => Promise<T>,
71
- describe: (tool: RepoToolName, fallback: string) => string,
72
- about: (
73
- tool: RepoToolName,
74
- name: string,
75
- fallback?: string,
76
- ) => { description?: string },
71
+ describe: (tool: RepoToolName) => string,
72
+ about: (tool: RepoToolName, name: string) => { description?: string },
77
73
  repoSchema: (tool: RepoToolName) => TString,
78
74
  ): ToolContribution[] {
79
75
  return [
80
76
  defineTool({
81
77
  name: "repo_task_list",
82
78
  minTier: "owner",
83
- description: describe(
84
- "repo_task_list",
85
- "List running and queued coding tasks with id, repository, who started each, when, and the first line of its task. An agent sees the tasks it started; an owner sees all.",
86
- ),
79
+ description: describe("repo_task_list"),
87
80
  parameters: Type.Object({
88
- repo: Type.Optional(
89
- Type.String(
90
- about(
91
- "repo_task_list",
92
- "repo",
93
- "Only this repository, owner/repo.",
94
- ),
95
- ),
96
- ),
81
+ repo: Type.Optional(Type.String(about("repo_task_list", "repo"))),
97
82
  }),
98
83
  run: ({ repo }, turn) => refusal(async () => listTasks(desk, turn, repo)),
99
84
  }),
100
85
  defineTool({
101
86
  name: "repo_task_cancel",
102
87
  minTier: "owner",
103
- description: describe(
104
- "repo_task_cancel",
105
- "Cancel a coding task by id. A queued task is dropped and never runs; a running worker is stopped, and its commits stay on its branch and worktree, not merged into the clone. An agent may cancel the tasks it started; an owner may cancel any.",
106
- ),
88
+ description: describe("repo_task_cancel"),
107
89
  parameters: Type.Object({
108
90
  repo: repoSchema("repo_task_cancel"),
109
91
  id: Type.Integer({
110
92
  minimum: 1,
111
- ...about("repo_task_cancel", "id", "The task's number, as #N."),
93
+ ...about("repo_task_cancel", "id"),
112
94
  }),
113
95
  reason: Type.Optional(
114
96
  Type.String({
115
97
  maxLength: 200,
116
- ...about("repo_task_cancel", "reason", "Why, for its report."),
98
+ ...about("repo_task_cancel", "reason"),
117
99
  }),
118
100
  ),
119
101
  }),
@@ -0,0 +1,54 @@
1
+ import type { CodingToolText, RepoToolName } from "./coding-options.ts";
2
+
3
+ const REPO = "A managed repository, owner/repo.";
4
+
5
+ /**
6
+ * The wording of each repository tool as the package ships it: the description, and the argument
7
+ * descriptions by argument name (an argument absent here has none). A host words only what must
8
+ * differ through `toolText`, such as
9
+ * `{ repo_task: { description: `${DEFAULT_TOOL_TEXT.repo_task.description} Extra.` } }`, and
10
+ * compares against this to see what a new package version changed.
11
+ */
12
+ export const DEFAULT_TOOL_TEXT: Readonly<
13
+ Record<RepoToolName, Required<CodingToolText>>
14
+ > = {
15
+ repo_list: {
16
+ description:
17
+ "List managed clones, branch, upstream counts, dirty files, last commit, summary, CI hints and linked skills. Fetch first only when requested.",
18
+ parameters: {},
19
+ },
20
+ repo_add: {
21
+ description:
22
+ "Clone owner/repo into the shelf using the host's Git login (GitHub CLI by default).",
23
+ parameters: { repo: REPO },
24
+ },
25
+ repo_change_report: {
26
+ description:
27
+ "Fetch and report commits and changed files for the default branch. Requires a clean, ahead-only clone. Review checks before requesting this report.",
28
+ parameters: { repo: REPO },
29
+ },
30
+ repo_push: {
31
+ description:
32
+ "Push the SHA from the latest change report to its default branch, without force. Held for owner approval unless the trusted host policy explicitly marks the clone owner-owned.",
33
+ parameters: { repo: REPO },
34
+ },
35
+ repo_task: {
36
+ description:
37
+ "Start a background Pi coding worker on a clone. Each worker has its own worktree and branch, so several may work on one repository; when it finishes, its commits are rebased onto the clone and fast-forwarded, and a conflict keeps the branch and is reported. When every worker slot is taken the task waits in a queue. The worker reads repository instructions, edits, checks and commits; shipping uses a separate report and approval. Report returns to this channel.",
38
+ parameters: { repo: REPO },
39
+ },
40
+ repo_task_list: {
41
+ description:
42
+ "List running and queued coding tasks with id, repository, who started each, when, and the first line of its task. An agent sees the tasks it started; an owner sees all.",
43
+ parameters: { repo: "Only this repository, owner/repo." },
44
+ },
45
+ repo_task_cancel: {
46
+ description:
47
+ "Cancel a coding task by id. A queued task is dropped and never runs; a running worker is stopped, and its commits stay on its branch and worktree, not merged into the clone. An agent may cancel the tasks it started; an owner may cancel any.",
48
+ parameters: {
49
+ repo: REPO,
50
+ id: "The task's number, as #N.",
51
+ reason: "Why, for its report.",
52
+ },
53
+ },
54
+ };
@@ -69,6 +69,45 @@ export function codingWorkerPrompt(dir: string): string {
69
69
  "Report changes and reasons, commits, checks and outcomes, held actions, and remaining work.",
70
70
  ].join("\n\n");
71
71
  }
72
+ /** The running session, for a stop to end its turn. */
73
+ let working: { abort(): Promise<void> } | undefined;
74
+ /** Set once the host's shutdown asked the worker to stop; the run's own report or failure then waits for it. */
75
+ let winding: Promise<never> | undefined;
76
+ /**
77
+ * The host's shutdown asked the worker to stop (SIGTERM; a cancel or a timeout kills instead): it
78
+ * ends its turn, keeps the tracked changes it made in a commit on its own branch, and exits, so
79
+ * the report can say where the work is. Untracked files are not committed; the report lists them.
80
+ */
81
+ async function windDown(dir: string): Promise<never> {
82
+ // A turn waiting for an approval never answers its abort, so the commit does not wait long for it.
83
+ await Promise.race([
84
+ working?.abort().catch(() => undefined),
85
+ Bun.sleep(1_000),
86
+ ]);
87
+ Bun.spawnSync(
88
+ [
89
+ "git",
90
+ "commit",
91
+ "--all",
92
+ "--no-verify",
93
+ "--message",
94
+ "wip: the host shut down while this task ran",
95
+ ],
96
+ {
97
+ cwd: dir,
98
+ stdin: "ignore",
99
+ stdout: "ignore",
100
+ stderr: "ignore",
101
+ timeout: 3_000,
102
+ },
103
+ );
104
+ process.send?.(
105
+ { type: "failure", message: "the worker was stopped", stopped: true },
106
+ () => process.exit(1),
107
+ );
108
+ // The parent kills the group if the message does not get out.
109
+ return new Promise<never>(() => {});
110
+ }
72
111
  const answers = new Map<
73
112
  number,
74
113
  (answer: HeldCallAnswer, reason?: string) => void
@@ -84,6 +123,9 @@ async function run({
84
123
  scratchDir,
85
124
  shellEnv,
86
125
  }: StartMessage): Promise<string> {
126
+ process.once("SIGTERM", () => {
127
+ winding ??= windDown(job.dir);
128
+ });
87
129
  const modelRuntime = await ModelRuntime.create({
88
130
  authPath: join(agentDir, "auth.json"),
89
131
  modelsPath: join(agentDir, "models.json"),
@@ -161,6 +203,7 @@ async function run({
161
203
  sessionManager: SessionManager.inMemory(job.dir),
162
204
  settingsManager: SettingsManager.inMemory({}),
163
205
  });
206
+ working = session;
164
207
  // Only what the host's progress posts read crosses: a message's text, never its thinking.
165
208
  if (progress)
166
209
  session.subscribe((event) => {
@@ -205,17 +248,20 @@ if (process.send) {
205
248
  } else if (message.type === "start" && !started) {
206
249
  started = true;
207
250
  void run(message as StartMessage).then(
208
- (report) => {
251
+ async (report) => {
252
+ await winding;
209
253
  process.send?.({ type: "report", report }, () => process.exit(0));
210
254
  },
211
- (error: unknown) =>
255
+ async (error: unknown) => {
256
+ await winding;
212
257
  process.send?.(
213
258
  {
214
259
  type: "failure",
215
260
  message: error instanceof Error ? error.message : String(error),
216
261
  },
217
262
  () => process.exit(1),
218
- ),
263
+ );
264
+ },
219
265
  );
220
266
  }
221
267
  });