pi-roundtable-coding 0.39.1 → 0.42.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,22 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.42.0] - 2026-11-08
6
+
7
+ ### Added
8
+
9
+ - A coding worker's yolo mode never approves a call whose class ends in `.yolo-never` (`YOLO_NEVER_CLASS`), even when `autonomy.yolo.allow` names it, matching the core yolo approver.
10
+
11
+ ## [0.41.0] - 2026-11-08
12
+
13
+ ### Added
14
+
15
+ - A coding task can be cancelled. `repo_task_cancel { repo, id, reason? }` drops a queued task before it runs, or stops a running worker the way a timeout does, closing the held actions it waited on; the stopped worker's commits stay on its branch and worktree, not merged into the clone, and its report says "cancelled by <name>" and names both. `repo_task_list { repo? }` lists running and queued tasks. An agent sees and cancels its own tasks, an owner any. The Settings page "Coding workers" lists the tasks with an owner-only Cancel action. `CodingDesk.cancel(id, by)` answers a `CancelResult` and `CodingDesk.tasks()` lists the tasks; `REPO_TOOLS` and `RepoToolName` gain the two names, and the `repo_task` result mentions `repo_task_cancel`.
16
+
17
+ ## [0.40.0] - 2026-11-08
18
+
19
+ - Release in lockstep with pi-roundtable 0.40.0 (interactive blocks answered in the app, and chats that cannot show them say so); no package-specific behavior changes.
20
+
5
21
  ## [0.39.1] - 2026-11-08
6
22
 
7
23
  ### Fixed
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.39.0 <0.40.0` as a peer dependency; this package uses only its public main, kit and testing entries.
10
+ - pi-roundtable `>=0.42.0 <0.43.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.
@@ -79,10 +79,12 @@ System report turns cannot call `repo_task`; do the work in the turn or hand it
79
79
  | `repo_add` | `repo` | Clone `owner/repo` into `shelfDir/owner/repo`; refuse invalid names and existing clones. |
80
80
  | `repo_list` | `fetch?` | List paths, branches, upstream ahead/behind counts, dirty files, last commits, prose summaries, CI hints and linked skills. |
81
81
  | `repo_task` | `repo`, `task`, `skills?` | Start a background worker in its own worktree, or queue it when every worker slot is taken, returning its job number (and queue position) immediately. The host's own turns, such as a report's, may not. |
82
+ | `repo_task_list` | `repo?` | List running and queued tasks with id, repository, who started each, when it started or was queued, and the first line of its task. |
83
+ | `repo_task_cancel` | `repo`, `id`, `reason?` | Cancel a task: a queued one is dropped and never runs; a running worker is stopped and its commits stay on its branch, unmerged. |
82
84
  | `repo_change_report` | `repo` | Fetch and post the commits and diffstat ahead of the default branch; return its full SHA. |
83
85
  | `repo_push` | `repo`, `sha` | Push the exact reported SHA to the reported default branch, without force, after the hold gate permits it. |
84
86
 
85
- All five tools have `minTier: "owner"` and are contributed through `defineTool` for agent and owner session selections.
87
+ All seven tools have `minTier: "owner"` and are contributed through `defineTool` for agent and owner session selections.
86
88
  The operator remains responsible for any tool-tier overrides.
87
89
  A custom owner claim with a restricted `ToolSelection` must include the exported `REPO_TOOLS` names; include `skill_list` separately when the host skills addon is enabled.
88
90
  The host's skills addon resolves explicit skills, or the calling agent's carried skills when omitted; an owner call carries none unless it names them.
@@ -115,6 +117,19 @@ Hosts call `desk.setMaxWorkers(n)` for the same change in code, and `desk.worker
115
117
  The page has built-in zh-TW wording for a zh-TW host; `presentation.messages`, keyed by the English text, words it otherwise.
116
118
  Past that a task waits in a first-in, first-out queue of at most `maxQueued` tasks (default 16), and `repo_task` answers at once with its queue position; one more is refused.
117
119
  A queued task starts when a worker slot frees.
120
+ ### Cancelling a task
121
+
122
+ `repo_task_cancel` cancels one task, and `repo_task_list` shows which there are.
123
+ An agent sees and cancels the tasks its own turns started; a turn an owner speaks sees and cancels any; outside an agent's turn a person sees the tasks they started.
124
+ The host's own turns, such as a report's, count as the agent they run for.
125
+ A queued task leaves the queue and never starts; its report says it was cancelled before it ran.
126
+ A running worker is aborted the way a timeout aborts it, and held actions it was waiting on are closed.
127
+ Its commits are kept on its branch and worktree and are not rebased into the clone; the report says "cancelled by <name>" and names the branch, the worktree path and the commits, to inspect, merge or delete.
128
+ The tool waits up to 30 seconds for the worker to settle and answers with the branch and the number of commits kept.
129
+ Cancelling frees the slot, so the next queued task starts; an unknown or finished id is refused.
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
+ `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
+
118
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.
119
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.
120
135
  Failures and timeouts also report the final Git state when it can be read.
@@ -237,7 +252,7 @@ The `CODING` service exposes `shelf: RepoShelf` and `desk: CodingDesk` for trust
237
252
  | `worker` | `PiCodingWorker` | Trusted worker runner replacement. |
238
253
  | `onResult` | surface reply | Report delivery integration. |
239
254
 
240
- `RepoShelf`, `CodingDesk`, `PiCodingWorker`, `CodingWorkerFailure`, `REPO_TOOLS`, `codingReport`, `integrationText`, `reportPost`, `WORKTREES_DIR` and their option/result types are exported for testing and host integrations.
255
+ `RepoShelf`, `CodingDesk`, `PiCodingWorker`, `CodingWorkerFailure`, `REPO_TOOLS`, `codingReport`, `integrationText`, `reportPost`, `WORKTREES_DIR` and their option/result types, `CancelResult` and `CodingTask` among them, are exported for testing and host integrations.
241
256
  `CodingResult.integration` tells what became of the worker's branch (`merged`, `nothing`, `conflict` with its files, or `refused` with the reason) and `CodingResult.autoApproved` the calls yolo mode approved; `CodingJob.starter` names the conversation and speaker whose modes the worker follows, and `CodingJob.branch` its branch.
242
257
  `resolveRun(turn)` receives the public `ToolTurn`, including the calling agent scope and channel.
243
258
  It returns `{ model, thinking, channel, origin? }`; skill selection still follows the caller, not the resolved report destination.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable-coding",
3
- "version": "0.39.1",
3
+ "version": "0.42.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.39.0 <0.40.0"
41
+ "pi-roundtable": ">=0.42.0 <0.43.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.39.1",
47
+ "pi-roundtable": "0.42.0",
48
48
  "typescript": "7.0.2"
49
49
  }
50
50
  }
@@ -1,175 +1,56 @@
1
1
  import {
2
2
  type ChannelKey,
3
- type ConversationModes,
4
3
  type HeldCall,
5
- type InterimTextMode,
6
- type Logger,
7
- type OwnerPrompts,
8
4
  SYSTEM_PRINCIPAL,
9
- type ThinkingLevel,
10
- type Tier,
11
5
  } from "pi-roundtable";
12
6
  import {
13
7
  AgentError,
14
8
  approvalCard,
15
9
  approvalDetails,
16
- type DispatchThread,
17
- type DispatchThreads,
18
10
  InterimPoster,
19
11
  type PromptSlot,
20
12
  promptSlot,
21
13
  workTimeout,
22
14
  YOLO_CARDED_SHELL_CLASSES,
15
+ YOLO_NEVER_CLASS,
23
16
  } from "pi-roundtable/kit";
24
- import { checkCount, checkMaxWorkers, checkTime } from "./limits.ts";
17
+ import { codingReport } from "./coding-report.ts";
25
18
  import type {
26
- Integration,
27
- RepoShelf,
28
- RepoState,
29
- WorkerTree,
30
- } from "./repo-shelf.ts";
19
+ CodingDeskOptions,
20
+ CodingJob,
21
+ CodingResult,
22
+ CodingStart,
23
+ HeldCallAnswer,
24
+ } from "./desk-types.ts";
25
+ import { checkCount, checkMaxWorkers, checkTime } from "./limits.ts";
26
+ import type { Integration, RepoState, WorkerTree } from "./repo-shelf.ts";
27
+ import {
28
+ type CancelResult,
29
+ type CodingTask,
30
+ cancelledText,
31
+ droppedText,
32
+ within,
33
+ } from "./task-control.ts";
31
34
  import { CodingWorkerFailure } from "./worker-failure.ts";
32
35
 
36
+ export { codingReport, integrationText } from "./coding-report.ts";
37
+ export type {
38
+ CodingAutonomy,
39
+ CodingDeskOptions,
40
+ CodingJob,
41
+ CodingLimits,
42
+ CodingModes,
43
+ CodingProgress,
44
+ CodingResult,
45
+ CodingSpeaker,
46
+ CodingStart,
47
+ CodingStarter,
48
+ CodingThreadText,
49
+ CodingWorker,
50
+ HeldCallAnswer,
51
+ } from "./desk-types.ts";
33
52
  export { checkLimit } from "./limits.ts";
34
53
 
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
54
  export const MAX_CODING_TASK_CHARS = 8_000;
174
55
  const MAX_REPORT_CHARS = 20_000;
175
56
  const MAX_HELD_ENTRIES = 10;
@@ -199,6 +80,13 @@ interface Running {
199
80
  job: CodingJob;
200
81
  controller: AbortController;
201
82
  done?: Promise<void>;
83
+ /** Who cancelled it; its branch is then kept, not merged. */
84
+ cancelledBy?: string;
85
+ /** Resolves with its kept commits once the worker settles. */
86
+ settled?: Promise<string[]>;
87
+ settle?: (commits: string[]) => void;
88
+ /** Its worktree, once made. */
89
+ dir?: string;
202
90
  }
203
91
 
204
92
  /**
@@ -239,6 +127,7 @@ export class CodingDesk {
239
127
  const carded = new Set<string>(YOLO_CARDED_SHELL_CLASSES);
240
128
  // The core's yolo rules: a carded class or rule never, an unclassed call only by its rule's name.
241
129
  this.#yoloApproves = (id) => {
130
+ if (id.endsWith(`.${YOLO_NEVER_CLASS}`)) return false;
242
131
  if (card.has(id) || card.has(ruleOf(id))) return false;
243
132
  if (!id.includes(".")) return allow.has(id);
244
133
  return !carded.has(id) || allow.has(id);
@@ -258,10 +147,7 @@ export class CodingDesk {
258
147
  const { size: running } = this.#running;
259
148
  return { max: this.#maxWorkers, running, queued: this.#queue.length };
260
149
  }
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
- */
150
+ /** Sets the workers run at once, 1 to 64: a higher limit starts queued tasks now; a lower one stops none. */
265
151
  setMaxWorkers(max: number): void {
266
152
  checkMaxWorkers(max);
267
153
  this.#maxWorkers = max;
@@ -314,6 +200,52 @@ export class CodingDesk {
314
200
  // A run that ends starts the next queued one before it settles, so look again.
315
201
  while (this.#pending.size) await Promise.all(this.#pending);
316
202
  }
203
+ /** The running tasks, then the queued ones in queue order. */
204
+ tasks(): CodingTask[] {
205
+ return [
206
+ ...[...this.#running.values()].map(({ job }) => ({
207
+ job,
208
+ status: "running" as const,
209
+ })),
210
+ ...this.#queue.map((job, index) => ({
211
+ job,
212
+ status: "queued" as const,
213
+ queuePosition: index + 1,
214
+ })),
215
+ ];
216
+ }
217
+ /**
218
+ * Cancels a task: a queued one never starts; a running one is stopped as a timeout stops it,
219
+ * and its commits stay on its branch and worktree, not merged. Waits up to `waitMs` for the
220
+ * worker to settle; the report reaches `deliver` as for any run.
221
+ */
222
+ async cancel(id: number, by: string, waitMs = 30_000): Promise<CancelResult> {
223
+ const queued = this.#queue.findIndex((job) => job.id === id);
224
+ if (queued !== -1) {
225
+ const [job] = this.#queue.splice(queued, 1);
226
+ if (!job) throw new Error("unreachable");
227
+ this.#track(this.#drop(job, droppedText(by)));
228
+ return { status: "dropped", job };
229
+ }
230
+ const run = this.#running.get(id);
231
+ if (!run || run.cancelledBy !== undefined)
232
+ return {
233
+ status: "refused",
234
+ reason: `No running or queued coding task #${id}; it may have finished already.`,
235
+ };
236
+ run.cancelledBy = by;
237
+ run.controller.abort();
238
+ const commits = run.settled && (await within(run.settled, waitMs));
239
+ const { job } = run;
240
+ return {
241
+ status: "stopped",
242
+ job,
243
+ ...(job.branch ? { branch: job.branch } : {}),
244
+ ...(run.dir ? { dir: run.dir } : {}),
245
+ commits: commits ?? [],
246
+ settled: commits !== undefined,
247
+ };
248
+ }
317
249
  /** Stops the running workers and drops the queued tasks, telling each that it never ran. */
318
250
  async stop(): Promise<void> {
319
251
  this.#stopped = true;
@@ -361,15 +293,21 @@ export class CodingDesk {
361
293
  #launch(job: CodingJob): void {
362
294
  job.startedAt = new Date();
363
295
  const run: Running = { job, controller: new AbortController() };
296
+ run.settled = new Promise((resolve) => {
297
+ run.settle = resolve;
298
+ });
364
299
  this.#running.set(job.id, run);
365
- run.done = this.#run(job, run.controller)
300
+ run.done = this.#run(job, run)
366
301
  .catch(() => {
367
302
  this.#options.logger.error(
368
303
  { job: job.id },
369
304
  "Coding report delivery failed.",
370
305
  );
371
306
  })
372
- .finally(() => this.#free(job));
307
+ .finally(() => {
308
+ run.settle?.([]);
309
+ this.#free(job);
310
+ });
373
311
  this.#track(run.done);
374
312
  }
375
313
  /** Frees the job's slot and starts the next queued tasks. */
@@ -387,15 +325,14 @@ export class CodingDesk {
387
325
  if (next) this.#launch(next);
388
326
  }
389
327
  }
390
- async #drop(job: CodingJob): Promise<void> {
328
+ async #drop(
329
+ job: CodingJob,
330
+ error = "the host stopped before this queued task started; nothing ran, so start it again",
331
+ ): Promise<void> {
391
332
  try {
392
333
  await this.#options.deliver({
393
334
  job,
394
- outcome: {
395
- ok: false,
396
- error:
397
- "the host stopped before this queued task started; nothing ran, so start it again",
398
- },
335
+ outcome: { ok: false, error },
399
336
  held: [],
400
337
  commits: [],
401
338
  });
@@ -493,7 +430,8 @@ export class CodingDesk {
493
430
  this.#integrations.delete(repo);
494
431
  }
495
432
  }
496
- async #run(job: CodingJob, controller: AbortController): Promise<void> {
433
+ async #run(job: CodingJob, run: Running): Promise<void> {
434
+ const { controller } = run;
497
435
  const { shelf, worker, prompts, threads, threadText, deliver } =
498
436
  this.#options;
499
437
  const slot = promptSlot();
@@ -514,6 +452,7 @@ export class CodingDesk {
514
452
  tree = await shelf.addWorktree(job.repo, job.id);
515
453
  job.startHead = tree.base.slice(0, 12);
516
454
  job.branch = tree.branch;
455
+ run.dir = tree.dir;
517
456
  if (controller.signal.aborted)
518
457
  throw new AgentError("the worker was stopped");
519
458
  if (threads) {
@@ -626,6 +565,8 @@ export class CodingDesk {
626
565
  if (controller.signal.aborted) message = "the worker was stopped";
627
566
  if (timedOut !== undefined)
628
567
  message = `the worker ran out of time (${Math.round(timedOut / 60_000)} minutes)`;
568
+ if (run.cancelledBy !== undefined)
569
+ message = cancelledText(run.cancelledBy);
629
570
  outcome = { ok: false, error: message };
630
571
  } finally {
631
572
  cancel();
@@ -634,7 +575,15 @@ export class CodingDesk {
634
575
  await interim?.flush();
635
576
  }
636
577
  let integration: Integration | undefined;
637
- if (tree)
578
+ // A cancelled worker's commits stay on its branch for the owner to inspect, merge or delete.
579
+ if (tree && run.cancelledBy !== undefined)
580
+ integration = {
581
+ status: "refused",
582
+ branch: tree.branch,
583
+ dir: tree.dir,
584
+ reason: `the task was cancelled by ${run.cancelledBy}`,
585
+ };
586
+ else if (tree)
638
587
  try {
639
588
  integration = await this.#integrate(tree);
640
589
  } catch (error) {
@@ -693,51 +642,9 @@ export class CodingDesk {
693
642
  } catch {
694
643
  this.#options.logger.warn({ job: job.id }, "Coding thread close failed.");
695
644
  }
645
+ run.settle?.(commits);
696
646
  // The work is over: free the slot and the repository before the report turn, so that turn can ship it.
697
647
  this.#free(job);
698
648
  await deliver(result);
699
649
  }
700
650
  }
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
- }
@@ -34,7 +34,9 @@ export type RepoToolName =
34
34
  | "repo_add"
35
35
  | "repo_change_report"
36
36
  | "repo_push"
37
- | "repo_task";
37
+ | "repo_task"
38
+ | "repo_task_list"
39
+ | "repo_task_cancel";
38
40
  /** Trusted wording of one repository tool, as the model reads it; unset fields keep the defaults. */
39
41
  export interface CodingToolText {
40
42
  description?: string;
@@ -33,6 +33,7 @@ import {
33
33
  import { checkCount, checkMaxWorkers } from "./limits.ts";
34
34
  import { PiCodingWorker } from "./pi-coding-worker.ts";
35
35
  import { RepoShelf, reportPost } from "./repo-shelf.ts";
36
+ import { taskTools } from "./task-tools.ts";
36
37
  import { workerHolds } from "./worker-holds.ts";
37
38
 
38
39
  export type {
@@ -419,6 +420,7 @@ export function coding(options: CodingOptions) {
419
420
  const { speaker } = turn;
420
421
  const job = await desk.start({
421
422
  ...run,
423
+ ...(turn.agent ? { agent: turn.agent.name } : {}),
422
424
  // Its modes follow the conversation this turn runs in, as the turn's own would.
423
425
  ...(speaker
424
426
  ? {
@@ -449,14 +451,15 @@ export function coding(options: CodingOptions) {
449
451
  job.queuePosition,
450
452
  skipped,
451
453
  ) ??
452
- `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}.${skippedText}`
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}`
453
455
  );
454
456
  return (
455
457
  options.presentation?.taskStarted?.(job, skipped) ??
456
- `Started coding task #${job.id} in ${repo} on ${job.model}; its report returns to ${job.channel}.${skippedText}`
458
+ `Started coding task #${job.id} in ${repo} on ${job.model}; its report returns to ${job.channel}, and repo_task_cancel cancels it.${skippedText}`
457
459
  );
458
460
  }),
459
461
  }),
462
+ ...taskTools(desk, refusal, describe, about, repoSchema),
460
463
  ],
461
464
  };
462
465
  },
@@ -0,0 +1,45 @@
1
+ import type { CodingResult } from "./coding-desk.ts";
2
+ import type { Integration } from "./repo-shelf.ts";
3
+
4
+ /** What became of the worker's branch, for the report. */
5
+ export function integrationText(
6
+ integration: Integration | undefined,
7
+ branch: string | undefined,
8
+ ): string | undefined {
9
+ switch (integration?.status) {
10
+ case "merged":
11
+ return `Merged ${integration.branch}: rebased onto the clone's branch and fast-forwarded it.`;
12
+ case "nothing":
13
+ return `${branch ?? "The worker's branch"} added no commits; its worktree is removed.`;
14
+ case "conflict":
15
+ 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.`;
16
+ case "refused":
17
+ return `Not merged: ${integration.reason}\nThe branch ${integration.branch} and its worktree ${integration.dir} are kept.`;
18
+ default:
19
+ return undefined;
20
+ }
21
+ }
22
+
23
+ export function codingReport(result: CodingResult, started: string): string {
24
+ const { job, outcome, state, commits, held, autoApproved, integration } =
25
+ result;
26
+ const merge = integrationText(integration, job.branch);
27
+ return [
28
+ `## Coding task #${job.id}: ${job.repo}`,
29
+ `Started: ${started}`,
30
+ outcome.ok ? outcome.report : outcome.error,
31
+ "### Held",
32
+ held.length ? held.join("\n") : "None.",
33
+ ...(autoApproved?.length
34
+ ? ["### Approved by yolo mode", autoApproved.join("\n")]
35
+ : []),
36
+ "### Repository",
37
+ [
38
+ ...(merge ? [merge] : []),
39
+ state
40
+ ? `Branch ${state.branch}, HEAD ${state.head} (was ${job.startHead}).\nNew commits:\n${commits.join("\n") || "None."}\nUncommitted:\n${state.uncommitted.join("\n") || "None."}`
41
+ : "Unreadable.",
42
+ ].join("\n"),
43
+ "Review the changes and checks, then use repo_change_report before repo_push.",
44
+ ].join("\n\n");
45
+ }
@@ -77,6 +77,8 @@ export interface SettingsWebApp {
77
77
  }
78
78
  interface SettingsViewer {
79
79
  tier: Tier;
80
+ /** The name the app shows for them, for a cancelled task's report. */
81
+ name?: string;
80
82
  }
81
83
  type SettingsResult =
82
84
  | { ok: true; notice?: string }
@@ -90,6 +92,20 @@ export interface SettingsPage {
90
92
  title: string;
91
93
  sections: readonly (
92
94
  | { kind: "markdown"; text: string }
95
+ | {
96
+ kind: "list";
97
+ title?: string;
98
+ rows: {
99
+ title: string;
100
+ subtitle?: string;
101
+ actions?: {
102
+ id: string;
103
+ label: string;
104
+ style?: "danger";
105
+ confirm?: string;
106
+ }[];
107
+ }[];
108
+ }
93
109
  | {
94
110
  kind: "form";
95
111
  action: string;
@@ -123,7 +139,7 @@ export const SETTINGS_PAGE_ID = "coding-workers";
123
139
  export function settingsWording(
124
140
  locale: Locale,
125
141
  messages: Readonly<Record<string, string>> = {},
126
- ): (text: string, values?: Record<string, number>) => string {
142
+ ): (text: string, values?: Record<string, number | string>) => string {
127
143
  const catalog = { ...(locale === "zh-TW" ? ZH_TW : {}), ...messages };
128
144
  return (text, values = {}) =>
129
145
  (catalog[text] ?? text).replace(/\{(\w+)\}/g, (whole, name: string) =>
@@ -156,6 +172,7 @@ export function settingsPage(
156
172
  { max, running, queued },
157
173
  ),
158
174
  },
175
+ ...taskList(desk, t),
159
176
  {
160
177
  kind: "form",
161
178
  action: "save",
@@ -184,6 +201,34 @@ export function settingsPage(
184
201
  act: async (viewer, action, input) => {
185
202
  if (!owner(viewer))
186
203
  return { ok: false, error: t("Only an owner changes this.") };
204
+ const cancel = /^cancel:(\d{1,9})$/.exec(action);
205
+ if (cancel) {
206
+ const id = Number(cancel[1]);
207
+ const result = await desk.cancel(
208
+ id,
209
+ viewer.name ? `${viewer.name} (web app)` : "an owner (web app)",
210
+ );
211
+ changed();
212
+ if (result.status === "refused")
213
+ return {
214
+ ok: false,
215
+ error: t("Coding task #{id} is no longer running or queued.", {
216
+ id,
217
+ }),
218
+ };
219
+ return {
220
+ ok: true,
221
+ notice:
222
+ result.status === "dropped"
223
+ ? t("Coding task #{id} was dropped from the queue.", { id })
224
+ : result.branch
225
+ ? t(
226
+ "Coding task #{id} was stopped; its commits stay on {branch}, not merged.",
227
+ { id, branch: result.branch },
228
+ )
229
+ : t("Coding task #{id} was stopped.", { id }),
230
+ };
231
+ }
187
232
  if (action !== "save")
188
233
  return { ok: false, error: t("This page has no such action.") };
189
234
  const text = input.maxWorkers;
@@ -213,6 +258,67 @@ export function settingsPage(
213
258
  };
214
259
  }
215
260
 
261
+ /** The running and queued tasks, each with a Cancel action; none when nothing runs or waits. */
262
+ function taskList(
263
+ desk: CodingDesk,
264
+ t: ReturnType<typeof settingsWording>,
265
+ ): {
266
+ kind: "list";
267
+ title: string;
268
+ rows: {
269
+ title: string;
270
+ subtitle: string;
271
+ actions: {
272
+ id: string;
273
+ label: string;
274
+ style: "danger";
275
+ confirm: string;
276
+ }[];
277
+ }[];
278
+ }[] {
279
+ const tasks = desk.tasks().slice(0, 100);
280
+ if (!tasks.length) return [];
281
+ return [
282
+ {
283
+ kind: "list",
284
+ title: t("Tasks"),
285
+ rows: tasks.map((task) => {
286
+ const { job } = task;
287
+ const id = job.id;
288
+ const who = job.agent ?? job.starter?.speaker.name ?? "";
289
+ return {
290
+ title: `#${id} ${job.repo}: ${job.task.split("\n", 1)[0] ?? ""}`,
291
+ subtitle:
292
+ task.status === "running"
293
+ ? t("Running since {at}, started by {who}", {
294
+ at: job.startedAt.toISOString(),
295
+ who,
296
+ })
297
+ : t("Queued (position {position}) since {at}, started by {who}", {
298
+ position: task.queuePosition ?? 0,
299
+ at: (job.queuedAt ?? job.startedAt).toISOString(),
300
+ who,
301
+ }),
302
+ actions: [
303
+ {
304
+ id: `cancel:${id}`,
305
+ label: t("Cancel"),
306
+ style: "danger",
307
+ confirm:
308
+ task.status === "running"
309
+ ? t(
310
+ "Stop coding task #{id}? Its commits stay on its branch, not merged.",
311
+ { id },
312
+ )
313
+ : t("Drop coding task #{id} from the queue?", { id }),
314
+ },
315
+ ],
316
+ };
317
+ }),
318
+ },
319
+ ];
320
+ }
321
+
216
322
  /** Registers the settings page when the web app is there; the web app must be registered first. */
217
323
  export function registerSettingsPage(
218
324
  context: Pick<PluginContext, "services" | "logger" | "env">,
@@ -0,0 +1,153 @@
1
+ import type {
2
+ ChannelKey,
3
+ ConversationModes,
4
+ HeldCall,
5
+ InterimTextMode,
6
+ Logger,
7
+ OwnerPrompts,
8
+ ThinkingLevel,
9
+ Tier,
10
+ } from "pi-roundtable";
11
+ import type { DispatchThread, DispatchThreads } from "pi-roundtable/kit";
12
+ import type { Integration, RepoShelf, RepoState } from "./repo-shelf.ts";
13
+
14
+ export type HeldCallAnswer = "approved" | "declined" | "held";
15
+ /** Who spoke the turn that started a job, as yolo and long-running modes need to know. */
16
+ export interface CodingSpeaker {
17
+ id: string;
18
+ principalId: string;
19
+ name?: string;
20
+ tier?: Tier;
21
+ }
22
+ /** The conversation whose turn started a job, whose modes the worker follows live. */
23
+ export interface CodingStarter {
24
+ channel: ChannelKey;
25
+ speaker: CodingSpeaker;
26
+ }
27
+ export interface CodingJob {
28
+ id: number;
29
+ repo: string;
30
+ task: string;
31
+ channel: ChannelKey;
32
+ /** The agent whose turn started it, which may list and cancel it. */
33
+ agent?: string;
34
+ /** The calling turn's channel, where a progress thread opens. */
35
+ origin?: ChannelKey;
36
+ /** The conversation that started it; its yolo and long-running modes apply while it works. */
37
+ starter?: CodingStarter;
38
+ /** Host-resolved names of the skills carried to this run. */
39
+ skillNames?: string[];
40
+ /** Progress thread, when the surface supports one. */
41
+ thread?: DispatchThread;
42
+ model: string;
43
+ thinking: ThinkingLevel;
44
+ skillFiles: string[];
45
+ /** When it was asked for; a queued job starts later. */
46
+ queuedAt?: Date;
47
+ /** When its worker started. */
48
+ startedAt: Date;
49
+ startHead: string;
50
+ /** The worker's own branch, in its own worktree, once it has started. */
51
+ branch?: string;
52
+ }
53
+ /** A started or queued job, as `CodingDesk.start` answers. */
54
+ export type CodingStart = CodingJob & {
55
+ /** Its place in the queue, from 1, when every worker slot is taken; absent when it started. */
56
+ queuePosition?: number;
57
+ };
58
+ /** What the worker writes and runs as it goes, for its thread's progress posts. */
59
+ export interface CodingProgress {
60
+ /** A finished message of the worker's session: its role, stop reason, and text. */
61
+ messageEnd(message: {
62
+ role: string;
63
+ content?: unknown;
64
+ stopReason?: string;
65
+ }): void;
66
+ /** A tool the worker started. */
67
+ toolStart(name: string): void;
68
+ }
69
+ export interface CodingWorker {
70
+ /** `progress`, when given, hears the session's messages and tools as the worker goes. */
71
+ run(
72
+ job: CodingJob & { dir: string },
73
+ signal: AbortSignal,
74
+ review: (call: HeldCall) => Promise<HeldCallAnswer>,
75
+ progress?: CodingProgress,
76
+ ): Promise<string>;
77
+ }
78
+ export interface CodingResult {
79
+ job: CodingJob;
80
+ outcome: { ok: true; report: string } | { ok: false; error: string };
81
+ held: string[];
82
+ /** Held calls the starter's yolo mode approved without a card. */
83
+ autoApproved?: string[];
84
+ state?: RepoState;
85
+ commits: string[];
86
+ /** How the worker's branch came back into the clone; absent when no worktree was made. */
87
+ integration?: Integration;
88
+ }
89
+ /** The conversations' modes, read live for each held call and at each work-time limit. */
90
+ export type CodingModes = Pick<ConversationModes, "peek"> &
91
+ Partial<Pick<ConversationModes, "autoApproved">>;
92
+ /**
93
+ * The host's autonomy limits, as its `autonomy` config resolves them: what yolo may approve, and
94
+ * how long a long-running run works in all.
95
+ */
96
+ export interface CodingAutonomy {
97
+ yolo?: { allow?: readonly string[]; card?: readonly string[] };
98
+ /** Default four hours; at most 2147483647. */
99
+ longRunningMaxMs?: number;
100
+ }
101
+ export interface CodingThreadText {
102
+ initial?(job: CodingJob): string;
103
+ held?(entry: string, job: CodingJob): string;
104
+ approvalTitle?(job: CodingJob): string;
105
+ report?(result: CodingResult): string;
106
+ }
107
+ export interface CodingDeskOptions {
108
+ shelf: Pick<
109
+ RepoShelf,
110
+ | "dirOf"
111
+ | "state"
112
+ | "addWorktree"
113
+ | "integrate"
114
+ | "treeState"
115
+ | "treeCommits"
116
+ >;
117
+ worker: CodingWorker;
118
+ prompts?(channel: ChannelKey): OwnerPrompts | undefined;
119
+ /** When configured, approval cards stay in the job's thread; no thread means held. */
120
+ threads?: Pick<DispatchThreads, "open">;
121
+ threadText?: CodingThreadText;
122
+ deliver(result: CodingResult): Promise<void>;
123
+ logger: Logger;
124
+ timeoutMs?: number;
125
+ limits?: CodingLimits;
126
+ /**
127
+ * Whether the worker posts the text it writes before its report into its thread as it goes,
128
+ * as the host's turns do; "on" by default. A thread whose host cannot edit its posts gets none.
129
+ */
130
+ interimText?: InterimTextMode;
131
+ /** Length from which an intermediate text is posted as its own message; default 400. */
132
+ interimPrimaryChars?: number;
133
+ /** Workers running at once on the host, across repositories and channels; default 4. */
134
+ maxWorkers?: number;
135
+ /** Tasks waiting for a worker slot, first in first out; one more is refused. Default 16. */
136
+ maxQueued?: number;
137
+ /**
138
+ * The conversations' modes: with them a worker follows the yolo and long-running modes of the
139
+ * conversation that started it, read live, when an owner other than the host spoke that turn.
140
+ */
141
+ modes?: CodingModes;
142
+ /** The host's autonomy limits for those modes; pass the same values its `autonomy` config sets. */
143
+ autonomy?: CodingAutonomy;
144
+ }
145
+ /** What a coding report keeps of a long run; each is a count of characters or entries, or `Infinity` for no bound. */
146
+ export interface CodingLimits {
147
+ /** Longest worker report, and longest thread report; default 20,000 characters. */
148
+ reportChars?: number;
149
+ /** Held actions listed in the report, the rest counted; default 10. */
150
+ heldEntries?: number;
151
+ /** Longest held-action entry; default 1,000 characters. */
152
+ heldChars?: number;
153
+ }
package/src/i18n/zh-tw.ts CHANGED
@@ -13,4 +13,19 @@ export const ZH_TW: Readonly<Record<string, string>> = {
13
13
  "Give a whole number from 1 to {most}.": "請輸入 1 到 {most} 的整數。",
14
14
  "Up to {max} coding workers now run at once.":
15
15
  "現在同時最多執行 {max} 個程式工作者。",
16
+ Tasks: "任務",
17
+ Cancel: "取消",
18
+ "Running since {at}, started by {who}": "自 {at} 執行中,由 {who} 啟動",
19
+ "Queued (position {position}) since {at}, started by {who}":
20
+ "自 {at} 排隊中(第 {position} 位),由 {who} 啟動",
21
+ "Stop coding task #{id}? Its commits stay on its branch, not merged.":
22
+ "要停止程式任務 #{id} 嗎?它的提交會留在自己的分支上,不會合併。",
23
+ "Drop coding task #{id} from the queue?": "要把程式任務 #{id} 移出佇列嗎?",
24
+ "Coding task #{id} is no longer running or queued.":
25
+ "程式任務 #{id} 已不在執行或排隊中。",
26
+ "Coding task #{id} was dropped from the queue.":
27
+ "程式任務 #{id} 已移出佇列。",
28
+ "Coding task #{id} was stopped; its commits stay on {branch}, not merged.":
29
+ "程式任務 #{id} 已停止;它的提交留在 {branch},沒有合併。",
30
+ "Coding task #{id} was stopped.": "程式任務 #{id} 已停止。",
16
31
  };
package/src/index.ts CHANGED
@@ -42,4 +42,5 @@ export {
42
42
  WORKTREES_DIR,
43
43
  } from "./repo-shelf.ts";
44
44
  export { REPO_TOOLS } from "./repo-tools.ts";
45
+ export type { CancelResult, CodingTask } from "./task-control.ts";
45
46
  export { CodingWorkerFailure } from "./worker-failure.ts";
package/src/repo-tools.ts CHANGED
@@ -5,4 +5,6 @@ export const REPO_TOOLS = [
5
5
  "repo_change_report",
6
6
  "repo_push",
7
7
  "repo_task",
8
+ "repo_task_list",
9
+ "repo_task_cancel",
8
10
  ] as const;
@@ -0,0 +1,91 @@
1
+ import { SYSTEM_PRINCIPAL, type ToolTurn } from "pi-roundtable";
2
+ import type { CodingJob } from "./coding-desk.ts";
3
+
4
+ /** A running or queued coding task, as `CodingDesk.tasks` lists it. */
5
+ export interface CodingTask {
6
+ job: CodingJob;
7
+ status: "running" | "queued";
8
+ /** Its place in the queue, from 1, for a queued task. */
9
+ queuePosition?: number;
10
+ }
11
+ /** What `CodingDesk.cancel` did. */
12
+ export type CancelResult =
13
+ /** The task was queued and is dropped; it never ran. */
14
+ | { status: "dropped"; job: CodingJob }
15
+ /**
16
+ * The worker was stopped. Its commits stay on `branch` in the worktree `dir`, unmerged;
17
+ * `settled` is false when the worker had not settled yet as the answer was given.
18
+ */
19
+ | {
20
+ status: "stopped";
21
+ job: CodingJob;
22
+ branch?: string;
23
+ dir?: string;
24
+ commits: string[];
25
+ settled: boolean;
26
+ }
27
+ /** No running or queued task has that id. */
28
+ | { status: "refused"; reason: string };
29
+
30
+ /** What a cancelled run's report says in place of the worker's own. */
31
+ export function cancelledText(by: string): string {
32
+ return `cancelled by ${by}; the worker was stopped and its commits were not merged into the clone`;
33
+ }
34
+ export function droppedText(by: string): string {
35
+ return `cancelled by ${by} before it ran; nothing ran, so start it again if it is still wanted`;
36
+ }
37
+
38
+ /** Whether the turn may see and cancel the job: an owner speaking sees all, an agent its own. */
39
+ export function mayControl(job: CodingJob, turn: ToolTurn): boolean {
40
+ const { speaker } = turn;
41
+ if (speaker?.tier === "owner" && speaker.principalId !== SYSTEM_PRINCIPAL)
42
+ return true;
43
+ if (turn.agent) return job.agent === turn.agent.name;
44
+ // Outside an agent's turn, the person who started it, never the host's own turns.
45
+ return (
46
+ job.agent === undefined &&
47
+ speaker !== undefined &&
48
+ speaker.principalId !== SYSTEM_PRINCIPAL &&
49
+ job.starter?.speaker.principalId === speaker.principalId
50
+ );
51
+ }
52
+
53
+ /** Who a turn is, for "cancelled by …". */
54
+ export function callerName(turn: ToolTurn): string {
55
+ return (
56
+ turn.speaker?.name ??
57
+ turn.agent?.name ??
58
+ turn.speaker?.principalId ??
59
+ "the host"
60
+ );
61
+ }
62
+
63
+ /** One line for a task in a list. */
64
+ export function taskLine(task: CodingTask): string {
65
+ const { job } = task;
66
+ const who = job.agent ?? job.starter?.speaker.name ?? "the owner";
67
+ const when =
68
+ task.status === "running"
69
+ ? `running since ${job.startedAt.toISOString()}`
70
+ : `queued (position ${task.queuePosition}) since ${(job.queuedAt ?? job.startedAt).toISOString()}`;
71
+ const first = job.task.split("\n", 1)[0]?.slice(0, 200) ?? "";
72
+ return `#${job.id} ${job.repo}, ${when}, started by ${who}: ${first}`;
73
+ }
74
+
75
+ /** The promise's value, or undefined when it takes longer than `ms`. */
76
+ export async function within<T>(
77
+ promise: Promise<T>,
78
+ ms: number,
79
+ ): Promise<T | undefined> {
80
+ let timer: Timer | undefined;
81
+ try {
82
+ return await Promise.race([
83
+ promise,
84
+ new Promise<undefined>((resolve) => {
85
+ timer = setTimeout(resolve, ms);
86
+ }),
87
+ ]);
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
@@ -0,0 +1,123 @@
1
+ import {
2
+ defineTool,
3
+ type ToolContribution,
4
+ type ToolTurn,
5
+ } from "pi-roundtable";
6
+ import { AgentError } from "pi-roundtable/kit";
7
+ import { type TString, Type } from "typebox";
8
+ import type { CodingDesk } from "./coding-desk.ts";
9
+ import type { RepoToolName } from "./coding-options.ts";
10
+ import { callerName, mayControl, taskLine } from "./task-control.ts";
11
+
12
+ /** The repo_task_list answer: the running and queued tasks the turn may see. */
13
+ export function listTasks(
14
+ desk: Pick<CodingDesk, "tasks">,
15
+ turn: ToolTurn,
16
+ repo?: string,
17
+ ): string {
18
+ const lines = desk
19
+ .tasks()
20
+ .filter(
21
+ ({ job }) =>
22
+ (repo === undefined || job.repo === repo) && mayControl(job, turn),
23
+ )
24
+ .map(taskLine);
25
+ return lines.length
26
+ ? lines.join("\n")
27
+ : "No running or queued coding tasks you may see.";
28
+ }
29
+
30
+ /** The repo_task_cancel answer; a task the turn may not see is refused as if unknown. */
31
+ export async function cancelTask(
32
+ desk: Pick<CodingDesk, "tasks" | "cancel">,
33
+ turn: ToolTurn,
34
+ input: { repo: string; id: number; reason?: string },
35
+ ): Promise<string> {
36
+ const task = desk
37
+ .tasks()
38
+ .find(({ job }) => job.id === input.id && job.repo === input.repo);
39
+ if (!task)
40
+ throw new AgentError(
41
+ `No running or queued coding task #${input.id} in ${input.repo}; it may have finished already. repo_task_list shows the tasks.`,
42
+ );
43
+ if (!mayControl(task.job, turn))
44
+ throw new AgentError(
45
+ `Coding task #${input.id} was started by someone else; only they or an owner may cancel it.`,
46
+ );
47
+ const reason = input.reason?.trim();
48
+ const by = `${callerName(turn)}${reason ? ` (${reason.slice(0, 200)})` : ""}`;
49
+ const result = await desk.cancel(input.id, by);
50
+ switch (result.status) {
51
+ case "refused":
52
+ throw new AgentError(result.reason);
53
+ case "dropped":
54
+ return `Dropped coding task #${input.id} in ${input.repo} from the queue; it never ran.`;
55
+ case "stopped": {
56
+ const kept = result.branch
57
+ ? ` Its commits (${result.commits.length}) are kept, not merged, on the branch ${result.branch}${result.dir ? ` in the worktree ${result.dir}` : ""}; inspect, merge or delete them.`
58
+ : " It had not made its worktree yet.";
59
+ const pending = result.settled
60
+ ? ""
61
+ : " The worker is still stopping; its report follows.";
62
+ return `Stopped coding task #${input.id} in ${input.repo}.${kept}${pending}`;
63
+ }
64
+ }
65
+ }
66
+
67
+ /** The repo_task_list and repo_task_cancel tools, worded like the other repository tools. */
68
+ export function taskTools(
69
+ desk: CodingDesk,
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 },
77
+ repoSchema: (tool: RepoToolName) => TString,
78
+ ): ToolContribution[] {
79
+ return [
80
+ defineTool({
81
+ name: "repo_task_list",
82
+ 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
+ ),
87
+ 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
+ ),
97
+ }),
98
+ run: ({ repo }, turn) => refusal(async () => listTasks(desk, turn, repo)),
99
+ }),
100
+ defineTool({
101
+ name: "repo_task_cancel",
102
+ 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
+ ),
107
+ parameters: Type.Object({
108
+ repo: repoSchema("repo_task_cancel"),
109
+ id: Type.Integer({
110
+ minimum: 1,
111
+ ...about("repo_task_cancel", "id", "The task's number, as #N."),
112
+ }),
113
+ reason: Type.Optional(
114
+ Type.String({
115
+ maxLength: 200,
116
+ ...about("repo_task_cancel", "reason", "Why, for its report."),
117
+ }),
118
+ ),
119
+ }),
120
+ run: (input, turn) => refusal(() => cancelTask(desk, turn, input)),
121
+ }),
122
+ ];
123
+ }