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/git-run.ts ADDED
@@ -0,0 +1,120 @@
1
+ import {
2
+ AgentError,
3
+ checkRepoName,
4
+ childEnv,
5
+ scrubDiagnostic,
6
+ } from "pi-roundtable/kit";
7
+ import type { CloneCommand } from "./repo-types.ts";
8
+
9
+ const GIT_TIMEOUT_MS = 60_000;
10
+
11
+ /**
12
+ * Host variables git and gh need besides the shell's: their config files and homes, the identity a
13
+ * rebase commits as, ssh agent and ssh command, and gh's host; never a token, which comes from
14
+ * `githubToken`.
15
+ */
16
+ const GIT_ENV_NAMES = [
17
+ "XDG_CONFIG_HOME",
18
+ "GIT_CONFIG_GLOBAL",
19
+ "GIT_CONFIG_SYSTEM",
20
+ "GIT_CONFIG_NOSYSTEM",
21
+ "GIT_AUTHOR_NAME",
22
+ "GIT_AUTHOR_EMAIL",
23
+ "GIT_COMMITTER_NAME",
24
+ "GIT_COMMITTER_EMAIL",
25
+ "GH_CONFIG_DIR",
26
+ "GH_HOST",
27
+ "SSH_AUTH_SOCK",
28
+ "GIT_SSH",
29
+ "GIT_SSH_COMMAND",
30
+ ];
31
+
32
+ /** The environment of a git or gh call: the shell's whitelist, git's own names, and the token as GH_TOKEN. */
33
+ function gitEnv(token: string | undefined): Record<string, string> {
34
+ return childEnv(process.env, {
35
+ pass: GIT_ENV_NAMES,
36
+ ...(token ? { set: { GH_TOKEN: token } } : {}),
37
+ });
38
+ }
39
+
40
+ async function run(
41
+ command: string[],
42
+ cwd: string | undefined,
43
+ env: Record<string, string>,
44
+ ): Promise<{ out: string; err: string; code: number }> {
45
+ const safeCommand =
46
+ command[0] === "git"
47
+ ? [
48
+ "git",
49
+ "-c",
50
+ "core.fsmonitor=false",
51
+ "-c",
52
+ "core.hooksPath=/dev/null",
53
+ ...command.slice(1),
54
+ ]
55
+ : command;
56
+ const child = Bun.spawn(safeCommand, {
57
+ ...(cwd ? { cwd } : {}),
58
+ env,
59
+ stdout: "pipe",
60
+ stderr: "pipe",
61
+ timeout: GIT_TIMEOUT_MS,
62
+ });
63
+ const [out, err, code] = await Promise.all([
64
+ new Response(child.stdout).text(),
65
+ new Response(child.stderr).text(),
66
+ child.exited,
67
+ ]);
68
+ return { out: out.trimEnd(), err: err.trim(), code };
69
+ }
70
+
71
+ /**
72
+ * Clones with gh, which authenticates with `token` as GH_TOKEN (default the host's GH_TOKEN, read
73
+ * at each clone) or its own login; a failure's stderr is cut at `diagnosticChars`.
74
+ */
75
+ export const ghCloneWith =
76
+ (diagnosticChars?: number, token?: () => string | undefined): CloneCommand =>
77
+ async (repo, dir) => {
78
+ checkRepoName(repo);
79
+ if (repo.startsWith("-"))
80
+ throw new AgentError("Repository owner cannot start with a dash.");
81
+ const { err, code } = await run(
82
+ ["gh", "repo", "clone", repo, dir, "--", "--quiet"],
83
+ undefined,
84
+ gitEnv(token ? token() : process.env.GH_TOKEN),
85
+ );
86
+ if (code !== 0)
87
+ throw new AgentError(
88
+ `Cloning ${repo} failed: ${scrubDiagnostic(err, diagnosticChars) || `exit ${code}`}`,
89
+ );
90
+ };
91
+ export const ghClone: CloneCommand = ghCloneWith();
92
+
93
+ /** Git and gh calls that carry the shelf's token and no other host secret. */
94
+ export class GitRunner {
95
+ readonly #token: () => string | undefined;
96
+ readonly diagnosticChars: number | undefined;
97
+
98
+ constructor(token: () => string | undefined, diagnosticChars?: number) {
99
+ this.#token = token;
100
+ this.diagnosticChars = diagnosticChars;
101
+ }
102
+
103
+ /** A git or gh call with the shelf's token and no other host secret. */
104
+ run(
105
+ command: string[],
106
+ cwd?: string,
107
+ ): Promise<{ out: string; err: string; code: number }> {
108
+ return run(command, cwd, gitEnv(this.#token()));
109
+ }
110
+
111
+ /** `git -C dir <args>`, its stdout; a failure throws with the scrubbed stderr. */
112
+ async git(dir: string, ...args: string[]): Promise<string> {
113
+ const { out, err, code } = await this.run(["git", "-C", dir, ...args]);
114
+ if (code !== 0)
115
+ throw new AgentError(
116
+ `git ${args[0]} failed in ${dir}: ${scrubDiagnostic(err, this.diagnosticChars) || `exit ${code}`}`,
117
+ );
118
+ return out;
119
+ }
120
+ }
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
+ }
@@ -0,0 +1,72 @@
1
+ import {
2
+ closeSync,
3
+ constants,
4
+ fstatSync,
5
+ lstatSync,
6
+ openSync,
7
+ readdirSync,
8
+ readSync,
9
+ } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ const MAX_SUMMARY_CHARS = 120;
13
+ const MAX_METADATA_BYTES = 65_536;
14
+
15
+ /** Metadata discovery never follows links or opens devices/FIFOs; each file is bounded. */
16
+ function metadataText(path: string): string | undefined {
17
+ let fd: number | undefined;
18
+ try {
19
+ if (!lstatSync(path).isFile()) return undefined;
20
+ fd = openSync(
21
+ path,
22
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
23
+ );
24
+ if (!fstatSync(fd).isFile()) return undefined;
25
+ const bytes = Buffer.alloc(MAX_METADATA_BYTES);
26
+ const count = readSync(fd, bytes, 0, bytes.length, 0);
27
+ return bytes.subarray(0, count).toString("utf8");
28
+ } catch {
29
+ return undefined;
30
+ } finally {
31
+ if (fd !== undefined) closeSync(fd);
32
+ }
33
+ }
34
+
35
+ /** The first prose line of a README or AGENTS.md: no frontmatter, heading, badge, or markup. */
36
+ export function summaryOf(dir: string): string | undefined {
37
+ for (const name of ["README.md", "AGENTS.md"]) {
38
+ const file = join(dir, name);
39
+ const content = metadataText(file);
40
+ if (!content) continue;
41
+ const text = content.replace(/^---\n[\s\S]*?\n---\n/, "");
42
+ const line = text
43
+ .split("\n")
44
+ .map((l) => l.trim())
45
+ .find((l) => /\p{L}/u.test(l) && !/^([#!<>|`[\-*=]|\d+\.)/.test(l));
46
+ if (line)
47
+ return line.length > MAX_SUMMARY_CHARS
48
+ ? `${line.slice(0, MAX_SUMMARY_CHARS - 1)}…`
49
+ : line;
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ export function ciOnPush(dir: string): boolean {
55
+ const workflows = join(dir, ".github", "workflows");
56
+ try {
57
+ if (
58
+ !lstatSync(join(dir, ".github")).isDirectory() ||
59
+ !lstatSync(workflows).isDirectory()
60
+ )
61
+ return false;
62
+ return readdirSync(workflows)
63
+ .filter((name) => /\.ya?ml$/.test(name))
64
+ .some((name) =>
65
+ /^\s*(on:\s*\[?[^\n]*\bpush\b|push\s*:)/m.test(
66
+ metadataText(join(workflows, name)) ?? "",
67
+ ),
68
+ );
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
@@ -0,0 +1,16 @@
1
+ import type { ChangeReport } from "./repo-types.ts";
2
+
3
+ /** The report as posted for the owner. */
4
+ export function reportPost(report: ChangeReport, direct = false): string {
5
+ return [
6
+ `**Change report**: \`${report.repo}\`, commit \`${report.sha}\`, default branch \`${report.branch}\`.`,
7
+ `**Push destination**: \`${report.target}\``,
8
+ `**Commits (${report.commits.length})**`,
9
+ ...report.commits.map((c) => `- \`${c.slice(0, 12)}\`${c.slice(12)}`),
10
+ "**Changed files**",
11
+ `\`\`\`\n${report.diffstat}\n\`\`\``,
12
+ direct
13
+ ? "This repository is explicitly owner-owned; repo_push does not need an approval card."
14
+ : `After approval: repo_push ${report.repo} ${report.sha}`,
15
+ ].join("\n");
16
+ }