crysk 0.0.0 → 0.3.1
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/LICENSE +176 -0
- package/README.md +611 -3
- package/bin/pr-hero.js +166 -0
- package/config/models/anthropic.json +5 -0
- package/dist/SKILL-7e3725zn.md +496 -0
- package/dist/SKILL-7q35wcaz.md +66 -0
- package/dist/SKILL-9at22381.md +74 -0
- package/dist/SKILL-ex2hxxh3.md +134 -0
- package/dist/SKILL-y8rv8msh.md +134 -0
- package/dist/SKILL-ygka1bs0.md +515 -0
- package/dist/adjudicator-dtg2axnh.md +86 -0
- package/dist/admission-config.example-a9vqmmad.json +9 -0
- package/dist/ci-admission-camfbx2b.md +122 -0
- package/dist/ci-admission-qk9r9taq.md +124 -0
- package/dist/cli.js +42501 -0
- package/dist/consolidate-ac0mnfyj.md +24 -0
- package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
- package/dist/deep-review-logic-a6b1gczf.md +156 -0
- package/dist/deep-review-parity-0ec904db.md +120 -0
- package/dist/deep-review-reliability-qyakbjb9.md +125 -0
- package/dist/deep-review-resilience-3tz8y26e.md +118 -0
- package/dist/index.js +20190 -0
- package/dist/opencode-ci-7b0be64p.md +141 -0
- package/dist/review-refuter-j4e9gezy.md +71 -0
- package/dist/scout-yvp153q7.md +140 -0
- package/dist/summarizer-zca44nxa.md +18 -0
- package/dist/workflow-w1g9szna.yml +151 -0
- package/package.json +81 -4
- package/prompts/consolidate.md +24 -0
- package/prompts/default/PROVENANCE.md +18 -0
- package/prompts/default/deep-review-lifecycle.md +362 -0
- package/prompts/default/deep-review-logic.md +156 -0
- package/prompts/default/deep-review-parity.md +120 -0
- package/prompts/default/deep-review-reliability.md +125 -0
- package/prompts/default/deep-review-resilience.md +118 -0
- package/prompts/default/review-refuter.md +71 -0
- package/prompts/scout.md +140 -0
- package/prompts/summarizer.md +18 -0
- package/skills/crysk/SKILL.md +74 -0
- package/skills/crysk-ci-setup/SKILL.md +134 -0
- package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
- package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
- package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
- package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
- package/skills/crysk-loop/SKILL.md +515 -0
- package/skills/crysk-loop/adjudicator.md +86 -0
- package/skills/crysk-pr/SKILL.md +66 -0
- package/src/agent-env.ts +1084 -0
- package/src/asset-manifest.ts +83 -0
- package/src/assets.d.ts +6 -0
- package/src/assets.ts +183 -0
- package/src/brand-paths.ts +155 -0
- package/src/brand.ts +255 -0
- package/src/ci/admission-ledger.ts +350 -0
- package/src/ci/classify-error.ts +73 -0
- package/src/ci/cli-record.ts +271 -0
- package/src/ci/force-comment.ts +39 -0
- package/src/ci/gates.ts +945 -0
- package/src/ci/outcome.ts +2181 -0
- package/src/ci/override.ts +187 -0
- package/src/ci/publish.ts +1639 -0
- package/src/ci/reporter.ts +626 -0
- package/src/ci/review-admission.ts +910 -0
- package/src/ci/review-levels.ts +310 -0
- package/src/ci/review-policy.ts +18 -0
- package/src/ci/review-risk.ts +184 -0
- package/src/ci/setup.ts +844 -0
- package/src/ci/trigger.ts +1353 -0
- package/src/cli.ts +348 -0
- package/src/commands/activity.ts +67 -0
- package/src/commands/ci-setup-questions.ts +397 -0
- package/src/commands/ci-setup.ts +381 -0
- package/src/commands/config.ts +99 -0
- package/src/commands/doctor.ts +108 -0
- package/src/commands/init.ts +139 -0
- package/src/commands/mcp.ts +10 -0
- package/src/commands/menu.ts +129 -0
- package/src/commands/post.ts +302 -0
- package/src/commands/skills.ts +83 -0
- package/src/commands/status.ts +173 -0
- package/src/commands/triage.ts +342 -0
- package/src/commands/uninstall.ts +37 -0
- package/src/commands/upgrade.ts +214 -0
- package/src/commands/usage.ts +98 -0
- package/src/compare/compare.ts +28 -0
- package/src/compare/floor-test.ts +471 -0
- package/src/compare/martian-adapter.ts +80 -0
- package/src/config/config.ts +267 -0
- package/src/corpus/corpus.ts +1094 -0
- package/src/corpus/preflight.ts +1789 -0
- package/src/diversity/accounting.ts +90 -0
- package/src/diversity/adjudication.ts +145 -0
- package/src/diversity/admission.ts +60 -0
- package/src/diversity/benchmark.ts +195 -0
- package/src/diversity/clustering.ts +285 -0
- package/src/diversity/errors.ts +7 -0
- package/src/diversity/identity.ts +285 -0
- package/src/diversity/index.ts +11 -0
- package/src/diversity/pipeline-integration.ts +448 -0
- package/src/diversity/projection.ts +57 -0
- package/src/diversity/self-contained.ts +68 -0
- package/src/diversity/target-validation.ts +179 -0
- package/src/doctor-migration.ts +209 -0
- package/src/doctor.ts +723 -0
- package/src/errors.ts +83 -0
- package/src/execution/admission.ts +75 -0
- package/src/execution/atomic-write.ts +35 -0
- package/src/execution/attempt-evidence.ts +415 -0
- package/src/execution/bucket-id.ts +136 -0
- package/src/execution/concurrency-limiter.ts +175 -0
- package/src/execution/contracts.ts +443 -0
- package/src/execution/failure-classification.ts +42 -0
- package/src/execution/failure-policy.ts +240 -0
- package/src/execution/harness.ts +2548 -0
- package/src/execution/settlement.ts +348 -0
- package/src/execution/spawned-process.ts +66 -0
- package/src/execution/spend-limiter.ts +424 -0
- package/src/execution/step-artifacts.ts +55 -0
- package/src/execution/usage-normalized.ts +469 -0
- package/src/git/git.ts +396 -0
- package/src/git/identity.ts +64 -0
- package/src/git/refs.ts +140 -0
- package/src/home-preflight.ts +443 -0
- package/src/home.ts +243 -0
- package/src/ignore-file.ts +336 -0
- package/src/ignore-read.ts +118 -0
- package/src/index.ts +34 -0
- package/src/legacy-launchd.ts +29 -0
- package/src/mcp/mcp.ts +150 -0
- package/src/mcp/preflight.ts +407 -0
- package/src/menu-context.ts +192 -0
- package/src/model/catalog.ts +251 -0
- package/src/model/exec-snapshots.ts +390 -0
- package/src/model/free-discovery.ts +302 -0
- package/src/model/provider-capabilities.ts +814 -0
- package/src/model/routing.ts +600 -0
- package/src/pr/admission.ts +984 -0
- package/src/pr/answered-findings.ts +169 -0
- package/src/pr/ci-admission-gate.ts +743 -0
- package/src/pr/ci-publish.ts +76 -0
- package/src/pr/discovery.ts +432 -0
- package/src/pr/inline.ts +507 -0
- package/src/pr/plan.ts +366 -0
- package/src/pr/posting.ts +115 -0
- package/src/pr/pr-status.ts +845 -0
- package/src/pr/pr.ts +3642 -0
- package/src/pr/preflight.ts +1031 -0
- package/src/pr/publish-outcome.ts +361 -0
- package/src/pr/range.ts +119 -0
- package/src/pr/reverts-preflight.ts +606 -0
- package/src/pr/reverts.ts +377 -0
- package/src/pr/review-pr.ts +927 -0
- package/src/pr/status.ts +154 -0
- package/src/pr/target.ts +388 -0
- package/src/pr/teardown.ts +437 -0
- package/src/pr/worktree-setup.ts +60 -0
- package/src/production-runtime.ts +1877 -0
- package/src/progress.ts +487 -0
- package/src/rereview/adjudicate.ts +89 -0
- package/src/rereview/classify.ts +362 -0
- package/src/rereview/identity.ts +211 -0
- package/src/rereview/plan.ts +308 -0
- package/src/rereview/prepare.ts +1025 -0
- package/src/rereview/state.ts +767 -0
- package/src/rereview/verify.ts +241 -0
- package/src/review/boundary.ts +105 -0
- package/src/review/consolidate.ts +246 -0
- package/src/review/dedupe.ts +368 -0
- package/src/review/drafts.ts +448 -0
- package/src/review/findings-conformance.ts +120 -0
- package/src/review/findings.ts +714 -0
- package/src/review/pipeline.ts +3977 -0
- package/src/review/preflight.ts +3575 -0
- package/src/review/prompt-set.ts +177 -0
- package/src/review/proof-refs.ts +187 -0
- package/src/review/report.ts +1821 -0
- package/src/review/review.ts +490 -0
- package/src/review/root-cause.ts +120 -0
- package/src/review/route-preflight.ts +289 -0
- package/src/review/run.ts +601 -0
- package/src/review/scout.ts +323 -0
- package/src/review/size-gate.ts +595 -0
- package/src/review/spec.ts +235 -0
- package/src/review/step-runner.ts +233 -0
- package/src/runner-authority.ts +596 -0
- package/src/security/binding-policy.ts +115 -0
- package/src/security/credential-broker.ts +773 -0
- package/src/security/evidence-redaction.ts +62 -0
- package/src/security/execution-authority.ts +27 -0
- package/src/security/redact.ts +71 -0
- package/src/security/workspace-read-broker.ts +466 -0
- package/src/server/client.ts +190 -0
- package/src/server/preflight.ts +217 -0
- package/src/server/server.ts +327 -0
- package/src/signal-handler.ts +50 -0
- package/src/store/activity.ts +413 -0
- package/src/store/backfill-preflight.ts +49 -0
- package/src/store/backfill.ts +141 -0
- package/src/store/gc-preflight.ts +206 -0
- package/src/store/gc.ts +424 -0
- package/src/store/metrics-preflight.ts +229 -0
- package/src/store/metrics.ts +236 -0
- package/src/store/preflight.ts +748 -0
- package/src/store/store.ts +693 -0
- package/src/system-tools.ts +355 -0
- package/src/transport-registry.ts +1124 -0
- package/src/transports/claude-code-cli.ts +1348 -0
- package/src/transports/opencode-admission.ts +515 -0
- package/src/transports/opencode-client.ts +3328 -0
- package/src/transports/opencode-evidence.ts +557 -0
- package/src/transports/opencode-mcp.ts +248 -0
- package/src/transports/opencode-sdk.ts +2294 -0
- package/src/transports/opencode-server.ts +535 -0
- package/src/triage/adjudication.ts +113 -0
- package/src/triage/reply.ts +125 -0
- package/src/triage/triage.ts +255 -0
- package/src/ui/activity.ts +173 -0
- package/src/ui/config-edit.ts +816 -0
- package/src/ui/config.ts +462 -0
- package/src/ui/menu.ts +1325 -0
- package/src/ui/plan.ts +1039 -0
- package/src/ui/primitives.ts +300 -0
- package/src/ui/progress.ts +298 -0
- package/src/ui/result.ts +552 -0
- package/src/ui/review-menu.ts +312 -0
- package/src/ui/select.ts +528 -0
- package/src/ui/tree.ts +178 -0
- package/src/uninstaller.ts +479 -0
- package/src/updater.ts +836 -0
- package/src/usage.ts +77 -0
- package/src/watch/preflight.ts +1389 -0
- package/src/watch/watch.ts +1235 -0
- package/src/wizard.ts +877 -0
|
@@ -0,0 +1,1348 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync } from "node:fs";
|
|
3
|
+
import { isEffort } from "#model/catalog";
|
|
4
|
+
import { CLAUDE_CAPABILITY_STATICS } from "#model/provider-capabilities";
|
|
5
|
+
import { spawnModelForClaudeCli } from "#model/routing";
|
|
6
|
+
import type { BucketScope } from "../execution/bucket-id";
|
|
7
|
+
import { deriveBucketId } from "../execution/bucket-id";
|
|
8
|
+
import type {
|
|
9
|
+
FailureCredential,
|
|
10
|
+
ObservedModel,
|
|
11
|
+
ProviderCapabilityReport,
|
|
12
|
+
ProviderTerminalProof,
|
|
13
|
+
ProviderTransport,
|
|
14
|
+
ResolvedModelRoute,
|
|
15
|
+
TransportFailureCause,
|
|
16
|
+
TransportOutcome,
|
|
17
|
+
TransportRequest,
|
|
18
|
+
} from "../execution/contracts";
|
|
19
|
+
import {
|
|
20
|
+
ACTIVE_CHILD_PROCS,
|
|
21
|
+
type SpawnedProcess,
|
|
22
|
+
} from "../execution/spawned-process";
|
|
23
|
+
import type { NormalizedUsage } from "../execution/usage-normalized";
|
|
24
|
+
import {
|
|
25
|
+
envBillsMetered,
|
|
26
|
+
METERED_CREDENTIAL_ENV,
|
|
27
|
+
normalizePartialUsage,
|
|
28
|
+
normalizeUnavailableUsage,
|
|
29
|
+
} from "../execution/usage-normalized";
|
|
30
|
+
|
|
31
|
+
// §9.2 non-secret provider label this transport's route always resolves to
|
|
32
|
+
// (the only route it drives is Anthropic-via-Claude-CLI). A per-request
|
|
33
|
+
// `route.provider` exists on TransportRequest but capabilities() is called
|
|
34
|
+
// before any specific request, so the identity string is this transport's
|
|
35
|
+
// own fixed provider — never inferred from a request that may not exist yet.
|
|
36
|
+
const BUCKET_IDENTITY_PROVIDER = "anthropic";
|
|
37
|
+
|
|
38
|
+
// D1-08 PR3 (§9.2): input a caller MAY supply once it has resolved a
|
|
39
|
+
// credential's projection and its bucketScope — none does yet (that wiring
|
|
40
|
+
// is PR5a's job). Omitting this argument keeps capabilities() byte-identical
|
|
41
|
+
// to pre-PR3 behavior: rateLimitBucketId stays undefined.
|
|
42
|
+
export interface ClaudeCliCapabilitiesInput {
|
|
43
|
+
readonly credentialFingerprint: string;
|
|
44
|
+
readonly bucketScope?: BucketScope;
|
|
45
|
+
readonly localKey: Uint8Array;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// §5.2 CLI/POSIX cascade: SIGTERM -> 5,000 ms grace -> SIGKILL -> reap bound
|
|
49
|
+
// 2,000 ms, all inside the harness's 7,500 ms deadline including scheduler
|
|
50
|
+
// margin. The numbers are contract, not taste — do not tune them here.
|
|
51
|
+
const TERM_GRACE_MS = 5000;
|
|
52
|
+
const KILL_REAP_MS = 2000;
|
|
53
|
+
|
|
54
|
+
export interface PromptFileStatus {
|
|
55
|
+
readonly mode: number;
|
|
56
|
+
readonly isSymbolicLink: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function systemPromptStatus(promptPath: string): PromptFileStatus | undefined {
|
|
60
|
+
try {
|
|
61
|
+
const stats = lstatSync(promptPath);
|
|
62
|
+
return { mode: stats.mode, isSymbolicLink: stats.isSymbolicLink() };
|
|
63
|
+
} catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function hashPromptFile(promptPath: string): string {
|
|
69
|
+
return createHash("sha256").update(readFileSync(promptPath)).digest("hex");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// #177, 2026-09-02. WHICH basis this attempt's money is filed on, decided from
|
|
73
|
+
// the env the CHILD is spawned with — the one fact that separates a
|
|
74
|
+
// subscription run (quota, nothing charged) from an API-key run (a real
|
|
75
|
+
// per-token invoice).
|
|
76
|
+
//
|
|
77
|
+
// #173 applied the subscription rule STATICALLY here and was right about its
|
|
78
|
+
// reasoning and wrong about its premise. Its premise was
|
|
79
|
+
// `credentialKindForRoute` (runner-authority.ts), which returns
|
|
80
|
+
// `claude_subscription_oauth` for this backend UNCONDITIONALLY without ever
|
|
81
|
+
// reading the environment — so it cannot distinguish the two, and taking it as
|
|
82
|
+
// proof made every API-key user's real spend render as "at list price, not
|
|
83
|
+
// charged". Worse, §8 makes budget enforcement cash-only, so that user's spend
|
|
84
|
+
// ceiling read $0 and effectively stopped existing. Under-reporting, shipped by
|
|
85
|
+
// the change that set out to stop it.
|
|
86
|
+
//
|
|
87
|
+
// The fix is deliberately NARROW: it does not derive `credentialKindForRoute`,
|
|
88
|
+
// and it does not touch route admission. See the guard on `envBillsMetered`.
|
|
89
|
+
// #197 removed the REASON that guard used to give — a metered claude-code
|
|
90
|
+
// route is no longer refused for lack of pricing, because `pricingReady` is
|
|
91
|
+
// now `true` for this transport — but not the guard: which credential a route
|
|
92
|
+
// runs on is `credentialKindForRoute`'s single decision (#161), and
|
|
93
|
+
// deriving it from the env HERE would fork it. This only decides how an
|
|
94
|
+
// attempt that already ran gets FILED.
|
|
95
|
+
//
|
|
96
|
+
// What each arm claims:
|
|
97
|
+
// * metered — `costSource: "provider"` because the CLI's own figure is what
|
|
98
|
+
// the API bills at (its per-model `costBasis` is `"list"`, and on a
|
|
99
|
+
// per-token key list price IS the charge). This restores #173's cash
|
|
100
|
+
// filing for this credential; `billingMode` is a truthful UPGRADE over the
|
|
101
|
+
// pre-#173 shape, which said "subscription" on every route.
|
|
102
|
+
// * subscription — #173's rule, unchanged: nothing is charged, so the list
|
|
103
|
+
// figure is notional and `costSource` is `"subscription"` (not "provider":
|
|
104
|
+
// it is not what the provider charged; not "versioned_rate_table": we
|
|
105
|
+
// computed nothing).
|
|
106
|
+
//
|
|
107
|
+
// Returned as ONE object rather than two reads so `noSpawnUsage` and the two
|
|
108
|
+
// parse arms cannot drift: `sumNormalizedUsage` collapses `billingMode` AND
|
|
109
|
+
// `costSource` to "unknown" the moment two attempts of one step disagree, and
|
|
110
|
+
// this transport retries.
|
|
111
|
+
function claudeCliCostBasis(
|
|
112
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
113
|
+
): {
|
|
114
|
+
readonly billingMode: NormalizedUsage["billingMode"];
|
|
115
|
+
readonly costSource: NormalizedUsage["costSource"];
|
|
116
|
+
} {
|
|
117
|
+
return envBillsMetered(env)
|
|
118
|
+
? { billingMode: "metered", costSource: "provider" }
|
|
119
|
+
: { billingMode: "subscription", costSource: "subscription" };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// A denial before spawn, or a PGID proof failure that refuses to signal a
|
|
123
|
+
// child we never trust, is genuine zero cost — no attempt reached the
|
|
124
|
+
// provider, so nothing was spent. This is deliberately NOT
|
|
125
|
+
// `normalizeUnavailableUsage`: "unavailable" means an attempt ran and its
|
|
126
|
+
// cost is unknown, which would misfile a $0 refusal as an unresolved spend
|
|
127
|
+
// once PR5's spend ledger reads completeness.
|
|
128
|
+
//
|
|
129
|
+
// #173, 2026-09-02: `costSource` was `"provider"` here, which was never true
|
|
130
|
+
// — no provider was contacted. It has to match the parse arms below for a
|
|
131
|
+
// second, mechanical reason: an unclassified failure legacy-classifies as
|
|
132
|
+
// "format" (step-runner.ts `classifyFailure`), which has a retry, so a denied
|
|
133
|
+
// attempt 1 can be summed with a spawned attempt 2 — and `sumNormalizedUsage`
|
|
134
|
+
// collapses `costSource` to "unknown" whenever two attempts disagree. Leaving
|
|
135
|
+
// this one behind would have erased the run's cost basis on exactly the retry
|
|
136
|
+
// path this transport already supports.
|
|
137
|
+
//
|
|
138
|
+
// #177, 2026-09-02: that obligation is now owed on TWO bases, so the basis is
|
|
139
|
+
// no longer written out here — `claudeCliCostBasis` is the single source both
|
|
140
|
+
// this function and the parse arms consume. Only `cashCostUsd: 0` stays local,
|
|
141
|
+
// and it is a genuine zero on either basis: no attempt reached the provider.
|
|
142
|
+
// With `tokens: {}` it also cannot trip the metered-zero rule
|
|
143
|
+
// (`settlementFromUsage`), which needs output tokens to fire.
|
|
144
|
+
function noSpawnUsage(
|
|
145
|
+
wallMs: number,
|
|
146
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
147
|
+
): NormalizedUsage {
|
|
148
|
+
return {
|
|
149
|
+
wallMs,
|
|
150
|
+
tokens: {},
|
|
151
|
+
completeness: "complete",
|
|
152
|
+
...claudeCliCostBasis(env),
|
|
153
|
+
cashCostUsd: 0,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface RawClaudeCliResult {
|
|
158
|
+
readonly total_cost_usd?: number;
|
|
159
|
+
// #299. Read through `toolInvocationsFromCliResult`, never directly: the
|
|
160
|
+
// type is `unknown` because the only trustworthy shape is an integer >= 1.
|
|
161
|
+
readonly num_turns?: unknown;
|
|
162
|
+
readonly usage?: {
|
|
163
|
+
readonly input_tokens?: number;
|
|
164
|
+
readonly output_tokens?: number;
|
|
165
|
+
readonly cache_creation_input_tokens?: number;
|
|
166
|
+
readonly cache_read_input_tokens?: number;
|
|
167
|
+
};
|
|
168
|
+
// #175 half 2. The CLI reports, per model it actually ran, an entry keyed
|
|
169
|
+
// on the exact snapshot. Only the two identity fields are declared:
|
|
170
|
+
// `canonicalModel` (the family) and the key itself.
|
|
171
|
+
//
|
|
172
|
+
// The real block also carries `costUSD`, `costBasis` and token counts. They
|
|
173
|
+
// are deliberately NOT read here. Cost already has ONE parse site
|
|
174
|
+
// (`normalizeClaudeCliUsage`, from `total_cost_usd`) and one filing
|
|
175
|
+
// decision; a second reader of a second cost field is exactly how two
|
|
176
|
+
// numbers for one attempt start disagreeing.
|
|
177
|
+
//
|
|
178
|
+
// #173 closed the `costBasis: "list"` problem this comment used to defer,
|
|
179
|
+
// and closed it WITHOUT reading the field. `costBasis` is in the response,
|
|
180
|
+
// but the FILING decision follows the credential's billing mode rather than
|
|
181
|
+
// the response's label: `normalizeClaudeCliUsage` files `total_cost_usd` as
|
|
182
|
+
// notional on the strength of the route being a subscription, which is true
|
|
183
|
+
// whatever any per-model entry says. Parsing `costBasis` per model would add
|
|
184
|
+
// the second cost reader this paragraph exists to refuse. What is still unread and still
|
|
185
|
+
// wanted is the per-model SPLIT (#173 records it): one `--model sonnet`
|
|
186
|
+
// invocation ran two models, so a single route-level cost is an incomplete
|
|
187
|
+
// provenance claim in the same way a single `modelSnapshot` is.
|
|
188
|
+
readonly modelUsage?: Readonly<
|
|
189
|
+
Record<string, { readonly canonicalModel?: unknown } | null | undefined>
|
|
190
|
+
>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// #175 half 2: which models the provider says it ran, in the order it
|
|
194
|
+
// reported them.
|
|
195
|
+
//
|
|
196
|
+
// Absence over fabrication, three ways: unparseable stdout, no `modelUsage`
|
|
197
|
+
// key, and an EMPTY `modelUsage` all answer `undefined`. An empty array would
|
|
198
|
+
// assert "we looked and nothing ran", which is a claim about the provider we
|
|
199
|
+
// have no basis for — the same distinction `normalizeUnavailableUsage` draws
|
|
200
|
+
// between an unknown cost and a zero one.
|
|
201
|
+
//
|
|
202
|
+
// Parsed separately from `normalizeClaudeCliUsage` rather than folded into
|
|
203
|
+
// it: that function's contract is the §8 numeric shape, and its every branch
|
|
204
|
+
// is about not fabricating a token count. Identity is a different fact with
|
|
205
|
+
// different failure modes, so it gets its own parse and its own honest
|
|
206
|
+
// absence.
|
|
207
|
+
function observedModelsFromCliResult(
|
|
208
|
+
rawStdout: string,
|
|
209
|
+
): readonly ObservedModel[] | undefined {
|
|
210
|
+
let parsed: RawClaudeCliResult;
|
|
211
|
+
try {
|
|
212
|
+
parsed = JSON.parse(rawStdout);
|
|
213
|
+
} catch {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
const raw = parsed.modelUsage;
|
|
217
|
+
if (raw === undefined || raw === null || typeof raw !== "object") {
|
|
218
|
+
return undefined;
|
|
219
|
+
}
|
|
220
|
+
const observed: ObservedModel[] = [];
|
|
221
|
+
for (const [model, entry] of Object.entries(raw)) {
|
|
222
|
+
if (model.trim().length === 0) continue;
|
|
223
|
+
// A non-string canonicalModel is dropped rather than coerced: the field
|
|
224
|
+
// is a model IDENTITY, and `String(someObject)` would put "[object
|
|
225
|
+
// Object]" into a provenance record that reads as a model name.
|
|
226
|
+
const canonicalModel =
|
|
227
|
+
entry !== null &&
|
|
228
|
+
typeof entry === "object" &&
|
|
229
|
+
typeof entry.canonicalModel === "string" &&
|
|
230
|
+
entry.canonicalModel.trim().length > 0
|
|
231
|
+
? entry.canonicalModel
|
|
232
|
+
: undefined;
|
|
233
|
+
observed.push({
|
|
234
|
+
model,
|
|
235
|
+
...(canonicalModel === undefined ? {} : { canonicalModel }),
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
return observed.length === 0 ? undefined : observed;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// #299 (2026-10-01): how many tool calls the model made, as far as the CLI's
|
|
242
|
+
// result lets us say. `num_turns` counts ASSISTANT turns, and every turn after
|
|
243
|
+
// the first begins from tool results, so `num_turns - 1` is a LOWER BOUND on
|
|
244
|
+
// tool calls: parallel calls inside one turn count once. That is exact on the
|
|
245
|
+
// one distinction the vacuous-hunt gate needs, zero versus nonzero, and
|
|
246
|
+
// deliberately not offered as a call count. Observed 2026-10-01: 1 turn with no
|
|
247
|
+
// tools, 2 turns for one Read, 17 turns for a deep hunt.
|
|
248
|
+
//
|
|
249
|
+
// `undefined` — never a fabricated 0 — unless `num_turns` is an integer >= 1.
|
|
250
|
+
// A 0 here asserts "we looked and the model issued none", which would fail a
|
|
251
|
+
// hunt on the strength of a field we never saw (missing, a string, a float, or
|
|
252
|
+
// a turn count of 0, which no completed attempt can have). Each attempt is its
|
|
253
|
+
// own `claude -p` process, with no `--resume`, so `num_turns` is per attempt
|
|
254
|
+
// and a retry cannot inherit the previous attempt's count.
|
|
255
|
+
function toolInvocationsFromCliResult(rawStdout: string): number | undefined {
|
|
256
|
+
let parsed: RawClaudeCliResult;
|
|
257
|
+
try {
|
|
258
|
+
parsed = JSON.parse(rawStdout);
|
|
259
|
+
} catch {
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
// `JSON.parse("null")` is valid JSON and not an object.
|
|
263
|
+
if (parsed === null || typeof parsed !== "object") return undefined;
|
|
264
|
+
const turns = parsed.num_turns;
|
|
265
|
+
return typeof turns === "number" && Number.isInteger(turns) && turns >= 1
|
|
266
|
+
? turns - 1
|
|
267
|
+
: undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// #173 (§8, docs/multi-runtime-model-diversity-design.md:462): "Subscription
|
|
271
|
+
// OAuth may truthfully report `cashCostUsd: 0`; optional catalog cost is
|
|
272
|
+
// `notionalCostUsd` and never mixed with cash." This is the one site that
|
|
273
|
+
// applies that rule for this transport.
|
|
274
|
+
//
|
|
275
|
+
// #177, 2026-09-02: it is applied per-credential, NOT statically. #173 applied
|
|
276
|
+
// it statically on the strength of `credentialKindForRoute`
|
|
277
|
+
// (runner-authority.ts) returning `claude_subscription_oauth` for this backend
|
|
278
|
+
// unconditionally — and "unconditionally" is the whole problem: that function
|
|
279
|
+
// never reads the environment, so it says subscription for an
|
|
280
|
+
// ANTHROPIC_API_KEY route that is spending real per-token money. The branch is
|
|
281
|
+
// therefore neither unreachable nor untestable, and `claudeCliCostBasis` above
|
|
282
|
+
// is what decides it, from the env this transport spawns the child with.
|
|
283
|
+
//
|
|
284
|
+
// The figure itself is list-basis, verified live 2026-09-02 rather than
|
|
285
|
+
// inferred: the CLI's `modelUsage` block labels each model's `costUSD` with
|
|
286
|
+
// `"costBasis": "list"`, and `total_cost_usd` is their sum. On a subscription
|
|
287
|
+
// nothing is charged, so filing it as cash recorded spend that never happened.
|
|
288
|
+
// On a per-token key, list price IS the charge, so cash is exactly where it
|
|
289
|
+
// belongs — and `notionalCostUsd` stays absent rather than duplicating it,
|
|
290
|
+
// because the same figure in both fields would report one attempt's tokens as
|
|
291
|
+
// real spend AND as an untaken list price.
|
|
292
|
+
//
|
|
293
|
+
// Note the two fields answer to different things. `notionalCostUsd` follows
|
|
294
|
+
// the provider: absent when the CLI reported no total, because inventing 0
|
|
295
|
+
// there would claim the attempt consumed nothing. `cashCostUsd` follows the
|
|
296
|
+
// CREDENTIAL: it is 0 on the subscription arm because the subscription charges
|
|
297
|
+
// nothing, whatever the CLI said.
|
|
298
|
+
//
|
|
299
|
+
// §8: `--output-format json`'s usage block is already disjoint-additive —
|
|
300
|
+
// input_tokens (uncached), cache_read_input_tokens, and
|
|
301
|
+
// cache_creation_input_tokens sum to total input (verified against the real
|
|
302
|
+
// CLI); this is NOT OpenAI's "total that includes a subset" shape, so the
|
|
303
|
+
// leaves are read straight across rather than split from a total via
|
|
304
|
+
// `normalizeInclusiveUsage`. Corrupted stdout, and valid JSON carrying no
|
|
305
|
+
// `usage` block at all (a safety-blocked or otherwise usage-less response),
|
|
306
|
+
// both yield `normalizeUnavailableUsage` — never a fabricated zero leaf, the
|
|
307
|
+
// exact "$0 on parse failure" collapse this slice exists to kill.
|
|
308
|
+
function normalizeClaudeCliUsage(
|
|
309
|
+
rawStdout: string,
|
|
310
|
+
wallMs: number,
|
|
311
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
312
|
+
): NormalizedUsage {
|
|
313
|
+
const basis = claudeCliCostBasis(env);
|
|
314
|
+
// The two cost fields decided TOGETHER, so no future editor can move cash
|
|
315
|
+
// without moving notional. `total_cost_usd` lands in exactly ONE of them —
|
|
316
|
+
// as CASH when a per-token credential is paying for it, as NOTIONAL when a
|
|
317
|
+
// subscription is — and never in both: the same figure in both fields would
|
|
318
|
+
// report one attempt's tokens as spend AND as an untaken list price.
|
|
319
|
+
//
|
|
320
|
+
// Absence stays absence on either arm. A CLI that reported no
|
|
321
|
+
// `total_cost_usd` gives a subscription no list figure to record, and gives
|
|
322
|
+
// a metered route no answer to "how much real money was this?" — so the
|
|
323
|
+
// metered arm leaves cash undefined and `settlementFromUsage` calls the
|
|
324
|
+
// attempt unresolved, rather than settling a fabricated $0. That is the
|
|
325
|
+
// same "$0 on parse failure" collapse §8 exists to kill, one door over.
|
|
326
|
+
//
|
|
327
|
+
// `cashCostUsd` on the subscription arm is the one unconditional value: it
|
|
328
|
+
// is 0 because the subscription charges nothing, whatever the CLI said.
|
|
329
|
+
const costFor = (
|
|
330
|
+
total: number | undefined,
|
|
331
|
+
): { cashCostUsd?: number; notionalCostUsd?: number } =>
|
|
332
|
+
basis.billingMode === "metered"
|
|
333
|
+
? { cashCostUsd: total }
|
|
334
|
+
: { cashCostUsd: 0, notionalCostUsd: total };
|
|
335
|
+
let parsed: RawClaudeCliResult;
|
|
336
|
+
try {
|
|
337
|
+
parsed = JSON.parse(rawStdout);
|
|
338
|
+
} catch {
|
|
339
|
+
return normalizeUnavailableUsage({
|
|
340
|
+
wallMs,
|
|
341
|
+
billingMode: basis.billingMode,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
const raw = parsed.usage;
|
|
345
|
+
if (raw === undefined) {
|
|
346
|
+
return normalizeUnavailableUsage({
|
|
347
|
+
wallMs,
|
|
348
|
+
billingMode: basis.billingMode,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
const leafValues = [
|
|
352
|
+
raw.input_tokens,
|
|
353
|
+
raw.cache_read_input_tokens,
|
|
354
|
+
raw.cache_creation_input_tokens,
|
|
355
|
+
raw.output_tokens,
|
|
356
|
+
];
|
|
357
|
+
const allLeavesDefined = leafValues.every((v) => typeof v === "number");
|
|
358
|
+
if (!allLeavesDefined) {
|
|
359
|
+
const providerReportedTotal = leafValues.reduce<number>(
|
|
360
|
+
(sum, v) => sum + (typeof v === "number" ? v : 0),
|
|
361
|
+
0,
|
|
362
|
+
);
|
|
363
|
+
return normalizePartialUsage({
|
|
364
|
+
wallMs,
|
|
365
|
+
providerReportedTotal,
|
|
366
|
+
...basis,
|
|
367
|
+
...costFor(parsed.total_cost_usd),
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
const inputUncached = leafValues[0] as number;
|
|
371
|
+
const inputCacheRead = leafValues[1] as number;
|
|
372
|
+
const inputCacheWrite = leafValues[2] as number;
|
|
373
|
+
const outputVisible = leafValues[3] as number;
|
|
374
|
+
const inputKnown = inputUncached + inputCacheRead + inputCacheWrite;
|
|
375
|
+
return {
|
|
376
|
+
wallMs,
|
|
377
|
+
tokens: {
|
|
378
|
+
inputUncached,
|
|
379
|
+
inputCacheRead,
|
|
380
|
+
inputCacheWrite,
|
|
381
|
+
outputVisible,
|
|
382
|
+
inputKnown,
|
|
383
|
+
outputKnown: outputVisible,
|
|
384
|
+
totalKnown: inputKnown + outputVisible,
|
|
385
|
+
providerReportedTotal: inputKnown + outputVisible,
|
|
386
|
+
},
|
|
387
|
+
completeness: "complete",
|
|
388
|
+
...basis,
|
|
389
|
+
...costFor(parsed.total_cost_usd),
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
type CliProc = SpawnedProcess & { readonly pid: number };
|
|
394
|
+
|
|
395
|
+
type CascadeResult =
|
|
396
|
+
| { kind: "term" }
|
|
397
|
+
| { kind: "kill" }
|
|
398
|
+
| { kind: "kill_unreaped" }
|
|
399
|
+
| { kind: "signal_failed"; error: unknown };
|
|
400
|
+
|
|
401
|
+
export interface ClaudeCodeCliTransportOptions {
|
|
402
|
+
readonly spawnFn?: typeof Bun.spawn;
|
|
403
|
+
readonly getPgid?: (pid: number) => number | undefined;
|
|
404
|
+
readonly killFn?: (pid: number, signal?: string | number) => unknown;
|
|
405
|
+
readonly termGraceMs?: number;
|
|
406
|
+
readonly killReapMs?: number;
|
|
407
|
+
// §6.3 pre-spawn prompt verification surface; injectable for offline tests,
|
|
408
|
+
// production defaults lstat + sha256 over the real file.
|
|
409
|
+
readonly promptLstatFn?: (path: string) => PromptFileStatus | undefined;
|
|
410
|
+
readonly promptHashFn?: (path: string) => string | Promise<string>;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Bun does not (yet) expose process.getpgid; when a future runtime grows one we
|
|
414
|
+
// use it, otherwise the pgid comes from `ps -o pgid= -p <pid>` on this POSIX host.
|
|
415
|
+
const runtimeWithGetpgid = process as typeof process & {
|
|
416
|
+
getpgid?: (pid: number) => number;
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
function systemGetPgid(pid: number): number | undefined {
|
|
420
|
+
if (typeof runtimeWithGetpgid.getpgid === "function") {
|
|
421
|
+
try {
|
|
422
|
+
return runtimeWithGetpgid.getpgid(pid);
|
|
423
|
+
} catch {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const probe = Bun.spawnSync(["ps", "-o", "pgid=", "-p", String(pid)]);
|
|
428
|
+
if (probe.exitCode !== 0) return undefined;
|
|
429
|
+
const raw = probe.stdout.toString().trim();
|
|
430
|
+
if (raw.length === 0) return undefined;
|
|
431
|
+
const pgid = Number(raw);
|
|
432
|
+
return Number.isInteger(pgid) ? pgid : undefined;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Resolves true when `p` settled first, false once `ms` elapsed first.
|
|
436
|
+
function raceExitFirst(p: Promise<unknown>, ms: number): Promise<boolean> {
|
|
437
|
+
return new Promise((resolve) => {
|
|
438
|
+
let settled = false;
|
|
439
|
+
const finish = (value: boolean) => {
|
|
440
|
+
if (!settled) {
|
|
441
|
+
settled = true;
|
|
442
|
+
clearTimeout(timer);
|
|
443
|
+
resolve(value);
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
const timer = setTimeout(() => finish(false), ms);
|
|
447
|
+
p.then(
|
|
448
|
+
() => finish(true),
|
|
449
|
+
() => finish(true),
|
|
450
|
+
);
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async function boundedText(
|
|
455
|
+
pending: Promise<string>,
|
|
456
|
+
ms: number,
|
|
457
|
+
): Promise<string | undefined> {
|
|
458
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
459
|
+
const timeout = new Promise<undefined>((resolve) => {
|
|
460
|
+
timer = setTimeout(() => resolve(undefined), ms);
|
|
461
|
+
});
|
|
462
|
+
const value = await Promise.race([pending, timeout]);
|
|
463
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
464
|
+
return value;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export class ClaudeCodeCliTransport implements ProviderTransport {
|
|
468
|
+
readonly backend = "claude-code";
|
|
469
|
+
readonly admissionIdentity = {
|
|
470
|
+
executable: "claude",
|
|
471
|
+
provider: "anthropic",
|
|
472
|
+
} as const;
|
|
473
|
+
readonly cancellationSemantics = "process-exit" as const;
|
|
474
|
+
readonly defaultRoute: ResolvedModelRoute = {
|
|
475
|
+
backend: "claude-code",
|
|
476
|
+
provider: "anthropic",
|
|
477
|
+
modelFamily: "claude",
|
|
478
|
+
modelSnapshot: "sonnet",
|
|
479
|
+
};
|
|
480
|
+
get billingMode(): NormalizedUsage["billingMode"] {
|
|
481
|
+
return claudeCliCostBasis(process.env).billingMode;
|
|
482
|
+
}
|
|
483
|
+
private readonly spawnFn: typeof Bun.spawn;
|
|
484
|
+
private readonly getPgid: (pid: number) => number | undefined;
|
|
485
|
+
private readonly killFn: (pid: number, signal?: string | number) => unknown;
|
|
486
|
+
private readonly termGraceMs: number;
|
|
487
|
+
private readonly killReapMs: number;
|
|
488
|
+
private readonly promptLstatFn: (
|
|
489
|
+
path: string,
|
|
490
|
+
) => PromptFileStatus | undefined;
|
|
491
|
+
private readonly promptHashFn: (path: string) => string | Promise<string>;
|
|
492
|
+
|
|
493
|
+
constructor(options: ClaudeCodeCliTransportOptions = {}) {
|
|
494
|
+
this.spawnFn = options.spawnFn ?? Bun.spawn;
|
|
495
|
+
this.getPgid = options.getPgid ?? systemGetPgid;
|
|
496
|
+
this.killFn = options.killFn ?? process.kill;
|
|
497
|
+
this.termGraceMs = options.termGraceMs ?? TERM_GRACE_MS;
|
|
498
|
+
this.killReapMs = options.killReapMs ?? KILL_REAP_MS;
|
|
499
|
+
this.promptLstatFn = options.promptLstatFn ?? systemPromptStatus;
|
|
500
|
+
this.promptHashFn = options.promptHashFn ?? hashPromptFile;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// §6.3: system prompts are 0600, non-symlink files whose hashes are checked
|
|
504
|
+
// immediately before spawn. Returns the denial reason, or undefined when
|
|
505
|
+
// verification holds.
|
|
506
|
+
private async verifyPromptIntegrity(
|
|
507
|
+
request: TransportRequest,
|
|
508
|
+
): Promise<string | undefined> {
|
|
509
|
+
const status = await this.promptLstatFn(request.systemPromptPath);
|
|
510
|
+
if (status === undefined) {
|
|
511
|
+
return `system prompt unreadable: ${request.systemPromptPath}`;
|
|
512
|
+
}
|
|
513
|
+
if (status.isSymbolicLink) {
|
|
514
|
+
return `system prompt is a symlink: ${request.systemPromptPath}`;
|
|
515
|
+
}
|
|
516
|
+
// Raw lstat mode carries file-type bits; only the permission bits must be
|
|
517
|
+
// exactly 0600.
|
|
518
|
+
if ((status.mode & 0o777) !== 0o600) {
|
|
519
|
+
return `system prompt mode is ${(status.mode & 0o777).toString(8)}, expected 600`;
|
|
520
|
+
}
|
|
521
|
+
const actualSha256 = await this.promptHashFn(request.systemPromptPath);
|
|
522
|
+
if (actualSha256 !== request.systemPromptSha256) {
|
|
523
|
+
return "system prompt hash mismatch against request.systemPromptSha256";
|
|
524
|
+
}
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// §11/D1-09: static report built from the SAME constants the report
|
|
529
|
+
// producer reads (CLAUDE_CAPABILITY_STATICS), so transport and producer can
|
|
530
|
+
// never contradict each other. projectionReady/syntheticHome are
|
|
531
|
+
// contractual here, not probed: every execute() request must carry an
|
|
532
|
+
// IsolationProjection (credentialProjectionId + syntheticHome) or admission
|
|
533
|
+
// denies it. Unproven features are claimed false with a
|
|
534
|
+
// non-blocking issue, never assumed green: no bounded event sink is wired
|
|
535
|
+
// yet, no dedicated codegraph policy is enforced, and no pricing table
|
|
536
|
+
// exists — hence status "degraded", not "ready".
|
|
537
|
+
async capabilities(
|
|
538
|
+
input?: ClaudeCliCapabilitiesInput,
|
|
539
|
+
): Promise<ProviderCapabilityReport> {
|
|
540
|
+
return {
|
|
541
|
+
backend: "claude-code",
|
|
542
|
+
status: "degraded",
|
|
543
|
+
auth: {
|
|
544
|
+
kind: CLAUDE_CAPABILITY_STATICS.authKind,
|
|
545
|
+
projectionReady: true,
|
|
546
|
+
probe: "not_run",
|
|
547
|
+
},
|
|
548
|
+
isolation: {
|
|
549
|
+
syntheticHome: true,
|
|
550
|
+
workspaceReadBroker: CLAUDE_CAPABILITY_STATICS.workspaceReadBroker,
|
|
551
|
+
codegraphPolicy: false,
|
|
552
|
+
},
|
|
553
|
+
protocol: {
|
|
554
|
+
terminalProof: CLAUDE_CAPABILITY_STATICS.terminalProof,
|
|
555
|
+
boundedEvents: false,
|
|
556
|
+
usageMode: CLAUDE_CAPABILITY_STATICS.usageMode,
|
|
557
|
+
},
|
|
558
|
+
cancellation: {
|
|
559
|
+
deadlineMs: CLAUDE_CAPABILITY_STATICS.cancellationDeadlineMs,
|
|
560
|
+
conformance: CLAUDE_CAPABILITY_STATICS.cancellationConformance,
|
|
561
|
+
},
|
|
562
|
+
billing: {
|
|
563
|
+
mode: CLAUDE_CAPABILITY_STATICS.billingMode,
|
|
564
|
+
// #197. WHAT THIS FLAG ASSERTS, which is narrower than it reads.
|
|
565
|
+
// `pricingReady` lives inside `capabilities()`, built from
|
|
566
|
+
// CLAUDE_CAPABILITY_STATICS — a STATIC claim made at admission,
|
|
567
|
+
// before any spawn. No cost figure exists at the moment it is asked,
|
|
568
|
+
// for any transport, so it cannot be answering "is this attempt's
|
|
569
|
+
// cost a provider invoice?". It answers "will this transport tell you
|
|
570
|
+
// what the attempt cost?", and this one will: the CLI reports
|
|
571
|
+
// `total_cost_usd`, which #177 files as cash on a metered credential
|
|
572
|
+
// and as notional on a subscription.
|
|
573
|
+
//
|
|
574
|
+
// That is why the list-vs-invoice objection this comment used to
|
|
575
|
+
// carry does not survive. It rejected the CLI's figure for being a
|
|
576
|
+
// LIST computation (`costBasis: "list"`) while the alternative it
|
|
577
|
+
// preferred — the bundled `config/models/*-pricing.json` — was a
|
|
578
|
+
// hand-transcribed snapshot of the same published list prices. The
|
|
579
|
+
// choice was never invoice-over-list; it was OUR list price over the
|
|
580
|
+
// CLI's, on a ground that convicted our own. The tables are gone
|
|
581
|
+
// (#197); the CLI's figure tracks the tool the user already upgrades.
|
|
582
|
+
//
|
|
583
|
+
// THIS DELIBERATELY WIDENS ADMISSION, and that is the intent rather
|
|
584
|
+
// than a side effect to discover later. `tokenPricingAvailable`
|
|
585
|
+
// (production-runtime.ts) is now this flag and nothing else, so a
|
|
586
|
+
// metered claude-code route that the old gate refused for a missing
|
|
587
|
+
// or expired table is admitted and runs on the cost the CLI reports.
|
|
588
|
+
// #161 landed on top of this: `credentialKindForRoute`
|
|
589
|
+
// (runner-authority.ts) now derives `provider_api_token` — a metered
|
|
590
|
+
// kind — for a claude-code route whose environment carries
|
|
591
|
+
// ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN AND that has no
|
|
592
|
+
// credential broker projecting for it (no broker means nothing
|
|
593
|
+
// strips the key before the child sees it — the common case being
|
|
594
|
+
// Linux/CI, which has no Keychain to project from). A route that
|
|
595
|
+
// DOES have a broker attached, and whose projection SUCCEEDS, stays
|
|
596
|
+
// subscription regardless of what its env carries, because a
|
|
597
|
+
// successful projection strips the key before spawn — so a
|
|
598
|
+
// claude-code route CAN resolve metered today, not just in the
|
|
599
|
+
// gate's hypothetical, but only when nothing is about to project a
|
|
600
|
+
// credential for it. A degraded projection is #279's known
|
|
601
|
+
// exception: `credentialKindForRoute` still cannot see that a
|
|
602
|
+
// broker's projection failed and fell back to the unstripped env, so
|
|
603
|
+
// that one route keeps saying subscription while the key actually
|
|
604
|
+
// reaches and pays for the child — this ADMISSION-time answer is
|
|
605
|
+
// deliberately left that way (#279, fixed 2026-09-24, option 2: the
|
|
606
|
+
// fix lives downstream, in `StepExecutionHarness.run`, harness.ts,
|
|
607
|
+
// which re-applies `envBillsMetered` to this SAME child env this
|
|
608
|
+
// module stamps `billingMode: "metered"` from, and opens a
|
|
609
|
+
// spend-ledger reservation for that one attempt so it is settled or
|
|
610
|
+
// fenced exactly like a metered route). `pricingReady: true` here is what
|
|
611
|
+
// makes a metered route ADMITTED rather than refused for lack of
|
|
612
|
+
// pricing; #161 is what makes the route exist in the first place.
|
|
613
|
+
// This BACKEND-WIDE report still claims `mode: "subscription"`
|
|
614
|
+
// unconditionally — it is produced before any route resolves and has
|
|
615
|
+
// no per-route credential to read — and it is the EXACT binding
|
|
616
|
+
// (`FrozenRuntimeBinding.capabilities()`, production-runtime.ts) that
|
|
617
|
+
// upgrades to the real per-route mode via
|
|
618
|
+
// `credentialKindBillsMetered(credential.kind)`.
|
|
619
|
+
//
|
|
620
|
+
// The one gap this opens is settled, not hand-waved: `total_cost_usd`
|
|
621
|
+
// is OPTIONAL on `RawClaudeCliResult`, so a metered attempt can
|
|
622
|
+
// complete with no figure. It settles `unresolved` with no
|
|
623
|
+
// `knownUsd` rather than a fabricated $0 (`costFor` above,
|
|
624
|
+
// `settlementFromUsage` in spend-limiter.ts), pinned by "a metered
|
|
625
|
+
// run reporting no cash figure at all" in
|
|
626
|
+
// test/conformance/claude-cli-transport.test.ts.
|
|
627
|
+
pricingReady: true,
|
|
628
|
+
},
|
|
629
|
+
...(input !== undefined
|
|
630
|
+
? {
|
|
631
|
+
rateLimitBucketId: deriveBucketId(
|
|
632
|
+
{
|
|
633
|
+
provider: BUCKET_IDENTITY_PROVIDER,
|
|
634
|
+
credentialFingerprint: input.credentialFingerprint,
|
|
635
|
+
scope: input.bucketScope,
|
|
636
|
+
},
|
|
637
|
+
input.localKey,
|
|
638
|
+
),
|
|
639
|
+
}
|
|
640
|
+
: {}),
|
|
641
|
+
issues: [
|
|
642
|
+
{
|
|
643
|
+
code: "codegraph_policy_unenforced",
|
|
644
|
+
message:
|
|
645
|
+
"no dedicated codegraph sensitive-file policy is enforced yet; isolation relies on --strict-mcp-config with a codegraph-only mcp.json",
|
|
646
|
+
blocking: false,
|
|
647
|
+
},
|
|
648
|
+
{
|
|
649
|
+
code: "bounded_events_sink_missing",
|
|
650
|
+
message:
|
|
651
|
+
"bounded event streaming is not wired: the event sink is currently a no-op and usage arrives as a final snapshot",
|
|
652
|
+
blocking: false,
|
|
653
|
+
},
|
|
654
|
+
],
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
private runCascade(
|
|
659
|
+
proc: CliProc,
|
|
660
|
+
pgid: number | undefined,
|
|
661
|
+
): Promise<CascadeResult> {
|
|
662
|
+
const deliver = (signal: string): boolean => {
|
|
663
|
+
let delivered = false;
|
|
664
|
+
if (pgid !== undefined) {
|
|
665
|
+
// Negative-pgid signaling reaches every descendant the CLI spawned; a
|
|
666
|
+
// bare proc.kill() would orphan its subprocesses. Only reachable once
|
|
667
|
+
// the dedicated-PGID proof held.
|
|
668
|
+
try {
|
|
669
|
+
this.killFn(-pgid, signal);
|
|
670
|
+
delivered = true;
|
|
671
|
+
} catch {
|
|
672
|
+
void signal;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
// Direct line to the leader itself: redundant for a live child (it is in
|
|
676
|
+
// the group) but it unblocks offline doubles whose kill() settles their
|
|
677
|
+
// streams, and it is the only delivery possible when no kernel pid
|
|
678
|
+
// exists to prove a group for.
|
|
679
|
+
try {
|
|
680
|
+
proc.kill();
|
|
681
|
+
delivered = true;
|
|
682
|
+
} catch {
|
|
683
|
+
void signal;
|
|
684
|
+
}
|
|
685
|
+
return delivered;
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
return (async (): Promise<CascadeResult> => {
|
|
689
|
+
// §5.2: SIGTERM to -pgid, then a 5,000 ms grace window before escalation.
|
|
690
|
+
if (!deliver("SIGTERM")) {
|
|
691
|
+
return { kind: "signal_failed", error: new Error("SIGTERM failed") };
|
|
692
|
+
}
|
|
693
|
+
const exitedDuringGrace = await raceExitFirst(
|
|
694
|
+
proc.exited,
|
|
695
|
+
this.termGraceMs,
|
|
696
|
+
);
|
|
697
|
+
if (exitedDuringGrace) return { kind: "term" };
|
|
698
|
+
if (!deliver("SIGKILL")) {
|
|
699
|
+
return { kind: "signal_failed", error: new Error("SIGKILL failed") };
|
|
700
|
+
}
|
|
701
|
+
const reaped = await raceExitFirst(proc.exited, this.killReapMs);
|
|
702
|
+
return reaped ? { kind: "kill" } : { kind: "kill_unreaped" };
|
|
703
|
+
})();
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
async execute(
|
|
707
|
+
request: TransportRequest,
|
|
708
|
+
context: {
|
|
709
|
+
readonly signal: AbortSignal;
|
|
710
|
+
readonly events?: import("../execution/contracts").AsyncEventSink;
|
|
711
|
+
},
|
|
712
|
+
): Promise<TransportOutcome> {
|
|
713
|
+
// The engine owns the effort and ALWAYS passes it (#299). The CLI's own
|
|
714
|
+
// default is `high` except on Sonnet 5.5 / Opus 5.5 (`medium`), so a
|
|
715
|
+
// request that reaches here without a level would quietly put the step back
|
|
716
|
+
// on the implicit default this flag exists to replace. That is a
|
|
717
|
+
// programming error, not a case to fall back from, and it throws before the
|
|
718
|
+
// paid spawn. The child env is an allowlist without
|
|
719
|
+
// CLAUDE_CODE_EFFORT_LEVEL, so nothing the operator exports can override it.
|
|
720
|
+
if (typeof request.effort !== "string" || !isEffort(request.effort)) {
|
|
721
|
+
throw new Error(
|
|
722
|
+
`claude-code transport requires an explicit effort, got ${JSON.stringify(request.effort)}`,
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
// `-p` with NO positional prompt: the CLI then reads the prompt from
|
|
726
|
+
// stdin, which the spawn below supplies (#314 — see the WHY there).
|
|
727
|
+
const args = [
|
|
728
|
+
request.isolation.verifiedBinaryPath,
|
|
729
|
+
"-p",
|
|
730
|
+
"--append-system-prompt-file",
|
|
731
|
+
request.systemPromptPath,
|
|
732
|
+
"--output-format",
|
|
733
|
+
"json",
|
|
734
|
+
];
|
|
735
|
+
|
|
736
|
+
if (request.mcpConfigPath) {
|
|
737
|
+
args.push("--mcp-config", request.mcpConfigPath, "--strict-mcp-config");
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
args.push(
|
|
741
|
+
"--setting-sources",
|
|
742
|
+
"",
|
|
743
|
+
"--tools",
|
|
744
|
+
request.tools.join(","),
|
|
745
|
+
"--permission-mode",
|
|
746
|
+
"bypassPermissions",
|
|
747
|
+
"--model",
|
|
748
|
+
spawnModelForClaudeCli(request.route, request.executionModel),
|
|
749
|
+
"--effort",
|
|
750
|
+
request.effort,
|
|
751
|
+
// Moves the per-machine sections (cwd, env info, git status) out of the
|
|
752
|
+
// system prompt into the first user message. Without it every worktree
|
|
753
|
+
// path changes the system prompt, so no spawn could reuse the cached
|
|
754
|
+
// tools + base prompt another review wrote: measured 2026-10-21 (lab
|
|
755
|
+
// ledger, prompt-cache layout probe), a second repo wrote 6.6k cache
|
|
756
|
+
// tokens without the flag and 1.4k with it. Nothing leaves the context;
|
|
757
|
+
// isolation is unchanged.
|
|
758
|
+
"--exclude-dynamic-system-prompt-sections",
|
|
759
|
+
);
|
|
760
|
+
|
|
761
|
+
const start = performance.now();
|
|
762
|
+
|
|
763
|
+
// §6.3: hash/mode/symlink verification happens immediately before spawn;
|
|
764
|
+
// a failed check never reaches the provider.
|
|
765
|
+
const promptDenial = await this.verifyPromptIntegrity(request);
|
|
766
|
+
if (promptDenial !== undefined) {
|
|
767
|
+
return {
|
|
768
|
+
completion: "failed",
|
|
769
|
+
protocolIntegrity: "unverified",
|
|
770
|
+
finalText: "",
|
|
771
|
+
usage: noSpawnUsage(
|
|
772
|
+
Math.round(performance.now() - start),
|
|
773
|
+
request.isolation.env,
|
|
774
|
+
),
|
|
775
|
+
stderrTail: `[pr-hero] prompt integrity denied: ${promptDenial}; no spawn`,
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// detached: Bun maps this to setsid() on POSIX, so the child starts a new
|
|
780
|
+
// session and leads its own process group — the precondition for §5.2's
|
|
781
|
+
// negative-PGID cascade to be safe at all.
|
|
782
|
+
//
|
|
783
|
+
// stdin carries the user prompt, never argv (#314). The prompt embeds the
|
|
784
|
+
// whole patch, and Linux caps ONE argv string at MAX_ARG_STRLEN (131072
|
|
785
|
+
// bytes including the NUL): a 175,805-byte patch made execve fail with
|
|
786
|
+
// E2BIG, so every hunter on that PR died in 7s before reaching the
|
|
787
|
+
// provider. stdin has no such bound. `claude -p` with no positional
|
|
788
|
+
// prompt reads it from stdin (verified against claude 2.1.289 with a
|
|
789
|
+
// 175,865-byte prompt). Never pass both: which one the CLI would honor is
|
|
790
|
+
// unverified, and a positional prompt brings the size bug back. Same
|
|
791
|
+
// channel and reason as gh's report body in pr/pr.ts.
|
|
792
|
+
//
|
|
793
|
+
// A synchronous spawn throw (execve refused: E2BIG, ENOENT, EACCES) is a
|
|
794
|
+
// failed attempt with its reason, not a rejection (#314). Thrown, it
|
|
795
|
+
// escaped before the try below, the harness swallowed the rejection and
|
|
796
|
+
// settled the attempt as cancelled (the step's only recorded reason was
|
|
797
|
+
// "step cancelled; settled per §5.3"), and the run log said only "failed" —
|
|
798
|
+
// the E2BIG that killed every hunter was visible nowhere. Nothing was
|
|
799
|
+
// spawned, so nothing is registered and nothing was spent.
|
|
800
|
+
let proc: CliProc;
|
|
801
|
+
try {
|
|
802
|
+
proc = this.spawnFn(args, {
|
|
803
|
+
cwd: request.cwd,
|
|
804
|
+
env: request.isolation.env,
|
|
805
|
+
stdin: new TextEncoder().encode(request.userPrompt),
|
|
806
|
+
stdout: "pipe",
|
|
807
|
+
stderr: "pipe",
|
|
808
|
+
detached: true,
|
|
809
|
+
}) as unknown as CliProc;
|
|
810
|
+
} catch (error) {
|
|
811
|
+
return {
|
|
812
|
+
completion: "failed",
|
|
813
|
+
protocolIntegrity: "unverified",
|
|
814
|
+
finalText: "",
|
|
815
|
+
usage: noSpawnUsage(
|
|
816
|
+
Math.round(performance.now() - start),
|
|
817
|
+
request.isolation.env,
|
|
818
|
+
),
|
|
819
|
+
stderrTail: spawnFailureTail(error),
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
ACTIVE_CHILD_PROCS.add(proc);
|
|
824
|
+
|
|
825
|
+
let cascadePromise: Promise<CascadeResult> | undefined;
|
|
826
|
+
let provenPgid: number | undefined;
|
|
827
|
+
let notifyCascadeStart: (value: "cascade") => void = () => {};
|
|
828
|
+
const cascadeStarted = new Promise<"cascade">((resolve) => {
|
|
829
|
+
notifyCascadeStart = resolve;
|
|
830
|
+
});
|
|
831
|
+
const startCascade = () => {
|
|
832
|
+
// Only reachable past the PGID proof below: negative-pgid signaling is
|
|
833
|
+
// armed exclusively after the child was proven to lead its own group
|
|
834
|
+
// (or is an offline double with no group to signal at all).
|
|
835
|
+
if (cascadePromise) return;
|
|
836
|
+
cascadePromise = this.runCascade(proc, provenPgid);
|
|
837
|
+
notifyCascadeStart("cascade");
|
|
838
|
+
};
|
|
839
|
+
const onAbort = () => {
|
|
840
|
+
startCascade();
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
try {
|
|
844
|
+
// §5.2: proof that pid == pgid must hold BEFORE any negative-PGID signal
|
|
845
|
+
// path is armed. Failure means we never signal — a wrong guess could kill
|
|
846
|
+
// the host's own group instead of the child's. A child without a kernel
|
|
847
|
+
// pid is an offline test double: no group exists to prove or signal.
|
|
848
|
+
const rawPid = (proc as { pid?: unknown }).pid;
|
|
849
|
+
const kernelPid =
|
|
850
|
+
typeof rawPid === "number" && Number.isInteger(rawPid) && rawPid > 1
|
|
851
|
+
? rawPid
|
|
852
|
+
: undefined;
|
|
853
|
+
let provenGroup: number | undefined;
|
|
854
|
+
if (kernelPid !== undefined) {
|
|
855
|
+
const pgid = this.getPgid(kernelPid);
|
|
856
|
+
if (pgid === undefined || pgid !== kernelPid) {
|
|
857
|
+
return {
|
|
858
|
+
completion: "failed",
|
|
859
|
+
protocolIntegrity: "unverified",
|
|
860
|
+
finalText: "",
|
|
861
|
+
usage: noSpawnUsage(
|
|
862
|
+
Math.round(performance.now() - start),
|
|
863
|
+
request.isolation.env,
|
|
864
|
+
),
|
|
865
|
+
stderrTail:
|
|
866
|
+
pgid === undefined
|
|
867
|
+
? `[pr-hero] PGID proof failed: could not read pgid for pid ${kernelPid}; no signal sent`
|
|
868
|
+
: `[pr-hero] PGID proof failed: pid ${kernelPid} has pgid ${pgid}, expected ${kernelPid}; no signal sent`,
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
provenGroup = pgid;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
provenPgid = provenGroup;
|
|
875
|
+
|
|
876
|
+
const stdoutPending = new Response(proc.stdout).text();
|
|
877
|
+
const stderrPending = new Response(proc.stderr).text();
|
|
878
|
+
|
|
879
|
+
// Per-attempt step timeout is harness-owned (StepSpec.timeoutMs → watchdog
|
|
880
|
+
// → AbortSignal). Transports react only to the supplied signal.
|
|
881
|
+
|
|
882
|
+
if (context.signal.aborted) {
|
|
883
|
+
onAbort();
|
|
884
|
+
} else {
|
|
885
|
+
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
let exitCode: number | undefined;
|
|
889
|
+
let stdout: string;
|
|
890
|
+
let stderr: string;
|
|
891
|
+
let unreaped = false;
|
|
892
|
+
let escalatedToKill = false;
|
|
893
|
+
|
|
894
|
+
const natural = Promise.all([stdoutPending, stderrPending, proc.exited]);
|
|
895
|
+
|
|
896
|
+
// The ladder can be armed by the timeout while we are mid-await on the
|
|
897
|
+
// natural path; race it so an unkillable group cannot hang us forever.
|
|
898
|
+
const route = await Promise.race([
|
|
899
|
+
natural.then((): "natural" => "natural"),
|
|
900
|
+
cascadeStarted,
|
|
901
|
+
]);
|
|
902
|
+
|
|
903
|
+
if (route === "natural") {
|
|
904
|
+
[stdout, stderr, exitCode] = await natural;
|
|
905
|
+
if (cascadePromise !== undefined) {
|
|
906
|
+
const late = await cascadePromise;
|
|
907
|
+
escalatedToKill =
|
|
908
|
+
late.kind === "kill" || late.kind === "kill_unreaped";
|
|
909
|
+
}
|
|
910
|
+
} else {
|
|
911
|
+
if (cascadePromise === undefined) {
|
|
912
|
+
throw new Error("cascade route taken without an armed cascade");
|
|
913
|
+
}
|
|
914
|
+
const cascade = await cascadePromise;
|
|
915
|
+
escalatedToKill =
|
|
916
|
+
cascade.kind === "kill" || cascade.kind === "kill_unreaped";
|
|
917
|
+
if (
|
|
918
|
+
cascade.kind === "term" ||
|
|
919
|
+
cascade.kind === "kill" ||
|
|
920
|
+
cascade.kind === "signal_failed"
|
|
921
|
+
) {
|
|
922
|
+
[stdout, stderr, exitCode] = await natural;
|
|
923
|
+
} else {
|
|
924
|
+
// The group survived SIGKILL past the 2,000 ms reap bound: stop
|
|
925
|
+
// waiting, take whatever output landed, and record it rather than
|
|
926
|
+
// hang the harness past its 7,500 ms deadline.
|
|
927
|
+
unreaped = true;
|
|
928
|
+
stdout = (await boundedText(stdoutPending, this.killReapMs)) ?? "";
|
|
929
|
+
stderr = (await boundedText(stderrPending, this.killReapMs)) ?? "";
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
const wallMs = Math.round(performance.now() - start);
|
|
934
|
+
|
|
935
|
+
let fullResult = "";
|
|
936
|
+
let apiError: ProviderApiError | undefined;
|
|
937
|
+
try {
|
|
938
|
+
const parsed = JSON.parse(stdout) as CliResultEnvelope;
|
|
939
|
+
fullResult = typeof parsed.result === "string" ? parsed.result : "";
|
|
940
|
+
apiError = providerApiErrorOf(parsed);
|
|
941
|
+
} catch {
|
|
942
|
+
// non-json stdout
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
const usage = normalizeClaudeCliUsage(
|
|
946
|
+
stdout,
|
|
947
|
+
wallMs,
|
|
948
|
+
request.isolation.env,
|
|
949
|
+
);
|
|
950
|
+
const observedModels = observedModelsFromCliResult(stdout);
|
|
951
|
+
const toolInvocations = toolInvocationsFromCliResult(stdout);
|
|
952
|
+
|
|
953
|
+
let stderrTail = stderr.slice(-4096);
|
|
954
|
+
if (unreaped) {
|
|
955
|
+
stderrTail =
|
|
956
|
+
`${stderrTail}\n[pr-hero] child process group -${provenPgid ?? "(unproven)"} was not reaped within ${this.killReapMs}ms after SIGKILL`.slice(
|
|
957
|
+
-4096,
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
const terminalProof: ProviderTerminalProof | undefined =
|
|
962
|
+
exitCode === undefined
|
|
963
|
+
? undefined
|
|
964
|
+
: {
|
|
965
|
+
eventId: `${request.sessionId}-${request.attempt}-terminal`,
|
|
966
|
+
providerStatus: exitCode === 0 ? "completed" : "failed",
|
|
967
|
+
providerObservedAt: new Date().toISOString(),
|
|
968
|
+
exitCode,
|
|
969
|
+
...(escalatedToKill ? { signal: "SIGKILL" } : {}),
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
// The CLI exits 0 when the API rejected the request, with the provider's message in
|
|
973
|
+
// `result`. That message is not the agent's answer: it fails the attempt with its
|
|
974
|
+
// typed cause, is never handed to the draft parser (which would spend a format retry
|
|
975
|
+
// on it), and its words go to the attempt's diagnostics.
|
|
976
|
+
const failureCredential =
|
|
977
|
+
apiError === undefined
|
|
978
|
+
? undefined
|
|
979
|
+
: credentialOf(request.isolation.env);
|
|
980
|
+
if (apiError !== undefined) {
|
|
981
|
+
fullResult = "";
|
|
982
|
+
stderrTail = `${stderrTail}\n[pr-hero] ${apiError.detail}`.slice(-4096);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const isCancelled = context.signal.aborted;
|
|
986
|
+
const completion: TransportOutcome["completion"] = isCancelled
|
|
987
|
+
? "cancelled"
|
|
988
|
+
: apiError === undefined &&
|
|
989
|
+
exitCode === 0 &&
|
|
990
|
+
fullResult &&
|
|
991
|
+
terminalProof !== undefined
|
|
992
|
+
? "success"
|
|
993
|
+
: "failed";
|
|
994
|
+
|
|
995
|
+
if (terminalProof === undefined && !isCancelled) {
|
|
996
|
+
stderrTail =
|
|
997
|
+
`${stderrTail}\n[pr-hero] no terminal proof observed; refusing success`.slice(
|
|
998
|
+
-4096,
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
return {
|
|
1003
|
+
completion,
|
|
1004
|
+
protocolIntegrity:
|
|
1005
|
+
unreaped || terminalProof === undefined
|
|
1006
|
+
? "unverified"
|
|
1007
|
+
: stdout
|
|
1008
|
+
? "verified"
|
|
1009
|
+
: "unverified",
|
|
1010
|
+
...(terminalProof !== undefined ? { terminalProof } : {}),
|
|
1011
|
+
...(apiError === undefined
|
|
1012
|
+
? {}
|
|
1013
|
+
: {
|
|
1014
|
+
failureCause: apiError.cause,
|
|
1015
|
+
failureDetail: apiError.detail,
|
|
1016
|
+
...(failureCredential === undefined ? {} : { failureCredential }),
|
|
1017
|
+
}),
|
|
1018
|
+
finalText: fullResult,
|
|
1019
|
+
usage,
|
|
1020
|
+
stderrTail,
|
|
1021
|
+
...(observedModels === undefined ? {} : { observedModels }),
|
|
1022
|
+
...(toolInvocations === undefined ? {} : { toolInvocations }),
|
|
1023
|
+
...(exitCode !== undefined ? { exitCode } : {}),
|
|
1024
|
+
};
|
|
1025
|
+
} finally {
|
|
1026
|
+
ACTIVE_CHILD_PROCS.delete(proc);
|
|
1027
|
+
context.signal.removeEventListener("abort", onAbort);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
classifyFailure(
|
|
1032
|
+
outcome: TransportOutcome,
|
|
1033
|
+
): TransportFailureCause | undefined {
|
|
1034
|
+
// First, and definitive whatever the error text says (PR #315 review
|
|
1035
|
+
// F004): no child started, so nothing reached a provider and the same
|
|
1036
|
+
// argv would be refused again. Unclassified, it fell through to the
|
|
1037
|
+
// legacy "format" class and respawned once with a format reminder — a
|
|
1038
|
+
// longer prompt, against the E2BIG that a too-long argv caused. See
|
|
1039
|
+
// isSpawnFailureTail for why the whole tail is the witness.
|
|
1040
|
+
if (isSpawnFailureTail(outcome.stderrTail)) {
|
|
1041
|
+
return "runtime_unavailable";
|
|
1042
|
+
}
|
|
1043
|
+
const witness = `${outcome.stderrTail}\n${outcome.finalText}`;
|
|
1044
|
+
// The child's stderr, with no model output mixed in — see the two-witness
|
|
1045
|
+
// note on the backpressure branch below.
|
|
1046
|
+
const diagnostics = outcome.stderrTail;
|
|
1047
|
+
if (/Not logged in\s*[·.]\s*Please run \/login/i.test(witness)) {
|
|
1048
|
+
return "auth_invalid";
|
|
1049
|
+
}
|
|
1050
|
+
// Backpressure is tested BEFORE the generic network witness, and the
|
|
1051
|
+
// order is load-bearing: the real CLI string for an overload is
|
|
1052
|
+
// "API Error: 529 overloaded_error", which matches both. Tested second,
|
|
1053
|
+
// rate_limit would never fire for the exact witness it exists to catch.
|
|
1054
|
+
//
|
|
1055
|
+
// §7 gives these two causes different dispositions on purpose —
|
|
1056
|
+
// rate_limit waits (validated Retry-After or capped exponential),
|
|
1057
|
+
// network_transient retries immediately. Retrying instantly against a
|
|
1058
|
+
// server that just said it is saturated deepens the saturation and burns
|
|
1059
|
+
// the entire transient budget in milliseconds.
|
|
1060
|
+
//
|
|
1061
|
+
// Backpressure is read from TWO witnesses, because the two channels do
|
|
1062
|
+
// not carry the same kind of text. `finalText` is
|
|
1063
|
+
// `JSON.parse(stdout).result` — mixed: the CLI's own error text AND the
|
|
1064
|
+
// model's final message. pr-hero's model output is code-review prose
|
|
1065
|
+
// about exactly these failure modes ("this endpoint has no rate limit",
|
|
1066
|
+
// "consider returning 429"), so an English phrase or a bare status code
|
|
1067
|
+
// read from there matches the tool's own subject matter and routes a
|
|
1068
|
+
// healthy failure into a backoff it never earned. `stderrTail` is the
|
|
1069
|
+
// child's diagnostics channel and carries no model prose at all.
|
|
1070
|
+
//
|
|
1071
|
+
// So: provider error TYPES are machine tokens no reviewer writes in a
|
|
1072
|
+
// sentence, and are trusted from either channel — this is what keeps the
|
|
1073
|
+
// real witness "API Error: 529 overloaded_error" classified even when the
|
|
1074
|
+
// CLI surfaces it through `result`.
|
|
1075
|
+
if (/rate_limit_error|overloaded_error/i.test(witness)) {
|
|
1076
|
+
return "rate_limit";
|
|
1077
|
+
}
|
|
1078
|
+
// Everything prose-shaped — bare phrases and bare status codes — is read
|
|
1079
|
+
// from diagnostics ONLY. Word boundaries keep a token count like 15291 or
|
|
1080
|
+
// a job id like 1429 from being read as a status.
|
|
1081
|
+
if (
|
|
1082
|
+
/\b429\b|\b529\b|\b503\b|overloaded|rate[ _-]?limit|too many requests|service unavailable/i.test(
|
|
1083
|
+
diagnostics,
|
|
1084
|
+
)
|
|
1085
|
+
) {
|
|
1086
|
+
return "rate_limit";
|
|
1087
|
+
}
|
|
1088
|
+
// Connection-level only. Nothing upstream asked us to slow down, and
|
|
1089
|
+
// waiting out a reset socket buys nothing. 502 stays here: a bad gateway
|
|
1090
|
+
// is a proxy failure, not a capacity signal.
|
|
1091
|
+
if (
|
|
1092
|
+
/API Error|Connection closed|ECONNRESET|socket hang up|timed out|\b502\b/i.test(
|
|
1093
|
+
witness,
|
|
1094
|
+
)
|
|
1095
|
+
) {
|
|
1096
|
+
return "network_transient";
|
|
1097
|
+
}
|
|
1098
|
+
return undefined;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// The envelope fields the error map reads. `result` is the model's answer on a normal run
|
|
1103
|
+
// and the CLI's own message on an error.
|
|
1104
|
+
interface CliResultEnvelope {
|
|
1105
|
+
readonly result?: unknown;
|
|
1106
|
+
readonly subtype?: unknown;
|
|
1107
|
+
readonly is_error?: unknown;
|
|
1108
|
+
readonly terminal_reason?: unknown;
|
|
1109
|
+
readonly api_error_status?: unknown;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
interface ProviderApiError {
|
|
1113
|
+
readonly cause: TransportFailureCause;
|
|
1114
|
+
readonly detail: string;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
const API_ERROR_DETAIL_MAX = 160;
|
|
1118
|
+
const UNNAMED_TAG_MAX = 60;
|
|
1119
|
+
|
|
1120
|
+
// Text witnesses that split ONE status into two causes (S3 of odd/tasks/claude-error-map.md).
|
|
1121
|
+
// A 400 is a spent balance or limit, or a plain malformed request; a 429 is a usage limit
|
|
1122
|
+
// that will not clear within minutes ("You've hit your 5-hour limit · resets 12:40pm", a
|
|
1123
|
+
// tier spend cap), or a rate limit that will. They are read ONLY once a status picked the
|
|
1124
|
+
// branch, never alone.
|
|
1125
|
+
//
|
|
1126
|
+
// The patterns are Anthropic's real wordings: "Credit balance is too low", "You have reached
|
|
1127
|
+
// your specified workspace API usage limits" (a 400), "You've hit your 5-hour limit"
|
|
1128
|
+
// (a subscription), a tier "spend cap". Bare "limit reached" and "resets" are NOT witnesses:
|
|
1129
|
+
// an ordinary per-minute rate-limit message can say either and must keep its backoff retry.
|
|
1130
|
+
const CREDIT_OR_SPEND_LIMIT = /credit balance|spend limit|usage limit/i;
|
|
1131
|
+
const SUBSCRIPTION_OR_SPEND_CAP =
|
|
1132
|
+
/hit your .*limit|usage limit|spend cap|spend limit/i;
|
|
1133
|
+
// A usage-limit message that arrives with no status is the same terminal limit.
|
|
1134
|
+
const USAGE_LIMIT_NO_STATUS =
|
|
1135
|
+
/hit your .*limit|usage limit|credit balance|spend cap|spend limit/i;
|
|
1136
|
+
const NOT_LOGGED_IN = /Not logged in\s*[·.]\s*Please run \/login/i;
|
|
1137
|
+
|
|
1138
|
+
// The map from one error envelope to its typed cause. The CLI prints `is_error: true` with
|
|
1139
|
+
// the HTTP status of the API's refusal in `api_error_status`, and `terminal_reason` /
|
|
1140
|
+
// `subtype` for the run-level errors that have no status. The exit code is NOT a signal:
|
|
1141
|
+
// an API rejection exits 0 (CLI 2.1.312) or 1 (anthropics/claude-code#103807).
|
|
1142
|
+
//
|
|
1143
|
+
// The status is read first, then the reason, and a message only to split one status. The
|
|
1144
|
+
// retry rule is the cause's own (failure-policy.ts): only rate_limit and network_transient
|
|
1145
|
+
// retry. So the causes that cannot clear in minutes (an empty balance, a subscription
|
|
1146
|
+
// window) are terminal, and a server-side failure is never made terminal, since the CLI
|
|
1147
|
+
// wraps 5xx and 529 in this same envelope.
|
|
1148
|
+
//
|
|
1149
|
+
// An `is_error` the map does not name (a stop hook, a budget cap, a reason a later CLI adds)
|
|
1150
|
+
// returns undefined here, and providerApiErrorOf fails it terminally rather than let the
|
|
1151
|
+
// error text be parsed as a draft and earn a format retry that hides the cause.
|
|
1152
|
+
function claudeCliErrorCause(
|
|
1153
|
+
envelope: CliResultEnvelope,
|
|
1154
|
+
): TransportFailureCause | undefined {
|
|
1155
|
+
const status =
|
|
1156
|
+
typeof envelope.api_error_status === "number" &&
|
|
1157
|
+
Number.isInteger(envelope.api_error_status)
|
|
1158
|
+
? envelope.api_error_status
|
|
1159
|
+
: undefined;
|
|
1160
|
+
const reason =
|
|
1161
|
+
typeof envelope.terminal_reason === "string"
|
|
1162
|
+
? envelope.terminal_reason
|
|
1163
|
+
: undefined;
|
|
1164
|
+
const subtype =
|
|
1165
|
+
typeof envelope.subtype === "string" ? envelope.subtype : undefined;
|
|
1166
|
+
const message = typeof envelope.result === "string" ? envelope.result : "";
|
|
1167
|
+
|
|
1168
|
+
// The prompt-too-long reason is the CLI's own, and the API reports it as a 400.
|
|
1169
|
+
if (reason === "prompt_too_long" || status === 413) {
|
|
1170
|
+
return "context_window_exceeded";
|
|
1171
|
+
}
|
|
1172
|
+
if (status !== undefined) {
|
|
1173
|
+
if (status === 401 || status === 403) return "auth_invalid";
|
|
1174
|
+
if (status === 402) return "quota_exhausted";
|
|
1175
|
+
if (status === 404) return "model_unavailable";
|
|
1176
|
+
if (status === 400) {
|
|
1177
|
+
return CREDIT_OR_SPEND_LIMIT.test(message)
|
|
1178
|
+
? "quota_exhausted"
|
|
1179
|
+
: "provider_configuration_invalid";
|
|
1180
|
+
}
|
|
1181
|
+
if (status === 429) {
|
|
1182
|
+
return SUBSCRIPTION_OR_SPEND_CAP.test(message)
|
|
1183
|
+
? "quota_exhausted"
|
|
1184
|
+
: "rate_limit";
|
|
1185
|
+
}
|
|
1186
|
+
// 503 backs off like 529: an instant retry against a saturated server burns the whole
|
|
1187
|
+
// transient budget in milliseconds (the same reason classifyFailure reads it as
|
|
1188
|
+
// rate_limit). Every other 5xx is a failure to try again at once.
|
|
1189
|
+
if (status === 529 || status === 503) return "rate_limit";
|
|
1190
|
+
if (status >= 500) return "network_transient";
|
|
1191
|
+
if (status >= 400) return "provider_configuration_invalid";
|
|
1192
|
+
return undefined;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// No status: the CLI's own words, then the run-level reasons.
|
|
1196
|
+
if (NOT_LOGGED_IN.test(message)) return "auth_invalid";
|
|
1197
|
+
if (reason === "max_output_tokens" || /max_output_tokens/.test(message)) {
|
|
1198
|
+
return "output_limit_exceeded";
|
|
1199
|
+
}
|
|
1200
|
+
if (subtype === "error_max_turns" || reason === "max_turns") {
|
|
1201
|
+
return "output_limit_exceeded";
|
|
1202
|
+
}
|
|
1203
|
+
if (reason === "model_error" || reason === "malformed_tool_use_exhausted") {
|
|
1204
|
+
return "protocol_mismatch";
|
|
1205
|
+
}
|
|
1206
|
+
if (USAGE_LIMIT_NO_STATUS.test(message)) return "quota_exhausted";
|
|
1207
|
+
if (/overloaded|rate_limit_error|service unavailable/i.test(message)) {
|
|
1208
|
+
return "rate_limit";
|
|
1209
|
+
}
|
|
1210
|
+
if (
|
|
1211
|
+
reason === "aborted_streaming" ||
|
|
1212
|
+
reason === "aborted_tools" ||
|
|
1213
|
+
subtype === "error_during_execution" ||
|
|
1214
|
+
reason === "api_error"
|
|
1215
|
+
) {
|
|
1216
|
+
return "network_transient";
|
|
1217
|
+
}
|
|
1218
|
+
return undefined;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// The typed cause and one short line of the CLI's own words, or undefined for a result
|
|
1222
|
+
// that is not an error the map names.
|
|
1223
|
+
function providerApiErrorOf(
|
|
1224
|
+
envelope: CliResultEnvelope,
|
|
1225
|
+
): ProviderApiError | undefined {
|
|
1226
|
+
if (envelope.is_error !== true) return undefined;
|
|
1227
|
+
const cause = claudeCliErrorCause(envelope);
|
|
1228
|
+
|
|
1229
|
+
const status =
|
|
1230
|
+
typeof envelope.api_error_status === "number"
|
|
1231
|
+
? envelope.api_error_status
|
|
1232
|
+
: undefined;
|
|
1233
|
+
const reason =
|
|
1234
|
+
typeof envelope.terminal_reason === "string"
|
|
1235
|
+
? envelope.terminal_reason
|
|
1236
|
+
: undefined;
|
|
1237
|
+
const subtype =
|
|
1238
|
+
typeof envelope.subtype === "string" ? envelope.subtype : undefined;
|
|
1239
|
+
const message = typeof envelope.result === "string" ? envelope.result : "";
|
|
1240
|
+
|
|
1241
|
+
// An error the map does not name. The CLI said it failed, so the text is not an answer;
|
|
1242
|
+
// the request is not one a retry can fix, so it is terminal, and the reason is quoted
|
|
1243
|
+
// beside the CLI's words so CI shows what happened instead of a generic failure.
|
|
1244
|
+
if (cause === undefined) {
|
|
1245
|
+
// The tag is the CLI's text too: one line, and short enough that the message keeps
|
|
1246
|
+
// room in the 160 characters.
|
|
1247
|
+
const tag =
|
|
1248
|
+
oneLine(
|
|
1249
|
+
reason ??
|
|
1250
|
+
(subtype !== undefined && subtype !== "success" ? subtype : ""),
|
|
1251
|
+
UNNAMED_TAG_MAX,
|
|
1252
|
+
) || "unknown";
|
|
1253
|
+
const suffix = ` (${tag}${status === undefined ? "" : `, HTTP ${status}`})`;
|
|
1254
|
+
const prefix = "Claude CLI: ";
|
|
1255
|
+
const words = oneLine(
|
|
1256
|
+
message.trim() === "" ? "no message" : message,
|
|
1257
|
+
API_ERROR_DETAIL_MAX - prefix.length - suffix.length,
|
|
1258
|
+
);
|
|
1259
|
+
return {
|
|
1260
|
+
cause: "provider_configuration_invalid",
|
|
1261
|
+
detail: `${prefix}${words}${suffix}`,
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// A run-level error has no message of its own; its reason names it.
|
|
1266
|
+
const named =
|
|
1267
|
+
subtype !== undefined && subtype !== "success" ? subtype : reason;
|
|
1268
|
+
const words = message.trim() === "" ? (named ?? "") : message;
|
|
1269
|
+
const prefix =
|
|
1270
|
+
status !== undefined || reason === "api_error"
|
|
1271
|
+
? "Anthropic API: "
|
|
1272
|
+
: "Claude CLI: ";
|
|
1273
|
+
|
|
1274
|
+
// One line, no control characters, and short enough for a commit status.
|
|
1275
|
+
const suffix = status === undefined ? "" : ` (HTTP ${status})`;
|
|
1276
|
+
const room = API_ERROR_DETAIL_MAX - prefix.length - suffix.length;
|
|
1277
|
+
return { cause, detail: `${prefix}${oneLine(words, room)}${suffix}` };
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// The CLI's words as one line: control characters become spaces, whitespace collapses, and
|
|
1281
|
+
// the text is cut with an ellipsis to fit `room` characters.
|
|
1282
|
+
function oneLine(words: string, room: number): string {
|
|
1283
|
+
const flat = Array.from(words, (char) => {
|
|
1284
|
+
const code = char.charCodeAt(0);
|
|
1285
|
+
return code < 0x20 || code === 0x7f ? " " : char;
|
|
1286
|
+
})
|
|
1287
|
+
.join("")
|
|
1288
|
+
.replace(/\s+/g, " ")
|
|
1289
|
+
.trim();
|
|
1290
|
+
return flat.length <= room ? flat : `${flat.slice(0, room - 1)}…`;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// The secret the child ran on. The per-token variables (the list envBillsMetered reads) win
|
|
1294
|
+
// over CLAUDE_CODE_OAUTH_TOKEN, and a whitespace-only value is no credential (the same trim).
|
|
1295
|
+
//
|
|
1296
|
+
// The precedence is observed, not assumed. With CLI 2.1.312 and both an API key and an
|
|
1297
|
+
// OAuth login present, the CLI prints "claude.ai connectors are disabled because
|
|
1298
|
+
// ANTHROPIC_API_KEY or another auth source is set and takes precedence over your claude.ai
|
|
1299
|
+
// login". On juanmaagd/pr-hero CI with both secrets bound, every request used the API key
|
|
1300
|
+
// ("Credit balance is too low") while CLAUDE_CODE_OAUTH_TOKEN was valid.
|
|
1301
|
+
function credentialOf(
|
|
1302
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
1303
|
+
): FailureCredential | undefined {
|
|
1304
|
+
for (const name of METERED_CREDENTIAL_ENV) {
|
|
1305
|
+
if (env[name]?.trim()) return name;
|
|
1306
|
+
}
|
|
1307
|
+
if (env.CLAUDE_CODE_OAUTH_TOKEN?.trim()) return "CLAUDE_CODE_OAUTH_TOKEN";
|
|
1308
|
+
return undefined;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// The failed outcome execute() returns when spawn throws, and its exact
|
|
1312
|
+
// witness for classifyFailure. Producer and matcher share these two
|
|
1313
|
+
// constants so a reworded message cannot silently become retryable again.
|
|
1314
|
+
// The WHOLE tail is matched, not a line inside it: this outcome never has a
|
|
1315
|
+
// child, so its stderrTail is exactly this string and nothing else, while a
|
|
1316
|
+
// real child's stderr that merely quotes the phrase starts with the child's
|
|
1317
|
+
// own output. classifyFailure runs on the transport's outcome before the
|
|
1318
|
+
// harness appends its own annotations, so the suffix is still the end. The
|
|
1319
|
+
// message between them can span lines; prefix and suffix cannot.
|
|
1320
|
+
const SPAWN_FAILURE_PREFIX = "[pr-hero] spawn failed: ";
|
|
1321
|
+
const SPAWN_FAILURE_SUFFIX = "; no child started";
|
|
1322
|
+
|
|
1323
|
+
function spawnFailureTail(error: unknown): string {
|
|
1324
|
+
return `${SPAWN_FAILURE_PREFIX}${describeSpawnError(error)}${SPAWN_FAILURE_SUFFIX}`;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function isSpawnFailureTail(stderrTail: string): boolean {
|
|
1328
|
+
return (
|
|
1329
|
+
stderrTail.startsWith(SPAWN_FAILURE_PREFIX) &&
|
|
1330
|
+
stderrTail.endsWith(SPAWN_FAILURE_SUFFIX)
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
// "<code>: <message>" for a spawn throw, without repeating a code the message
|
|
1335
|
+
// already leads with (Bun's system errors often do). A non-Error throw is
|
|
1336
|
+
// stringified rather than dropped: the reason is the whole point (#314).
|
|
1337
|
+
function describeSpawnError(error: unknown): string {
|
|
1338
|
+
if (!(error instanceof Error)) return String(error);
|
|
1339
|
+
const code = (error as { code?: unknown }).code;
|
|
1340
|
+
if (
|
|
1341
|
+
typeof code === "string" &&
|
|
1342
|
+
code !== "" &&
|
|
1343
|
+
!error.message.includes(code)
|
|
1344
|
+
) {
|
|
1345
|
+
return `${code}: ${error.message}`;
|
|
1346
|
+
}
|
|
1347
|
+
return error.message;
|
|
1348
|
+
}
|