next-issue 12.5.10 → 13.1.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/README.md +10 -9
- package/dist/agents.mjs +158 -89
- package/dist/prompts.mjs +3 -3
- package/dist/serve.mjs +47 -8
- package/dist/worker-server.mjs +20 -0
- package/package.json +4 -5
- package/dist/agent-session.mjs +0 -59
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# next-issue
|
|
2
2
|
|
|
3
|
-
A small harness that works through the open issues of a GitHub repository with the [
|
|
3
|
+
A small harness that works through the open issues of a GitHub repository with the [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview). Run it inside a git repository.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
npx -y next-issue@latest start
|
|
@@ -73,7 +73,7 @@ The implementer and the fixer get these rules in their prompt, and the first rev
|
|
|
73
73
|
- reuse existing code and patterns, stay consistent with the repository and pick the simpler option;
|
|
74
74
|
- check an API, a command or a url in the repository or its dependencies before using it, and invent none.
|
|
75
75
|
|
|
76
|
-
The reviewer rates a missing documentation update or a test that is not observable as a finding. In every round, it gives the file and line, or the command output, that supports each finding. Personal style rules, such as spelling, code comments or binding names, belong in the `
|
|
76
|
+
The reviewer rates a missing documentation update or a test that is not observable as a finding. In every round, it gives the file and line, or the command output, that supports each finding. Personal style rules, such as spelling, code comments or binding names, belong in the `CLAUDE.md` of each repository.
|
|
77
77
|
|
|
78
78
|
## Stops for a loop
|
|
79
79
|
|
|
@@ -139,13 +139,13 @@ Every run has an id, `<timestamp>`, and writes these under `.next-issue/runs/`:
|
|
|
139
139
|
|
|
140
140
|
- `<id>.jsonl` — one JSON object per event, with `ts`, `runId`, `kind`, and the `issue`, `role` or `round` in scope. A run whose fetch of the issues fails ends with an `issues.fail` event. A run that fails in any other way once this file is open, for example when `gh repo view` fails at the start or an issue crashes the run, ends with a `run.fail` event (after `run.end` when the run got that far). Both carry the `error`;
|
|
141
141
|
- `<id>.summary.json` — token totals per agent role, event counts, and one report per issue with the outcome, the reason and the budgets used (in a watch run, an issue skipped in several passes gets one report, and an issue handled in more than one pass keeps a report for each; when an issue crashes the run, the file still holds the reports of the issues that finished);
|
|
142
|
-
- `<id>/sessions/` — the full
|
|
142
|
+
- `<id>/sessions/` — the full Claude Code session of each agent call, one message per line, with every message, tool call and tool result. The session id in a `usage` event is the file name.
|
|
143
143
|
|
|
144
144
|
At the start of a run, the harness deletes the files and folders under `.next-issue/runs/` that are older than `keepRunDays`. The age of a folder is the time since the last change to it or to anything inside it, so the sessions of a long run stay while it still writes them. Set the field to `0` to keep them all.
|
|
145
145
|
|
|
146
146
|
A short text summary of the same data goes to standard output. All progress goes to standard error.
|
|
147
147
|
|
|
148
|
-
Recorded for each step: `claim`, `comments`, `reply`, `worktree`, `setup`, `editors`, `implement`, `review`, `fix`, `commit-fix`, `rebase`, `land`, `ci-checks`, `revert` and `hunt`, each with a `.start`, `.end` or `.error` event and a duration in `ms`. Every `git` and `gh` command is recorded with its exit code and duration. A `tool` event holds the tool name. For a `
|
|
148
|
+
Recorded for each step: `claim`, `comments`, `reply`, `worktree`, `setup`, `editors`, `implement`, `review`, `fix`, `commit-fix`, `rebase`, `land`, `ci-checks`, `revert` and `hunt`, each with a `.start`, `.end` or `.error` event and a duration in `ms`. Every `git` and `gh` command is recorded with its exit code and duration. A `tool` event holds the tool name. For a `Bash` tool it holds the command too, and for a `Read`, `Write`, `Edit`, `Grep`, `Glob` or `NotebookEdit` tool the `path` it got, relative to the worktree when inside it. Each agent call adds a `usage` event with the tokens, the turn count, the tool-call count, the model and the session id. A call that times out, ends with a model error or is stopped after its session started adds one too, and its tokens count in the summary totals.
|
|
149
149
|
|
|
150
150
|
```bash
|
|
151
151
|
jq -r 'select(.kind=="usage") | [.issue,.role,.turns,.total] | @tsv' \
|
|
@@ -162,7 +162,7 @@ The console shows the run and issue milestones, verdicts, hand-overs, errors, ea
|
|
|
162
162
|
- git 2.40 or later (every commit runs `git hook run`, every conflict with the base runs `git check-attr --source`). A run or `serve` run on an older git stops before it claims an issue, with an error that names both versions.
|
|
163
163
|
- `gh`, authenticated with write access to the repository
|
|
164
164
|
- a `remote` on GitHub: `github.com`, or a GitHub Enterprise host. Every `gh` call names the host of the remote url (`--repo <host>/<owner>/<name>`, `gh api --hostname <host>`) when it is not `github.com`, so `gh` must be logged in to that host. For an ssh url the harness reads the real host of an ssh alias with `ssh -G`. The host `ssh.github.com` (GitHub's ssh over port 443) means `github.com`. Other hosts, such as GitLab, are not supported.
|
|
165
|
-
-
|
|
165
|
+
- Claude Code, logged in, such as with a Pro or Max plan. The harness asks for no API key. The agents run the Claude Code that comes with the Agent SDK, with the model (unless `models` sets one), the settings, the plugins, the skills and the `CLAUDE.md` files of your Claude Code setup, except the plugin `next-issue@next-issue`, whose skills are for people, not for the agents. The agents run with every permission granted, as no person is there to answer a prompt. The implementer and the fixer get every tool. The reviewer gets every tool except `Write`, `Edit` and `NotebookEdit`. The agents run with `GIT_OPTIONAL_LOCKS=0`, so a `git status` from an agent does not hold the index lock while the harness commits.
|
|
166
166
|
|
|
167
167
|
## Configuration
|
|
168
168
|
|
|
@@ -240,7 +240,7 @@ With no file, every field keeps its default. A field that is not in the file kee
|
|
|
240
240
|
| `maxCiFixes` | `5` | The budget for check fixes per issue |
|
|
241
241
|
| `maxCommitFixes` | `10` | The budget for fixes of a commit that a git hook stopped, per issue |
|
|
242
242
|
| `maxReviewRounds` | `5` | The budget for review rounds per issue |
|
|
243
|
-
| `models` | `null` per role | The
|
|
243
|
+
| `models` | `null` per role | The Claude model ID per agent role, such as `claude-opus-5-5`: `default`, `implementer`, `reviewer`, `fixer`, `hunter` |
|
|
244
244
|
| `remote` | `origin` | The git remote for the repository and the branches |
|
|
245
245
|
| `setupCommand` | from the lock file | A shell command to run in a new worktree, before the implementer, and after each merge of the base before the `checks` |
|
|
246
246
|
| `setupTimeoutMinutes` | `15` | The limit for the setup command, at most `35791` |
|
|
@@ -255,7 +255,7 @@ The harness compares the labels on an issue with the configured names without ca
|
|
|
255
255
|
|
|
256
256
|
The log gives the reason for a skipped issue as `stop-label`, `not-ready`, `in-flight` or `blocked`, the last one with the open blockers.
|
|
257
257
|
|
|
258
|
-
A role set to `null`, or with no entry in `models`, uses `models.default`. When `models.default` is `null` or missing too, it uses the default model of your
|
|
258
|
+
A role set to `null`, or with no entry in `models`, uses `models.default`. When `models.default` is `null` or missing too, it uses the default model of your Claude Code settings. A model in the old `provider/model` form, such as `anthropic/claude-opus-5-5`, makes the agent fail with an error that asks for a Claude model ID.
|
|
259
259
|
|
|
260
260
|
Without a `setupCommand`, the harness looks for a lock file in the new worktree, and in the worktree after each merge of the base before the `checks`, and runs the install command that goes with it:
|
|
261
261
|
|
|
@@ -277,7 +277,7 @@ A `setupCommand` that fails, or that does not finish in `setupTimeoutMinutes`, h
|
|
|
277
277
|
|
|
278
278
|
Every agent prompt holds `.next-issue/notes.md` when it exists, so lessons such as test commands, tool quirks and deliberate behaviour carry over from one issue to the next. The implementer and the fixer may add a short note to it, and the prompt asks them to keep only what still holds. The reviewer and the hunter only read it.
|
|
279
279
|
|
|
280
|
-
Every agent also reads each `
|
|
280
|
+
Every agent also reads each `CLAUDE.md` that Claude Code finds, such as the one in `~/.claude` and the one in the repository. Claude Code does not read `AGENTS.md`; a repository that keeps its rules there can add a `CLAUDE.md` that holds `@AGENTS.md`. The other rules there, such as code conventions and test style, still apply. But the harness owns the issue, the worktree, the branch, git, the commit, the push and the checks, and the prompt says so: a workflow rule in `CLAUDE.md` about these, such as "push to main" or "watch ci", does not apply to the agent. The hunter still files its issues with `gh issue create`.
|
|
281
281
|
|
|
282
282
|
## Retry an issue that waits for a person
|
|
283
283
|
|
|
@@ -355,6 +355,7 @@ In a run of the `serve` worker, a client can switch hunting and watching on or o
|
|
|
355
355
|
`next-issue serve` runs one worker for the repository it is run in. The [`@ravshansbox/pi-next-issue`](../pi-next-issue) extension and `next-issue start` start it and talk to it. `serve` takes no flags apart from `--help` and refuses any other with an error, because runs start from a client, not from `serve`. Each repository has its own worker, so the runs, restarts and upgrades of one repository never affect another. The worker:
|
|
356
356
|
|
|
357
357
|
- listens with WebSocket on the socket file `.next-issue/worker.sock` in the repository. Only your user can open the file. It works on macOS and Linux. When the path of the socket file is too long for the system, about 103 bytes on macOS and 107 on Linux, it exits with an error that says so;
|
|
358
|
+
- also answers plain HTTP on the same socket file, for a client with no WebSocket. `GET /` answers `[{ "type": "hello", ... }, { "type": "runs", ... }]`. `POST /` takes one client message as its JSON body, such as `{ "type": "start", "root": "<path>" }`, and answers a JSON list of the messages the worker sends that client in reply (an `error`, `stopping`, `questions` or `upcoming` message), then the `runs` message after the change. A body that is not a client message gets status 400 and `[{ "type": "error", "root": "<path>", "message": "the request is not a next-issue message" }]`; another path gets 404 and another method 405. An HTTP client does not get the `output`, `pass` and `end` messages, so it polls `GET /` for the progress;
|
|
358
359
|
- holds `.next-issue/worker.lock` in the repository, with its process id and the start time of that process, so only one worker goes per repository. A worker that starts while another process holds the lock exits with `another worker is running`. A lock is stale, and is taken over, when no process has that id or the process with that id started at another time, for example because the system gave the id of a worker that was killed or lost in a reboot to another process. A lock without a start time, from an older version, is held while a process with that id is alive, and stale otherwise. A worker that cannot read its own start time exits with an error and takes no lock. When several workers start at once, one takes the lock and the others exit with `another worker is running`. A worker that stops removes the lock file only while it still holds the lock, and the socket file only while it is still the socket it bound;
|
|
359
360
|
- refuses a `start`, `stop`, `watch`, `hunt`, `questions` or `upcoming` message whose `root` is not the exact path of its repository with an `error` message, and starts or stops nothing;
|
|
360
361
|
- sends each `error` as `{ "type": "error", "root": "<path>", "message": "<text>" }`. When a `start`, `stop`, `watch`, `hunt` or `refresh` message carries an `"id"`, the `error` that refuses it carries the same `id`;
|
|
@@ -369,7 +370,7 @@ In a run of the `serve` worker, a client can switch hunting and watching on or o
|
|
|
369
370
|
- switches watching of a run on or off when a client sends `{ "type": "watch", "root": "<path>", "on": true | false }`. The run keeps its issues, worktrees and progress, and nothing restarts. A run starts with watching on, unless it was started with `--watch off`. On keeps the run going after the current pass, as with `--watch on`. On for a run that a person asked to stop gets an `error` (`the run is stopping`, with the `id` of the request) and changes nothing; on for a run that stops for an upgrade keeps the upgrade, so the run is still resumed. Off ends the run after the current pass, or at once when it waits between passes, and also turns hunting off. With no run going, the message gets an `error` and starts nothing;
|
|
370
371
|
- switches hunting of a run on or off when a client sends `{ "type": "hunt", "root": "<path>", "on": true | false }`. The run keeps its issues, worktrees and progress, and nothing restarts. Every run of the worker has a hunter: a run started with `--hunt on` starts with hunting on, and any other run with it off. Off lets a hunt that is going finish, so the issues it files stay, and starts no new hunt. On wakes the hunter at once, with no back-off wait, and also turns watching on. On for a run that a person asked to stop gets the same `error` as watch on. With no run going, the message gets an `error` and starts nothing. The settings last for the run only: a new run takes them from its own flags. The progress of each run carries `hunting`, `true` while hunting is on, and `watching`, `true` when the run watches for issues;
|
|
371
372
|
- asks a watching run to check for new issues now when a client sends `{ "type": "refresh", "root": "<path>" }`. A run that waits between passes starts a new pass at once, and its next wait starts again at 1 minute; a refresh during the last read of the open issues of a pass, or while the pass ends, also starts a new pass at once; a waiting hunter checks the ready count again. While a pass runs, the run reads the open issues again, so its open-issue count is current, and claims a new issue only when a slot is free. A refresh for a run that is stopping or does not watch, or with no run going, changes nothing and gets no answer;
|
|
372
|
-
- exits, and removes its socket and lock files, when no run is going
|
|
373
|
+
- exits, and removes its socket and lock files, when no run is going, no client is connected and no HTTP request came in the last 30 seconds, or when no client connects in the 30 seconds after it starts;
|
|
373
374
|
- waits up to 5 seconds for the lock when a worker that is closing still holds it;
|
|
374
375
|
- closes once no run is going when a client with a newer version connects, so that the client can start the newer worker. The `hello` of a client can say how to start the worker of its version, as `"launch": { "command": "<command>", "args": ["<arg>", ...] }`: pi sends `npx -y next-issue@<version> serve`, and `next-issue start` its own `node <script> serve`. A run that watches is stopped between issues for that, as `stop` with `issue` does: it claims nothing new, and its running issues and its current hunt finish. Its progress then holds `"upgrade": { "from": "<worker version>", "to": "<client version>" }`, with `"resumes": true` when the first newer client gave a `launch`. A stop by a person, or turning watching off, drops that field, so the run does not start again. With `resumes`, once the run ends, the worker stops listening, runs that command in the repository with its output in `.next-issue/worker.log` (or uses a worker that already listens there), waits up to 2 minutes for it to listen, as pi does, since `npx` may first download it, and asks the newer worker to start the run again with `--watch on` and the same `--hunt` setting, before it closes. This works with no client connected. When the newer worker does not start or does not start the run, the worker writes the reason to `.next-issue/worker.log`, and its clients see the run `failed` with an `error` that starts with `the worker could not start next-issue <version>`. Without `resumes`, a client starts the newer worker and the run again. A run that does not watch is left alone; a run that `next-issue start` started is not, and `start` follows it to the newer worker. Meanwhile the worker refuses every start with `the worker is restarting, try again soon`. A `start` with `"resume": true` gets no error when the worker refuses it;
|
|
375
376
|
- stops every agent and command and exits on `SIGTERM`, `SIGHUP` or `SIGINT`, and removes its socket and lock files;
|
package/dist/agents.mjs
CHANGED
|
@@ -1,150 +1,219 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { onStop, refuseWhenStopped } from './children.mjs';
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { query } from '@anthropic-ai/claude-agent-sdk';
|
|
5
|
+
import { killTree, onStop, refuseWhenStopped, watch } from './children.mjs';
|
|
7
6
|
import { deadline, elapsedMs } from './durations.mjs';
|
|
8
7
|
import { isRecord } from './records.mjs';
|
|
9
8
|
import { emptyUsage } from './usage.mjs';
|
|
10
9
|
export const REVIEWING = {
|
|
11
|
-
|
|
10
|
+
disallowedTools: ['Write', 'Edit', 'NotebookEdit'],
|
|
12
11
|
};
|
|
13
12
|
export const CODING = {
|
|
14
|
-
|
|
13
|
+
disallowedTools: [],
|
|
15
14
|
};
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
const root = dirname(dirname(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'))));
|
|
19
|
-
const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
20
|
-
return join(root, manifest.bin.pi);
|
|
21
|
-
}
|
|
15
|
+
export const OWN_PLUGIN = 'next-issue@next-issue';
|
|
16
|
+
const OWN_SETTINGS = { enabledPlugins: { [OWN_PLUGIN]: false } };
|
|
22
17
|
export async function runAgent(recorder, request) {
|
|
18
|
+
checkModel(request.model);
|
|
23
19
|
const log = recorder.scope({ role: request.name });
|
|
24
|
-
const agentDir = request.runtime?.agentDir ?? getAgentDir();
|
|
25
20
|
const started = Date.now();
|
|
26
|
-
process.env.GIT_OPTIONAL_LOCKS = '0';
|
|
27
|
-
process.argv[1] = PI_CLI;
|
|
28
21
|
log.event('agent.start', { model: request.model, timeoutMs: request.timeoutMs });
|
|
29
|
-
// pi drops an abort that comes before its run starts (during bindExtensions or the prompt
|
|
30
|
-
// preflight), so remember it and abort again once the run is active, before its first turn.
|
|
31
|
-
let opened;
|
|
32
22
|
let ended = false;
|
|
33
|
-
let
|
|
34
|
-
const expired = new Promise((resolve) => {
|
|
35
|
-
expire = () => resolve(undefined);
|
|
36
|
-
});
|
|
23
|
+
let child;
|
|
37
24
|
const end = () => {
|
|
38
25
|
ended = true;
|
|
39
|
-
|
|
26
|
+
if (child !== undefined) {
|
|
27
|
+
killTree(child);
|
|
28
|
+
}
|
|
40
29
|
};
|
|
41
|
-
const timer = deadline(request.timeoutMs,
|
|
42
|
-
expire();
|
|
43
|
-
end();
|
|
44
|
-
});
|
|
45
|
-
const session = await openWithin(openSession(recorder, log, request, agentDir), expired).catch((error) => {
|
|
46
|
-
timer.clear();
|
|
47
|
-
throw error;
|
|
48
|
-
});
|
|
49
|
-
if (session === undefined) {
|
|
50
|
-
throw timeoutError(request);
|
|
51
|
-
}
|
|
52
|
-
opened = session;
|
|
53
|
-
const unsubscribe = session.subscribe((event) => observe(log, event, request.cwd));
|
|
30
|
+
const timer = deadline(request.timeoutMs, end);
|
|
54
31
|
const release = onStop(end);
|
|
32
|
+
const session = {
|
|
33
|
+
messages: [],
|
|
34
|
+
usages: new Map(),
|
|
35
|
+
tools: new Map(),
|
|
36
|
+
toolCalls: 0,
|
|
37
|
+
text: '',
|
|
38
|
+
};
|
|
55
39
|
try {
|
|
56
40
|
refuseWhenStopped();
|
|
57
|
-
await session.bindExtensions({});
|
|
58
41
|
let result;
|
|
59
42
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
43
|
+
const agent = query({
|
|
44
|
+
prompt: request.prompt,
|
|
45
|
+
options: {
|
|
46
|
+
cwd: request.cwd,
|
|
47
|
+
disallowedTools: request.profile.disallowedTools,
|
|
48
|
+
permissionMode: 'bypassPermissions',
|
|
49
|
+
allowDangerouslySkipPermissions: true,
|
|
50
|
+
persistSession: false,
|
|
51
|
+
settings: OWN_SETTINGS,
|
|
52
|
+
env: { ...process.env, ...request.runtime?.env, GIT_OPTIONAL_LOCKS: '0' },
|
|
53
|
+
...(request.model === undefined ? {} : { model: request.model }),
|
|
54
|
+
spawnClaudeCodeProcess: ({ command, args, cwd, env }) => {
|
|
55
|
+
child = spawn(command, args, {
|
|
56
|
+
cwd,
|
|
57
|
+
env,
|
|
58
|
+
detached: true,
|
|
59
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
60
|
+
});
|
|
61
|
+
const unwatch = watch(child.pid);
|
|
62
|
+
child.once('exit', unwatch);
|
|
63
|
+
if (ended) {
|
|
64
|
+
killTree(child);
|
|
66
65
|
}
|
|
66
|
+
return child;
|
|
67
67
|
},
|
|
68
|
-
}
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
for await (const message of agent) {
|
|
71
|
+
observe(log, session, message, request.cwd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (!ended && session.failure === undefined) {
|
|
76
|
+
throw error;
|
|
69
77
|
}
|
|
70
78
|
}
|
|
71
79
|
finally {
|
|
72
80
|
// A call that times out, fails or is stopped has spent tokens too.
|
|
73
|
-
result = sessionResult(recorder, request, session, started);
|
|
81
|
+
result = await sessionResult(recorder, request, session, started);
|
|
74
82
|
}
|
|
75
83
|
refuseWhenStopped();
|
|
76
84
|
if (timer.timedOut()) {
|
|
77
|
-
throw
|
|
85
|
+
throw new Error(`The ${request.name} agent did not finish in ${request.timeoutMs} ms.`);
|
|
78
86
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
throw new Error(`The ${request.name} agent failed: ${failure}`);
|
|
87
|
+
if (session.failure !== undefined) {
|
|
88
|
+
throw new Error(`The ${request.name} agent failed: ${session.failure}`);
|
|
82
89
|
}
|
|
83
90
|
return result;
|
|
84
91
|
}
|
|
85
92
|
finally {
|
|
86
93
|
timer.clear();
|
|
87
94
|
release();
|
|
88
|
-
unsubscribe();
|
|
89
|
-
session.dispose();
|
|
90
95
|
}
|
|
91
96
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
opening.then((late) => late.dispose(), () => undefined);
|
|
97
|
+
function checkModel(model) {
|
|
98
|
+
if (model?.includes('/') === true) {
|
|
99
|
+
throw new Error(`The model ${model} is not a Claude model ID. Use an ID such as claude-opus-5-5.`);
|
|
96
100
|
}
|
|
97
|
-
return session;
|
|
98
|
-
}
|
|
99
|
-
function timeoutError(request) {
|
|
100
|
-
return new Error(`The ${request.name} agent did not finish in ${request.timeoutMs} ms.`);
|
|
101
101
|
}
|
|
102
|
-
function
|
|
103
|
-
|
|
104
|
-
if (
|
|
105
|
-
|
|
102
|
+
function observe(log, session, message, cwd) {
|
|
103
|
+
session.messages.push(message);
|
|
104
|
+
if (message.type === 'system' && message.subtype === 'init') {
|
|
105
|
+
session.model = message.model;
|
|
106
|
+
session.sessionId = message.session_id;
|
|
106
107
|
}
|
|
107
|
-
|
|
108
|
+
else if (message.type === 'assistant' &&
|
|
109
|
+
message.parent_tool_use_id === null &&
|
|
110
|
+
message.error === undefined) {
|
|
111
|
+
const { id, usage, content } = message.message;
|
|
112
|
+
session.usages.set(id, {
|
|
113
|
+
...emptyUsage(),
|
|
114
|
+
input: usage.input_tokens,
|
|
115
|
+
output: usage.output_tokens,
|
|
116
|
+
cacheRead: usage.cache_read_input_tokens ?? 0,
|
|
117
|
+
cacheWrite: usage.cache_creation_input_tokens ?? 0,
|
|
118
|
+
});
|
|
119
|
+
for (const block of content) {
|
|
120
|
+
if (block.type === 'tool_use') {
|
|
121
|
+
session.toolCalls += 1;
|
|
122
|
+
session.tools.set(block.id, block.name);
|
|
123
|
+
log.event('tool', toolFields(block.name, block.input, cwd));
|
|
124
|
+
}
|
|
125
|
+
else if (block.type === 'text') {
|
|
126
|
+
session.text = block.text;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else if (message.type === 'user' && Array.isArray(message.message.content)) {
|
|
131
|
+
for (const block of message.message.content) {
|
|
132
|
+
if (block.type === 'tool_result' && block.is_error === true) {
|
|
133
|
+
log.event('tool.error', { tool: session.tools.get(block.tool_use_id) });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (message.type === 'result') {
|
|
138
|
+
session.final = emptyUsage();
|
|
139
|
+
for (const usage of Object.values(message.modelUsage)) {
|
|
140
|
+
session.final.input += usage.inputTokens;
|
|
141
|
+
session.final.output += usage.outputTokens;
|
|
142
|
+
session.final.cacheRead += usage.cacheReadInputTokens;
|
|
143
|
+
session.final.cacheWrite += usage.cacheCreationInputTokens;
|
|
144
|
+
}
|
|
145
|
+
if (message.subtype === 'success' && !message.is_error) {
|
|
146
|
+
session.text = message.result;
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
session.failure =
|
|
150
|
+
message.subtype === 'success'
|
|
151
|
+
? message.result
|
|
152
|
+
: message.errors.join('; ') || message.subtype;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function totalOf(usage) {
|
|
157
|
+
return { ...usage, total: usage.input + usage.output + usage.cacheRead + usage.cacheWrite };
|
|
108
158
|
}
|
|
109
|
-
function sessionResult(recorder, request, session, started) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
159
|
+
async function sessionResult(recorder, request, session, started) {
|
|
160
|
+
let usage = session.final;
|
|
161
|
+
if (usage === undefined) {
|
|
162
|
+
usage = emptyUsage();
|
|
163
|
+
for (const each of session.usages.values()) {
|
|
164
|
+
usage.input += each.input;
|
|
165
|
+
usage.output += each.output;
|
|
166
|
+
usage.cacheRead += each.cacheRead;
|
|
167
|
+
usage.cacheWrite += each.cacheWrite;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
usage = totalOf(usage);
|
|
171
|
+
const model = request.model ?? session.model;
|
|
172
|
+
const turns = session.usages.size;
|
|
113
173
|
const ms = elapsedMs(started);
|
|
174
|
+
await saveSession(recorder, session);
|
|
114
175
|
recorder.usage(request.name, usage, ms, {
|
|
115
|
-
turns
|
|
116
|
-
toolCalls:
|
|
117
|
-
model
|
|
118
|
-
session:
|
|
176
|
+
turns,
|
|
177
|
+
toolCalls: session.toolCalls,
|
|
178
|
+
model,
|
|
179
|
+
session: session.sessionId,
|
|
119
180
|
});
|
|
120
181
|
return {
|
|
121
|
-
text:
|
|
182
|
+
text: session.text.trim(),
|
|
122
183
|
usage,
|
|
123
|
-
turns
|
|
124
|
-
toolCalls:
|
|
184
|
+
turns,
|
|
185
|
+
toolCalls: session.toolCalls,
|
|
125
186
|
ms,
|
|
126
|
-
model
|
|
127
|
-
sessionId:
|
|
187
|
+
model,
|
|
188
|
+
sessionId: session.sessionId,
|
|
128
189
|
};
|
|
129
190
|
}
|
|
130
|
-
function
|
|
131
|
-
if (
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
else if (event.type === 'tool_execution_end' && event.isError) {
|
|
135
|
-
log.event('tool.error', { tool: event.toolName });
|
|
191
|
+
async function saveSession(recorder, session) {
|
|
192
|
+
if (session.sessionId === undefined) {
|
|
193
|
+
return;
|
|
136
194
|
}
|
|
195
|
+
await mkdir(recorder.sessionDir, { recursive: true });
|
|
196
|
+
await writeFile(join(recorder.sessionDir, `${session.sessionId}.jsonl`), session.messages.map((message) => `${JSON.stringify(message)}\n`).join(''));
|
|
137
197
|
}
|
|
138
|
-
const
|
|
198
|
+
const PATH_FIELDS = {
|
|
199
|
+
Read: 'file_path',
|
|
200
|
+
Write: 'file_path',
|
|
201
|
+
Edit: 'file_path',
|
|
202
|
+
Grep: 'path',
|
|
203
|
+
Glob: 'path',
|
|
204
|
+
NotebookEdit: 'notebook_path',
|
|
205
|
+
};
|
|
139
206
|
export function toolFields(name, input, cwd) {
|
|
140
207
|
if (!isRecord(input)) {
|
|
141
208
|
return { tool: name };
|
|
142
209
|
}
|
|
143
|
-
const { command
|
|
144
|
-
if (name === '
|
|
210
|
+
const { command } = input;
|
|
211
|
+
if (name === 'Bash' && typeof command === 'string') {
|
|
145
212
|
return { tool: name, command };
|
|
146
213
|
}
|
|
147
|
-
|
|
214
|
+
const field = PATH_FIELDS[name];
|
|
215
|
+
const path = field === undefined ? undefined : input[field];
|
|
216
|
+
if (typeof path === 'string') {
|
|
148
217
|
return { tool: name, path: shortPath(path, cwd) };
|
|
149
218
|
}
|
|
150
219
|
return { tool: name };
|
package/dist/prompts.mjs
CHANGED
|
@@ -7,9 +7,9 @@ const ENGINEERING_RULES = [
|
|
|
7
7
|
'Reuse existing code and patterns, stay consistent with the repository and pick the simpler option.',
|
|
8
8
|
'Check an API, a command or a url in the repository or its dependencies before you use it. Do not invent one.',
|
|
9
9
|
].join('\n');
|
|
10
|
-
const OTHER_RULES = 'The other rules of `
|
|
10
|
+
const OTHER_RULES = 'The other rules of `CLAUDE.md`, such as code conventions and test style, still apply.';
|
|
11
11
|
const HARNESS_RULES = [
|
|
12
|
-
'The harness owns the issue, the worktree, the branch, git, the commit, the push and the checks. The workflow rules of `
|
|
12
|
+
'The harness owns the issue, the worktree, the branch, git, the commit, the push and the checks. The workflow rules of `CLAUDE.md` about these do not apply to you.',
|
|
13
13
|
OTHER_RULES,
|
|
14
14
|
].join('\n');
|
|
15
15
|
const COMMIT_RULES = [
|
|
@@ -240,7 +240,7 @@ export function huntPrompt(instructions, ready, source, count, repository) {
|
|
|
240
240
|
'## Rules',
|
|
241
241
|
[
|
|
242
242
|
'Run no test suite and no build. Change no file. Do not commit or push.',
|
|
243
|
-
'The harness owns the worktree, git and the checks. The workflow rules of `
|
|
243
|
+
'The harness owns the worktree, git and the checks. The workflow rules of `CLAUDE.md` about these do not apply to you.',
|
|
244
244
|
OTHER_RULES,
|
|
245
245
|
`File up to ${issues}, your most serious findings first. File nothing when you find no real problem.`,
|
|
246
246
|
`Before you file an issue, search the open and closed issues for a duplicate, for example with \`gh issue list --repo ${repository} --state all --search "<words>"\`. Do not file a finding when a duplicate exists.`,
|
package/dist/serve.mjs
CHANGED
|
@@ -8,8 +8,8 @@ import { stopChildren, withRunChildren } from './children.mjs';
|
|
|
8
8
|
import { message } from './errors.mjs';
|
|
9
9
|
import { lock } from './lock.mjs';
|
|
10
10
|
import { startProgress } from './progress.mjs';
|
|
11
|
-
import { isNewer } from './protocol.mjs';
|
|
12
|
-
import { listQuestions, questionSender, send } from './questions.mjs';
|
|
11
|
+
import { isNewer, } from './protocol.mjs';
|
|
12
|
+
import { listQuestions, questionSender, send, } from './questions.mjs';
|
|
13
13
|
import { runRepo } from './run.mjs';
|
|
14
14
|
import { listUpcoming, sendUpcoming } from './upcoming.mjs';
|
|
15
15
|
import { packageVersion } from './version.mjs';
|
|
@@ -17,7 +17,7 @@ import { resumeOnSuccessor } from './worker-client.mjs';
|
|
|
17
17
|
import { keepLogTrimmed, LOG_CHECK_MS } from './worker-log.mjs';
|
|
18
18
|
import { checkSocketPath, workerPaths } from './worker-paths.mjs';
|
|
19
19
|
import { active, dropUpgrade, endStatus, newRun, requestRefresh, requestStop, requestUpgrade, runControls, runsMessage, setHunting, setWatching, startRefusal, stoppingMessage, stopPoint, switchRefusal, } from './worker-run.mjs';
|
|
20
|
-
import { broadcast, closer, fileId, isLaunch, listen, parseMessage, removeOwned, sendAll, shutdown, stopListening, } from './worker-server.mjs';
|
|
20
|
+
import { broadcast, closer, fileId, isLaunch, listen, parseMessage, readBody, removeOwned, reply, sendAll, shutdown, stopListening, } from './worker-server.mjs';
|
|
21
21
|
const LOCK_WAIT_MS = 5_000;
|
|
22
22
|
const IDLE_MS = 30_000;
|
|
23
23
|
export async function startWorker(options) {
|
|
@@ -44,6 +44,9 @@ export async function startWorker(options) {
|
|
|
44
44
|
const outsideRuns = AsyncLocalStorage.snapshot();
|
|
45
45
|
const busy = () => [...runs.values()].some(active);
|
|
46
46
|
let idleTimer;
|
|
47
|
+
const idleMs = options.idleMs ?? IDLE_MS;
|
|
48
|
+
let polledAt = Number.NEGATIVE_INFINITY;
|
|
49
|
+
const polled = () => Date.now() - polledAt < idleMs;
|
|
47
50
|
const handOver = async (how, run) => {
|
|
48
51
|
const listening = stopListening(server);
|
|
49
52
|
removeOwned(owned);
|
|
@@ -69,7 +72,7 @@ export async function startWorker(options) {
|
|
|
69
72
|
}
|
|
70
73
|
});
|
|
71
74
|
const closeWhenIdle = () => {
|
|
72
|
-
if ((restart !== undefined || sockets.clients.size === 0) && !busy()) {
|
|
75
|
+
if ((restart !== undefined || (sockets.clients.size === 0 && !polled())) && !busy()) {
|
|
73
76
|
void close();
|
|
74
77
|
}
|
|
75
78
|
};
|
|
@@ -200,11 +203,12 @@ export async function startWorker(options) {
|
|
|
200
203
|
requestRefresh(runs.get(value.root));
|
|
201
204
|
}
|
|
202
205
|
else if (value.type === 'questions') {
|
|
203
|
-
|
|
206
|
+
return sendQuestions(value.root, () => [socket], value.id);
|
|
204
207
|
}
|
|
205
208
|
else if (value.type === 'upcoming') {
|
|
206
|
-
|
|
209
|
+
return sendUpcoming(options.upcoming ?? listUpcoming, socket, value.root);
|
|
207
210
|
}
|
|
211
|
+
return undefined;
|
|
208
212
|
};
|
|
209
213
|
sockets.on('connection', (socket) => {
|
|
210
214
|
send(socket, { type: 'hello', version: options.version });
|
|
@@ -219,19 +223,54 @@ export async function startWorker(options) {
|
|
|
219
223
|
}
|
|
220
224
|
const refuse = refuser(socket, value, options.root);
|
|
221
225
|
try {
|
|
222
|
-
receive(socket, value, refuse);
|
|
226
|
+
void receive(socket, value, refuse);
|
|
223
227
|
}
|
|
224
228
|
catch (error) {
|
|
225
229
|
refuse(message(error));
|
|
226
230
|
}
|
|
227
231
|
});
|
|
228
232
|
});
|
|
233
|
+
const answer = async (request, response) => {
|
|
234
|
+
polledAt = Date.now();
|
|
235
|
+
clearTimeout(idleTimer);
|
|
236
|
+
idleTimer = setTimeout(closeWhenIdle, idleMs);
|
|
237
|
+
const refusal = (text) => [
|
|
238
|
+
{ type: 'error', root: options.root, message: text },
|
|
239
|
+
];
|
|
240
|
+
if (request.url !== '/') {
|
|
241
|
+
reply(response, 404, refusal('the worker answers on / only'));
|
|
242
|
+
}
|
|
243
|
+
else if (request.method === 'GET') {
|
|
244
|
+
reply(response, 200, [{ type: 'hello', version: options.version }, runsMessage(runs)]);
|
|
245
|
+
}
|
|
246
|
+
else if (request.method !== 'POST') {
|
|
247
|
+
reply(response, 405, refusal('the worker answers GET and POST only'));
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
const value = parseMessage(await readBody(request));
|
|
251
|
+
if (value === undefined) {
|
|
252
|
+
reply(response, 400, refusal('the request is not a next-issue message'));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const replies = [];
|
|
256
|
+
const peer = { send: (data) => replies.push(JSON.parse(data)) };
|
|
257
|
+
const refuse = refuser(peer, value, options.root);
|
|
258
|
+
try {
|
|
259
|
+
await receive(peer, value, refuse);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
refuse(message(error));
|
|
263
|
+
}
|
|
264
|
+
reply(response, 200, [...replies, runsMessage(runs)]);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
server.on('request', (request, response) => void answer(request, response));
|
|
229
268
|
const draft = join(dirname(options.socketPath), `~${basename(options.socketPath).slice(1)}`);
|
|
230
269
|
await rm(draft, { force: true });
|
|
231
270
|
await listen(server, draft);
|
|
232
271
|
await rename(draft, options.socketPath);
|
|
233
272
|
owned.socket = fileId(options.socketPath);
|
|
234
|
-
idleTimer = setTimeout(closeWhenIdle,
|
|
273
|
+
idleTimer = setTimeout(closeWhenIdle, idleMs);
|
|
235
274
|
return { closed, close, release: () => removeOwned(owned) };
|
|
236
275
|
}
|
|
237
276
|
function upgradedRun(run) {
|
package/dist/worker-server.mjs
CHANGED
|
@@ -46,6 +46,26 @@ export function sendAll(sockets, value) {
|
|
|
46
46
|
send(socket, value);
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
|
+
const BODY_LIMIT = 1024 * 1024;
|
|
50
|
+
export function readBody(request) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
let body = '';
|
|
53
|
+
request.setEncoding('utf8');
|
|
54
|
+
request.on('data', (chunk) => {
|
|
55
|
+
body += chunk;
|
|
56
|
+
if (body.length > BODY_LIMIT) {
|
|
57
|
+
resolve('');
|
|
58
|
+
request.destroy();
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
request.on('end', () => resolve(body));
|
|
62
|
+
request.on('error', reject);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export function reply(response, status, messages) {
|
|
66
|
+
response.writeHead(status, { 'content-type': 'application/json', connection: 'close' });
|
|
67
|
+
response.end(JSON.stringify(messages));
|
|
68
|
+
}
|
|
49
69
|
export function listen(server, path) {
|
|
50
70
|
return new Promise((resolve, reject) => {
|
|
51
71
|
server.once('error', reject);
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-issue",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Autonomous issue harness driven by the
|
|
3
|
+
"version": "13.1.0",
|
|
4
|
+
"description": "Autonomous issue harness driven by the Claude Agent SDK",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"github",
|
|
7
7
|
"issues",
|
|
8
8
|
"agent",
|
|
9
|
-
"
|
|
9
|
+
"claude",
|
|
10
10
|
"automation",
|
|
11
11
|
"cli"
|
|
12
12
|
],
|
|
@@ -41,7 +41,6 @@
|
|
|
41
41
|
"prepack": "npm run build"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@earendil-works/pi-ai": "^1.5.2",
|
|
45
44
|
"@types/node": "^26.6.6",
|
|
46
45
|
"@types/ws": "^8.18.2",
|
|
47
46
|
"oxfmt": "^0.78.0",
|
|
@@ -49,7 +48,7 @@
|
|
|
49
48
|
"typescript": "^7.0.2"
|
|
50
49
|
},
|
|
51
50
|
"dependencies": {
|
|
52
|
-
"@
|
|
51
|
+
"@anthropic-ai/claude-agent-sdk": "^0.3.327",
|
|
53
52
|
"ws": "^8.23.0"
|
|
54
53
|
}
|
|
55
54
|
}
|
package/dist/agent-session.mjs
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
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
|
-
const parts = path.split(sep);
|
|
5
|
-
return parts.some((part, index) => part === 'pi-next-issue' &&
|
|
6
|
-
((parts[index + 1] === 'index.ts' && index + 2 === parts.length) ||
|
|
7
|
-
parts[index + 1] === 'skills'));
|
|
8
|
-
}
|
|
9
|
-
export async function openSession(recorder, log, request, agentDir) {
|
|
10
|
-
const runtime = request.runtime ?? {};
|
|
11
|
-
const resourceLoader = await loadResources(request.cwd, agentDir);
|
|
12
|
-
const modelRuntime = runtime.modelRuntime ??
|
|
13
|
-
(await ModelRuntime.create({
|
|
14
|
-
authPath: join(agentDir, 'auth.json'),
|
|
15
|
-
modelsPath: join(agentDir, 'models.json'),
|
|
16
|
-
}));
|
|
17
|
-
const model = request.model === undefined ? undefined : await findModel(modelRuntime, request.model);
|
|
18
|
-
const { session, modelFallbackMessage } = await createAgentSession({
|
|
19
|
-
cwd: request.cwd,
|
|
20
|
-
agentDir,
|
|
21
|
-
resourceLoader,
|
|
22
|
-
sessionManager: SessionManager.create(request.cwd, recorder.sessionDir),
|
|
23
|
-
tools: request.profile.tools,
|
|
24
|
-
modelRuntime,
|
|
25
|
-
...(runtime.settingsManager === undefined ? {} : { settingsManager: runtime.settingsManager }),
|
|
26
|
-
...(model === undefined ? {} : { model }),
|
|
27
|
-
});
|
|
28
|
-
if (modelFallbackMessage !== undefined) {
|
|
29
|
-
log.event('agent.model', { note: modelFallbackMessage });
|
|
30
|
-
}
|
|
31
|
-
return session;
|
|
32
|
-
}
|
|
33
|
-
async function loadResources(cwd, agentDir) {
|
|
34
|
-
const resourceLoader = new DefaultResourceLoader({
|
|
35
|
-
cwd,
|
|
36
|
-
agentDir,
|
|
37
|
-
extensionsOverride: (base) => ({
|
|
38
|
-
...base,
|
|
39
|
-
extensions: base.extensions.filter((extension) => !isOwnResource(extension.resolvedPath)),
|
|
40
|
-
}),
|
|
41
|
-
skillsOverride: (base) => ({
|
|
42
|
-
...base,
|
|
43
|
-
skills: base.skills.filter((skill) => !isOwnResource(skill.filePath)),
|
|
44
|
-
}),
|
|
45
|
-
});
|
|
46
|
-
await resourceLoader.reload();
|
|
47
|
-
return resourceLoader;
|
|
48
|
-
}
|
|
49
|
-
async function findModel(modelRuntime, name) {
|
|
50
|
-
const slash = name.indexOf('/');
|
|
51
|
-
if (slash <= 0) {
|
|
52
|
-
throw new Error(`The model ${name} is not in the form provider/model.`);
|
|
53
|
-
}
|
|
54
|
-
const found = modelRuntime.getModel(name.slice(0, slash), name.slice(slash + 1));
|
|
55
|
-
if (found === undefined) {
|
|
56
|
-
throw new Error(`The model ${name} is not known to pi.`);
|
|
57
|
-
}
|
|
58
|
-
return found;
|
|
59
|
-
}
|