ticket-runner 0.6.2 → 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 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
- rate limit이나 일시적인 API 장애로 멈춘 세션은 아무것도 잃지 않습니다. 이슈는 보드로 돌아가고, Run은 한도가
28
- 풀리는 시각을 알려 주며, 다음 Run이 멈춘 곳부터 이어 합니다.
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이나 일시적인 API 장애로 멈춘 세션은 아무것도 잃지
38
40
  [`mattpocock-skills`](https://github.com/mattpocock/skills) 플러그인 1.2.3 이상 버전을 설치한 `claude`가
39
41
  있습니다.
40
42
 
41
- 파이프라인은 묻지 않고 base branch에 merge합니다. 그걸 원하는 저장소에 쓰세요.
43
+ 파이프라인은 묻지 않고 Base branch에 merge합니다. 그걸 원하는 저장소에 쓰세요.
42
44
 
43
45
  ## 써 보기
44
46
 
@@ -46,12 +48,15 @@ rate limit이나 일시적인 API 장애로 멈춘 세션은 아무것도 잃지
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 stop` | 진행 중인 Run에게 맡은 것만 끝내고 더 맡지 말라고 합니다 |
69
- | `ticket-runner remove` | 이 저장소에서 파이프라인을 걷어 냅니다 |
70
- | `ticket-runner -v` | Version을 출력합니다 |
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,7 +97,7 @@ 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)에, 설계 결정은
package/README.md CHANGED
@@ -24,9 +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
- A session stopped by your subscription's rate limit, or by the API failing on its side, costs
28
- nothing: the issue goes back on the board, the Run says when the limit resets, and the next Run
29
- carries on from where it stopped.
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.
30
32
 
31
33
  ## Is it for you?
32
34
 
@@ -40,7 +42,7 @@ It fits a repository where:
40
42
  [`gh`](https://cli.github.com/), and `claude` with the
41
43
  [`mattpocock-skills`](https://github.com/mattpocock/skills) plugin, version 1.2.3 or later
42
44
 
43
- It merges to your base branch without asking. It is for repositories where that is what you want.
45
+ It merges to your Base branch without asking. It is for repositories where that is what you want.
44
46
 
45
47
  ## Try it
46
48
 
@@ -48,12 +50,15 @@ In the repository you want it to work in (the **Target**):
48
50
 
49
51
  ```bash
50
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
51
55
  npx ticket-runner run # work through every ready issue
52
56
  ```
53
57
 
54
58
  `init` writes a few files for you to review and commit: `.gitignore` lines, a conventions
55
59
  document, a section in `CLAUDE.md` and a Claude skill. It also creates the triage labels and
56
- 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`.
57
62
 
58
63
  To keep it, install it globally:
59
64
 
@@ -67,12 +72,13 @@ npm install -g ticket-runner
67
72
  | `ticket-runner run` | Work through every ready issue, one at a time |
68
73
  | `ticket-runner run 12 14` | The same, taking only #12 and #14 |
69
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 |
70
76
  | `ticket-runner stop` | Ask the Run in progress to finish what it holds and take no more |
71
77
  | `ticket-runner remove` | Take the pipeline out of this repository |
72
78
  | `ticket-runner -v` | Print the Version |
73
79
 
74
80
  A Run can also be started from the Claude app, in a Claude Code cloud session on the Target:
75
- say "run it".
81
+ say "run it". A cloud session always runs on your plan, so it refuses `--api-key`.
76
82
 
77
83
  ## Take it out again
78
84
 
@@ -94,7 +100,7 @@ The [project wiki](https://jjongs2.github.io/ticket-runner/) explains the pipeli
94
100
  - [Running](https://jjongs2.github.io/ticket-runner/guide/running)
95
101
  - [Configuration](https://jjongs2.github.io/ticket-runner/guide/configuration)
96
102
  - [From Ticket to merge](https://jjongs2.github.io/ticket-runner/guide/ticket-to-merge)
97
- - [Stopping and resuming](https://jjongs2.github.io/ticket-runner/guide/stopping-and-resuming)
103
+ - [Hand-offs, stopping and resuming](https://jjongs2.github.io/ticket-runner/guide/stopping-and-resuming)
98
104
  - [Internals](https://jjongs2.github.io/ticket-runner/guide/internals)
99
105
 
100
106
  The vocabulary is defined in [`GLOSSARY.md`](https://github.com/jjongs2/ticket-runner/blob/main/GLOSSARY.md), the decisions in
@@ -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.2",
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",
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { API_KEY_ENV_VAR, type Credential } from "../credential.js";
4
5
  import {
5
6
  type AgentPreflight,
6
7
  type AgentRunner,
@@ -76,6 +77,16 @@ interface ResultEvent {
76
77
  api_error_status?: number | null;
77
78
  }
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;
88
+ }
89
+
79
90
  /**
80
91
  * A `rate_limit_event` of a stream-json run: the CLI's own word on where the
81
92
  * subscription stands, printed as each request's answer comes back.
@@ -141,6 +152,7 @@ export class ClaudeAgentRunner implements AgentRunner {
141
152
  cwd: request.cwd,
142
153
  timeoutMs: request.maxMinutes * 60_000,
143
154
  extraEnv: env,
155
+ ...(request.credential === "subscription" ? { unsetEnv: [API_KEY_ENV_VAR] } : {}),
144
156
  mark: session,
145
157
  onStdout: log.appendStdout,
146
158
  onStderr: log.appendStderr,
@@ -154,12 +166,12 @@ export class ClaudeAgentRunner implements AgentRunner {
154
166
  const args = buildArgs(request);
155
167
  const session = { name: SESSION_ENV_VAR, value: randomUUID() };
156
168
  const env = this.stageEnv(request, session);
157
- const commandLine = quoteCommand(env, this.binary, args);
169
+ const commandLine = quoteCommand(request.credential, env, this.binary, args);
158
170
  const startedAt = Date.now();
159
171
 
160
172
  // Started before the child, so a Run killed mid-Stage still leaves the
161
173
  // command line and everything printed so far behind.
162
- const log = startStageLog(request, commandLine);
174
+ const log = startStageLog(request, commandLine, process.env[API_KEY_ENV_VAR]);
163
175
  const execution = await this.spawn(request, args, env, session, log);
164
176
 
165
177
  const events = parseEvents(execution.stdout);
@@ -170,6 +182,7 @@ export class ClaudeAgentRunner implements AgentRunner {
170
182
  const structured = request.jsonSchema === undefined ? undefined : structuredOutput(results);
171
183
  const turns = countTurns(results);
172
184
  const resetsAt = failure === "rate-limited" ? limitResetsAt(events) : undefined;
185
+ const apiKeySource = keySource(events);
173
186
 
174
187
  return {
175
188
  ok: failure === undefined,
@@ -179,6 +192,7 @@ export class ClaudeAgentRunner implements AgentRunner {
179
192
  transcriptPath: log.transcriptPath,
180
193
  ...(turns === undefined ? {} : { turns }),
181
194
  ...(resetsAt === undefined ? {} : { limitResetsAt: resetsAt }),
195
+ ...(apiKeySource === undefined ? {} : { apiKeySource }),
182
196
  // The clock is the runner's own. A session that woke for a background
183
197
  // agent reports one `duration_ms` per waking, and the time it spent
184
198
  // waiting for that agent belongs to none of them.
@@ -260,6 +274,13 @@ interface StageLog {
260
274
  close: (execution: Execution, events: unknown[]) => void;
261
275
  }
262
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
+
263
284
  /**
264
285
  * Put the Stage's command line on disk and empty its output files, before
265
286
  * anything is spawned. Chunks are appended as they arrive rather than saved at
@@ -267,9 +288,16 @@ interface StageLog {
267
288
  * alive to write them (#12). The transcript is the one derivation that has to
268
289
  * wait: it is parsed out of the stdout the session has finished printing.
269
290
  */
270
- function startStageLog(request: StageRequest, commandLine: string): StageLog {
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 {
271
297
  mkdirSync(request.logDir, { recursive: true });
272
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);
273
301
 
274
302
  writeFileSync(path("command"), `${commandLine}\n`);
275
303
  // Emptied up front, so a Stage never appends to output from an earlier one.
@@ -277,11 +305,18 @@ function startStageLog(request: StageRequest, commandLine: string): StageLog {
277
305
  writeFileSync(path("stderr"), "");
278
306
 
279
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: "" };
280
312
  // Appending happens inside the child's stream handler, where a throw would
281
313
  // take the whole Run down. A write that fails is left to `close` to redo.
282
314
  const append = (suffix: "stdout" | "stderr") => (chunk: string) => {
283
315
  try {
284
- appendFileSync(path(suffix), chunk);
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));
285
320
  appended[suffix] += chunk.length;
286
321
  } catch {
287
322
  // Nothing is lost: the chunk is still part of the Execution.
@@ -295,21 +330,38 @@ function startStageLog(request: StageRequest, commandLine: string): StageLog {
295
330
  close: (execution, events) => {
296
331
  // Whatever the appends missed — a failed write, or a process runner that
297
332
  // delivered no chunks at all — is written back whole here, so a Stage
298
- // that ran to the end always has its full output on disk.
299
- if (appended.stdout !== execution.stdout.length) {
300
- writeFileSync(path("stdout"), execution.stdout);
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));
301
339
  }
302
- if (appended.stderr !== execution.stderr.length) {
303
- writeFileSync(path("stderr"), execution.stderr);
340
+ if (keyed || appended.stderr !== execution.stderr.length) {
341
+ writeFileSync(path("stderr"), redact(execution.stderr));
304
342
  }
305
343
  writeFileSync(
306
344
  path("transcript.jsonl"),
307
- events.map((event) => JSON.stringify(event)).join("\n") + (events.length ? "\n" : ""),
345
+ redact(
346
+ events.map((event) => JSON.stringify(event)).join("\n") + (events.length ? "\n" : ""),
347
+ ),
308
348
  );
309
349
  },
310
350
  };
311
351
  }
312
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
+
313
365
  function parseEvents(stdout: string): unknown[] {
314
366
  const events: unknown[] = [];
315
367
  for (const line of stdout.split("\n")) {
@@ -328,6 +380,19 @@ function isResultEvent(event: unknown): event is ResultEvent {
328
380
  return isEvent(event, "result");
329
381
  }
330
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
+
331
396
  function isRateLimitEvent(event: unknown): event is RateLimitEvent {
332
397
  return isEvent(event, "rate_limit_event");
333
398
  }
@@ -357,6 +422,8 @@ function classify(
357
422
  // still succeeds.
358
423
  const failed = execution.exitCode !== 0 || result?.is_error === true || result === undefined;
359
424
  if (failed) {
425
+ // Before the rate limit, whose wording the spend limit's message matches.
426
+ if (outOfBudget(result)) return "out-of-budget";
360
427
  if (rateLimited(execution, events, result)) return "rate-limited";
361
428
  if (transientApiFailure(result)) return "api-error";
362
429
  return "nonzero-exit";
@@ -374,7 +441,20 @@ function classify(
374
441
  }
375
442
 
376
443
  /**
377
- * Whether a session that failed was stopped by the subscription rate limit.
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.
378
458
  *
379
459
  * The CLI says so in three places, and any one of them is enough: the `result`
380
460
  * event carries the API's 429, a `rate_limit_event` reports the request
@@ -469,14 +549,25 @@ function structuredOutputOf(result: ResultEvent): unknown {
469
549
  /**
470
550
  * Shell-quote the command so a human can paste it back into a terminal, with
471
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.
472
557
  */
473
558
  function quoteCommand(
559
+ credential: Credential,
474
560
  extraEnv: Record<string, string>,
475
561
  binary: string,
476
562
  args: string[],
477
563
  ): string {
478
564
  const assignments = Object.entries(extraEnv).map(([name, value]) => `${name}=${value}`);
479
- return [...assignments, binary, ...args]
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]
480
570
  .map((part) => (/^[\w./:=-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
481
571
  .join(" ");
572
+ return `${differed} ${quoted}`;
482
573
  }
@@ -27,6 +27,8 @@ export interface ExecOptions {
27
27
  killGraceMs?: number;
28
28
  /** Variables merged over the environment the child inherits, not replacing it. */
29
29
  extraEnv?: Record<string, string>;
30
+ /** Variables the child does not inherit, whatever this process carries. */
31
+ unsetEnv?: string[];
30
32
  /**
31
33
  * A variable set over `extraEnv`, whose value nothing else on the Host
32
34
  * carries. A kill at `timeoutMs` also takes every process still carrying it,
@@ -84,9 +86,10 @@ export function exec(
84
86
  const { mark } = options;
85
87
  const extraEnv =
86
88
  mark === undefined ? options.extraEnv : { ...options.extraEnv, [mark.name]: mark.value };
89
+ const env = childEnv(extraEnv, options.unsetEnv);
87
90
  const child = spawn(command, args, {
88
91
  ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
89
- ...(extraEnv === undefined ? {} : { env: { ...process.env, ...extraEnv } }),
92
+ ...(env === undefined ? {} : { env }),
90
93
  shell: options.shell ?? false,
91
94
  stdio: ["ignore", "pipe", "pipe"],
92
95
  });
@@ -196,3 +199,17 @@ export function throwOnFailure(
196
199
  }
197
200
  return result;
198
201
  }
202
+
203
+ /**
204
+ * The environment a child is given, or nothing where it inherits this
205
+ * process's own untouched.
206
+ */
207
+ function childEnv(
208
+ extraEnv: Record<string, string> | undefined,
209
+ unsetEnv: string[] | undefined,
210
+ ): NodeJS.ProcessEnv | undefined {
211
+ if (extraEnv === undefined && (unsetEnv === undefined || unsetEnv.length === 0)) return undefined;
212
+ const env: NodeJS.ProcessEnv = { ...process.env, ...extraEnv };
213
+ for (const name of unsetEnv ?? []) delete env[name];
214
+ return env;
215
+ }
@@ -147,7 +147,7 @@ export class GitWorkspace implements Workspace {
147
147
 
148
148
  constructor(
149
149
  private readonly repoRoot: string,
150
- private readonly remote = "origin",
150
+ readonly remote = "origin",
151
151
  { host = currentHost(process.env), checkProcess = checkProcessTable }: LockOptions = {},
152
152
  ) {
153
153
  this.host = host;
@@ -575,6 +575,15 @@ export class GitWorkspace implements Workspace {
575
575
  return stdout.trim() !== "";
576
576
  }
577
577
 
578
+ async readRemoteFile(branch: string, path: string): Promise<string | undefined> {
579
+ // Fetched first, as a worktree is made from it: the checkout's own
580
+ // remote-tracking ref may predate a push another clone made.
581
+ const tracking = await this.fetchBranch(branch);
582
+ if (tracking === undefined) return undefined;
583
+ const read = await this.tryGit(["cat-file", "blob", `${tracking}:${path}`]);
584
+ return read.exitCode === 0 ? read.stdout : undefined;
585
+ }
586
+
578
587
  async deleteRemoteBranch(branch: string): Promise<void> {
579
588
  // Asked before anything is sent: a repository that deletes a merged branch
580
589
  // has usually done it by now, and a cloud Host, which may delete nothing,
@@ -34,6 +34,10 @@ Usage:
34
34
  Options:
35
35
  --lanes <n> With \`run\`: work on up to <n> issues at once,
36
36
  whatever \`lanes\` in ticket-runner.json says.
37
+ --api-key With \`run\`: bill every session to the
38
+ ANTHROPIC_API_KEY this shell exports. Without
39
+ it, sessions run on your Claude login and the
40
+ key is kept from them. Not on a cloud session.
37
41
  -y, --yes With \`remove\`: go ahead without asking.
38
42
  -h, --help Show this message.
39
43
  -v, --version Show which version this pipeline is.`;
@@ -75,6 +79,11 @@ export function readCommandLine(argv: string[]): CommandLine {
75
79
  return refused("`--lanes` is for `run` only, which has a Frontier to share out.");
76
80
  }
77
81
 
82
+ // The same for `--api-key`: only `run` starts the sessions it would bill.
83
+ if (values["api-key"] === true && command !== "run") {
84
+ return refused("`--api-key` is for `run` only, the one command that starts Stages.");
85
+ }
86
+
78
87
  // The same for `--yes` everywhere but `remove`, the one command that asks
79
88
  // before it acts: given to any other, it answers a question nobody asks.
80
89
  if (values.yes === true && command !== "remove") {
@@ -101,6 +110,7 @@ export function readCommandLine(argv: string[]): CommandLine {
101
110
  command: "run",
102
111
  ...(lanes === undefined ? {} : { lanes }),
103
112
  ...(tickets.length === 0 ? {} : { tickets }),
113
+ ...(values["api-key"] === true ? { apiKey: true as const } : {}),
104
114
  },
105
115
  };
106
116
  }
@@ -148,7 +158,13 @@ function refused(complaint: string): CommandLine {
148
158
  /** What `parseArgs` makes of the arguments: the options, and the rest. */
149
159
  interface ParsedArgs {
150
160
  positionals: string[];
151
- values: { help?: boolean; version?: boolean; lanes?: string; yes?: boolean };
161
+ values: {
162
+ help?: boolean;
163
+ version?: boolean;
164
+ lanes?: string;
165
+ "api-key"?: boolean;
166
+ yes?: boolean;
167
+ };
152
168
  }
153
169
 
154
170
  /**
@@ -169,6 +185,7 @@ function parseCommandLine(argv: string[]): ParsedArgs | string {
169
185
  help: { type: "boolean", short: "h" },
170
186
  version: { type: "boolean", short: "v" },
171
187
  lanes: { type: "string" },
188
+ "api-key": { type: "boolean" },
172
189
  yes: { type: "boolean", short: "y" },
173
190
  },
174
191
  allowPositionals: true,
@@ -0,0 +1,75 @@
1
+ import type { HostKind } from "./host.js";
2
+
3
+ /**
4
+ * Whose money a Run's Stages spend, decided once when the Run starts and held
5
+ * for the whole Run: the subscription the Host is logged in with, or the API
6
+ * key the Host exports, which a Run uses only when it was started with
7
+ * `--api-key`. The choice is the Host's business, so it is a flag and never a
8
+ * field of the Target's config.
9
+ */
10
+ export type Credential = "subscription" | "api-key";
11
+
12
+ /**
13
+ * The variable the CLI reads an API key from. Under `-p` it outranks the
14
+ * subscription login without asking, so a Stage of a subscription Run is
15
+ * started without it, whatever the Host exports.
16
+ */
17
+ export const API_KEY_ENV_VAR = "ANTHROPIC_API_KEY";
18
+
19
+ /** The credential, as the Run summary's header and the log name it. */
20
+ export const CREDENTIAL_WORDS: Record<Credential, string> = {
21
+ subscription: "subscription",
22
+ "api-key": "API key",
23
+ };
24
+
25
+ /**
26
+ * The `apiKeySource` a Stage's `system/init` event reports when it ran on the
27
+ * Run's credential. Any other is a Stage billed somewhere the Run did not
28
+ * choose: a key an `apiKeyHelper` in the Host's settings supplied, say, which
29
+ * no environment variable removes.
30
+ */
31
+ export function expectedKeySource(credential: Credential): string {
32
+ return credential === "api-key" ? API_KEY_ENV_VAR : "none";
33
+ }
34
+
35
+ /**
36
+ * A Stage that reported another `apiKeySource` than its Run's credential
37
+ * expects, which the Run's log and its summary each name.
38
+ */
39
+ export interface StrayStage {
40
+ ticket: number;
41
+ stage: string;
42
+ /** What the Stage's `system/init` event said it ran on. */
43
+ apiKeySource: string;
44
+ }
45
+
46
+ /**
47
+ * Why a Run on `credential` will not start on this Host, or nothing where it
48
+ * can.
49
+ *
50
+ * Only an `--api-key` Run can be refused. A cloud Host always runs its
51
+ * sessions on the subscription whatever its environment says, so the flag
52
+ * would be a Run spending the subscription without a word; and a Host that
53
+ * exports no key has none to hand the Stages.
54
+ */
55
+ export function credentialRefusal(
56
+ credential: Credential,
57
+ host: HostKind,
58
+ env: Record<string, string | undefined>,
59
+ ): string | undefined {
60
+ if (credential !== "api-key") return undefined;
61
+ if (host === "cloud") {
62
+ return (
63
+ "`--api-key` needs a workstation Host: a cloud session runs every Stage on the " +
64
+ `subscription, whatever \`${API_KEY_ENV_VAR}\` says. Run without \`--api-key\`, or ` +
65
+ "start the Run on a workstation."
66
+ );
67
+ }
68
+ if ((env[API_KEY_ENV_VAR] ?? "") === "") {
69
+ return (
70
+ `\`--api-key\` runs every Stage on the \`${API_KEY_ENV_VAR}\` this shell exports, and it ` +
71
+ "exports none. Export the key, or run without `--api-key` to run on the subscription."
72
+ );
73
+ }
74
+ return undefined;
75
+ }