pi-roundtable-coding 0.42.0 → 0.44.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/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
  });
@@ -0,0 +1,248 @@
1
+ import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
2
+ import { isAbsolute, join, relative, resolve } from "node:path";
3
+ import { AgentError, scrubDiagnostic } from "pi-roundtable/kit";
4
+ import type { GitRunner } from "./git-run.ts";
5
+ import {
6
+ type Integration,
7
+ type RepoState,
8
+ WORKTREES_DIR,
9
+ type WorkerTree,
10
+ } from "./repo-types.ts";
11
+
12
+ /** The worker worktrees under one shelf: cut from a clone, integrated back, removed. */
13
+ export class WorkerTrees {
14
+ readonly #shelfDir: string;
15
+ readonly #dirOf: (repo: string) => string;
16
+ readonly #runner: GitRunner;
17
+ /** The last change to each clone's worktrees, which the next waits for. */
18
+ readonly #changing = new Map<string, Promise<unknown>>();
19
+
20
+ constructor(
21
+ shelfDir: string,
22
+ dirOf: (repo: string) => string,
23
+ runner: GitRunner,
24
+ ) {
25
+ this.#shelfDir = shelfDir;
26
+ this.#dirOf = dirOf;
27
+ this.#runner = runner;
28
+ }
29
+
30
+ /**
31
+ * Cuts a worktree for coding job `id` from the clone's HEAD, on a fresh branch `worker/<id>`
32
+ * (with a suffix when an earlier run kept one of that name), under `<shelf>/.worktrees/`.
33
+ */
34
+ async add(repo: string, id: number): Promise<WorkerTree> {
35
+ const clone = this.#dirOf(repo);
36
+ const base = await this.#runner.git(clone, "rev-parse", "HEAD");
37
+ const parent = join(this.#shelfDir, WORKTREES_DIR, repo);
38
+ mkdirSync(parent, { recursive: true });
39
+ const rel = relative(realpathSync(this.#shelfDir), realpathSync(parent));
40
+ if (rel.startsWith("..") || isAbsolute(rel))
41
+ throw new AgentError("The worktree folder escapes the shelf.");
42
+ for (let attempt = 1; ; attempt++) {
43
+ const name = attempt === 1 ? `${id}` : `${id}-${attempt}`;
44
+ const branch = `worker/${name}`;
45
+ const dir = join(parent, name);
46
+ const taken =
47
+ existsSync(dir) ||
48
+ (
49
+ await this.#runner.run([
50
+ "git",
51
+ "-C",
52
+ clone,
53
+ "rev-parse",
54
+ "--verify",
55
+ "--quiet",
56
+ `refs/heads/${branch}`,
57
+ ])
58
+ ).code === 0;
59
+ if (taken) continue;
60
+ await this.#alone(clone, () =>
61
+ this.#runner.git(
62
+ clone,
63
+ "worktree",
64
+ "add",
65
+ "--quiet",
66
+ "-b",
67
+ branch,
68
+ dir,
69
+ base,
70
+ ),
71
+ );
72
+ return { repo, dir: realpathSync(dir), branch, base };
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Rebases the worker's branch onto the clone's current HEAD inside its worktree and
78
+ * fast-forwards the clone, then removes the worktree and branch. The clone is never left
79
+ * mid-rebase: a conflict aborts the rebase in the worktree and keeps both. A clone or worktree
80
+ * with uncommitted changes is not touched. The caller serializes integrations of one clone.
81
+ */
82
+ async integrate(tree: WorkerTree): Promise<Integration> {
83
+ const clone = this.#dirOf(tree.repo);
84
+ const kept = { branch: tree.branch, dir: tree.dir };
85
+ const dirty = await this.#runner.git(clone, "status", "--porcelain");
86
+ if (dirty)
87
+ return {
88
+ status: "refused",
89
+ ...kept,
90
+ reason: `the clone has uncommitted changes, so it was left as it is:\n${dirty}`,
91
+ };
92
+ const head = await this.#runner.git(clone, "rev-parse", "HEAD");
93
+ const ahead = Number(
94
+ await this.#runner.git(
95
+ clone,
96
+ "rev-list",
97
+ "--count",
98
+ `${head}..${tree.branch}`,
99
+ ),
100
+ );
101
+ if (ahead === 0) {
102
+ await this.remove(tree);
103
+ return { status: "nothing" };
104
+ }
105
+ const treeDir = this.#treeDir(tree);
106
+ const treeDirty = await this.#runner.git(treeDir, "status", "--porcelain");
107
+ if (treeDirty)
108
+ return {
109
+ status: "refused",
110
+ ...kept,
111
+ reason: `the worker left uncommitted changes in its worktree:\n${treeDirty}`,
112
+ };
113
+ const rebase = await this.#runner.run([
114
+ "git",
115
+ "-C",
116
+ treeDir,
117
+ "rebase",
118
+ "--quiet",
119
+ head,
120
+ ]);
121
+ if (rebase.code !== 0) {
122
+ const conflicted = await this.#runner.run([
123
+ "git",
124
+ "-C",
125
+ treeDir,
126
+ "diff",
127
+ "--name-only",
128
+ "--diff-filter=U",
129
+ ]);
130
+ await this.#runner.run(["git", "-C", treeDir, "rebase", "--abort"]);
131
+ return {
132
+ status: "conflict",
133
+ ...kept,
134
+ files: conflicted.out ? conflicted.out.split("\n") : [],
135
+ };
136
+ }
137
+ const merge = await this.#runner.run([
138
+ "git",
139
+ "-C",
140
+ clone,
141
+ "merge",
142
+ "--ff-only",
143
+ "--quiet",
144
+ tree.branch,
145
+ ]);
146
+ if (merge.code !== 0)
147
+ return {
148
+ status: "refused",
149
+ ...kept,
150
+ reason: `the clone could not fast-forward to the branch: ${scrubDiagnostic(merge.err, this.#runner.diagnosticChars) || `exit ${merge.code}`}`,
151
+ };
152
+ const log = await this.#runner.git(
153
+ clone,
154
+ "log",
155
+ "--format=%h %s",
156
+ "--abbrev=12",
157
+ `${head}..HEAD`,
158
+ );
159
+ await this.remove(tree);
160
+ return {
161
+ status: "merged",
162
+ branch: tree.branch,
163
+ commits: log ? log.split("\n") : [],
164
+ };
165
+ }
166
+
167
+ /** A worker worktree's state, as `state` reads a clone's. */
168
+ async state(tree: WorkerTree): Promise<RepoState> {
169
+ const dir = this.#treeDir(tree);
170
+ const status = await this.#runner.git(dir, "status", "--porcelain");
171
+ return {
172
+ branch: await this.#runner.git(dir, "rev-parse", "--abbrev-ref", "HEAD"),
173
+ head: await this.#runner.git(dir, "rev-parse", "--short=12", "HEAD"),
174
+ uncommitted: status ? status.split("\n") : [],
175
+ };
176
+ }
177
+
178
+ /** `<short sha> <subject>` of each commit on the worker's branch after its base, newest first. */
179
+ async commits(tree: WorkerTree): Promise<string[]> {
180
+ const log = await this.#runner.git(
181
+ this.#treeDir(tree),
182
+ "log",
183
+ "--format=%h %s",
184
+ "--abbrev=12",
185
+ `${tree.base}..HEAD`,
186
+ );
187
+ return log ? log.split("\n") : [];
188
+ }
189
+
190
+ /** Removes a worker's worktree and its branch; what is already gone is skipped. */
191
+ async remove(tree: WorkerTree): Promise<void> {
192
+ const clone = this.#dirOf(tree.repo);
193
+ this.#treeDir(tree, false);
194
+ await this.#alone(clone, async () => {
195
+ await this.#runner.run([
196
+ "git",
197
+ "-C",
198
+ clone,
199
+ "worktree",
200
+ "remove",
201
+ "--force",
202
+ tree.dir,
203
+ ]);
204
+ if (existsSync(tree.dir))
205
+ rmSync(tree.dir, { recursive: true, force: true });
206
+ await this.#runner.run(["git", "-C", clone, "worktree", "prune"]);
207
+ await this.#runner.run([
208
+ "git",
209
+ "-C",
210
+ clone,
211
+ "branch",
212
+ "-D",
213
+ "--quiet",
214
+ tree.branch,
215
+ ]);
216
+ });
217
+ }
218
+
219
+ /**
220
+ * Runs a change to a clone's worktrees after the one before it. Git lists every linked
221
+ * worktree while it adds, removes or prunes one, and fails on a folder another such call is
222
+ * still writing (`failed to read .git/worktrees/1/commondir`), so two workers starting at
223
+ * once, or one starting as another's branch is removed, cannot each go ahead alone.
224
+ */
225
+ async #alone<T>(clone: string, change: () => Promise<T>): Promise<T> {
226
+ const previous = this.#changing.get(clone) ?? Promise.resolve();
227
+ const mine = previous.catch(() => {}).then(change);
228
+ this.#changing.set(clone, mine);
229
+ try {
230
+ return await mine;
231
+ } finally {
232
+ if (this.#changing.get(clone) === mine) this.#changing.delete(clone);
233
+ }
234
+ }
235
+
236
+ /** A worktree path, refused unless it lies in this repository's worktree folder. */
237
+ #treeDir(tree: WorkerTree, mustExist = true): string {
238
+ const parent = resolve(this.#shelfDir, WORKTREES_DIR, tree.repo);
239
+ const path = mustExist ? realpathSync(tree.dir) : resolve(tree.dir);
240
+ const root = existsSync(parent) ? realpathSync(parent) : parent;
241
+ const rel = relative(root, path);
242
+ if (!rel || rel.startsWith("..") || isAbsolute(rel) || rel.includes("/"))
243
+ throw new AgentError(
244
+ "The worktree lies outside the shelf's worktree folder.",
245
+ );
246
+ return path;
247
+ }
248
+ }