next-issue 2.21.2 → 4.0.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.
Files changed (73) hide show
  1. package/README.md +90 -125
  2. package/dist/agent-reply.mjs +13 -0
  3. package/dist/agent-session.mjs +56 -0
  4. package/dist/agents.mjs +47 -88
  5. package/dist/args.mjs +26 -31
  6. package/dist/base-checks.mjs +37 -0
  7. package/dist/budget.mjs +16 -0
  8. package/dist/check-poll.mjs +73 -0
  9. package/dist/checks.mjs +67 -0
  10. package/dist/children.mjs +52 -0
  11. package/dist/cli.mjs +25 -15
  12. package/dist/command-records.mjs +15 -0
  13. package/dist/config-fields.mjs +32 -0
  14. package/dist/config.mjs +36 -71
  15. package/dist/conflict.mjs +43 -42
  16. package/dist/durations.mjs +37 -0
  17. package/dist/enter-review.mjs +13 -0
  18. package/dist/errors.mjs +20 -0
  19. package/dist/exec.mjs +71 -107
  20. package/dist/files.mjs +28 -0
  21. package/dist/fix.mjs +61 -50
  22. package/dist/gate.mjs +31 -43
  23. package/dist/gh.mjs +55 -0
  24. package/dist/git-commit.mjs +36 -0
  25. package/dist/git-land.mjs +30 -0
  26. package/dist/git-merge.mjs +42 -0
  27. package/dist/git.mjs +42 -166
  28. package/dist/github.mjs +31 -388
  29. package/dist/gitignore.mjs +13 -0
  30. package/dist/hand-over-comments.mjs +78 -0
  31. package/dist/handover.mjs +60 -107
  32. package/dist/implement.mjs +32 -0
  33. package/dist/interrupt.mjs +6 -19
  34. package/dist/job.mjs +28 -17
  35. package/dist/labels.mjs +65 -0
  36. package/dist/land.mjs +66 -0
  37. package/dist/lock.mjs +54 -0
  38. package/dist/logs.mjs +84 -62
  39. package/dist/loop.mjs +12 -37
  40. package/dist/observe.mjs +24 -98
  41. package/dist/open-job.mjs +39 -0
  42. package/dist/pending.mjs +46 -0
  43. package/dist/pipeline.mjs +34 -217
  44. package/dist/poll.mjs +20 -0
  45. package/dist/ports.mjs +18 -4
  46. package/dist/progress.mjs +36 -23
  47. package/dist/prompts.mjs +31 -36
  48. package/dist/protocol.mjs +17 -11
  49. package/dist/prune-runs.mjs +33 -0
  50. package/dist/pull-requests.mjs +60 -0
  51. package/dist/questions.mjs +45 -0
  52. package/dist/records.mjs +3 -0
  53. package/dist/render.mjs +19 -0
  54. package/dist/revert.mjs +27 -0
  55. package/dist/review.mjs +63 -83
  56. package/dist/run-logs.mjs +23 -0
  57. package/dist/run.mjs +59 -58
  58. package/dist/serve.mjs +46 -214
  59. package/dist/setup.mjs +2 -5
  60. package/dist/skip.mjs +54 -0
  61. package/dist/state.mjs +27 -39
  62. package/dist/summary.mjs +11 -7
  63. package/dist/text.mjs +15 -0
  64. package/dist/usage.mjs +45 -0
  65. package/dist/verdict.mjs +20 -13
  66. package/dist/watch.mjs +38 -0
  67. package/dist/worker-paths.mjs +16 -0
  68. package/dist/worker-run.mjs +56 -0
  69. package/dist/worker-server.mjs +56 -0
  70. package/dist/worktree-setup.mjs +25 -0
  71. package/dist/worktree.mjs +58 -0
  72. package/package.json +1 -1
  73. package/dist/merge.mjs +0 -75
package/README.md CHANGED
@@ -9,21 +9,21 @@ npx -y next-issue@latest
9
9
 
10
10
  ## Overview
11
11
 
12
- The harness claims the oldest open issue with the `status:todo` label and gives it its own git worktree and branch. An implementer agent does the work, and the harness commits, pushes and opens a draft pull request. It then waits for the checks. A fixer agent repairs a red build, and a reviewer agent judges the diff. The fixer deals with any open finding, and the checks and review run again. With no open finding left, the pull request is marked ready and the issue gets `status:done`. When a budget runs out or the work cannot go on, the issue gets `status:needs-human` and goes to a person. Then the harness takes the next issue.
12
+ The harness claims the oldest open issue with the `status:todo` label and gives it its own git worktree and branch. An implementer agent does the work and the harness commits it. A reviewer agent judges the diff, and a fixer agent deals with any open finding, and the review runs again. With no open finding left, the harness rebases the change onto the base branch as one commit, pushes it there with no pull request and waits for the checks of that commit. The fixer repairs a red build, and the fix lands the same way. When the checks pass, the issue is closed and gets `status:done`. When a budget runs out or the work cannot go on, the issue gets `status:needs-human` and goes to a person. Then the harness takes the next issue.
13
13
 
14
14
  ```mermaid
15
15
  flowchart TD
16
16
  claim[Claim the oldest status:todo issue] --> worktree[Add a worktree and branch]
17
- worktree --> implement[Implementer does the work, harness commits and pushes]
18
- implement --> pr[Open a draft pull request]
19
- pr --> checks{Checks pass?}
20
- checks -- no --> fixCi[Fixer repairs the build]
21
- fixCi --> checks
22
- checks -- yes --> review{Reviewer finds an open finding?}
17
+ worktree --> implement[Implementer does the work, harness commits]
18
+ implement --> review{Reviewer finds an open finding?}
23
19
  review -- yes --> fixReview[Fixer deals with the findings]
24
- fixReview --> checks
25
- review -- no --> done[Mark ready, set status:done]
26
- fixCi -. budget runs out .-> human[Hand over to a person: status:needs-human]
20
+ fixReview --> review
21
+ review -- no --> land[Rebase onto the base branch and push there]
22
+ land --> checks{Checks on the base branch pass?}
23
+ checks -- no --> fixCi[Fixer repairs the build]
24
+ fixCi --> land
25
+ checks -- yes --> done[Close the issue, set status:done]
26
+ fixCi -. budget runs out .-> human[Revert, hand over to a person: status:needs-human]
27
27
  fixReview -. budget runs out .-> human
28
28
  done --> claim
29
29
  human --> claim
@@ -49,7 +49,7 @@ the run handles one issue. For each issue:
49
49
  `status:in-progress` or `status:in-review` label. A `status:done`,
50
50
  `status:needs-human` or `status:blocked` label always stops the claim, a
51
51
  resume too. An issue that GitHub lists as blocked by an open issue waits,
52
- because its blocker closes only when the pull request of the blocker merges.
52
+ because its blocker closes only when the change of the blocker lands.
53
53
  An issue with saved state under `.next-issue/` resumes instead, whatever its
54
54
  other labels and blockers. Such an issue joins the list also when it is
55
55
  closed, if its pull request is merged.
@@ -67,7 +67,8 @@ the run handles one issue. For each issue:
67
67
  base when there is none. A fast-forward of the base that is not safe
68
68
  leaves the local base branch as it is and writes a `base.behind` event. A
69
69
  new branch then starts from the remote base.
70
- 4. Let the implementer agent do the work, then commit and push. When a git
70
+ 4. Let the implementer agent do the work, then commit it. The branch is not
71
+ pushed. When a git
71
72
  hook stops a commit, the agent that made the change gets the hook output,
72
73
  fixes it, and the harness commits again. A `commit:` line in the reply of
73
74
  the agent replaces the subject, so a hook that rejects the subject can pass.
@@ -75,33 +76,8 @@ the run handles one issue. For each issue:
75
76
  the run with an error. An implementer that makes no change hands the issue
76
77
  to a person, unless the branch is already ahead of the base, for example
77
78
  after the state file was lost: the run then carries on with the commits on
78
- the branch, and the newest of them gives the title of the pull request.
79
- 5. Open a draft pull request that closes the issue. Its title is the subject
80
- of the commit that starts it, so a squash merge gives a conventional
81
- commit.
82
- 6. Wait for the checks, once the pull request shows the pushed commit. A
83
- pending state waits again, up to `checkTimeoutMinutes`. A read that fails
84
- is tried three times before the run stops. A watch that exits with an error
85
- while no check failed counts as such a read, not as a red build. A repository that reports no
86
- check keeps asking for `checkGraceSeconds`, because a new pull request often
87
- shows no check yet, and only then goes straight to the review. The later
88
- gates of the same issue ask once. GitHub runs no check on a pull request
89
- that conflicts with its base, so no check and a conflict start a merge of
90
- the remote base into the branch. While GitHub still works out whether the
91
- pull request can merge, the run asks again until `checkTimeoutMinutes`.
92
- When git merges the base cleanly, the harness commits the merge with no
93
- agent. When git reports conflicted files, the fixer gets the list, removes
94
- the conflict markers, and the harness commits the merge. The harness then
95
- pushes without force, and the run goes to step 6 again. The merge commit
96
- runs the `pre-commit` and `commit-msg` hooks like any other commit. When
97
- the branch already holds the base, the harness only pushes. Each attempt
98
- comes from the check budget, `maxCiFixes`. With the budget used up, or when
99
- the fixer leaves a conflict marker or the merge unresolved, or the fixer
100
- fails, the harness undoes the merge and hands the issue to a person with the
101
- reason `merge conflict`.
102
- 7. On a red build, give the failed job logs to the fixer agent, then go to step
103
- 6 again. The budget is `maxCiFixes`.
104
- 8. Let the reviewer agent judge the diff, at most `diffMaxChars` of it. The
79
+ the branch, and the newest of them gives the subject of the landed commit.
80
+ 5. Let the reviewer agent judge the diff, at most `diffMaxChars` of it. The
105
81
  reviewer reads files and runs commands in the worktree, so it can prove a
106
82
  finding with the tests or the type check. The harness then throws away every
107
83
  change that the reviewer left, so no such change can reach a later commit.
@@ -109,41 +85,45 @@ the run handles one issue. For each issue:
109
85
  summary and one entry per finding, each rated `blocking` or `minor`. A
110
86
  reply without a valid block hands the issue to a person. The findings are the only ground
111
87
  truth. The reviewer gives no approve or reject field, because such a field
112
- can contradict the findings. The harness puts the result on the pull
113
- request.
114
- 9. An open finding is any finding, blocking or minor, while a review round is
88
+ can contradict the findings. The harness puts the result on the issue.
89
+ 6. An open finding is any finding, blocking or minor, while a review round is
115
90
  left. In the last round, only a blocking finding stays open: a minor finding
116
- there goes on the pull request but starts no fix, because a fix in the last
91
+ there goes on the issue but starts no fix, because a fix in the last
117
92
  round gets no review. Thus `maxReviewRounds` of `1` never fixes a minor
118
93
  finding.
119
- 10. No open finding means approval: mark the pull request ready for review and
120
- set `status:done`. The merge stays with you, unless you pass `--merge`:
121
- then the harness first asks whether the pull request conflicts with its
122
- base. A conflict starts the merge of the base from step 6, and the run
123
- goes to step 6 again. With no conflict, the harness squash-merges the pull
124
- request, deletes the remote branch, waits until the pull request is merged,
125
- for example through a merge queue, and then waits for the checks that the
126
- merge commit starts on the base branch. A cancelled run there is no
127
- failure. When those checks fail, the fixer gets their logs on a branch
128
- reset to the base branch, from the check budget, and the harness
129
- force-pushes the fix, reopens the issue and opens a new pull request that
130
- goes to step 6 again, with fresh review rounds. The next issue waits for
131
- this, and a second ctrl-c stops only after it. The worktree, the local
132
- branch and the state file go away. A resume whose pull request is already
133
- merged goes straight to the wait for the checks on the base branch, and
134
- opens no new pull request. A resume that stopped inside the fix of the
135
- base branch carries on with that fix, and uses no more of the check
136
- budget. Without `--merge`, the remote branch stays, and a resume whose
137
- pull request a person merged sets `status:done` and waits for no check. A
138
- problem that the reviewer leaves out of the findings thus gets an
139
- approval: only the findings count.
140
- 11. With an open finding, run the fixer agent and go to step 6 again. The
141
- budget is `maxReviewRounds`. A fixer that holds every finding to be wrong
142
- changes nothing and gives its reason instead. The reason goes on the pull
143
- request and into the next round, where it answers every finding of its own
144
- round, so the reviewer withdraws them all or repeats them all. With only
145
- some findings wrong, the fixer fixes the correct ones, and the next round
146
- holds the rest.
94
+ 7. No open finding means approval: the change lands on the base branch.
95
+ Approved changes land one at a time, so the next one waits until the
96
+ checks of the last one end, and other issues go on meanwhile. The
97
+ harness fetches the remote base, merges it into the branch and makes the
98
+ change one commit on top of it, with the subject of the newest commit of
99
+ the change. When git merges the base cleanly, no agent runs. When git
100
+ reports conflicted files, the fixer gets the list from the check budget,
101
+ `maxCiFixes`, removes the conflict markers, and the harness commits the
102
+ merge. With the budget used up, or when the fixer leaves a conflict marker
103
+ or the merge unresolved, or the fixer fails, the harness undoes the merge
104
+ and hands the issue to a person with the reason `merge conflict`. The
105
+ harness then pushes the commit to the base branch, without force. A push
106
+ that the remote refuses, for example because the base moved, starts the
107
+ rebase again, three times at most. The harness then waits for the checks
108
+ of the pushed commit on the base branch. A repository that reports no
109
+ check keeps asking for `checkGraceSeconds`. A pending state waits again,
110
+ up to `checkTimeoutMinutes`. A read that fails is tried three times. When
111
+ the checks pass, the harness closes the issue and sets `status:done`, and
112
+ the worktree, the local branch and the state file go away. When the checks
113
+ fail, the fixer gets their logs from the check budget, and its fix lands
114
+ the same way. When the fixer cannot fix them, its fix cannot land, or the
115
+ budget runs out, the harness reverts every commit of the change on the
116
+ base branch, pushes the revert and hands the issue to a person. A resume
117
+ that stopped while the checks of a landed commit ran waits for them
118
+ again, and a fix that was committed but not landed lands first. A problem that the reviewer leaves
119
+ out of the findings thus gets an approval: only the findings count.
120
+ 8. With an open finding, run the fixer agent and go to step 5 again. The
121
+ budget is `maxReviewRounds`. A fixer that holds every finding to be wrong
122
+ changes nothing and gives its reason instead. The reason goes on the issue
123
+ and into the next round, where it answers every finding of its own
124
+ round, so the reviewer withdraws them all or repeats them all. With only
125
+ some findings wrong, the fixer fixes the correct ones, and the next round
126
+ holds the rest.
147
127
 
148
128
  ## Issue format
149
129
 
@@ -160,8 +140,7 @@ The list lives in `src/issue-format.mts`. The `create-issue` skill of [`@ravshan
160
140
  ## Stops for a loop
161
141
 
162
142
  The harness hands the issue to a person, with the `status:needs-human` label,
163
- and comments the reason on the pull request, or on the issue when there is no
164
- pull request yet, when:
143
+ and comments the reason on the issue, when:
165
144
 
166
145
  - the check budget or the review budget runs out. A finding that the reviewer
167
146
  repeats, even one that the fixer disputed, goes back to the fixer until the
@@ -169,31 +148,23 @@ pull request yet, when:
169
148
  - a fixer round adds no commit and gives no reason, so there is no progress;
170
149
  - the fixer reports that the checks fail for a reason the change did not cause,
171
150
  such as a test already broken on the base branch or one that fails only under
172
- load. It changes nothing and the reason reaches the pull request, rather than
151
+ load. It changes nothing and the reason reaches the issue, rather than
173
152
  the fixer spending its whole budget on a failure it cannot fix. A commit it
174
153
  makes anyway moves aside, as for a dispute of the findings;
175
154
  - a fixer disputes the findings and leaves a change behind, either in the
176
155
  worktree or in a commit of its own. A dispute carries a reason, not a diff,
177
156
  so the harness throws none of it away: an unclean worktree stays on the
178
157
  disk, and a commit of the fixer moves to a new local
179
- `<n>-dispute-<commit>` branch, so the `<n>` branch keeps only what the pull
180
- request holds. The worktree drops the change of that commit, unless the fixer
158
+ `<n>-dispute-<commit>` branch, so the `<n>` branch keeps only what will land. The worktree drops the change of that commit, unless the fixer
181
159
  edited the worktree after the commit: then the worktree keeps both and stays
182
- on the disk. Neither is pushed, so the pull request shows no such change. It
183
- holds the reason of the dispute, and the change is on the machine that ran
160
+ on the disk. Neither lands. The issue holds the reason of the dispute, and the change is on the machine that ran
184
161
  the harness. The `<n>-dispute-<commit>` branches go away with the `<n>`
185
162
  branch when the issue is done;
186
163
  - the reviewer gives no verdict, or the checks do not finish in time;
187
- - someone pushes to the pull request while the harness waits for the checks,
188
- so the pull request no longer shows the commit that the harness pushed;
189
- - with `--merge`, the merge of an approved pull request fails, for example
190
- because branch protection asks for a human approval;
191
- - with `--merge`, a queued merge does not finish in `checkTimeoutMinutes`, or
192
- the pull request closes without a merge;
193
- - with `--merge`, the checks on the base branch fail after the merge and the
194
- fixer cannot fix them, or they do not finish in time. The base branch is
195
- then broken, so the run claims no new issue and ends once the running
196
- issues end;
164
+ - the push to the base branch fails three times;
165
+ - the checks on the base branch fail and the fixer cannot fix them, or they
166
+ do not finish in time. The base branch is then broken, so the run claims
167
+ no new issue and ends once the running issues end;
197
168
  - an agent does not finish in `agentTimeoutMinutes`;
198
169
  - the setup command fails, or does not finish in `setupTimeoutMinutes`;
199
170
  - a step of the run fails with an error. A `gh` call that is safe to repeat,
@@ -205,12 +176,13 @@ The fixer sees the findings of all earlier rounds, not only the last one, with
205
176
  its own disputes next to them. From round two, the reviewer judges only the
206
177
  earlier findings and any regression.
207
178
 
208
- Each agent that writes to the pull request names itself in the first line of the
179
+ Each agent that writes to the issue names itself in the first line of the
209
180
  comment: `### Review: approved`, `### Review: changes requested` and
210
181
  `### Fixer: no change`. The account is the same for all of them, so the heading,
211
- not the author, tells them apart. The agents read the comments of the issue, not
212
- of the pull request, so a comment of an agent never returns to a prompt: the
213
- dispute of the fixer reaches the reviewer through the state file. The one
182
+ not the author, tells them apart. The agents get no comment that starts with
183
+ one of these headings or with `next-issue needs help:`, so a comment of an
184
+ agent never returns to a prompt: the dispute of the fixer reaches the reviewer
185
+ through the state file. The one
214
186
  exception is the answer to a hand-over, see
215
187
  [Retry an issue that waits for a person](#retry-an-issue-that-waits-for-a-person).
216
188
 
@@ -221,8 +193,8 @@ Press `Ctrl-C` to stop the run step by step:
221
193
  1. The first press stops new claims. The harness finishes every issue that it
222
194
  holds and then writes the summary as usual.
223
195
  2. The second press stops every running issue after its current round: the
224
- implementation, one checks round (wait, then fix) or one review round
225
- (review, then fix). The issue ends as `stopped`. Its state, worktree and
196
+ implementation or one review round (review, then fix). An issue that
197
+ lands goes on until its checks on the base branch end. The issue ends as `stopped`. Its state, worktree and
226
198
  labels stay, so the next run carries on from that point.
227
199
  3. The third press stops every agent, kills the command that runs and every
228
200
  child of it, so the run dies in the middle of a step. The saved state lets the next run continue the
@@ -233,12 +205,6 @@ Each of the first two presses prints a line that says what happens next. The
233
205
  agents run inside the harness, and their commands and the harness commands run
234
206
  in a process group of their own, so a press reaches only the harness.
235
207
 
236
- A status label that the harness puts on the issue goes on the pull request too,
237
- but only if the pull request exists at that moment. The `status:in-progress`
238
- label of a fresh issue comes before the pull request, and stays on the issue
239
- alone. Thus a draft pull request shows work that the harness has not finished,
240
- and a `status:needs-human` pull request shows work that waits for a person.
241
-
242
208
  The harness runs all git and `gh` commands itself. The commit holds all the
243
209
  changes in the worktree, so a setup command that writes a file outside
244
210
  `.gitignore` puts that file in the commit. The reviewer is the one agent whose
@@ -442,13 +408,12 @@ silent skip.
442
408
 
443
409
  A hand-over marks the state file as handed over. To give the issue another try,
444
410
  take the `status:needs-human` label off. The next run that claims the issue puts
445
- the budgets and the findings back to zero, clears the mark and keeps the branch,
446
- the pull request and the step that the last run reached, so the work carries on
447
- where it stopped. A commit that you pushed to the pull request in the meantime
448
- is fetched first. An issue that still has the label is not claimed.
411
+ the budgets and the findings back to zero, clears the mark and keeps the branch
412
+ and the step that the last run reached, so the work carries on where it
413
+ stopped. After a revert, the branch holds the change again on top of the
414
+ revert, so the change goes back to the review. An issue that still has the label is not claimed.
449
415
 
450
- To give guidance, answer the hand-over with a comment in the same place: on the
451
- pull request, or on the issue when there is no pull request. When the run
416
+ To give guidance, answer the hand-over with a comment on the issue. When the run
452
417
  resumes the issue, it reads the comments posted after its last
453
418
  `next-issue needs help:` comment there. Only comments from users with write
454
419
  access to the repository count, for the hand-over comment too. The implementer
@@ -462,22 +427,22 @@ state of an issue that a label still holds back stays as it was.
462
427
 
463
428
  ## Commands and options
464
429
 
465
- | Argument | Effect |
466
- | ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
467
- | `init` | Write the config file with the defaults |
468
- | `serve` | Run the worker of this repository that pi extensions talk to, see [Worker](#worker) |
469
- | `stop` | Stop the worker of this repository, see [Worker](#worker) |
470
- | `logs` | Show the latest run log and follow it, see [Observability](#observability) |
471
- | `--force` | Replace an existing config file, with `init` |
472
- | `--once` | Stop after the first handled issue |
473
- | `--max <n>` | Handle at most n issues |
474
- | `--merge` | Squash-merge the pull request after the approval, delete the remote branch and fix a failure of the checks on the base branch |
475
- | `--watch` | Keep running, and read the open issues again after each pass |
476
- | `--reset` | Drop the saved budgets and findings, and keep the rest of the state |
477
- | `--json` | Print the machine summary instead of the text one, or the raw JSON lines with `logs` |
478
- | `--verbose` | Show every command and all agent output |
479
- | `--quiet` | Show only the milestones and the summary |
480
- | `--help` | Show the option list |
430
+ | Argument | Effect |
431
+ | ----------- | ------------------------------------------------------------------------------------ |
432
+ | `init` | Write the config file with the defaults |
433
+ | `serve` | Run the worker of this repository that pi extensions talk to, see [Worker](#worker) |
434
+ | `stop` | Stop the worker of this repository, see [Worker](#worker) |
435
+ | `logs` | Show the latest run log and follow it, see [Observability](#observability) |
436
+ | `--force` | Replace an existing config file, with `init` |
437
+ | `--once` | Stop after the first handled issue |
438
+ | `--max <n>` | Handle at most n issues |
439
+ | `--merge` | No effect: an approved change always lands on the base branch |
440
+ | `--watch` | Keep running, and read the open issues again after each pass |
441
+ | `--reset` | Drop the saved budgets and findings, and keep the rest of the state |
442
+ | `--json` | Print the machine summary instead of the text one, or the raw JSON lines with `logs` |
443
+ | `--verbose` | Show every command and all agent output |
444
+ | `--quiet` | Show only the milestones and the summary |
445
+ | `--help` | Show the option list |
481
446
 
482
447
  The exit code is 1 when an issue needs a person or failed, and 0 when it does
483
448
  not, so a cron job or a CI step can read the result of the run.
@@ -506,8 +471,8 @@ The watch stops:
506
471
 
507
472
  - at the first `Ctrl-C` during a wait, at once;
508
473
  - at the first `Ctrl-C` during an issue, after the running issues;
509
- - after a pass that halts the run, for example when the base branch is broken
510
- after `--merge`;
474
+ - after a pass that halts the run, for example when the checks on the base
475
+ branch failed;
511
476
  - when the open issues cannot be read.
512
477
 
513
478
  ## Worker
@@ -532,7 +497,7 @@ of one repository never affect another. The worker:
532
497
  - sends every client a `questions` message for each repository: the open
533
498
  issues with the `needsHuman` label, each with its number, title, the reason
534
499
  of the hand-over, the url of the comment that holds it, the `owner/name`
535
- repository, the pull request when there is one, and the `needsHuman` and
500
+ repository, and the `needsHuman` and
536
501
  `skip` labels. It reads them
537
502
  from GitHub, so the list is the same after a restart. It sends them when a
538
503
  client connects, for its repository, after each issue of a run
@@ -0,0 +1,13 @@
1
+ function lastMatch(text, pattern) {
2
+ return [...text.matchAll(pattern)].at(-1)?.[1]?.trim();
3
+ }
4
+ export function parseUnrelated(text) {
5
+ const note = lastMatch(text, /^unrelated:\s*(.+)$/gim);
6
+ return note === '' ? undefined : note;
7
+ }
8
+ export function parseCommitSubject(text, fallback) {
9
+ const subject = lastMatch(text, /^commit:\s*(.+)$/gim)
10
+ ?.replace(/^`+|`+$/g, '')
11
+ .trim();
12
+ return subject || fallback;
13
+ }
@@ -0,0 +1,56 @@
1
+ import { join, sep } from 'node:path';
2
+ import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, } from '@earendil-works/pi-coding-agent';
3
+ export function isOwnResource(path) {
4
+ return path.split(sep).includes('pi-next-issue');
5
+ }
6
+ export async function openSession(recorder, log, request, agentDir) {
7
+ const runtime = request.runtime ?? {};
8
+ const resourceLoader = await loadResources(request.cwd, agentDir);
9
+ const modelRuntime = runtime.modelRuntime ??
10
+ (await ModelRuntime.create({
11
+ authPath: join(agentDir, 'auth.json'),
12
+ modelsPath: join(agentDir, 'models.json'),
13
+ }));
14
+ const model = request.model === undefined ? undefined : await findModel(modelRuntime, request.model);
15
+ const { session, modelFallbackMessage } = await createAgentSession({
16
+ cwd: request.cwd,
17
+ agentDir,
18
+ resourceLoader,
19
+ sessionManager: SessionManager.create(request.cwd, recorder.sessionDir),
20
+ tools: request.profile.tools,
21
+ modelRuntime,
22
+ ...(runtime.settingsManager === undefined ? {} : { settingsManager: runtime.settingsManager }),
23
+ ...(model === undefined ? {} : { model }),
24
+ });
25
+ if (modelFallbackMessage !== undefined) {
26
+ log.event('agent.model', { note: modelFallbackMessage }, 'quiet');
27
+ }
28
+ return session;
29
+ }
30
+ async function loadResources(cwd, agentDir) {
31
+ const resourceLoader = new DefaultResourceLoader({
32
+ cwd,
33
+ agentDir,
34
+ extensionsOverride: (base) => ({
35
+ ...base,
36
+ extensions: base.extensions.filter((extension) => !isOwnResource(extension.resolvedPath)),
37
+ }),
38
+ skillsOverride: (base) => ({
39
+ ...base,
40
+ skills: base.skills.filter((skill) => !isOwnResource(skill.filePath)),
41
+ }),
42
+ });
43
+ await resourceLoader.reload();
44
+ return resourceLoader;
45
+ }
46
+ async function findModel(modelRuntime, name) {
47
+ const slash = name.indexOf('/');
48
+ if (slash <= 0) {
49
+ throw new Error(`The model ${name} is not in the form provider/model.`);
50
+ }
51
+ const found = modelRuntime.getModel(name.slice(0, slash), name.slice(slash + 1));
52
+ if (found === undefined) {
53
+ throw new Error(`The model ${name} is not known to pi.`);
54
+ }
55
+ return found;
56
+ }
package/dist/agents.mjs CHANGED
@@ -1,114 +1,73 @@
1
- import { join, sep } from 'node:path';
2
- import { createAgentSession, DefaultResourceLoader, getAgentDir, ModelRuntime, SessionManager, } from '@earendil-works/pi-coding-agent';
3
- import { onStop } from './exec.mjs';
4
- import { emptyUsage } from './observe.mjs';
5
- const REVIEWING = {
1
+ import { getAgentDir, } from '@earendil-works/pi-coding-agent';
2
+ import { openSession } from './agent-session.mjs';
3
+ import { onStop } from './children.mjs';
4
+ import { deadline, elapsedMs } from './durations.mjs';
5
+ import { isRecord } from './records.mjs';
6
+ import { emptyUsage } from './usage.mjs';
7
+ export const REVIEWING = {
6
8
  tools: ['+grep', '+find', '+ls', '-edit', '-write'],
7
9
  };
8
- const CODING = {
10
+ export const CODING = {
9
11
  tools: ['+grep', '+find', '+ls'],
10
12
  };
11
- export { CODING, REVIEWING };
12
- export function isOwnResource(path) {
13
- return path.split(sep).includes('pi-next-issue');
14
- }
15
13
  export async function runAgent(recorder, request) {
16
14
  const log = recorder.scope({ role: request.name });
17
- const runtime = request.runtime ?? {};
18
- const agentDir = runtime.agentDir ?? getAgentDir();
15
+ const agentDir = request.runtime?.agentDir ?? getAgentDir();
19
16
  const started = Date.now();
20
17
  process.env.GIT_OPTIONAL_LOCKS = '0';
21
- log.event('agent.start', { model: request.model, timeoutMs: request.timeoutMs }, 'normal');
22
- const resourceLoader = new DefaultResourceLoader({
23
- cwd: request.cwd,
24
- agentDir,
25
- extensionsOverride: (base) => ({
26
- ...base,
27
- extensions: base.extensions.filter((extension) => !isOwnResource(extension.resolvedPath)),
28
- }),
29
- skillsOverride: (base) => ({
30
- ...base,
31
- skills: base.skills.filter((skill) => !isOwnResource(skill.filePath)),
32
- }),
33
- });
34
- await resourceLoader.reload();
35
- const modelRuntime = runtime.modelRuntime ??
36
- (await ModelRuntime.create({
37
- authPath: join(agentDir, 'auth.json'),
38
- modelsPath: join(agentDir, 'models.json'),
39
- }));
40
- const model = request.model === undefined ? undefined : await findModel(modelRuntime, request.model);
41
- const { session, modelFallbackMessage } = await createAgentSession({
42
- cwd: request.cwd,
43
- agentDir,
44
- resourceLoader,
45
- sessionManager: SessionManager.create(request.cwd, recorder.sessionDir),
46
- tools: request.profile.tools,
47
- modelRuntime,
48
- ...(runtime.settingsManager === undefined ? {} : { settingsManager: runtime.settingsManager }),
49
- ...(model === undefined ? {} : { model }),
50
- });
51
- if (modelFallbackMessage !== undefined) {
52
- log.event('agent.model', { note: modelFallbackMessage }, 'quiet');
53
- }
54
- let timedOut = false;
55
- const timer = request.timeoutMs === undefined
56
- ? undefined
57
- : setTimeout(() => {
58
- timedOut = true;
59
- void session.abort();
60
- }, request.timeoutMs);
18
+ log.event('agent.start', { model: request.model, timeoutMs: request.timeoutMs });
19
+ const session = await openSession(recorder, log, request, agentDir);
20
+ const timer = deadline(request.timeoutMs, () => void session.abort());
61
21
  const unsubscribe = session.subscribe((event) => observe(log, event));
62
22
  const release = onStop(() => void session.abort());
63
23
  try {
64
24
  await session.bindExtensions({});
65
25
  await session.prompt(request.prompt, { expandPromptTemplates: false });
66
- if (timedOut) {
26
+ if (timer.timedOut()) {
67
27
  throw new Error(`The ${request.name} agent did not finish in ${request.timeoutMs} ms.`);
68
28
  }
69
- const last = session.messages.findLast((message) => message.role === 'assistant');
70
- if (last !== undefined && 'stopReason' in last && last.stopReason === 'error') {
71
- throw new Error(`The ${request.name} agent failed: ${last.errorMessage ?? 'no reason given'}`);
29
+ const failure = lastFailure(session);
30
+ if (failure !== undefined) {
31
+ throw new Error(`The ${request.name} agent failed: ${failure}`);
72
32
  }
73
- const stats = session.getSessionStats();
74
- const usage = { ...emptyUsage(), ...stats.tokens };
75
- const name = session.model === undefined ? undefined : `${session.model.provider}/${session.model.id}`;
76
- const ms = Date.now() - started;
77
- recorder.usage(request.name, usage, ms, {
78
- turns: stats.assistantMessages,
79
- toolCalls: stats.toolCalls,
80
- model: name,
81
- session: stats.sessionId,
82
- costUsd: stats.cost,
83
- });
84
- return {
85
- text: (session.getLastAssistantText() ?? '').trim(),
86
- usage,
87
- turns: stats.assistantMessages,
88
- toolCalls: stats.toolCalls,
89
- ms,
90
- costUsd: stats.cost,
91
- model: name,
92
- sessionId: stats.sessionId,
93
- };
33
+ return sessionResult(recorder, request, session, started);
94
34
  }
95
35
  finally {
96
- clearTimeout(timer);
36
+ timer.clear();
97
37
  release();
98
38
  unsubscribe();
99
39
  session.dispose();
100
40
  }
101
41
  }
102
- async function findModel(modelRuntime, name) {
103
- const slash = name.indexOf('/');
104
- if (slash <= 0) {
105
- throw new Error(`The model ${name} is not in the form provider/model.`);
42
+ function lastFailure(session) {
43
+ const last = session.messages.findLast((message) => message.role === 'assistant');
44
+ if (last === undefined || !('stopReason' in last) || last.stopReason !== 'error') {
45
+ return undefined;
106
46
  }
107
- const found = modelRuntime.getModel(name.slice(0, slash), name.slice(slash + 1));
108
- if (found === undefined) {
109
- throw new Error(`The model ${name} is not known to pi.`);
110
- }
111
- return found;
47
+ return last.errorMessage ?? 'no reason given';
48
+ }
49
+ function sessionResult(recorder, request, session, started) {
50
+ const stats = session.getSessionStats();
51
+ const usage = { ...emptyUsage(), ...stats.tokens };
52
+ const name = session.model === undefined ? undefined : `${session.model.provider}/${session.model.id}`;
53
+ const ms = elapsedMs(started);
54
+ recorder.usage(request.name, usage, ms, {
55
+ turns: stats.assistantMessages,
56
+ toolCalls: stats.toolCalls,
57
+ model: name,
58
+ session: stats.sessionId,
59
+ costUsd: stats.cost,
60
+ });
61
+ return {
62
+ text: (session.getLastAssistantText() ?? '').trim(),
63
+ usage,
64
+ turns: stats.assistantMessages,
65
+ toolCalls: stats.toolCalls,
66
+ ms,
67
+ costUsd: stats.cost,
68
+ model: name,
69
+ sessionId: stats.sessionId,
70
+ };
112
71
  }
113
72
  function observe(log, event) {
114
73
  if (event.type === 'tool_execution_start') {
@@ -124,7 +83,7 @@ function observe(log, event) {
124
83
  }
125
84
  }
126
85
  export function toolFields(name, input) {
127
- if (name !== 'bash' || typeof input !== 'object' || input === null) {
86
+ if (name !== 'bash' || !isRecord(input)) {
128
87
  return { tool: name };
129
88
  }
130
89
  const { command } = input;