ticket-runner 0.6.1 → 0.6.3
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.ko.md +21 -15
- package/README.md +14 -7
- package/docs/templates/operator-skill.md +1 -0
- package/package.json +3 -3
- package/src/adapters/claude-agent-runner.ts +210 -26
- package/src/adapters/exec.ts +52 -6
- package/src/adapters/gh-tracker.ts +10 -46
- package/src/adapters/git-workspace.ts +33 -3
- package/src/adapters/process-tree.ts +227 -0
- package/src/branch.ts +8 -0
- package/src/command-line.ts +18 -1
- package/src/config.ts +3 -3
- package/src/conventions.ts +2 -1
- package/src/credential.ts +75 -0
- package/src/failing-base.ts +132 -0
- package/src/guards.ts +1 -1
- package/src/host.ts +1 -1
- package/src/log-tail.ts +51 -0
- package/src/note-schema.ts +21 -0
- package/src/notes.ts +8 -4
- package/src/orchestrator.ts +460 -68
- package/src/ports/agent-runner.ts +27 -2
- package/src/ports/tracker.ts +5 -4
- package/src/ports/workspace.ts +38 -2
- package/src/prompts.ts +125 -18
- package/src/readiness.ts +67 -11
- package/src/resume.ts +7 -5
- package/src/run.ts +96 -25
- package/src/start.ts +57 -14
- package/src/templates.ts +134 -15
- package/src/title.ts +2 -2
package/README.ko.md
CHANGED
|
@@ -23,9 +23,11 @@ Acceptance Criteria 체크리스트가 달리고, blocker가 연결됩니다. **
|
|
|
23
23
|
5. rebase하고, pull request를 열고, CI를 기다린 뒤 squash merge합니다.
|
|
24
24
|
|
|
25
25
|
한 번 실패하면 고치는 세션 한 번과 두 번째 검사를 받습니다. 그래도 끝내지 못한 일은 사람에게 돌아옵니다.
|
|
26
|
-
`ready-for-human` 라벨과 draft pull request, 무엇이 실패했는지 적은 코멘트가 함께 남습니다.
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
`ready-for-human` 라벨과 draft pull request, 무엇이 실패했는지 적은 코멘트가 함께 남습니다.
|
|
27
|
+
세션은 Claude 요금제로 돌고, 셸이 export한 `ANTHROPIC_API_KEY`는 세션에 넘기지 않습니다. `run --api-key`로
|
|
28
|
+
시작하면 대신 그 키로 과금합니다. rate limit이나 일시적인 API 장애, 키의 크레딧 소진이나 사용 한도 도달로
|
|
29
|
+
멈춘 세션은 아무것도 잃지 않습니다. 이슈는 보드로 돌아가고, Run은 무엇이 멈췄는지와 알 수 있으면 한도가 풀리는
|
|
30
|
+
시각을 알려 주며, 다음 Run이 멈춘 곳부터 이어 합니다.
|
|
29
31
|
|
|
30
32
|
## 나에게 맞을까?
|
|
31
33
|
|
|
@@ -38,7 +40,7 @@ rate limit에 걸려 멈춘 세션은 아무것도 잃지 않습니다. 이슈
|
|
|
38
40
|
[`mattpocock-skills`](https://github.com/mattpocock/skills) 플러그인 1.2.3 이상 버전을 설치한 `claude`가
|
|
39
41
|
있습니다.
|
|
40
42
|
|
|
41
|
-
파이프라인은 묻지 않고
|
|
43
|
+
파이프라인은 묻지 않고 Base branch에 merge합니다. 그걸 원하는 저장소에 쓰세요.
|
|
42
44
|
|
|
43
45
|
## 써 보기
|
|
44
46
|
|
|
@@ -46,12 +48,15 @@ rate limit에 걸려 멈춘 세션은 아무것도 잃지 않습니다. 이슈
|
|
|
46
48
|
|
|
47
49
|
```bash
|
|
48
50
|
npx ticket-runner init # Target을 준비하고, 아직 빠진 것을 알려 줍니다
|
|
51
|
+
git add .gitignore CLAUDE.md ticket-runner.json docs/agents .claude/skills/ticket-runner
|
|
52
|
+
git commit -m "chore: set up ticket-runner" && git push
|
|
49
53
|
npx ticket-runner run # 준비된 이슈를 모두 처리합니다
|
|
50
54
|
```
|
|
51
55
|
|
|
52
56
|
`init`은 검토하고 commit할 파일 몇 개를 씁니다. `.gitignore` 줄, conventions 문서, `CLAUDE.md`의 한
|
|
53
57
|
섹션, Claude skill 하나입니다. 또 triage 라벨을 만들고, squash merge와 merge 시 branch 삭제를 켭니다.
|
|
54
|
-
commit은 하지 않습니다.
|
|
58
|
+
commit은 하지 않습니다. 세션은 이 파일들이 Base branch에 올라간 뒤에야 읽으므로, 첫 `run` 전에
|
|
59
|
+
push하세요.
|
|
55
60
|
|
|
56
61
|
계속 쓰려면 전역으로 설치하세요.
|
|
57
62
|
|
|
@@ -61,16 +66,17 @@ npm install -g ticket-runner
|
|
|
61
66
|
|
|
62
67
|
| 명령 | 하는 일 |
|
|
63
68
|
|---|---|
|
|
64
|
-
| `ticket-runner init` | 이 저장소를 준비하고, 사람이 고쳐야 할 것을 알려
|
|
65
|
-
| `ticket-runner run` | 준비된 이슈를 하나씩 모두
|
|
66
|
-
| `ticket-runner run 12 14` | 같은 일을 하되 #12와 #14만
|
|
67
|
-
| `ticket-runner run --lanes 2` | 이슈 두 개를 동시에
|
|
68
|
-
| `ticket-runner
|
|
69
|
-
| `ticket-runner
|
|
70
|
-
| `ticket-runner
|
|
69
|
+
| `ticket-runner init` | 이 저장소를 준비하고, 사람이 고쳐야 할 것을 알려 줍니다. |
|
|
70
|
+
| `ticket-runner run` | 준비된 이슈를 하나씩 모두 처리합니다. |
|
|
71
|
+
| `ticket-runner run 12 14` | 같은 일을 하되 #12와 #14만 맡습니다. |
|
|
72
|
+
| `ticket-runner run --lanes 2` | 이슈 두 개를 동시에 처리합니다. |
|
|
73
|
+
| `ticket-runner run --api-key` | 모든 세션을 Claude 요금제 대신 `ANTHROPIC_API_KEY`로 과금합니다. |
|
|
74
|
+
| `ticket-runner stop` | 진행 중인 Run에게 맡은 것만 끝내고 더 맡지 말라고 합니다. |
|
|
75
|
+
| `ticket-runner remove` | 이 저장소에서 파이프라인을 걷어 냅니다. |
|
|
76
|
+
| `ticket-runner -v` | Version을 출력합니다. |
|
|
71
77
|
|
|
72
78
|
Claude 앱에서도 Run을 시작할 수 있습니다. Target에서 Claude Code 클라우드 세션을 열고 "run it"이라고
|
|
73
|
-
말하면 됩니다.
|
|
79
|
+
말하면 됩니다. 클라우드 세션은 늘 요금제로 돌기 때문에 `--api-key`를 거절합니다.
|
|
74
80
|
|
|
75
81
|
## 다시 걷어 내기
|
|
76
82
|
|
|
@@ -91,10 +97,10 @@ npm uninstall -g ticket-runner # 전역 설치
|
|
|
91
97
|
- [실행하기](https://jjongs2.github.io/ticket-runner/ko/guide/running)
|
|
92
98
|
- [설정](https://jjongs2.github.io/ticket-runner/ko/guide/configuration)
|
|
93
99
|
- [Ticket 하나가 merge되기까지](https://jjongs2.github.io/ticket-runner/ko/guide/ticket-to-merge)
|
|
94
|
-
- [멈추고 이어 하기](https://jjongs2.github.io/ticket-runner/ko/guide/stopping-and-resuming)
|
|
100
|
+
- [Hand-off, 멈추고 이어 하기](https://jjongs2.github.io/ticket-runner/ko/guide/stopping-and-resuming)
|
|
95
101
|
- [내부 구조](https://jjongs2.github.io/ticket-runner/ko/guide/internals)
|
|
96
102
|
|
|
97
|
-
용어는 [`
|
|
103
|
+
용어는 [`GLOSSARY.md`](https://github.com/jjongs2/ticket-runner/blob/main/GLOSSARY.md)에, 설계 결정은
|
|
98
104
|
[`docs/adr/`](https://github.com/jjongs2/ticket-runner/tree/main/docs/adr)에, 파이프라인 자체를 고칠
|
|
99
105
|
때의 규칙은 [`CONTRIBUTING.md`](https://github.com/jjongs2/ticket-runner/blob/main/CONTRIBUTING.md)에
|
|
100
106
|
있습니다. 모두 영어입니다.
|
package/README.md
CHANGED
|
@@ -24,8 +24,11 @@ every such issue whose blockers have closed, it:
|
|
|
24
24
|
|
|
25
25
|
One failure buys one fix session and a second pass. Anything it still cannot finish goes back
|
|
26
26
|
to you, labelled `ready-for-human`, with a draft pull request and a comment saying what failed.
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
Sessions run on your Claude plan, and an `ANTHROPIC_API_KEY` your shell exports is kept from
|
|
28
|
+
them; `run --api-key` bills them to that key instead. A session stopped by the rate limit, by the
|
|
29
|
+
API failing on its side, or by the key running out of credit or into its spend limit costs
|
|
30
|
+
nothing: the issue goes back on the board, the Run says what stopped it, and when the limit
|
|
31
|
+
resets where it can, and the next Run carries on from where it stopped.
|
|
29
32
|
|
|
30
33
|
## Is it for you?
|
|
31
34
|
|
|
@@ -39,7 +42,7 @@ It fits a repository where:
|
|
|
39
42
|
[`gh`](https://cli.github.com/), and `claude` with the
|
|
40
43
|
[`mattpocock-skills`](https://github.com/mattpocock/skills) plugin, version 1.2.3 or later
|
|
41
44
|
|
|
42
|
-
It merges to your
|
|
45
|
+
It merges to your Base branch without asking. It is for repositories where that is what you want.
|
|
43
46
|
|
|
44
47
|
## Try it
|
|
45
48
|
|
|
@@ -47,12 +50,15 @@ In the repository you want it to work in (the **Target**):
|
|
|
47
50
|
|
|
48
51
|
```bash
|
|
49
52
|
npx ticket-runner init # set the Target up and report what is still missing
|
|
53
|
+
git add .gitignore CLAUDE.md ticket-runner.json docs/agents .claude/skills/ticket-runner
|
|
54
|
+
git commit -m "chore: set up ticket-runner" && git push
|
|
50
55
|
npx ticket-runner run # work through every ready issue
|
|
51
56
|
```
|
|
52
57
|
|
|
53
58
|
`init` writes a few files for you to review and commit: `.gitignore` lines, a conventions
|
|
54
59
|
document, a section in `CLAUDE.md` and a Claude skill. It also creates the triage labels and
|
|
55
|
-
turns on squash merging and branch deletion on merge. It commits nothing
|
|
60
|
+
turns on squash merging and branch deletion on merge. It commits nothing, and a session reads
|
|
61
|
+
those files only once they are on your Base branch, so push them before the first `run`.
|
|
56
62
|
|
|
57
63
|
To keep it, install it globally:
|
|
58
64
|
|
|
@@ -66,12 +72,13 @@ npm install -g ticket-runner
|
|
|
66
72
|
| `ticket-runner run` | Work through every ready issue, one at a time |
|
|
67
73
|
| `ticket-runner run 12 14` | The same, taking only #12 and #14 |
|
|
68
74
|
| `ticket-runner run --lanes 2` | Two issues at once |
|
|
75
|
+
| `ticket-runner run --api-key` | Bill every session to your `ANTHROPIC_API_KEY`, not your Claude plan |
|
|
69
76
|
| `ticket-runner stop` | Ask the Run in progress to finish what it holds and take no more |
|
|
70
77
|
| `ticket-runner remove` | Take the pipeline out of this repository |
|
|
71
78
|
| `ticket-runner -v` | Print the Version |
|
|
72
79
|
|
|
73
80
|
A Run can also be started from the Claude app, in a Claude Code cloud session on the Target:
|
|
74
|
-
say "run it".
|
|
81
|
+
say "run it". A cloud session always runs on your plan, so it refuses `--api-key`.
|
|
75
82
|
|
|
76
83
|
## Take it out again
|
|
77
84
|
|
|
@@ -93,9 +100,9 @@ The [project wiki](https://jjongs2.github.io/ticket-runner/) explains the pipeli
|
|
|
93
100
|
- [Running](https://jjongs2.github.io/ticket-runner/guide/running)
|
|
94
101
|
- [Configuration](https://jjongs2.github.io/ticket-runner/guide/configuration)
|
|
95
102
|
- [From Ticket to merge](https://jjongs2.github.io/ticket-runner/guide/ticket-to-merge)
|
|
96
|
-
- [
|
|
103
|
+
- [Hand-offs, stopping and resuming](https://jjongs2.github.io/ticket-runner/guide/stopping-and-resuming)
|
|
97
104
|
- [Internals](https://jjongs2.github.io/ticket-runner/guide/internals)
|
|
98
105
|
|
|
99
|
-
The vocabulary is defined in [`
|
|
106
|
+
The vocabulary is defined in [`GLOSSARY.md`](https://github.com/jjongs2/ticket-runner/blob/main/GLOSSARY.md), the decisions in
|
|
100
107
|
[`docs/adr/`](https://github.com/jjongs2/ticket-runner/tree/main/docs/adr), and the conventions for working on the pipeline itself in
|
|
101
108
|
[`CONTRIBUTING.md`](https://github.com/jjongs2/ticket-runner/blob/main/CONTRIBUTING.md).
|
|
@@ -48,6 +48,7 @@ Start what the human asked for as a background command, so the session stays fre
|
|
|
48
48
|
- `ticket-runner run` to work through every Ticket that is ready.
|
|
49
49
|
- `ticket-runner run <n>...` when the human names Tickets, one number each. The Run takes only those, lowest number first whatever order they were named in, and leaves every other Ticket alone.
|
|
50
50
|
- `ticket-runner run --lanes <count>` when the human asks for a number of Tickets at once, with or without numbers. Pass it only when they do; otherwise the repository's own config decides.
|
|
51
|
+
- `ticket-runner run --api-key` when the human asks for the Run to bill their API key rather than their Claude plan, beside numbers or `--lanes` or without. Pass it only when they do. Tell them an API-key Run needs a workstation Host: a cloud Host refuses it, because a cloud session runs every Stage on the subscription whatever key it exports.
|
|
51
52
|
|
|
52
53
|
Start one at a time. While a Run of yours is running, start no other.
|
|
53
54
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ticket-runner",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "Drives the mattpocock-skills chain: humans plan, the pipeline executes.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@types/node": "^22.18.9",
|
|
43
|
-
"typescript": "^
|
|
44
|
-
"vitest": "^
|
|
43
|
+
"typescript": "^7.0.2",
|
|
44
|
+
"vitest": "^5.0.4"
|
|
45
45
|
},
|
|
46
46
|
"allowScripts": {
|
|
47
47
|
"esbuild@0.28.2": true
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
4
|
+
import { API_KEY_ENV_VAR, type Credential } from "../credential.js";
|
|
3
5
|
import {
|
|
4
6
|
type AgentPreflight,
|
|
5
7
|
type AgentRunner,
|
|
@@ -10,12 +12,44 @@ import {
|
|
|
10
12
|
} from "../ports/agent-runner.js";
|
|
11
13
|
import { STAGE_ENV_VAR } from "../stage-guard.js";
|
|
12
14
|
import { type Execution, type RunProcess, exec } from "./exec.js";
|
|
15
|
+
import type { Mark } from "./process-tree.js";
|
|
13
16
|
|
|
14
17
|
export interface ClaudeAgentRunnerOptions {
|
|
15
18
|
binary?: string;
|
|
16
19
|
run?: RunProcess;
|
|
20
|
+
/** Whether a file is on the Host, asked of the Stage's shell. */
|
|
21
|
+
exists?: (path: string) => boolean;
|
|
17
22
|
}
|
|
18
23
|
|
|
24
|
+
/**
|
|
25
|
+
* The shell a Stage's commands run in. The Host user's own may be zsh, which
|
|
26
|
+
* aborts the whole command line on a glob that matches nothing or a word that
|
|
27
|
+
* starts with `=`, so the session would spend turns finding out why.
|
|
28
|
+
*/
|
|
29
|
+
const STAGE_SHELL = "/bin/bash";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The Session mark: a variable every Stage carries at a value no other Stage
|
|
33
|
+
* session shares, and every process it starts inherits. A Stage killed at its
|
|
34
|
+
* time limit is killed with every process still carrying its value, whoever
|
|
35
|
+
* their parent is by then.
|
|
36
|
+
*/
|
|
37
|
+
const SESSION_ENV_VAR = "TICKET_RUNNER_SESSION";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The tools that act beyond a Stage's worktree and its session: a cloud
|
|
41
|
+
* routine, a scheduled prompt, a notification, a wakeup after the Stage has
|
|
42
|
+
* ended, a workflow of further agents. Nothing a Stage is asked to do needs one.
|
|
43
|
+
*/
|
|
44
|
+
const DISALLOWED_TOOLS = [
|
|
45
|
+
"CronCreate",
|
|
46
|
+
"CronDelete",
|
|
47
|
+
"RemoteTrigger",
|
|
48
|
+
"PushNotification",
|
|
49
|
+
"ScheduleWakeup",
|
|
50
|
+
"Workflow",
|
|
51
|
+
];
|
|
52
|
+
|
|
19
53
|
/**
|
|
20
54
|
* How long one preflight question may take. Generous for a CLI printing its
|
|
21
55
|
* own version, and short enough that `init` cannot hang on a binary that never
|
|
@@ -31,8 +65,26 @@ interface ResultEvent {
|
|
|
31
65
|
num_turns?: number;
|
|
32
66
|
result?: unknown;
|
|
33
67
|
structured_output?: unknown;
|
|
34
|
-
/**
|
|
35
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Why the session's loop stopped. `api_error` is a request the API answered
|
|
70
|
+
* with an error, or never answered, after the CLI's own retries ran out.
|
|
71
|
+
*/
|
|
72
|
+
terminal_reason?: string;
|
|
73
|
+
/**
|
|
74
|
+
* The HTTP status of the API error that ended the session, when one did. The
|
|
75
|
+
* CLI prints `null` for a request that never got an answer.
|
|
76
|
+
*/
|
|
77
|
+
api_error_status?: number | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The `system/init` event a stream-json run opens with, as far as we rely on
|
|
82
|
+
* it: what the session says it is billed to.
|
|
83
|
+
*/
|
|
84
|
+
interface InitEvent {
|
|
85
|
+
type: "system";
|
|
86
|
+
subtype?: string;
|
|
87
|
+
apiKeySource?: unknown;
|
|
36
88
|
}
|
|
37
89
|
|
|
38
90
|
/**
|
|
@@ -41,7 +93,8 @@ interface ResultEvent {
|
|
|
41
93
|
*/
|
|
42
94
|
interface RateLimitEvent {
|
|
43
95
|
type: "rate_limit_event";
|
|
44
|
-
|
|
96
|
+
/** `resetsAt` is when the limit resets, in seconds since the epoch. */
|
|
97
|
+
rate_limit_info?: { status?: string; resetsAt?: number };
|
|
45
98
|
}
|
|
46
99
|
|
|
47
100
|
/**
|
|
@@ -53,10 +106,12 @@ interface RateLimitEvent {
|
|
|
53
106
|
export class ClaudeAgentRunner implements AgentRunner {
|
|
54
107
|
private readonly binary: string;
|
|
55
108
|
private readonly runProcess: RunProcess;
|
|
109
|
+
private readonly exists: (path: string) => boolean;
|
|
56
110
|
|
|
57
111
|
constructor(options: ClaudeAgentRunnerOptions = {}) {
|
|
58
112
|
this.binary = options.binary ?? "claude";
|
|
59
113
|
this.runProcess = options.run ?? exec;
|
|
114
|
+
this.exists = options.exists ?? existsSync;
|
|
60
115
|
}
|
|
61
116
|
|
|
62
117
|
/**
|
|
@@ -88,14 +143,17 @@ export class ClaudeAgentRunner implements AgentRunner {
|
|
|
88
143
|
private async spawn(
|
|
89
144
|
request: StageRequest,
|
|
90
145
|
args: string[],
|
|
146
|
+
env: Record<string, string>,
|
|
147
|
+
session: Mark,
|
|
91
148
|
log: StageLog,
|
|
92
149
|
): Promise<Execution> {
|
|
93
150
|
try {
|
|
94
151
|
return await this.runProcess(this.binary, args, {
|
|
95
152
|
cwd: request.cwd,
|
|
96
153
|
timeoutMs: request.maxMinutes * 60_000,
|
|
97
|
-
|
|
98
|
-
|
|
154
|
+
extraEnv: env,
|
|
155
|
+
...(request.credential === "subscription" ? { unsetEnv: [API_KEY_ENV_VAR] } : {}),
|
|
156
|
+
mark: session,
|
|
99
157
|
onStdout: log.appendStdout,
|
|
100
158
|
onStderr: log.appendStderr,
|
|
101
159
|
});
|
|
@@ -106,13 +164,15 @@ export class ClaudeAgentRunner implements AgentRunner {
|
|
|
106
164
|
|
|
107
165
|
async run(request: StageRequest): Promise<StageResult> {
|
|
108
166
|
const args = buildArgs(request);
|
|
109
|
-
const
|
|
167
|
+
const session = { name: SESSION_ENV_VAR, value: randomUUID() };
|
|
168
|
+
const env = this.stageEnv(request, session);
|
|
169
|
+
const commandLine = quoteCommand(request.credential, env, this.binary, args);
|
|
110
170
|
const startedAt = Date.now();
|
|
111
171
|
|
|
112
172
|
// Started before the child, so a Run killed mid-Stage still leaves the
|
|
113
173
|
// command line and everything printed so far behind.
|
|
114
|
-
const log = startStageLog(request, commandLine);
|
|
115
|
-
const execution = await this.spawn(request, args, log);
|
|
174
|
+
const log = startStageLog(request, commandLine, process.env[API_KEY_ENV_VAR]);
|
|
175
|
+
const execution = await this.spawn(request, args, env, session, log);
|
|
116
176
|
|
|
117
177
|
const events = parseEvents(execution.stdout);
|
|
118
178
|
log.close(execution, events);
|
|
@@ -121,6 +181,8 @@ export class ClaudeAgentRunner implements AgentRunner {
|
|
|
121
181
|
const failure = classify(request, execution, events);
|
|
122
182
|
const structured = request.jsonSchema === undefined ? undefined : structuredOutput(results);
|
|
123
183
|
const turns = countTurns(results);
|
|
184
|
+
const resetsAt = failure === "rate-limited" ? limitResetsAt(events) : undefined;
|
|
185
|
+
const apiKeySource = keySource(events);
|
|
124
186
|
|
|
125
187
|
return {
|
|
126
188
|
ok: failure === undefined,
|
|
@@ -129,12 +191,28 @@ export class ClaudeAgentRunner implements AgentRunner {
|
|
|
129
191
|
commandLine,
|
|
130
192
|
transcriptPath: log.transcriptPath,
|
|
131
193
|
...(turns === undefined ? {} : { turns }),
|
|
194
|
+
...(resetsAt === undefined ? {} : { limitResetsAt: resetsAt }),
|
|
195
|
+
...(apiKeySource === undefined ? {} : { apiKeySource }),
|
|
132
196
|
// The clock is the runner's own. A session that woke for a background
|
|
133
197
|
// agent reports one `duration_ms` per waking, and the time it spent
|
|
134
198
|
// waiting for that agent belongs to none of them.
|
|
135
199
|
durationMs: Date.now() - startedAt,
|
|
136
200
|
};
|
|
137
201
|
}
|
|
202
|
+
|
|
203
|
+
/** What a Stage's environment carries beyond the one it inherits. */
|
|
204
|
+
private stageEnv(request: StageRequest, session: Mark): Record<string, string> {
|
|
205
|
+
return {
|
|
206
|
+
// The Stage mark the CLI refuses on, so the session cannot nest a Run.
|
|
207
|
+
[STAGE_ENV_VAR]: request.stage,
|
|
208
|
+
// Two Lanes in the same Stage share the Stage mark, never this one.
|
|
209
|
+
[session.name]: session.value,
|
|
210
|
+
// The Host user's memory is about their own projects, not the Target.
|
|
211
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
|
|
212
|
+
// Where the Host has no bash, its own shell is still better than none.
|
|
213
|
+
...(this.exists(STAGE_SHELL) ? { CLAUDE_CODE_SHELL: STAGE_SHELL } : {}),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
138
216
|
}
|
|
139
217
|
|
|
140
218
|
/**
|
|
@@ -155,11 +233,6 @@ async function spawnFailure(error: unknown): Promise<Execution> {
|
|
|
155
233
|
return { exitCode: 1, stdout: "", stderr: message, output: message, timedOut: false };
|
|
156
234
|
}
|
|
157
235
|
|
|
158
|
-
/** What a Stage's shell carries beyond the environment it inherits. */
|
|
159
|
-
function stageEnv(request: StageRequest): Record<string, string> {
|
|
160
|
-
return { [STAGE_ENV_VAR]: request.stage };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
236
|
function buildArgs(request: StageRequest): string[] {
|
|
164
237
|
const args = [
|
|
165
238
|
"--print",
|
|
@@ -172,6 +245,11 @@ function buildArgs(request: StageRequest): string[] {
|
|
|
172
245
|
"none",
|
|
173
246
|
"--permission-mode",
|
|
174
247
|
request.permissionMode,
|
|
248
|
+
// Without `--mcp-config`, this leaves the session no MCP server at all,
|
|
249
|
+
// the claude.ai connectors of the Host user's account included.
|
|
250
|
+
"--strict-mcp-config",
|
|
251
|
+
"--disallowedTools",
|
|
252
|
+
...DISALLOWED_TOOLS,
|
|
175
253
|
"--model",
|
|
176
254
|
request.model,
|
|
177
255
|
// Always passed, like the model: a Stage's logged command line is what a
|
|
@@ -196,6 +274,13 @@ interface StageLog {
|
|
|
196
274
|
close: (execution: Execution, events: unknown[]) => void;
|
|
197
275
|
}
|
|
198
276
|
|
|
277
|
+
/**
|
|
278
|
+
* What stands in a Stage's files for the Host's API key, wherever the session
|
|
279
|
+
* printed it: an `--api-key` Stage that runs `env` would otherwise put the key
|
|
280
|
+
* in a transcript, which reaches the Target's remote with a hand-off.
|
|
281
|
+
*/
|
|
282
|
+
const REDACTED_KEY = `<${API_KEY_ENV_VAR}>`;
|
|
283
|
+
|
|
199
284
|
/**
|
|
200
285
|
* Put the Stage's command line on disk and empty its output files, before
|
|
201
286
|
* anything is spawned. Chunks are appended as they arrive rather than saved at
|
|
@@ -203,9 +288,16 @@ interface StageLog {
|
|
|
203
288
|
* alive to write them (#12). The transcript is the one derivation that has to
|
|
204
289
|
* wait: it is parsed out of the stdout the session has finished printing.
|
|
205
290
|
*/
|
|
206
|
-
function startStageLog(
|
|
291
|
+
function startStageLog(
|
|
292
|
+
request: StageRequest,
|
|
293
|
+
commandLine: string,
|
|
294
|
+
/** The Host's API key, whose value no file of the Stage may carry. */
|
|
295
|
+
key: string | undefined,
|
|
296
|
+
): StageLog {
|
|
207
297
|
mkdirSync(request.logDir, { recursive: true });
|
|
208
298
|
const path = (suffix: string) => join(request.logDir, `${request.stage}.${suffix}`);
|
|
299
|
+
const redact = (text: string) =>
|
|
300
|
+
key === undefined || key === "" ? text : text.replaceAll(key, REDACTED_KEY);
|
|
209
301
|
|
|
210
302
|
writeFileSync(path("command"), `${commandLine}\n`);
|
|
211
303
|
// Emptied up front, so a Stage never appends to output from an earlier one.
|
|
@@ -213,11 +305,18 @@ function startStageLog(request: StageRequest, commandLine: string): StageLog {
|
|
|
213
305
|
writeFileSync(path("stderr"), "");
|
|
214
306
|
|
|
215
307
|
const appended = { stdout: 0, stderr: 0 };
|
|
308
|
+
// The tail of each stream that may be the start of a key the next chunk
|
|
309
|
+
// finishes. It stays off disk until that chunk shows it is not, so a Run
|
|
310
|
+
// killed between the two chunks leaves no part of the key behind.
|
|
311
|
+
const heldBack = { stdout: "", stderr: "" };
|
|
216
312
|
// Appending happens inside the child's stream handler, where a throw would
|
|
217
313
|
// take the whole Run down. A write that fails is left to `close` to redo.
|
|
218
314
|
const append = (suffix: "stdout" | "stderr") => (chunk: string) => {
|
|
219
315
|
try {
|
|
220
|
-
|
|
316
|
+
const text = redact(heldBack[suffix] + chunk);
|
|
317
|
+
const held = keyPrefixAtEnd(text, key);
|
|
318
|
+
heldBack[suffix] = text.slice(text.length - held);
|
|
319
|
+
appendFileSync(path(suffix), text.slice(0, text.length - held));
|
|
221
320
|
appended[suffix] += chunk.length;
|
|
222
321
|
} catch {
|
|
223
322
|
// Nothing is lost: the chunk is still part of the Execution.
|
|
@@ -231,21 +330,38 @@ function startStageLog(request: StageRequest, commandLine: string): StageLog {
|
|
|
231
330
|
close: (execution, events) => {
|
|
232
331
|
// Whatever the appends missed — a failed write, or a process runner that
|
|
233
332
|
// delivered no chunks at all — is written back whole here, so a Stage
|
|
234
|
-
// that ran to the end always has its full output on disk.
|
|
235
|
-
|
|
236
|
-
|
|
333
|
+
// that ran to the end always has its full output on disk. Where the
|
|
334
|
+
// Host has a key, both are written back whole whatever was appended,
|
|
335
|
+
// which also puts the tail held back from the last chunk on disk.
|
|
336
|
+
const keyed = key !== undefined && key !== "";
|
|
337
|
+
if (keyed || appended.stdout !== execution.stdout.length) {
|
|
338
|
+
writeFileSync(path("stdout"), redact(execution.stdout));
|
|
237
339
|
}
|
|
238
|
-
if (appended.stderr !== execution.stderr.length) {
|
|
239
|
-
writeFileSync(path("stderr"), execution.stderr);
|
|
340
|
+
if (keyed || appended.stderr !== execution.stderr.length) {
|
|
341
|
+
writeFileSync(path("stderr"), redact(execution.stderr));
|
|
240
342
|
}
|
|
241
343
|
writeFileSync(
|
|
242
344
|
path("transcript.jsonl"),
|
|
243
|
-
|
|
345
|
+
redact(
|
|
346
|
+
events.map((event) => JSON.stringify(event)).join("\n") + (events.length ? "\n" : ""),
|
|
347
|
+
),
|
|
244
348
|
);
|
|
245
349
|
},
|
|
246
350
|
};
|
|
247
351
|
}
|
|
248
352
|
|
|
353
|
+
/**
|
|
354
|
+
* How many characters at the end of `text` could be the start of `key`, so a
|
|
355
|
+
* key split across two chunks is redacted once the second arrives.
|
|
356
|
+
*/
|
|
357
|
+
function keyPrefixAtEnd(text: string, key: string | undefined): number {
|
|
358
|
+
if (key === undefined || key === "") return 0;
|
|
359
|
+
for (let length = Math.min(key.length - 1, text.length); length > 0; length--) {
|
|
360
|
+
if (text.endsWith(key.slice(0, length))) return length;
|
|
361
|
+
}
|
|
362
|
+
return 0;
|
|
363
|
+
}
|
|
364
|
+
|
|
249
365
|
function parseEvents(stdout: string): unknown[] {
|
|
250
366
|
const events: unknown[] = [];
|
|
251
367
|
for (const line of stdout.split("\n")) {
|
|
@@ -264,6 +380,19 @@ function isResultEvent(event: unknown): event is ResultEvent {
|
|
|
264
380
|
return isEvent(event, "result");
|
|
265
381
|
}
|
|
266
382
|
|
|
383
|
+
function isInitEvent(event: unknown): event is InitEvent {
|
|
384
|
+
return isEvent(event, "system") && (event as InitEvent).subtype === "init";
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* What the session said it was billed to: the first init event's word on it.
|
|
389
|
+
* A waking for a background agent is the same session on the same credential.
|
|
390
|
+
*/
|
|
391
|
+
function keySource(events: unknown[]): string | undefined {
|
|
392
|
+
const source = events.find(isInitEvent)?.apiKeySource;
|
|
393
|
+
return typeof source === "string" ? source : undefined;
|
|
394
|
+
}
|
|
395
|
+
|
|
267
396
|
function isRateLimitEvent(event: unknown): event is RateLimitEvent {
|
|
268
397
|
return isEvent(event, "rate_limit_event");
|
|
269
398
|
}
|
|
@@ -293,7 +422,10 @@ function classify(
|
|
|
293
422
|
// still succeeds.
|
|
294
423
|
const failed = execution.exitCode !== 0 || result?.is_error === true || result === undefined;
|
|
295
424
|
if (failed) {
|
|
425
|
+
// Before the rate limit, whose wording the spend limit's message matches.
|
|
426
|
+
if (outOfBudget(result)) return "out-of-budget";
|
|
296
427
|
if (rateLimited(execution, events, result)) return "rate-limited";
|
|
428
|
+
if (transientApiFailure(result)) return "api-error";
|
|
297
429
|
return "nonzero-exit";
|
|
298
430
|
}
|
|
299
431
|
// A schema the Stage answered with nothing is only a failure where the
|
|
@@ -309,7 +441,20 @@ function classify(
|
|
|
309
441
|
}
|
|
310
442
|
|
|
311
443
|
/**
|
|
312
|
-
* Whether a session that failed was
|
|
444
|
+
* Whether a session that failed was refused because its API key's organization
|
|
445
|
+
* is out of credit, or its workspace reached the spend limit set in the
|
|
446
|
+
* Console. Both are a 400, as a malformed request is, and the spend limit's
|
|
447
|
+
* `error` is `unknown`, so the message is what tells them apart: either
|
|
448
|
+
* wording of the credit balance, or the workspace's usage limits.
|
|
449
|
+
*/
|
|
450
|
+
function outOfBudget(result: ResultEvent | undefined): boolean {
|
|
451
|
+
if (result?.api_error_status !== 400) return false;
|
|
452
|
+
return /credit balance is too low|workspace API usage limits/i.test(String(result.result ?? ""));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Whether a session that failed was stopped by the rate limit: the
|
|
457
|
+
* subscription's, or the API's on a Stage run on a key.
|
|
313
458
|
*
|
|
314
459
|
* The CLI says so in three places, and any one of them is enough: the `result`
|
|
315
460
|
* event carries the API's 429, a `rate_limit_event` reports the request
|
|
@@ -326,13 +471,41 @@ function rateLimited(
|
|
|
326
471
|
result: ResultEvent | undefined,
|
|
327
472
|
): boolean {
|
|
328
473
|
if (result?.api_error_status === 429) return true;
|
|
329
|
-
const rejected = (event: unknown) =>
|
|
330
|
-
isRateLimitEvent(event) && event.rate_limit_info?.status === "rejected";
|
|
331
474
|
if (events.some(rejected)) return true;
|
|
332
475
|
const text = [result?.subtype ?? "", String(result?.result ?? ""), execution.stderr].join(" ");
|
|
333
476
|
return /usage limit|session limit|rate limit|rate_limit/i.test(text);
|
|
334
477
|
}
|
|
335
478
|
|
|
479
|
+
/** A `rate_limit_event` that says the request was refused, not merely warned about. */
|
|
480
|
+
function rejected(event: unknown): event is RateLimitEvent {
|
|
481
|
+
return isRateLimitEvent(event) && event.rate_limit_info?.status === "rejected";
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* When the limit that stopped a session resets, ISO-8601: the last rejecting
|
|
486
|
+
* event's word on it, or nothing when no rejecting event carried one.
|
|
487
|
+
*/
|
|
488
|
+
function limitResetsAt(events: unknown[]): string | undefined {
|
|
489
|
+
const resetsAt = events.filter(rejected).at(-1)?.rate_limit_info?.resetsAt;
|
|
490
|
+
if (typeof resetsAt !== "number" || !Number.isFinite(resetsAt)) return undefined;
|
|
491
|
+
return new Date(resetsAt * 1000).toISOString();
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Whether a session that failed, and was not rate-limited, was stopped by the
|
|
496
|
+
* API failing on its own side: an overloaded or broken server, a 5xx, or a
|
|
497
|
+
* request that never got an answer at all, which the CLI reports without a
|
|
498
|
+
* status. Asked only after {@link rateLimited}, because a 429 ends the session
|
|
499
|
+
* with the same `terminal_reason`. The CLI has already retried each of these by
|
|
500
|
+
* the time it gives up, so the session is not worth retrying in place either.
|
|
501
|
+
* Any other status — a prompt the API refused, say — is the session's own.
|
|
502
|
+
*/
|
|
503
|
+
function transientApiFailure(result: ResultEvent | undefined): boolean {
|
|
504
|
+
if (result?.terminal_reason !== "api_error") return false;
|
|
505
|
+
const status = result.api_error_status;
|
|
506
|
+
return status === undefined || status === null || (status >= 500 && status <= 599);
|
|
507
|
+
}
|
|
508
|
+
|
|
336
509
|
/**
|
|
337
510
|
* The Stage's structured output, from the last `result` event that carries one.
|
|
338
511
|
*
|
|
@@ -376,14 +549,25 @@ function structuredOutputOf(result: ResultEvent): unknown {
|
|
|
376
549
|
/**
|
|
377
550
|
* Shell-quote the command so a human can paste it back into a terminal, with
|
|
378
551
|
* the Stage's environment in front of it so the reproduction is exact.
|
|
552
|
+
*
|
|
553
|
+
* How the environment differed from the Host's leads it: a subscription Stage
|
|
554
|
+
* ran without the Host's key, which `env -u` removes again, and an API-key
|
|
555
|
+
* Stage ran on it, which is named and left for the shell to fill in. Its value
|
|
556
|
+
* is never written: command files reach the Target's remote with a hand-off.
|
|
379
557
|
*/
|
|
380
558
|
function quoteCommand(
|
|
559
|
+
credential: Credential,
|
|
381
560
|
extraEnv: Record<string, string>,
|
|
382
561
|
binary: string,
|
|
383
562
|
args: string[],
|
|
384
563
|
): string {
|
|
385
564
|
const assignments = Object.entries(extraEnv).map(([name, value]) => `${name}=${value}`);
|
|
386
|
-
|
|
565
|
+
const differed =
|
|
566
|
+
credential === "subscription"
|
|
567
|
+
? `env -u ${API_KEY_ENV_VAR}`
|
|
568
|
+
: `${API_KEY_ENV_VAR}="$${API_KEY_ENV_VAR}"`;
|
|
569
|
+
const quoted = [...assignments, binary, ...args]
|
|
387
570
|
.map((part) => (/^[\w./:=-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
|
|
388
571
|
.join(" ");
|
|
572
|
+
return `${differed} ${quoted}`;
|
|
389
573
|
}
|