issue-flow 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -274
- package/dist/agent-BXRIEKVM.js +238 -0
- package/dist/agent-BXRIEKVM.js.map +1 -0
- package/dist/{analyze-XV3K25K3.js → analyze-WS47UYGN.js} +32 -15
- package/dist/analyze-WS47UYGN.js.map +1 -0
- package/dist/{apply-WUJHDD7A.js → apply-OS62UWRN.js} +15 -5
- package/dist/{apply-WUJHDD7A.js.map → apply-OS62UWRN.js.map} +1 -1
- package/dist/bench-SA3BOME5.js +906 -0
- package/dist/bench-SA3BOME5.js.map +1 -0
- package/dist/chunk-37N2RJW2.js +120 -0
- package/dist/chunk-37N2RJW2.js.map +1 -0
- package/dist/chunk-3XLCNVMD.js +180 -0
- package/dist/chunk-3XLCNVMD.js.map +1 -0
- package/dist/chunk-5TB6KLC2.js +72 -0
- package/dist/chunk-5TB6KLC2.js.map +1 -0
- package/dist/{chunk-OBLVLIUS.js → chunk-664Y3NDX.js} +25 -13
- package/dist/chunk-664Y3NDX.js.map +1 -0
- package/dist/chunk-6FDFRNXZ.js +357 -0
- package/dist/chunk-6FDFRNXZ.js.map +1 -0
- package/dist/chunk-7KD66LIM.js +658 -0
- package/dist/chunk-7KD66LIM.js.map +1 -0
- package/dist/chunk-7Z4Y3VKM.js +26 -0
- package/dist/chunk-7Z4Y3VKM.js.map +1 -0
- package/dist/chunk-ARFVHC2F.js +1111 -0
- package/dist/chunk-ARFVHC2F.js.map +1 -0
- package/dist/{chunk-RKTEV6EG.js → chunk-BHJCGWQX.js} +141 -12
- package/dist/chunk-BHJCGWQX.js.map +1 -0
- package/dist/chunk-BQDQTIM7.js +74 -0
- package/dist/chunk-BQDQTIM7.js.map +1 -0
- package/dist/chunk-CNBYCMSU.js +2709 -0
- package/dist/chunk-CNBYCMSU.js.map +1 -0
- package/dist/chunk-CRGIQFUQ.js +83 -0
- package/dist/chunk-CRGIQFUQ.js.map +1 -0
- package/dist/chunk-DIG5XKQQ.js +298 -0
- package/dist/chunk-DIG5XKQQ.js.map +1 -0
- package/dist/chunk-FZDR7CGH.js +71 -0
- package/dist/chunk-FZDR7CGH.js.map +1 -0
- package/dist/chunk-HEF2RMKN.js +413 -0
- package/dist/chunk-HEF2RMKN.js.map +1 -0
- package/dist/{chunk-IVHZEYAX.js → chunk-HJGGNLWI.js} +25 -19
- package/dist/chunk-HJGGNLWI.js.map +1 -0
- package/dist/chunk-HQAHNIAR.js +283 -0
- package/dist/chunk-HQAHNIAR.js.map +1 -0
- package/dist/{chunk-GANSDJV7.js → chunk-IHIEXUTC.js} +46 -24
- package/dist/chunk-IHIEXUTC.js.map +1 -0
- package/dist/chunk-IV5SS4JN.js +84 -0
- package/dist/chunk-IV5SS4JN.js.map +1 -0
- package/dist/{chunk-HC2MT7BX.js → chunk-IYV6KNVF.js} +158 -592
- package/dist/chunk-IYV6KNVF.js.map +1 -0
- package/dist/{chunk-LVKQ2AKT.js → chunk-J62QSVP6.js} +10 -8
- package/dist/chunk-J62QSVP6.js.map +1 -0
- package/dist/chunk-KMMASOA6.js +134 -0
- package/dist/chunk-KMMASOA6.js.map +1 -0
- package/dist/chunk-KQHB7ZT3.js +559 -0
- package/dist/chunk-KQHB7ZT3.js.map +1 -0
- package/dist/chunk-L6HSKTQE.js +77 -0
- package/dist/chunk-L6HSKTQE.js.map +1 -0
- package/dist/{chunk-6N7LZZ5U.js → chunk-LZ6GFQAG.js} +474 -160
- package/dist/chunk-LZ6GFQAG.js.map +1 -0
- package/dist/{chunk-HQYXVIH6.js → chunk-MIVHK5YI.js} +5 -5
- package/dist/chunk-NEZZ6KDR.js +1217 -0
- package/dist/chunk-NEZZ6KDR.js.map +1 -0
- package/dist/{run-DBF2VWUN.js → chunk-OPNGPUKJ.js} +747 -594
- package/dist/chunk-OPNGPUKJ.js.map +1 -0
- package/dist/chunk-P3LRUNC6.js +16 -0
- package/dist/chunk-P3LRUNC6.js.map +1 -0
- package/dist/{chunk-BXCPXRBR.js → chunk-PIVGJM6K.js} +129 -32
- package/dist/chunk-PIVGJM6K.js.map +1 -0
- package/dist/{chunk-AAY6KM7N.js → chunk-PV4OX5TC.js} +167 -196
- package/dist/chunk-PV4OX5TC.js.map +1 -0
- package/dist/chunk-QCXPNSEL.js +141 -0
- package/dist/chunk-QCXPNSEL.js.map +1 -0
- package/dist/{chunk-34WNTK3K.js → chunk-QXDNBYQF.js} +53 -13
- package/dist/chunk-QXDNBYQF.js.map +1 -0
- package/dist/chunk-SNTTOQAD.js +30 -0
- package/dist/chunk-SNTTOQAD.js.map +1 -0
- package/dist/{chunk-EY6WMHV2.js → chunk-TM67EHSV.js} +67 -23
- package/dist/chunk-TM67EHSV.js.map +1 -0
- package/dist/chunk-TVN2JVOF.js +77 -0
- package/dist/chunk-TVN2JVOF.js.map +1 -0
- package/dist/chunk-TX5WIVYP.js +129 -0
- package/dist/chunk-TX5WIVYP.js.map +1 -0
- package/dist/{chunk-KQ4JQN7T.js → chunk-UJ7XWK7J.js} +83 -21
- package/dist/chunk-UJ7XWK7J.js.map +1 -0
- package/dist/{chunk-47VIN33V.js → chunk-UOCPC2Y2.js} +596 -17
- package/dist/chunk-UOCPC2Y2.js.map +1 -0
- package/dist/chunk-XEYH6ZZI.js +289 -0
- package/dist/chunk-XEYH6ZZI.js.map +1 -0
- package/dist/cli.js +390 -40
- package/dist/cli.js.map +1 -1
- package/dist/config-MEM2IWWN.js +76 -0
- package/dist/contract-JH2WBIO6.js +8 -0
- package/dist/conventions-WV4NDXGH.js +143 -0
- package/dist/conventions-WV4NDXGH.js.map +1 -0
- package/dist/execute-NITIHHCK.js +31 -0
- package/dist/{generate-TBVTLMOP.js → generate-MVQI7A45.js} +39 -19
- package/dist/{generate-TBVTLMOP.js.map → generate-MVQI7A45.js.map} +1 -1
- package/dist/git-YRVRUN3C.js +31 -0
- package/dist/init-OKWEC3EV.js +21 -0
- package/dist/operations-LU6JA3BX.js +374 -0
- package/dist/operations-LU6JA3BX.js.map +1 -0
- package/dist/permissions-7NMDFU27.js +18 -0
- package/dist/plan-LEJJF3DE.js +31 -0
- package/dist/{policy-XQW5NUIE.js → policy-JSYEK5B2.js} +17 -4
- package/dist/policy-JSYEK5B2.js.map +1 -0
- package/dist/pr-HPVUZ7S3.js +36 -0
- package/dist/pr-review-R2QZBT3F.js +29 -0
- package/dist/pr-review-R2QZBT3F.js.map +1 -0
- package/dist/prd-5O6GYCC6.js +30 -0
- package/dist/prd-5O6GYCC6.js.map +1 -0
- package/dist/ps-TNE44R5V.js +90 -0
- package/dist/ps-TNE44R5V.js.map +1 -0
- package/dist/recorder-XGF55WXI.js +31 -0
- package/dist/recorder-XGF55WXI.js.map +1 -0
- package/dist/registry-LGPE53QD.js +15 -0
- package/dist/registry-LGPE53QD.js.map +1 -0
- package/dist/resume-QMEPMSZW.js +238 -0
- package/dist/resume-QMEPMSZW.js.map +1 -0
- package/dist/review-YKWD6SNN.js +32 -0
- package/dist/review-YKWD6SNN.js.map +1 -0
- package/dist/routing-2ZUMZPJB.js +91 -0
- package/dist/routing-2ZUMZPJB.js.map +1 -0
- package/dist/run-YU4TR62R.js +50 -0
- package/dist/run-YU4TR62R.js.map +1 -0
- package/dist/state-manager-X3PT3FGT.js +36 -0
- package/dist/state-manager-X3PT3FGT.js.map +1 -0
- package/dist/usage-VCFLDA5Y.js +174 -0
- package/dist/usage-VCFLDA5Y.js.map +1 -0
- package/dist/{web-ANQQTTRD.js → web-XVHLX62B.js} +43 -27
- package/dist/web-XVHLX62B.js.map +1 -0
- package/package.json +6 -2
- package/prompts/execute.md +7 -8
- package/prompts/plan.md +4 -5
- package/prompts/pr.md +13 -6
- package/web/AGENTS.md +3 -3
- package/web/public/app.css +38 -0
- package/web/public/app.js +132 -10
- package/web/public/index.html +24 -0
- package/dist/analyze-XV3K25K3.js.map +0 -1
- package/dist/chunk-34WNTK3K.js.map +0 -1
- package/dist/chunk-3BOHTH4V.js +0 -58
- package/dist/chunk-3BOHTH4V.js.map +0 -1
- package/dist/chunk-47VIN33V.js.map +0 -1
- package/dist/chunk-6N7LZZ5U.js.map +0 -1
- package/dist/chunk-AAY6KM7N.js.map +0 -1
- package/dist/chunk-BXCPXRBR.js.map +0 -1
- package/dist/chunk-EWDJENFW.js +0 -303
- package/dist/chunk-EWDJENFW.js.map +0 -1
- package/dist/chunk-EY6WMHV2.js.map +0 -1
- package/dist/chunk-GANSDJV7.js.map +0 -1
- package/dist/chunk-HC2MT7BX.js.map +0 -1
- package/dist/chunk-HDV3YDTG.js +0 -52
- package/dist/chunk-HDV3YDTG.js.map +0 -1
- package/dist/chunk-IVHZEYAX.js.map +0 -1
- package/dist/chunk-KQ4JQN7T.js.map +0 -1
- package/dist/chunk-LVKQ2AKT.js.map +0 -1
- package/dist/chunk-OBLVLIUS.js.map +0 -1
- package/dist/chunk-RKTEV6EG.js.map +0 -1
- package/dist/chunk-VQ5VN7DF.js +0 -1018
- package/dist/chunk-VQ5VN7DF.js.map +0 -1
- package/dist/config-4THHOXNN.js +0 -41
- package/dist/execute-5OEKLM5X.js +0 -15
- package/dist/init-PRMOTQ7N.js +0 -9
- package/dist/plan-Y2BYZD24.js +0 -17
- package/dist/policy-XQW5NUIE.js.map +0 -1
- package/dist/pr-H6GLOSXF.js +0 -21
- package/dist/pr-review-CK5FR6WX.js +0 -17
- package/dist/prd-4PWLCGH5.js +0 -17
- package/dist/review-QGVAHEZF.js +0 -15
- package/dist/run-DBF2VWUN.js.map +0 -1
- package/dist/web-ANQQTTRD.js.map +0 -1
- /package/dist/{chunk-HQYXVIH6.js.map → chunk-MIVHK5YI.js.map} +0 -0
- /package/dist/{config-4THHOXNN.js.map → config-MEM2IWWN.js.map} +0 -0
- /package/dist/{execute-5OEKLM5X.js.map → contract-JH2WBIO6.js.map} +0 -0
- /package/dist/{init-PRMOTQ7N.js.map → execute-NITIHHCK.js.map} +0 -0
- /package/dist/{plan-Y2BYZD24.js.map → git-YRVRUN3C.js.map} +0 -0
- /package/dist/{pr-H6GLOSXF.js.map → init-OKWEC3EV.js.map} +0 -0
- /package/dist/{pr-review-CK5FR6WX.js.map → permissions-7NMDFU27.js.map} +0 -0
- /package/dist/{prd-4PWLCGH5.js.map → plan-LEJJF3DE.js.map} +0 -0
- /package/dist/{review-QGVAHEZF.js.map → pr-HPVUZ7S3.js.map} +0 -0
|
@@ -1,33 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
+
DEFAULT_BRANCH_CONVENTION,
|
|
3
4
|
loadRepositoryPolicy
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-UOCPC2Y2.js";
|
|
5
6
|
import {
|
|
6
|
-
getBaseBranch,
|
|
7
7
|
loadPolicyConfig
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-CNBYCMSU.js";
|
|
9
|
+
import {
|
|
10
|
+
getSessionPublisher
|
|
11
|
+
} from "./chunk-IYV6KNVF.js";
|
|
9
12
|
import {
|
|
10
|
-
getSessionPublisher,
|
|
11
13
|
hasUsageData,
|
|
12
14
|
isoNow,
|
|
13
15
|
sumUsage
|
|
14
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-DIG5XKQQ.js";
|
|
17
|
+
import {
|
|
18
|
+
getBaseBranch
|
|
19
|
+
} from "./chunk-KQHB7ZT3.js";
|
|
15
20
|
|
|
16
21
|
// src/core/session-metrics.ts
|
|
17
22
|
function elapsedSecondsSince(startedAtMs) {
|
|
18
23
|
return Math.max(0, Math.round((Date.now() - startedAtMs) / 1e3));
|
|
19
24
|
}
|
|
20
25
|
function createAccumulator() {
|
|
21
|
-
return { all: {}, byPhase: /* @__PURE__ */ new Map() };
|
|
26
|
+
return { all: {}, byPhase: /* @__PURE__ */ new Map(), byAgent: /* @__PURE__ */ new Map() };
|
|
22
27
|
}
|
|
23
28
|
var scopes = [createAccumulator()];
|
|
24
29
|
function current() {
|
|
25
30
|
return scopes[scopes.length - 1];
|
|
26
31
|
}
|
|
27
|
-
function recordRunUsage(phase, usage) {
|
|
32
|
+
function recordRunUsage(phase, usage, providerId) {
|
|
28
33
|
for (const scope of scopes) {
|
|
29
34
|
scope.all = sumUsage(scope.all, usage);
|
|
30
35
|
scope.byPhase.set(phase, sumUsage(scope.byPhase.get(phase), usage));
|
|
36
|
+
const agent = providerId ?? "claude";
|
|
37
|
+
scope.byAgent.set(agent, sumUsage(scope.byAgent.get(agent), usage));
|
|
31
38
|
}
|
|
32
39
|
}
|
|
33
40
|
function getRunUsageTotals() {
|
|
@@ -53,9 +60,9 @@ function beginUsageScope() {
|
|
|
53
60
|
}
|
|
54
61
|
};
|
|
55
62
|
}
|
|
56
|
-
function publishPhaseMetrics(phase, usage, startedAtMs) {
|
|
63
|
+
function publishPhaseMetrics(phase, usage, startedAtMs, providerId) {
|
|
57
64
|
if (usage == null || !hasUsageData(usage)) return;
|
|
58
|
-
recordRunUsage(phase, usage);
|
|
65
|
+
recordRunUsage(phase, usage, providerId);
|
|
59
66
|
getSessionPublisher().publish({
|
|
60
67
|
type: "metrics:update",
|
|
61
68
|
at: isoNow(),
|
|
@@ -68,9 +75,9 @@ function publishPhaseMetrics(phase, usage, startedAtMs) {
|
|
|
68
75
|
});
|
|
69
76
|
}
|
|
70
77
|
var EXECUTE_PHASE = "execute";
|
|
71
|
-
function publishIterationMetrics(iteration, usage, durationSeconds) {
|
|
78
|
+
function publishIterationMetrics(iteration, usage, durationSeconds, providerId) {
|
|
72
79
|
if (usage == null || !hasUsageData(usage)) return;
|
|
73
|
-
recordRunUsage(EXECUTE_PHASE, usage);
|
|
80
|
+
recordRunUsage(EXECUTE_PHASE, usage, providerId);
|
|
74
81
|
getSessionPublisher().publish({
|
|
75
82
|
type: "metrics:update",
|
|
76
83
|
at: isoNow(),
|
|
@@ -144,6 +151,12 @@ function renderConventions(policy) {
|
|
|
144
151
|
if (policy.git.commitConvention !== null) {
|
|
145
152
|
rows.push(`- Commit: ${policy.git.commitConvention}`);
|
|
146
153
|
}
|
|
154
|
+
if (policy.git.pullRequestTitleConvention !== null) {
|
|
155
|
+
rows.push(`- Pull Request title: ${policy.git.pullRequestTitleConvention}`);
|
|
156
|
+
}
|
|
157
|
+
if (policy.git.allowedTypes !== null && policy.git.allowedTypes.length > 0) {
|
|
158
|
+
rows.push(`- Allowed types: ${policy.git.allowedTypes.join(", ")}`);
|
|
159
|
+
}
|
|
147
160
|
return rows.join("\n");
|
|
148
161
|
}
|
|
149
162
|
function renderDocs(docs) {
|
|
@@ -243,7 +256,6 @@ function policyPlaceholders(policy, options = {}) {
|
|
|
243
256
|
};
|
|
244
257
|
}
|
|
245
258
|
var DEFAULT_POLICY_CONTEXT_BUDGET = 1500;
|
|
246
|
-
var DEFAULT_BRANCH_CONVENTION = "issue/{N}-{slug}";
|
|
247
259
|
function conventionPlaceholders(policy, baseBranchFallback) {
|
|
248
260
|
return {
|
|
249
261
|
__BASE_BRANCH__: policy?.pullRequests.baseBranch ?? baseBranchFallback,
|
|
@@ -282,4 +294,4 @@ export {
|
|
|
282
294
|
publishStoryMetrics,
|
|
283
295
|
resolvePolicyPlaceholders
|
|
284
296
|
};
|
|
285
|
-
//# sourceMappingURL=chunk-
|
|
297
|
+
//# sourceMappingURL=chunk-664Y3NDX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/session-metrics.ts","../src/policy/placeholders.ts"],"sourcesContent":["import { type ClaudeUsage, hasUsageData, sumUsage } from './metrics.js';\nimport { getSessionPublisher } from './session-publisher.js';\nimport { isoNow } from './state-manager.js';\n\n/**\n * Publication helper for the single-invocation phases (analyze, generate, prd,\n * plan, review, pr, pr-review).\n *\n * Each of them owns its own `runHeadless` call, so the metrics are published\n * from inside the command rather than from the `instrumentedRunners` wrapper in\n * run.ts: the wrapper only sees `() => Promise<void>` and never touches the\n * HeadlessResult. Publishing here also covers standalone invocations\n * (`issue-flow prd 42`), which never go through the pipeline wrapper at all.\n */\n\n/** Whole seconds elapsed since a `Date.now()` mark, never negative. */\nexport function elapsedSecondsSince(startedAtMs: number): number {\n return Math.max(0, Math.round((Date.now() - startedAtMs) / 1000));\n}\n\n/**\n * Process-owned totals, accumulated alongside every published event.\n *\n * The session snapshot now stays populated without `--web` (`MemoryPublisher`),\n * but the end-of-run summary box still reads these process-owned counters so a\n * standalone phase command (no publisher installed) does not print zeros.\n *\n * Only phase- and iteration-scoped usage is recorded. Story metrics are a\n * rateio of an iteration already counted here — adding them would double the\n * totals, the same rule the reducer follows.\n */\ninterface UsageAccumulator {\n all: ClaudeUsage;\n byPhase: Map<string, ClaudeUsage>;\n byAgent: Map<string, ClaudeUsage>;\n}\n\nfunction createAccumulator(): UsageAccumulator {\n return { all: {}, byPhase: new Map(), byAgent: new Map() };\n}\n\n/**\n * Stack of active accumulators, innermost last.\n *\n * The bottom entry is the process total and always exists. A multi-issue run\n * pushes one accumulator per issue (and one for the whole queue) so the terminal\n * summary of issue B never inherits what issue A spent — the leak `core/CLAUDE.md`\n * warned about when it stated that the module-level counters were safe \"only\n * under the current one-issue-per-process model\".\n *\n * Every publication feeds **all** active accumulators, so a scope is a view of\n * the same events rather than a redirection of them.\n */\nconst scopes: UsageAccumulator[] = [createAccumulator()];\n\n/** Innermost active scope: what `run` and the engine report right now. */\nfunction current(): UsageAccumulator {\n return scopes[scopes.length - 1] as UsageAccumulator;\n}\n\nfunction recordRunUsage(phase: string, usage: ClaudeUsage, providerId?: string): void {\n for (const scope of scopes) {\n scope.all = sumUsage(scope.all, usage);\n scope.byPhase.set(phase, sumUsage(scope.byPhase.get(phase), usage));\n const agent = providerId ?? 'claude';\n scope.byAgent.set(agent, sumUsage(scope.byAgent.get(agent), usage));\n }\n}\n\n/** Everything the innermost active scope has spent, across all phases. */\nexport function getRunUsageTotals(): ClaudeUsage {\n return { ...current().all };\n}\n\n/** What a single phase has spent so far. Empty when the phase reported nothing. */\nexport function getPhaseUsageTotals(phase: string): ClaudeUsage {\n return { ...(current().byPhase.get(phase) ?? {}) };\n}\n\n/** A usage scope opened by {@link beginUsageScope}. */\nexport interface UsageScope {\n /** Everything published while this scope was open. */\n totals(): ClaudeUsage;\n /** What one phase published while this scope was open. */\n phaseTotals(phase: string): ClaudeUsage;\n /** Close the scope. Idempotent, and safe to call out of order. */\n end(): ClaudeUsage;\n}\n\n/**\n * Open a nested usage scope, for a run that processes several issues in one\n * process.\n *\n * The scope accumulates only what is published while it is open, which is what\n * lets a queue report a per-issue cost and a consolidated total from the same\n * stream of events. Closing it never discards anything: the outer scopes were\n * fed in parallel.\n */\nexport function beginUsageScope(): UsageScope {\n const accumulator = createAccumulator();\n scopes.push(accumulator);\n let open = true;\n\n return {\n totals: () => ({ ...accumulator.all }),\n phaseTotals: (phase: string) => ({ ...(accumulator.byPhase.get(phase) ?? {}) }),\n end: () => {\n if (open) {\n const index = scopes.indexOf(accumulator);\n // Never pop the process total, even if a caller double-ends a scope.\n if (index > 0) scopes.splice(index, 1);\n open = false;\n }\n return { ...accumulator.all };\n },\n };\n}\n\n/** Test seam: the counters are module state and must be cleared between runs. */\nexport function resetRunUsageTotals(): void {\n scopes.splice(0, scopes.length, createAccumulator());\n}\n\n/**\n * Publish one `metrics:update` event of scope `phase` for a headless\n * invocation.\n *\n * A no-op when the CLI reported no usage at all: an event with every field\n * undefined would bump the snapshot version without adding information, and the\n * reducer would leave every counter at null anyway.\n *\n * A command with more than one invocation (the retrying phases, or `review`\n * inside a correction cycle) calls this once per invocation — the reducer's\n * summing is what turns them into the phase total.\n *\n * Never throws and never returns a value: publishing metrics must not be able\n * to change a command's exit code.\n */\nexport function publishPhaseMetrics(\n phase: string,\n usage: ClaudeUsage | null | undefined,\n startedAtMs?: number,\n providerId?: string,\n): void {\n if (usage == null || !hasUsageData(usage)) return;\n\n recordRunUsage(phase, usage, providerId);\n\n getSessionPublisher().publish({\n type: 'metrics:update',\n at: isoNow(),\n scope: 'phase',\n phase,\n ...usage,\n // Informational only: a phase's durationSeconds keeps coming exclusively\n // from phase:start/phase:end, so the reducer ignores this for scope 'phase'.\n durationSeconds: startedAtMs === undefined ? undefined : elapsedSecondsSince(startedAtMs),\n });\n}\n\n/** The execute loop is the only producer of iteration- and story-scoped metrics. */\nexport const EXECUTE_PHASE = 'execute';\n\n/**\n * Publish one `metrics:update` event of scope `iteration` for a pass of the\n * execute loop.\n *\n * Lands on the `execute` phase and on the issue-wide aggregate, exactly like a\n * phase-scoped event: an iteration *is* a slice of the execute phase. Failed\n * iterations (transient or fatal) publish too — those tokens were spent.\n *\n * A no-op when the CLI reported no usage. Never throws.\n */\nexport function publishIterationMetrics(\n iteration: number,\n usage: ClaudeUsage | null | undefined,\n durationSeconds?: number,\n providerId?: string,\n): void {\n if (usage == null || !hasUsageData(usage)) return;\n\n recordRunUsage(EXECUTE_PHASE, usage, providerId);\n\n getSessionPublisher().publish({\n type: 'metrics:update',\n at: isoNow(),\n scope: 'iteration',\n phase: EXECUTE_PHASE,\n iteration,\n ...usage,\n // Informational only: the reducer keeps a phase's durationSeconds coming\n // exclusively from phase:start/phase:end.\n durationSeconds,\n });\n}\n\n/**\n * Publish one `metrics:update` event of scope `story`.\n *\n * The values are the rateio of the iteration that completed the story, so the\n * reducer deliberately keeps them off the phase and the aggregate — the\n * iteration event of the same cycle already counted them there.\n *\n * A no-op when there is neither usage nor a duration to report. Never throws.\n */\nexport function publishStoryMetrics(\n storyId: string,\n usage: ClaudeUsage | null | undefined,\n durationSeconds?: number,\n): void {\n if (!hasUsageData(usage) && durationSeconds === undefined) return;\n\n getSessionPublisher().publish({\n type: 'metrics:update',\n at: isoNow(),\n scope: 'story',\n storyId,\n ...(usage ?? {}),\n durationSeconds,\n });\n}\n","import { loadPolicyConfig } from '../config.js';\nimport { DEFAULT_BRANCH_CONVENTION } from '../conventions/git/index.js';\nimport { getBaseBranch } from '../utils/git.js';\nimport { loadRepositoryPolicy } from './resolve.js';\nimport type { IssueTemplate, PolicyDocument, RepositoryPolicy } from './types.js';\n\n/**\n * Projection of a {@link RepositoryPolicy} onto the prompt placeholders.\n *\n * The prompts receive a **summary**, never the raw files. Dumping\n * `CONTRIBUTING.md` and three `AGENTS.md` into every prompt would cost tokens on\n * every single run and drown the actual instruction — and it would duplicate,\n * inside Issue Flow, a rule that already lives in the repository.\n *\n * The whole projection is empty when the repository declares nothing, which is\n * what lets a prompt render byte for byte as it did before this layer existed.\n */\n\n/** Every placeholder this module produces. Ordered as they appear in a prompt. */\nexport const POLICY_PLACEHOLDER_KEYS = [\n '__REPO_POLICY__',\n '__REPO_ISSUE_TEMPLATES__',\n '__REPO_LABELS__',\n '__REPO_ISSUE_TYPES__',\n '__REPO_PR_TEMPLATE__',\n '__REPO_BASE_BRANCH__',\n '__REPO_CONVENTIONS__',\n '__REPO_DOCS__',\n] as const;\n\nexport type PolicyPlaceholderKey = (typeof POLICY_PLACEHOLDER_KEYS)[number];\n\n/** Every placeholder empty — the projection of \"this repository declares nothing\". */\nexport function emptyPolicyPlaceholders(): Record<string, string> {\n return Object.fromEntries(POLICY_PLACEHOLDER_KEYS.map((key) => [key, ''])) as Record<\n string,\n string\n >;\n}\n\n/**\n * Rough token count of a rendered section.\n *\n * Four characters per token is the usual English/Portuguese approximation and is\n * deliberately crude: the budget exists to stop a policy from swallowing the\n * prompt, not to bill anyone. Erring high is the safe direction, so the estimate\n * rounds up.\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n// ── Section renderers ───────────────────────────────────────────────────────\n\nfunction renderIssueTemplates(templates: IssueTemplate[]): string {\n if (templates.length === 0) return '';\n\n const lines = templates.map((template) => {\n const parts = [`- **${template.name ?? template.path}** (\\`${template.path}\\`)`];\n if (template.type !== null) parts.push(`type: ${template.type}`);\n if (template.labels.length > 0) parts.push(`labels: ${template.labels.join(', ')}`);\n if (template.title !== null) parts.push(`title prefix: \\`${template.title}\\``);\n if (template.about !== null) parts.push(template.about);\n return parts.join(' — ');\n });\n\n return lines.join('\\n');\n}\n\nfunction renderLabels(policy: RepositoryPolicy): string {\n if (policy.issues.labels.length === 0) return '';\n\n return policy.issues.labels\n .map((label) =>\n label.description === null ? `- ${label.name}` : `- ${label.name} — ${label.description}`,\n )\n .join('\\n');\n}\n\nfunction renderConventions(policy: RepositoryPolicy): string {\n const rows: string[] = [];\n if (policy.issues.titleConvention !== null) {\n rows.push(`- Issue title: ${policy.issues.titleConvention}`);\n }\n if (policy.pullRequests.titleConvention !== null) {\n rows.push(`- Pull Request title: ${policy.pullRequests.titleConvention}`);\n }\n if (policy.git.branchConvention !== null) {\n rows.push(`- Branch: ${policy.git.branchConvention}`);\n }\n if (policy.git.commitConvention !== null) {\n rows.push(`- Commit: ${policy.git.commitConvention}`);\n }\n if (policy.git.pullRequestTitleConvention !== null) {\n rows.push(`- Pull Request title: ${policy.git.pullRequestTitleConvention}`);\n }\n if (policy.git.allowedTypes !== null && policy.git.allowedTypes.length > 0) {\n rows.push(`- Allowed types: ${policy.git.allowedTypes.join(', ')}`);\n }\n return rows.join('\\n');\n}\n\n/**\n * Paths of the applicable documents — **never their content**.\n *\n * The agent has `Read` and fetches what it needs. Embedding the documents would\n * multiply the cost of every run and, worse, freeze a copy of the repository's\n * own rule inside a prompt.\n */\nfunction renderDocs(docs: PolicyDocument[]): string {\n if (docs.length === 0) return '';\n\n return docs\n .map((doc) => {\n const scope = doc.scope === '' ? '' : ` (applies to \\`${doc.scope}/\\`)`;\n return `- \\`${doc.path}\\`${scope}`;\n })\n .join('\\n');\n}\n\n// ── The budgeted summary ────────────────────────────────────────────────────\n\ninterface Section {\n /** Heading inside the summary. */\n title: string;\n body: string;\n /**\n * Kept whole even when the budget is blown. The essentials are the taxonomy\n * an agent cannot guess: it can re-read a document, but it cannot invent the\n * label a repository actually uses.\n */\n essential: boolean;\n /** Shown in place of the body once the budget is exhausted. */\n pointer: string;\n}\n\n/**\n * Compose `__REPO_POLICY__` within `budgetTokens`.\n *\n * Sections are added whole, in priority order, while they fit. A section that\n * does not fit is replaced **whole** by a pointer to where the agent can read it\n * — nothing is ever cut mid-sentence, because a summary truncated mid-rule is\n * worse than one that says where the rule lives.\n */\nexport function renderPolicySummary(policy: RepositoryPolicy, budgetTokens: number): string {\n const sections: Section[] = [\n {\n title: 'Base branch',\n body: policy.pullRequests.baseBranch ?? '',\n essential: true,\n pointer: '',\n },\n {\n title: 'Conventions',\n body: renderConventions(policy),\n essential: true,\n pointer: '',\n },\n {\n title: 'Issue Types',\n body: policy.issues.types.join(', '),\n essential: true,\n pointer: '',\n },\n {\n title: 'Issue Templates',\n body: renderIssueTemplates(policy.issues.templates),\n essential: true,\n pointer: 'Run `issue-flow policy --json` to read the templates in full.',\n },\n {\n title: 'Labels',\n body: renderLabels(policy),\n essential: true,\n pointer: 'Run `gh label list` to read the labels of this repository.',\n },\n {\n title: 'Pull Request template',\n body: policy.pullRequests.templates[0]?.path ?? '',\n essential: false,\n pointer: '',\n },\n {\n title: 'Policy documents',\n body: renderDocs(policy.docs),\n essential: false,\n pointer: '',\n },\n ];\n\n const rendered: string[] = [];\n let used = 0;\n\n for (const section of sections) {\n if (section.body.trim() === '') continue;\n\n const block = `### ${section.title}\\n\\n${section.body}`;\n const cost = estimateTokens(block);\n\n if (used + cost <= budgetTokens) {\n rendered.push(block);\n used += cost;\n continue;\n }\n\n // Over budget. An essential section keeps its slot as a pointer; a\n // non-essential one simply drops out.\n if (section.essential && section.pointer !== '') {\n const fallback = `### ${section.title}\\n\\n${section.pointer}`;\n rendered.push(fallback);\n used += estimateTokens(fallback);\n }\n }\n\n return rendered.join('\\n\\n');\n}\n\n/** True when the policy carries nothing a prompt could act on. */\nexport function isEmptyPolicy(policy: RepositoryPolicy): boolean {\n return (\n policy.issues.templates.length === 0 &&\n policy.issues.types.length === 0 &&\n policy.issues.labels.length === 0 &&\n policy.issues.titleConvention === null &&\n policy.pullRequests.templates.length === 0 &&\n policy.pullRequests.baseBranch === null &&\n policy.pullRequests.titleConvention === null &&\n policy.git.branchConvention === null &&\n policy.git.commitConvention === null &&\n policy.docs.length === 0\n );\n}\n\nexport interface PolicyPlaceholderOptions {\n /** Token budget for `__REPO_POLICY__`. Defaults to the resolved configuration. */\n budgetTokens?: number;\n}\n\n/**\n * Project a resolved policy onto the prompt placeholders.\n *\n * A `null` policy — or one that carries nothing — yields every placeholder\n * empty, which is what makes the rendered prompt identical to the pre-policy\n * one. This is the contract the whole feature rests on.\n */\nexport function policyPlaceholders(\n policy: RepositoryPolicy | null,\n options: PolicyPlaceholderOptions = {},\n): Record<string, string> {\n if (policy === null || !policy.enabled || isEmptyPolicy(policy)) {\n return emptyPolicyPlaceholders();\n }\n\n const budget = options.budgetTokens ?? DEFAULT_POLICY_CONTEXT_BUDGET;\n\n return {\n __REPO_POLICY__: renderPolicySummary(policy, budget),\n __REPO_ISSUE_TEMPLATES__: renderIssueTemplates(policy.issues.templates),\n __REPO_LABELS__: renderLabels(policy),\n __REPO_ISSUE_TYPES__: policy.issues.types.join(', '),\n // The one place a whole file is projected verbatim: a Pull Request body has\n // to *be* the template, so a summary of it would be useless.\n __REPO_PR_TEMPLATE__: policy.pullRequests.template ?? '',\n __REPO_BASE_BRANCH__: policy.pullRequests.baseBranch ?? '',\n __REPO_CONVENTIONS__: renderConventions(policy),\n __REPO_DOCS__: renderDocs(policy.docs),\n };\n}\n\n/** Default token budget for `__REPO_POLICY__`, overridable via `policy.contextBudget`. */\nexport const DEFAULT_POLICY_CONTEXT_BUDGET = 1500;\n\n// ── Conventions that always have a value ────────────────────────────────────\n\nexport { DEFAULT_BRANCH_CONVENTION } from '../conventions/git/index.js';\n\n/**\n * Placeholders that must **never** render empty, because a prompt puts them\n * inside a command it asks the agent to run.\n *\n * `__BASE_BRANCH__` is the reason this group exists separately from the policy\n * projection. `prompts/pr.md` used to spell `main` three times — in\n * `git log main..HEAD`, in `git diff main...HEAD` and in `gh pr create --base\n * main`. In a repository whose base is `develop` that is not a missing feature\n * but an active defect: `main` often *exists* there too, so nothing fails — the\n * agent simply reviews the wrong diff and opens the Pull Request against the\n * wrong target.\n *\n * The resolution order is the repository's declared or discovered base, then\n * `getBaseBranch()`, whose own fallback is `main`. So a repository on `main`\n * renders exactly the text it rendered before.\n */\nexport function conventionPlaceholders(\n policy: RepositoryPolicy | null,\n baseBranchFallback: string,\n): Record<string, string> {\n return {\n __BASE_BRANCH__: policy?.pullRequests.baseBranch ?? baseBranchFallback,\n __BRANCH_CONVENTION__: policy?.git.branchConvention ?? DEFAULT_BRANCH_CONVENTION,\n // The one member of this group that may legitimately render empty: it gates\n // a conditional section rather than sitting inside a command.\n __COMMIT_CONVENTION__: policy?.git.commitConvention ?? '',\n };\n}\n\nexport interface ResolvePolicyPlaceholdersOptions {\n /** Repository root. Defaults to the git project root. */\n root?: string;\n /** Subdirectory the policy applies to, for monorepos. */\n scope?: string | null;\n}\n\n/**\n * Resolve the repository policy and project it, in one call.\n *\n * This is what every command uses. It **never throws and never warns**: a\n * repository that is not a git checkout, a discovery that fails, a `gh` that is\n * not installed — all of them yield the empty projection, and the command runs\n * exactly as it did before.\n *\n * The resolution itself is cached per `(root, scope)` by `loadRepositoryPolicy`,\n * so a pipeline that renders eight prompts still discovers once.\n */\nexport async function resolvePolicyPlaceholders(\n options: ResolvePolicyPlaceholdersOptions = {},\n): Promise<Record<string, string>> {\n let policy: RepositoryPolicy | null = null;\n let projection = emptyPolicyPlaceholders();\n try {\n policy = await loadRepositoryPolicy({ root: options.root, scope: options.scope ?? null });\n const config = await loadPolicyConfig({ projectRoot: policy.root });\n projection = policyPlaceholders(policy, { budgetTokens: config.contextBudget });\n } catch {\n // Discovery is an enrichment; the conventions below still have to resolve.\n policy = null;\n }\n\n let fallbackBase = 'main';\n try {\n fallbackBase = await getBaseBranch();\n } catch {\n // getBaseBranch() does not throw today, but its contract is \"never fails\",\n // and a base branch that cannot be resolved must not cost the whole prompt.\n }\n\n return { ...projection, ...conventionPlaceholders(policy, fallbackBase) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBO,SAAS,oBAAoB,aAA6B;AAC/D,SAAO,KAAK,IAAI,GAA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askPlan,
|
|
10
|
+
trimErrorMessage
|
|
11
|
+
} from "./chunk-DIG5XKQQ.js";
|
|
12
|
+
import {
|
|
13
|
+
classify
|
|
14
|
+
} from "./chunk-XEYH6ZZI.js";
|
|
15
|
+
|
|
16
|
+
// src/telemetry/recorder.ts
|
|
17
|
+
import { randomUUID } from "crypto";
|
|
18
|
+
import { hostname } from "os";
|
|
19
|
+
|
|
20
|
+
// src/telemetry/pricing.ts
|
|
21
|
+
var PRICING_TABLE_VERSION = "2026-08-30";
|
|
22
|
+
var TABLE = {
|
|
23
|
+
"claude-sonnet-4": {
|
|
24
|
+
inputPerMillion: 3,
|
|
25
|
+
outputPerMillion: 15,
|
|
26
|
+
cacheReadPerMillion: 0.3,
|
|
27
|
+
cacheWritePerMillion: 3.75
|
|
28
|
+
},
|
|
29
|
+
"claude-sonnet-4-5": {
|
|
30
|
+
inputPerMillion: 3,
|
|
31
|
+
outputPerMillion: 15,
|
|
32
|
+
cacheReadPerMillion: 0.3,
|
|
33
|
+
cacheWritePerMillion: 3.75
|
|
34
|
+
},
|
|
35
|
+
"claude-opus-4": {
|
|
36
|
+
inputPerMillion: 15,
|
|
37
|
+
outputPerMillion: 75,
|
|
38
|
+
cacheReadPerMillion: 1.5,
|
|
39
|
+
cacheWritePerMillion: 18.75
|
|
40
|
+
},
|
|
41
|
+
"gpt-5": { inputPerMillion: 1.25, outputPerMillion: 10 },
|
|
42
|
+
"gpt-5.1": { inputPerMillion: 1.25, outputPerMillion: 10 }
|
|
43
|
+
};
|
|
44
|
+
var ALIASES = {
|
|
45
|
+
sonnet: "claude-sonnet-4-5",
|
|
46
|
+
opus: "claude-opus-4"
|
|
47
|
+
};
|
|
48
|
+
function normalizeModelKey(modelKey) {
|
|
49
|
+
const lower = modelKey.trim().toLowerCase();
|
|
50
|
+
const withoutVendor = lower.slice(lower.lastIndexOf("/") + 1);
|
|
51
|
+
const withoutSnapshot = withoutVendor.replace(/-\d{8}$/, "").replace(/-latest$/, "");
|
|
52
|
+
return ALIASES[withoutSnapshot] ?? withoutSnapshot;
|
|
53
|
+
}
|
|
54
|
+
function rowFor(modelKey, overrides) {
|
|
55
|
+
const normalized = normalizeModelKey(modelKey);
|
|
56
|
+
const override = overrides[modelKey] ?? overrides[normalized];
|
|
57
|
+
const base = TABLE[modelKey] ?? TABLE[normalized];
|
|
58
|
+
if (override === void 0 && base === void 0) return null;
|
|
59
|
+
return {
|
|
60
|
+
inputPerMillion: override?.inputPerMillion ?? base?.inputPerMillion ?? 0,
|
|
61
|
+
outputPerMillion: override?.outputPerMillion ?? base?.outputPerMillion ?? 0,
|
|
62
|
+
cacheReadPerMillion: override?.cacheReadPerMillion ?? base?.cacheReadPerMillion,
|
|
63
|
+
cacheWritePerMillion: override?.cacheWritePerMillion ?? base?.cacheWritePerMillion
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function dollars(tokens, perMillion) {
|
|
67
|
+
if (tokens === void 0 || perMillion === void 0) return 0;
|
|
68
|
+
return tokens * perMillion / 1e6;
|
|
69
|
+
}
|
|
70
|
+
function resolveCost(options) {
|
|
71
|
+
if (options.reportedUsd !== void 0 && options.reportedUsd !== null) {
|
|
72
|
+
return { status: "reported", amount: options.reportedUsd, currency: "USD" };
|
|
73
|
+
}
|
|
74
|
+
if (!options.estimate) {
|
|
75
|
+
return { status: "unknown", reason: "not_reported" };
|
|
76
|
+
}
|
|
77
|
+
if (options.modelKey === null || options.modelKey === "") {
|
|
78
|
+
return { status: "unknown", reason: "unknown_model" };
|
|
79
|
+
}
|
|
80
|
+
const row = rowFor(options.modelKey, options.overrides ?? {});
|
|
81
|
+
if (row === null) {
|
|
82
|
+
return { status: "unknown", reason: "unknown_model" };
|
|
83
|
+
}
|
|
84
|
+
if (options.usage === null || options.usage.source === "unavailable") {
|
|
85
|
+
return { status: "unknown", reason: "not_reported" };
|
|
86
|
+
}
|
|
87
|
+
const amount = dollars(options.usage.inputTokens, row.inputPerMillion) + dollars(options.usage.outputTokens, row.outputPerMillion) + dollars(options.usage.cacheReadTokens, row.cacheReadPerMillion) + dollars(options.usage.cacheCreationTokens, row.cacheWritePerMillion);
|
|
88
|
+
const pricing = {
|
|
89
|
+
tableVersion: PRICING_TABLE_VERSION,
|
|
90
|
+
modelKey: options.modelKey,
|
|
91
|
+
inputPerMillion: row.inputPerMillion,
|
|
92
|
+
outputPerMillion: row.outputPerMillion,
|
|
93
|
+
capturedAt: isoNow(),
|
|
94
|
+
...row.cacheReadPerMillion === void 0 ? {} : { cacheReadPerMillion: row.cacheReadPerMillion },
|
|
95
|
+
...row.cacheWritePerMillion === void 0 ? {} : { cacheWritePerMillion: row.cacheWritePerMillion }
|
|
96
|
+
};
|
|
97
|
+
return { status: "estimated", amount, currency: "USD", pricing };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/telemetry/redact.ts
|
|
101
|
+
var SECRET = /(?:sk-ant-|sk-|ghp_|gho_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]{8,}/g;
|
|
102
|
+
var BEARER = /Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi;
|
|
103
|
+
var ENV_ASSIGN = /\b(?:[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|KEY|PASSWORD|PASS|AUTH)[A-Z0-9_]*)=([^\s]+)/g;
|
|
104
|
+
function redactSecrets(text) {
|
|
105
|
+
return text.replace(SECRET, "[redacted]").replace(BEARER, "Bearer [redacted]").replace(
|
|
106
|
+
ENV_ASSIGN,
|
|
107
|
+
(match, _value) => `${match.slice(0, match.indexOf("="))}=[redacted]`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
function redactFailureMessage(message) {
|
|
111
|
+
return trimErrorMessage(redactSecrets(message));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// src/telemetry/types.ts
|
|
115
|
+
var EXECUTION_PURPOSES = [
|
|
116
|
+
"analyze",
|
|
117
|
+
"generate",
|
|
118
|
+
"prd",
|
|
119
|
+
"plan",
|
|
120
|
+
"execute",
|
|
121
|
+
"review",
|
|
122
|
+
"pr",
|
|
123
|
+
"pr-review",
|
|
124
|
+
"verify"
|
|
125
|
+
];
|
|
126
|
+
var DEFAULT_TELEMETRY_CONFIG = {
|
|
127
|
+
enabled: true,
|
|
128
|
+
maxExecutions: 500,
|
|
129
|
+
pricing: { estimate: false, overrides: {} }
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// src/telemetry/recorder.ts
|
|
133
|
+
var context = null;
|
|
134
|
+
var discardedCount = 0;
|
|
135
|
+
function bindTelemetry(next) {
|
|
136
|
+
context = next;
|
|
137
|
+
}
|
|
138
|
+
function getTelemetryContext() {
|
|
139
|
+
return context;
|
|
140
|
+
}
|
|
141
|
+
function discardedExecutionCount() {
|
|
142
|
+
return discardedCount;
|
|
143
|
+
}
|
|
144
|
+
function resetTelemetryState() {
|
|
145
|
+
context = null;
|
|
146
|
+
discardedCount = 0;
|
|
147
|
+
setTelemetrySessionId(null);
|
|
148
|
+
}
|
|
149
|
+
async function resolveConfig(ctx) {
|
|
150
|
+
if (ctx.config !== void 0) return ctx.config;
|
|
151
|
+
try {
|
|
152
|
+
const { loadTelemetryConfig } = await import("./config-MEM2IWWN.js");
|
|
153
|
+
ctx.config = await loadTelemetryConfig();
|
|
154
|
+
return ctx.config;
|
|
155
|
+
} catch {
|
|
156
|
+
return DEFAULT_TELEMETRY_CONFIG;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function cap(records, max) {
|
|
160
|
+
if (records.length <= max) return records;
|
|
161
|
+
discardedCount += records.length - max;
|
|
162
|
+
return records.slice(records.length - max);
|
|
163
|
+
}
|
|
164
|
+
async function mutate(tasksPath, update) {
|
|
165
|
+
const plan = await loadTaskPlan(tasksPath);
|
|
166
|
+
await saveTaskPlan(tasksPath, update(plan));
|
|
167
|
+
}
|
|
168
|
+
function usageFromClaude(usage) {
|
|
169
|
+
if (usage === void 0 || usage === null) return null;
|
|
170
|
+
const next = { source: "provider" };
|
|
171
|
+
if (usage.inputTokens !== void 0) next.inputTokens = usage.inputTokens;
|
|
172
|
+
if (usage.outputTokens !== void 0) next.outputTokens = usage.outputTokens;
|
|
173
|
+
if (usage.cacheReadTokens !== void 0) next.cacheReadTokens = usage.cacheReadTokens;
|
|
174
|
+
if (usage.cacheCreationTokens !== void 0) next.cacheCreationTokens = usage.cacheCreationTokens;
|
|
175
|
+
return next;
|
|
176
|
+
}
|
|
177
|
+
async function beginExecution(input) {
|
|
178
|
+
const ctx = context;
|
|
179
|
+
if (ctx === null) return null;
|
|
180
|
+
const cfg = await resolveConfig(ctx);
|
|
181
|
+
if (!cfg.enabled) return null;
|
|
182
|
+
const id = randomUUID();
|
|
183
|
+
const record = {
|
|
184
|
+
id,
|
|
185
|
+
sessionId: ctx.sessionId ?? getTelemetrySessionId(),
|
|
186
|
+
purpose: input.purpose,
|
|
187
|
+
attempt: input.attempt ?? 1,
|
|
188
|
+
trigger: input.trigger ?? "initial",
|
|
189
|
+
triggerReason: input.triggerReason ?? null,
|
|
190
|
+
agent: {
|
|
191
|
+
harness: input.harness,
|
|
192
|
+
provider: input.provider ?? null,
|
|
193
|
+
harnessVersion: input.harnessVersion ?? null,
|
|
194
|
+
model: {
|
|
195
|
+
requested: input.modelRequested ?? null,
|
|
196
|
+
resolved: input.modelResolved ?? null,
|
|
197
|
+
source: input.modelSource ?? (input.modelResolved ? "provider" : "unavailable")
|
|
198
|
+
},
|
|
199
|
+
providerSessionId: null
|
|
200
|
+
},
|
|
201
|
+
startedAt: isoNow(),
|
|
202
|
+
finishedAt: null,
|
|
203
|
+
durationMs: null,
|
|
204
|
+
usage: null,
|
|
205
|
+
cost: { status: "unknown", reason: "not_reported" },
|
|
206
|
+
status: "running",
|
|
207
|
+
failure: null,
|
|
208
|
+
owner: { pid: process.pid, host: hostname() },
|
|
209
|
+
...input.iteration === void 0 ? {} : { iteration: input.iteration },
|
|
210
|
+
...input.routingDecision === void 0 || input.routingDecision === null ? {} : { routingDecision: input.routingDecision }
|
|
211
|
+
};
|
|
212
|
+
try {
|
|
213
|
+
await mutate(ctx.tasksPath, (plan) => ({
|
|
214
|
+
...plan,
|
|
215
|
+
executions: cap([...plan.executions ?? [], record], cfg.maxExecutions)
|
|
216
|
+
}));
|
|
217
|
+
return id;
|
|
218
|
+
} catch {
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function timingFromUsage(wallClockMs, usage) {
|
|
223
|
+
const cli = usage?.cliDurationMs;
|
|
224
|
+
const cliDurationMs = cli === void 0 ? null : cli;
|
|
225
|
+
const harnessStartupMs = wallClockMs !== null && cli !== void 0 ? Math.max(0, wallClockMs - cli) : null;
|
|
226
|
+
return {
|
|
227
|
+
cliDurationMs,
|
|
228
|
+
harnessStartupMs,
|
|
229
|
+
apiDurationMs: usage?.apiDurationMs ?? null,
|
|
230
|
+
ttftMs: usage?.ttftMs ?? null,
|
|
231
|
+
numTurns: usage?.numTurns ?? null
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function attachVerdict(verdict) {
|
|
235
|
+
const ctx = context;
|
|
236
|
+
if (ctx === null || verdict == null) return;
|
|
237
|
+
try {
|
|
238
|
+
await mutate(ctx.tasksPath, (plan) => {
|
|
239
|
+
const records = [...plan.executions ?? []];
|
|
240
|
+
if (records.length === 0) return plan;
|
|
241
|
+
const index = records.length - 1;
|
|
242
|
+
const current = records[index];
|
|
243
|
+
if (current === void 0) return plan;
|
|
244
|
+
records[index] = { ...current, verdict };
|
|
245
|
+
return { ...plan, executions: records };
|
|
246
|
+
});
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async function endExecution(input) {
|
|
251
|
+
const ctx = context;
|
|
252
|
+
if (ctx === null) return;
|
|
253
|
+
const cfg = await resolveConfig(ctx);
|
|
254
|
+
if (!cfg.enabled) return;
|
|
255
|
+
const usage = usageFromClaude(input.usage);
|
|
256
|
+
const timedOut = input.timedOut === true || /\btimed out\b/i.test(input.error ?? "");
|
|
257
|
+
const cancelled = input.cancelled === true;
|
|
258
|
+
let status = input.status ?? "completed";
|
|
259
|
+
if (input.status === void 0) {
|
|
260
|
+
if (cancelled) status = "cancelled";
|
|
261
|
+
else if (timedOut) status = "timeout";
|
|
262
|
+
else if (input.error) status = "failed";
|
|
263
|
+
}
|
|
264
|
+
const failure = status === "completed" ? null : {
|
|
265
|
+
kind: classify({
|
|
266
|
+
source: "agent",
|
|
267
|
+
stdout: input.error ?? "",
|
|
268
|
+
exitCode: input.exitCode,
|
|
269
|
+
timedOut
|
|
270
|
+
}).kind,
|
|
271
|
+
message: redactFailureMessage(input.error ?? status),
|
|
272
|
+
exitCode: input.exitCode ?? null
|
|
273
|
+
};
|
|
274
|
+
try {
|
|
275
|
+
await mutate(ctx.tasksPath, (plan) => {
|
|
276
|
+
const records = [...plan.executions ?? []];
|
|
277
|
+
const index = records.findIndex((record) => record.id === input.id);
|
|
278
|
+
if (index === -1) return plan;
|
|
279
|
+
const current = records[index];
|
|
280
|
+
if (current === void 0) return plan;
|
|
281
|
+
const started = Date.parse(current.startedAt);
|
|
282
|
+
const finishedAt = isoNow();
|
|
283
|
+
const modelResolved = input.modelResolved ?? current.agent.model.resolved;
|
|
284
|
+
const modelKey = modelResolved ?? current.agent.model.requested;
|
|
285
|
+
records[index] = {
|
|
286
|
+
...current,
|
|
287
|
+
agent: {
|
|
288
|
+
...current.agent,
|
|
289
|
+
harnessVersion: input.harnessVersion ?? current.agent.harnessVersion,
|
|
290
|
+
providerSessionId: input.providerSessionId ?? current.agent.providerSessionId,
|
|
291
|
+
model: {
|
|
292
|
+
...current.agent.model,
|
|
293
|
+
resolved: modelResolved,
|
|
294
|
+
source: input.modelSource ?? (modelResolved ? current.agent.model.source === "unavailable" ? "provider" : current.agent.model.source : current.agent.model.source)
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
finishedAt,
|
|
298
|
+
durationMs: Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,
|
|
299
|
+
...timingFromUsage(
|
|
300
|
+
Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,
|
|
301
|
+
input.usage
|
|
302
|
+
),
|
|
303
|
+
usage,
|
|
304
|
+
cost: resolveCost({
|
|
305
|
+
reportedUsd: input.reportedUsd ?? input.usage?.costUsd,
|
|
306
|
+
usage,
|
|
307
|
+
modelKey,
|
|
308
|
+
estimate: cfg.pricing.estimate,
|
|
309
|
+
overrides: cfg.pricing.overrides
|
|
310
|
+
}),
|
|
311
|
+
status,
|
|
312
|
+
failure,
|
|
313
|
+
owner: null,
|
|
314
|
+
...input.storyIds === void 0 ? {} : { storyIds: input.storyIds },
|
|
315
|
+
...input.stopReason === void 0 ? {} : { stopReason: input.stopReason }
|
|
316
|
+
};
|
|
317
|
+
return { ...plan, executions: records };
|
|
318
|
+
});
|
|
319
|
+
} catch {
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async function recordInvocation(input, invoke, finish) {
|
|
323
|
+
const id = await beginExecution(input);
|
|
324
|
+
try {
|
|
325
|
+
const result = await invoke();
|
|
326
|
+
if (id !== null) {
|
|
327
|
+
await endExecution({ ...finish(result), id });
|
|
328
|
+
}
|
|
329
|
+
return result;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
if (id !== null) {
|
|
332
|
+
await endExecution({
|
|
333
|
+
id,
|
|
334
|
+
status: "failed",
|
|
335
|
+
error: err instanceof Error ? err.message : String(err)
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
throw err;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export {
|
|
343
|
+
redactSecrets,
|
|
344
|
+
EXECUTION_PURPOSES,
|
|
345
|
+
DEFAULT_TELEMETRY_CONFIG,
|
|
346
|
+
bindTelemetry,
|
|
347
|
+
getTelemetryContext,
|
|
348
|
+
discardedExecutionCount,
|
|
349
|
+
resetTelemetryState,
|
|
350
|
+
usageFromClaude,
|
|
351
|
+
beginExecution,
|
|
352
|
+
timingFromUsage,
|
|
353
|
+
attachVerdict,
|
|
354
|
+
endExecution,
|
|
355
|
+
recordInvocation
|
|
356
|
+
};
|
|
357
|
+
//# sourceMappingURL=chunk-6FDFRNXZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/telemetry/recorder.ts","../src/telemetry/pricing.ts","../src/telemetry/redact.ts","../src/telemetry/types.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport type { ClaudeUsage } from '../core/metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { classify } from '../resilience/errors.js';\nimport type { TaskPlan } from '../types.js';\nimport { resolveCost } from './pricing.js';\nimport { redactFailureMessage } from './redact.js';\nimport { getTelemetrySessionId, setTelemetrySessionId } from './session-id.js';\nimport {\n DEFAULT_TELEMETRY_CONFIG,\n type ExecutionPurpose,\n type ExecutionRecord,\n type ExecutionStatus,\n type ExecutionTrigger,\n type NormalizedUsage,\n type StopReason,\n type TelemetryConfig,\n} from './types.js';\n\nexport interface TelemetryContext {\n tasksPath: string;\n sessionId?: string | null;\n config?: TelemetryConfig;\n}\n\nlet context: TelemetryContext | null = null;\nlet discardedCount = 0;\n\nexport function bindTelemetry(next: TelemetryContext | null): void {\n context = next;\n}\n\nexport function getTelemetryContext(): TelemetryContext | null {\n return context;\n}\n\nexport function discardedExecutionCount(): number {\n return discardedCount;\n}\n\nexport function resetTelemetryState(): void {\n context = null;\n discardedCount = 0;\n setTelemetrySessionId(null);\n}\n\nasync function resolveConfig(ctx: TelemetryContext): Promise<TelemetryConfig> {\n if (ctx.config !== undefined) return ctx.config;\n try {\n const { loadTelemetryConfig } = await import('../config.js');\n ctx.config = await loadTelemetryConfig();\n return ctx.config;\n } catch {\n return DEFAULT_TELEMETRY_CONFIG;\n }\n}\n\nfunction cap(records: ExecutionRecord[], max: number): ExecutionRecord[] {\n if (records.length <= max) return records;\n discardedCount += records.length - max;\n return records.slice(records.length - max);\n}\n\nasync function mutate(tasksPath: string, update: (plan: TaskPlan) => TaskPlan): Promise<void> {\n const plan = await loadTaskPlan(tasksPath);\n await saveTaskPlan(tasksPath, update(plan));\n}\n\nexport function usageFromClaude(usage: ClaudeUsage | null | undefined): NormalizedUsage | null {\n if (usage === undefined || usage === null) return null;\n const next: NormalizedUsage = { source: 'provider' };\n if (usage.inputTokens !== undefined) next.inputTokens = usage.inputTokens;\n if (usage.outputTokens !== undefined) next.outputTokens = usage.outputTokens;\n if (usage.cacheReadTokens !== undefined) next.cacheReadTokens = usage.cacheReadTokens;\n if (usage.cacheCreationTokens !== undefined) next.cacheCreationTokens = usage.cacheCreationTokens;\n return next;\n}\n\nexport interface BeginExecutionInput {\n purpose: ExecutionPurpose;\n attempt?: number;\n trigger?: ExecutionTrigger;\n triggerReason?: ExecutionRecord['triggerReason'];\n harness: string;\n provider?: string | null;\n harnessVersion?: string | null;\n modelRequested?: string | null;\n modelResolved?: string | null;\n modelSource?: ExecutionRecord['agent']['model']['source'];\n iteration?: number;\n routingDecision?: ExecutionRecord['routingDecision'];\n}\n\nexport async function beginExecution(input: BeginExecutionInput): Promise<string | null> {\n const ctx = context;\n if (ctx === null) return null;\n const cfg = await resolveConfig(ctx);\n if (!cfg.enabled) return null;\n\n const id = randomUUID();\n const record: ExecutionRecord = {\n id,\n sessionId: ctx.sessionId ?? getTelemetrySessionId(),\n purpose: input.purpose,\n attempt: input.attempt ?? 1,\n trigger: input.trigger ?? 'initial',\n triggerReason: input.triggerReason ?? null,\n agent: {\n harness: input.harness,\n provider: input.provider ?? null,\n harnessVersion: input.harnessVersion ?? null,\n model: {\n requested: input.modelRequested ?? null,\n resolved: input.modelResolved ?? null,\n source: input.modelSource ?? (input.modelResolved ? 'provider' : 'unavailable'),\n },\n providerSessionId: null,\n },\n startedAt: isoNow(),\n finishedAt: null,\n durationMs: null,\n usage: null,\n cost: { status: 'unknown', reason: 'not_reported' },\n status: 'running',\n failure: null,\n owner: { pid: process.pid, host: hostname() },\n ...(input.iteration === undefined ? {} : { iteration: input.iteration }),\n ...(input.routingDecision === undefined || input.routingDecision === null\n ? {}\n : { routingDecision: input.routingDecision }),\n };\n\n try {\n await mutate(ctx.tasksPath, (plan) => ({\n ...plan,\n executions: cap([...(plan.executions ?? []), record], cfg.maxExecutions),\n }));\n return id;\n } catch {\n return null;\n }\n}\n\n/** Wall clock vs CLI envelope: startup the harness does not report. */\nexport function timingFromUsage(\n wallClockMs: number | null,\n usage: ClaudeUsage | null | undefined,\n): Pick<\n ExecutionRecord,\n 'cliDurationMs' | 'harnessStartupMs' | 'apiDurationMs' | 'ttftMs' | 'numTurns'\n> {\n const cli = usage?.cliDurationMs;\n const cliDurationMs = cli === undefined ? null : cli;\n const harnessStartupMs =\n wallClockMs !== null && cli !== undefined ? Math.max(0, wallClockMs - cli) : null;\n return {\n cliDurationMs,\n harnessStartupMs,\n apiDurationMs: usage?.apiDurationMs ?? null,\n ttftMs: usage?.ttftMs ?? null,\n numTurns: usage?.numTurns ?? null,\n };\n}\n\nexport async function attachVerdict(verdict: ExecutionRecord['verdict']): Promise<void> {\n const ctx = context;\n if (ctx === null || verdict == null) return;\n try {\n await mutate(ctx.tasksPath, (plan) => {\n const records = [...(plan.executions ?? [])];\n if (records.length === 0) return plan;\n const index = records.length - 1;\n const current = records[index];\n if (current === undefined) return plan;\n records[index] = { ...current, verdict };\n return { ...plan, executions: records };\n });\n } catch {\n // Observational: a failed write must never change the invocation outcome.\n }\n}\n\nexport interface EndExecutionInput {\n id: string;\n status?: ExecutionStatus;\n usage?: ClaudeUsage | null;\n reportedUsd?: number | null;\n error?: string | null;\n exitCode?: number | null;\n storyIds?: string[];\n cancelled?: boolean;\n timedOut?: boolean;\n modelResolved?: string | null;\n modelSource?: ExecutionRecord['agent']['model']['source'];\n harnessVersion?: string | null;\n providerSessionId?: string | null;\n stopReason?: StopReason | null;\n}\n\nexport async function endExecution(input: EndExecutionInput): Promise<void> {\n const ctx = context;\n if (ctx === null) return;\n const cfg = await resolveConfig(ctx);\n if (!cfg.enabled) return;\n\n const usage = usageFromClaude(input.usage);\n const timedOut = input.timedOut === true || /\\btimed out\\b/i.test(input.error ?? '');\n const cancelled = input.cancelled === true;\n let status: ExecutionStatus = input.status ?? 'completed';\n if (input.status === undefined) {\n if (cancelled) status = 'cancelled';\n else if (timedOut) status = 'timeout';\n else if (input.error) status = 'failed';\n }\n\n const failure =\n status === 'completed'\n ? null\n : {\n kind: classify({\n source: 'agent',\n stdout: input.error ?? '',\n exitCode: input.exitCode,\n timedOut,\n }).kind,\n message: redactFailureMessage(input.error ?? status),\n exitCode: input.exitCode ?? null,\n };\n\n try {\n await mutate(ctx.tasksPath, (plan) => {\n const records = [...(plan.executions ?? [])];\n const index = records.findIndex((record) => record.id === input.id);\n if (index === -1) return plan;\n const current = records[index];\n if (current === undefined) return plan;\n const started = Date.parse(current.startedAt);\n const finishedAt = isoNow();\n const modelResolved = input.modelResolved ?? current.agent.model.resolved;\n const modelKey = modelResolved ?? current.agent.model.requested;\n records[index] = {\n ...current,\n agent: {\n ...current.agent,\n harnessVersion: input.harnessVersion ?? current.agent.harnessVersion,\n providerSessionId: input.providerSessionId ?? current.agent.providerSessionId,\n model: {\n ...current.agent.model,\n resolved: modelResolved,\n source:\n input.modelSource ??\n (modelResolved\n ? current.agent.model.source === 'unavailable'\n ? 'provider'\n : current.agent.model.source\n : current.agent.model.source),\n },\n },\n finishedAt,\n durationMs: Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,\n ...timingFromUsage(\n Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,\n input.usage,\n ),\n usage,\n cost: resolveCost({\n reportedUsd: input.reportedUsd ?? input.usage?.costUsd,\n usage,\n modelKey,\n estimate: cfg.pricing.estimate,\n overrides: cfg.pricing.overrides,\n }),\n status,\n failure,\n owner: null,\n ...(input.storyIds === undefined ? {} : { storyIds: input.storyIds }),\n ...(input.stopReason === undefined ? {} : { stopReason: input.stopReason }),\n };\n return { ...plan, executions: records };\n });\n } catch {\n // Observational: a failed write must never change the invocation outcome.\n }\n}\n\nexport async function recordInvocation<T>(\n input: BeginExecutionInput,\n invoke: () => Promise<T>,\n finish: (result: T) => EndExecutionInput,\n): Promise<T> {\n const id = await beginExecution(input);\n try {\n const result = await invoke();\n if (id !== null) {\n await endExecution({ ...finish(result), id });\n }\n return result;\n } catch (err) {\n if (id !== null) {\n await endExecution({\n id,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n });\n }\n throw err;\n }\n}\n","import { isoNow } from '../core/state-manager.js';\nimport type { CostRecord, NormalizedUsage, PricingSnapshot, TelemetryConfig } from './types.js';\n\nexport const PRICING_TABLE_VERSION = '2026-08-30';\n\ninterface PricingRow {\n inputPerMillion: number;\n outputPerMillion: number;\n cacheReadPerMillion?: number;\n cacheWritePerMillion?: number;\n}\n\n/** Microdollars-per-million would be more precise; dollars keep the snapshot readable. */\nconst TABLE: Record<string, PricingRow> = {\n 'claude-sonnet-4': {\n inputPerMillion: 3,\n outputPerMillion: 15,\n cacheReadPerMillion: 0.3,\n cacheWritePerMillion: 3.75,\n },\n 'claude-sonnet-4-5': {\n inputPerMillion: 3,\n outputPerMillion: 15,\n cacheReadPerMillion: 0.3,\n cacheWritePerMillion: 3.75,\n },\n 'claude-opus-4': {\n inputPerMillion: 15,\n outputPerMillion: 75,\n cacheReadPerMillion: 1.5,\n cacheWritePerMillion: 18.75,\n },\n 'gpt-5': { inputPerMillion: 1.25, outputPerMillion: 10 },\n 'gpt-5.1': { inputPerMillion: 1.25, outputPerMillion: 10 },\n};\n\n/** Aliases a harness accepts in place of a model id. */\nconst ALIASES: Record<string, string> = {\n sonnet: 'claude-sonnet-4-5',\n opus: 'claude-opus-4',\n};\n\n/**\n * Map a resolved model id onto a table key.\n *\n * What reaches here is whatever the harness reported: a dated snapshot\n * (`claude-sonnet-4-5-20250929`), a vendor-prefixed id\n * (`anthropic/claude-sonnet-4-5`) or a configured alias (`sonnet`). An exact\n * lookup misses all three, and the estimate silently degrades to `unknown`.\n * An override is always honoured under the key the user wrote.\n */\nexport function normalizeModelKey(modelKey: string): string {\n const lower = modelKey.trim().toLowerCase();\n const withoutVendor = lower.slice(lower.lastIndexOf('/') + 1);\n const withoutSnapshot = withoutVendor.replace(/-\\d{8}$/, '').replace(/-latest$/, '');\n return ALIASES[withoutSnapshot] ?? withoutSnapshot;\n}\n\nfunction rowFor(\n modelKey: string,\n overrides: TelemetryConfig['pricing']['overrides'],\n): PricingRow | null {\n const normalized = normalizeModelKey(modelKey);\n const override = overrides[modelKey] ?? overrides[normalized];\n const base = TABLE[modelKey] ?? TABLE[normalized];\n if (override === undefined && base === undefined) return null;\n return {\n inputPerMillion: override?.inputPerMillion ?? base?.inputPerMillion ?? 0,\n outputPerMillion: override?.outputPerMillion ?? base?.outputPerMillion ?? 0,\n cacheReadPerMillion: override?.cacheReadPerMillion ?? base?.cacheReadPerMillion,\n cacheWritePerMillion: override?.cacheWritePerMillion ?? base?.cacheWritePerMillion,\n };\n}\n\nfunction dollars(tokens: number | undefined, perMillion: number | undefined): number {\n if (tokens === undefined || perMillion === undefined) return 0;\n return (tokens * perMillion) / 1_000_000;\n}\n\nexport function resolveCost(options: {\n reportedUsd?: number | null;\n usage: NormalizedUsage | null;\n modelKey: string | null;\n estimate: boolean;\n overrides?: TelemetryConfig['pricing']['overrides'];\n}): CostRecord {\n if (options.reportedUsd !== undefined && options.reportedUsd !== null) {\n return { status: 'reported', amount: options.reportedUsd, currency: 'USD' };\n }\n if (!options.estimate) {\n return { status: 'unknown', reason: 'not_reported' };\n }\n if (options.modelKey === null || options.modelKey === '') {\n return { status: 'unknown', reason: 'unknown_model' };\n }\n const row = rowFor(options.modelKey, options.overrides ?? {});\n if (row === null) {\n return { status: 'unknown', reason: 'unknown_model' };\n }\n if (options.usage === null || options.usage.source === 'unavailable') {\n return { status: 'unknown', reason: 'not_reported' };\n }\n const amount =\n dollars(options.usage.inputTokens, row.inputPerMillion) +\n dollars(options.usage.outputTokens, row.outputPerMillion) +\n dollars(options.usage.cacheReadTokens, row.cacheReadPerMillion) +\n dollars(options.usage.cacheCreationTokens, row.cacheWritePerMillion);\n const pricing: PricingSnapshot = {\n tableVersion: PRICING_TABLE_VERSION,\n modelKey: options.modelKey,\n inputPerMillion: row.inputPerMillion,\n outputPerMillion: row.outputPerMillion,\n capturedAt: isoNow(),\n ...(row.cacheReadPerMillion === undefined\n ? {}\n : { cacheReadPerMillion: row.cacheReadPerMillion }),\n ...(row.cacheWritePerMillion === undefined\n ? {}\n : { cacheWritePerMillion: row.cacheWritePerMillion }),\n };\n return { status: 'estimated', amount, currency: 'USD', pricing };\n}\n\nexport function estimateCost(\n usage: NormalizedUsage,\n modelKey: string,\n overrides: TelemetryConfig['pricing']['overrides'] = {},\n): CostRecord {\n return resolveCost({ usage, modelKey, estimate: true, overrides });\n}\n","import { trimErrorMessage } from '../core/state-manager.js';\n\nconst SECRET = /(?:sk-ant-|sk-|ghp_|gho_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]{8,}/g;\nconst BEARER = /Bearer\\s+[A-Za-z0-9\\-._~+/]+=*/gi;\nconst ENV_ASSIGN =\n /\\b(?:[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|KEY|PASSWORD|PASS|AUTH)[A-Z0-9_]*)=([^\\s]+)/g;\n\n/** Strip credentials from a message that will be persisted. */\nexport function redactSecrets(text: string): string {\n return text\n .replace(SECRET, '[redacted]')\n .replace(BEARER, 'Bearer [redacted]')\n .replace(\n ENV_ASSIGN,\n (match, _value: string) => `${match.slice(0, match.indexOf('='))}=[redacted]`,\n );\n}\n\n/** Sanitize a failure message: secrets out, then the existing 8-line cap. */\nexport function redactFailureMessage(message: string): string {\n return trimErrorMessage(redactSecrets(message));\n}\n","import type { FailureKind } from '../resilience/errors.js';\n\nexport const EXECUTION_PURPOSES = [\n 'analyze',\n 'generate',\n 'prd',\n 'plan',\n 'execute',\n 'review',\n 'pr',\n 'pr-review',\n 'verify',\n] as const;\n\nexport type ExecutionPurpose = (typeof EXECUTION_PURPOSES)[number];\n\nexport type ExecutionTrigger = 'initial' | 'retry' | 'fallback' | 'correction' | 'escalation';\n\nexport type ExecutionStatus =\n | 'running'\n | 'completed'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'interrupted';\n\nexport type StopReason =\n | 'completed'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'max_attempts'\n | 'max_cost'\n | 'max_duration';\n\nexport type VerdictStatus = 'passed' | 'failed' | 'unverified';\n\nexport interface NormalizedUsage {\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n reasoningTokens?: number;\n details?: Record<string, number>;\n source: 'provider' | 'unavailable';\n}\n\nexport interface PricingSnapshot {\n tableVersion: string;\n modelKey: string;\n inputPerMillion: number;\n outputPerMillion: number;\n cacheReadPerMillion?: number;\n cacheWritePerMillion?: number;\n capturedAt: string;\n}\n\nexport type CostRecord =\n | { status: 'reported'; amount: number; currency: 'USD' }\n | { status: 'estimated'; amount: number; currency: 'USD'; pricing: PricingSnapshot }\n | {\n status: 'unknown';\n reason: 'not_reported' | 'no_pricing' | 'unknown_model' | 'subscription' | 'zero_rated';\n };\n\nexport interface ExecutionAgent {\n harness: string;\n provider: string | null;\n harnessVersion?: string | null;\n model: {\n requested: string | null;\n resolved: string | null;\n source: 'provider' | 'config' | 'unavailable';\n };\n providerSessionId: string | null;\n}\n\nexport interface ExecutionOwner {\n pid: number;\n host: string;\n}\n\nexport interface ExecutionVerdict {\n status: VerdictStatus;\n level?: string | null;\n independence?: string | null;\n}\n\nexport interface RoutingDecision {\n selected: string;\n actual?: string;\n candidates?: unknown[];\n reasonCodes?: string[];\n [key: string]: unknown;\n}\n\nexport interface ExecutionRecord {\n id: string;\n sessionId: string | null;\n purpose: ExecutionPurpose;\n attempt: number;\n trigger: ExecutionTrigger;\n triggerReason: FailureKind | null;\n agent: ExecutionAgent;\n startedAt: string;\n finishedAt: string | null;\n durationMs: number | null;\n /** Envelope duration when the CLI reports it. */\n cliDurationMs?: number | null;\n /** wallClock − cliDuration: startup the CLI does not see. */\n harnessStartupMs?: number | null;\n /** Envelope `duration_api_ms` when reported. */\n apiDurationMs?: number | null;\n /** Time to first output, when reported. */\n ttftMs?: number | null;\n numTurns?: number | null;\n usage: NormalizedUsage | null;\n cost: CostRecord;\n status: ExecutionStatus;\n failure: {\n kind: FailureKind;\n message: string;\n exitCode: number | null;\n } | null;\n stopReason?: StopReason | null;\n iteration?: number;\n storyIds?: string[];\n owner?: ExecutionOwner | null;\n routingDecision?: RoutingDecision | null;\n verdict?: ExecutionVerdict | null;\n}\n\nexport interface CostTotals {\n reported: number;\n estimated: number;\n unknownExecutions: number;\n}\n\nexport interface ExecutionSummary {\n count: number;\n discarded: number;\n byStatus: Partial<Record<ExecutionStatus, number>>;\n usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n reasoningTokens: number;\n };\n totalCost: CostTotals;\n}\n\nexport interface TelemetryConfig {\n enabled: boolean;\n maxExecutions: number;\n pricing: {\n estimate: boolean;\n overrides: Record<string, Partial<PricingSnapshot>>;\n };\n}\n\nexport const DEFAULT_TELEMETRY_CONFIG: TelemetryConfig = {\n enabled: true,\n maxExecutions: 500,\n pricing: { estimate: false, overrides: {} },\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;;;ACElB,IAAM,wBAAwB;AAUrC,IAAM,QAAoC;AAAA,EACxC,mBAAmB;AAAA,IACjB,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA,IACrB,sBAAsB;AAAA,EACxB;AAAA,EACA,qBAAqB;AAAA,IACnB,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA,IACrB,sBAAsB;AAAA,EACxB;AAAA,EACA,iBAAiB;AAAA,IACf,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA,IAC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