sprag-cli 3.89.2 → 3.90.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/bin/cli.js CHANGED
@@ -775,7 +775,13 @@ async function main() {
775
775
  maybeSpawnBudgetCheck();
776
776
  if (!caps || !Array.isArray(caps.windows) || caps.windows.length === 0) {
777
777
  const bw = budgetWindow();
778
- if (bw) caps = { windows: [bw] };
778
+ if (bw) {
779
+ caps = { windows: [bw] };
780
+ // The prompt hook reads the budget from last-caps.json, and the
781
+ // snapshot above was written before this window existed.
782
+ const { persistSnapshot } = await import('../src/caps-cache.js');
783
+ persistSnapshot({ caps, model });
784
+ }
779
785
  }
780
786
  } catch (e) {
781
787
  debug('litellm-budget:window', e);
package/docs/TEAM.md CHANGED
@@ -128,7 +128,7 @@ A machine holds one seat per organization. When it joins again, with `sprag team
128
128
  - **What a seat is.** One machine (one member key) that has not left and either sent anything in the last 30 days or is paused. A machine that has been silent for 30 days or more without being paused holds no seat. Members who left are not counted.
129
129
  - **Second machine.** When the same person uses two machines, an owner or admin can merge the second one into the first so the two share one seat. In the dashboard, use "Merge seat" on the member row; "Unmerge" gives it its own seat back. A merged row shows "shares a seat with <name>".
130
130
  - **The limit.** Each organization has a seat limit. A join past the limit is refused: `sprag team join` exits 1 with "This organization has no free seat. Ask your organization owner or admin to add seats", and an environment auto-join stays silent and tries again at a later session start. Lowering the limit below current use never removes anyone; it only refuses new joins until Sprag raises it again.
131
- - **Roles.** There are three permission levels. The superuser is Sprag staff: it sets the plan and the seat limit, suspends organizations, adds owners by email (an email without an account is invited), and sees every organization at sprag.io/ops/. An owner is a company's top level: it appoints and removes admins by email (an email without an account is invited and shown as waiting for its first sign-in until the owner cancels it or the person signs in), and does everything an admin does. An admin is a company's management level: it creates teams and manages members, rules and seats. The person who created a team has no special rights over it; only the organization's owners and admins and the superuser manage teams. Owners and admins see the seat limit in the dashboard. To add seats, write to support@sprag.io.
131
+ - **Roles.** There are three permission levels. The superuser is Sprag staff: it sets the plan and the seat limit, suspends organizations, sees every organization at sprag.io/ops/, and has every right an owner has in each organization, so it adds and removes owners and admins by email there (an email without an account is invited). An owner is a company's top level: it appoints and removes admins by email (an email without an account is invited and shown as waiting for its first sign-in until the owner cancels it or the person signs in), and does everything an admin does. An admin is a company's management level: it creates teams and manages members, rules and seats. The person who created a team has no special rights over it; only the organization's owners and admins and the superuser manage teams. Owners and admins see the seat limit in the dashboard. To add seats, write to support@sprag.io.
132
132
  - **The plan.** Sprag sets the plan (`pro` or `enterprise`) on the organization; owners and admins cannot change it. Prompt capture can be switched on only while the organization is on Enterprise. To change the plan, contact us.
133
133
 
134
134
  Create a team inside an organization you administer from the CLI with `sprag team create --org <org-id>`; without `--org` the server refuses, because only Sprag opens organizations. The command prints the organization name and how many seats are used. `sprag team status` shows the organization name.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.89.2",
3
+ "version": "3.90.0",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/brief.js CHANGED
@@ -236,7 +236,7 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
236
236
  for (const [kind, x] of fresh) {
237
237
  items.push(kind === 'route'
238
238
  ? `새 위임 후보가 감지되었습니다 — "${x.label}" 유형 ${x.count}회 반복(statusline의 route? R${x.id} 칩). 등록: sprag harness promote R${x.id} --global|--project (적용 범위는 사용자에게 확인) / 무시: route-scan dismiss ${x.id}`
239
- : `승인된 위임 룰의 최근 에러율이 기준(20%)을 넘었습니다 — "${x.label}" (${x.healthSource === 'delegated' ? `위임 실행 ${x.delegatedRuns}건 중 에러율 ${Math.round((x.delegatedErrRate || 0) * 100)}%` : `유사 에피소드 기준 에러율 ${Math.round((x.errRate || 0) * 100)}%`}, statusline의 rule-health 칩). 조건 좁히기/제거를 사용자와 상의하세요: sprag route-scan rules`);
239
+ : `승인된 위임 룰의 최근 에러율이 기준(${Math.round(mr.ruleReviewThreshold(x) * 100)}%)을 넘었습니다. "${x.label}" (${x.healthSource === 'delegated' ? `위임 실행 ${x.delegatedRuns}건 중 에러율 ${Math.round((x.delegatedErrRate || 0) * 100)}%` : `유사 에피소드 기준 에러율 ${Math.round((x.errRate || 0) * 100)}%`}, statusline의 rule-health 칩). 조건 좁히기/제거를 사용자와 상의하세요: sprag route-scan rules`);
240
240
  }
241
241
  s.briefed = [...briefed];
242
242
  } catch { /* caches unreadable — ctx briefing above still applies */ }
package/src/caps-cache.js CHANGED
@@ -86,3 +86,54 @@ export function loadRecentSnapshot({ maxAgeMs = 5 * 60 * 1000 } = {}) {
86
86
  return null;
87
87
  }
88
88
  }
89
+
90
+ /** Used percentage at which a window counts as under pressure. */
91
+ export const CAP_PRESSURE_HIGH = 70;
92
+ /** Used percentage at which a window counts as about to run out. */
93
+ export const CAP_PRESSURE_CRITICAL = 90;
94
+
95
+ const MODEL_FAMILY_RE = /opus|sonnet|haiku|fable/i;
96
+
97
+ function modelFamily(text) {
98
+ const m = MODEL_FAMILY_RE.exec(String(text || ''));
99
+ return m ? m[0].toLowerCase() : null;
100
+ }
101
+
102
+ /**
103
+ * How close the busiest usage window is to its limit, read from the statusline
104
+ * snapshot. The prompt hook uses it to say how hard to lean on delegation.
105
+ *
106
+ * A per-model window (`seven_day_opus` and the like) counts only for a session
107
+ * on that model family, because another family's quota does not constrain it.
108
+ * With the session's family unknown such a window is kept: overstating the
109
+ * pressure is cheaper than hiding it. `litellm_budget` is an ordinary window
110
+ * here and is reported with source 'litellm'.
111
+ *
112
+ * @param {object} [opts]
113
+ * @param {{caps?: object|null}|null} [opts.snapshot] defaults to the recent snapshot
114
+ * @param {string|null} [opts.sessionModel] model id or display name of the session
115
+ * @returns {{ level: 'normal'|'high'|'critical', pct: number, key: string,
116
+ * source: 'subscription'|'litellm' }|null}
117
+ * null when there is no fresh snapshot or no window with a usable percentage
118
+ */
119
+ export function capPressure({ snapshot = loadRecentSnapshot(), sessionModel } = {}) {
120
+ const windows = snapshot && snapshot.caps && Array.isArray(snapshot.caps.windows) ? snapshot.caps.windows : [];
121
+ const sessionFamily = modelFamily(sessionModel);
122
+ let top = null;
123
+ for (const w of windows) {
124
+ if (!w || typeof w.key !== 'string') continue;
125
+ if (typeof w.usedPct !== 'number' || !Number.isFinite(w.usedPct)) continue;
126
+ const family = modelFamily(w.key);
127
+ if (family && sessionFamily && family !== sessionFamily) continue;
128
+ if (!top || w.usedPct > top.usedPct) top = w;
129
+ }
130
+ if (!top) return null;
131
+ const level = top.usedPct >= CAP_PRESSURE_CRITICAL ? 'critical'
132
+ : top.usedPct >= CAP_PRESSURE_HIGH ? 'high' : 'normal';
133
+ return {
134
+ level,
135
+ pct: top.usedPct,
136
+ key: top.key,
137
+ source: top.key === 'litellm_budget' ? 'litellm' : 'subscription',
138
+ };
139
+ }
@@ -1,14 +1,16 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { loadCodexLedger } from './ledger.js';
3
3
  import { isFailedRun } from '../route-scan.js';
4
- import { wilsonLowerBound, HEALTH_ERR_RATE, HEALTH_MIN_SAMPLE_DELEGATED } from '../model-rules.js';
4
+ import { wilsonLowerBound, reviewThreshold, HEALTH_MIN_SAMPLE_DELEGATED } from '../model-rules.js';
5
5
  import { loadSharedModelRules, sharedModelRulesForProject, realProjectRoot } from '../shared-model-rules.js';
6
6
 
7
7
  /**
8
8
  * Measured outcome of one Codex rule, judged as Claude's rule health judges
9
9
  * its delegations: a run fails when interrupted or when its tool-error density
10
10
  * crosses isFailedRun's line, and the rule goes to review only when the Wilson
11
- * lower bound of the failure rate clears HEALTH_ERR_RATE over enough runs.
11
+ * lower bound of the failure rate clears reviewThreshold over enough runs.
12
+ * The Codex ledger records no episodes the session model handled itself, so
13
+ * there is no baseline and the threshold is the HEALTH_ERR_RATE floor.
12
14
  */
13
15
  export function codexRuleHealth(rule, { events = Object.values(loadCodexLedger().events) } = {}) {
14
16
  const since = Date.parse(rule.createdAt);
@@ -25,7 +27,7 @@ export function codexRuleHealth(rule, { events = Object.values(loadCodexLedger()
25
27
  function healthOf(runs) {
26
28
  const errs = runs.filter((e) => e.aborted || isFailedRun({ toolErrors: e.toolErrors, calls: e.calls })).length;
27
29
  const saved = runs.filter((e) => Number.isFinite(e.usd)).reduce((sum, e) => sum + e.usd, 0);
28
- const review = runs.length >= HEALTH_MIN_SAMPLE_DELEGATED && wilsonLowerBound(errs, runs.length) > HEALTH_ERR_RATE;
30
+ const review = runs.length >= HEALTH_MIN_SAMPLE_DELEGATED && wilsonLowerBound(errs, runs.length) > reviewThreshold(null);
29
31
  return { runs: runs.length, errs, rate: runs.length ? errs / runs.length : 0, saved, status: review ? 'review' : 'active' };
30
32
  }
31
33
 
@@ -66,7 +66,17 @@ export async function run({ hasFlag }) {
66
66
  // already reads it (src/delegation-guard.js). A payload without the field
67
67
  // leaves root undefined, which is the behaviour this had before.
68
68
  const match = routeMatch(ctx.prompt, { sessionRank, root: ctx.cwd });
69
- const hint = routeHint(ctx.prompt, { sessionRank, root: ctx.cwd, match });
69
+ // How near the usage limit is, from the statusline snapshot. Read only when
70
+ // a hint will be written, and only the file: no network in a prompt hook.
71
+ let pressure = null;
72
+ if (match) {
73
+ try {
74
+ const { capPressure } = await import('../caps-cache.js');
75
+ const { getSessionModel } = await import('../parser.js');
76
+ pressure = capPressure({ sessionModel: getSessionModel(ctx.transcript_path) });
77
+ } catch (e) { debug('brief:cap-pressure', e); }
78
+ }
79
+ const hint = routeHint(ctx.prompt, { sessionRank, root: ctx.cwd, match, pressure });
70
80
  if (hint) parts.push(hint);
71
81
  // Remember that this turn carried a delegation hint, so the PostToolUse
72
82
  // hook can nudge when the model looks things up itself instead. The
@@ -118,9 +118,13 @@ export async function run({ args, hasFlag, numArg }) {
118
118
  console.log(` ${lang === 'ko' ? '룰' : 'rule'}: ${e.rule || '(unattributed)'}`);
119
119
  }
120
120
  console.log('');
121
+ const v3Runs = events.filter((e) => e.basis === 'v3').length;
121
122
  console.log(lang === 'ko'
122
- ? '금액은 "룰 승격 전 그 유형을 처리하던 모델"과 실제 실행 모델의 가격 차이입니다 (토큰 수는 고정 가정).'
123
- : 'Each amount is the price gap between the model that handled this category before the rule and the model that actually ran it (token counts held constant).');
123
+ ? '금액은 실행 1건마다 "그 에피소드에서 가장 비싼 모델이 같은 일을 직접 했을 때의 비용"에서 실제로 든 비용을 뺀 값입니다. 직접 했다면 호출마다 다시 읽었을 캐시 컨텍스트와 이후 호출에 쌓였을 도구 결과를 앞쪽에 넣고, 위임 프롬프트와 돌아온 결과를 다시 읽는 비용은 실제 비용 쪽에 넣습니다.'
124
+ : 'Each amount, per run, is what the most expensive model in that episode would have cost doing the same work itself, minus what delegating actually cost. The first side counts the cached context it would have re-read on every call and the tool results it would have carried into later calls; the second adds the delegation prompt and the returned report, re-read on later calls.');
125
+ console.log(lang === 'ko'
126
+ ? `메인 세션 기록을 읽지 못한 실행과 이 계산법 이전 기록(${events.length - v3Runs}건)은 토큰 수를 고정하고 모델 가격 차이만 본 이전 방식입니다. 이번 목록에서 새 방식은 ${v3Runs}건입니다.`
127
+ : `Runs whose main-session numbers could not be read, and records from before this method (${events.length - v3Runs}), use the older price-gap method with token counts held constant. ${v3Runs} in this list use the new one.`);
124
128
  return;
125
129
  }
126
130
 
@@ -176,10 +180,17 @@ export async function run({ args, hasFlag, numArg }) {
176
180
  // Measured outcome of the rule actually firing, plus what it saved.
177
181
  // A rule with no measured delegations shows "—", never "$0.00": the
178
182
  // two mean opposite things (no data vs. data showing no value).
183
+ // The session model's own failure rate on the same work, so the user
184
+ // can tell a downgrade that hurts from work that fails on any model.
185
+ const base = r.baselineSample >= mr.HEALTH_MIN_SAMPLE && Number.isFinite(r.baselineErrRate)
186
+ ? (lang === 'ko'
187
+ ? ` (직접 처리 시 ${Math.round(r.baselineErrRate * 100)}%)`
188
+ : ` (session model ${Math.round(r.baselineErrRate * 100)}%)`)
189
+ : '';
179
190
  const measured = r.delegatedRuns
180
191
  ? (lang === 'ko'
181
- ? `실제 위임 ${r.delegatedRuns}건 · 에러율 ${Math.round((r.delegatedErrRate || 0) * 100)}% · 절감 ~${signedUsd(r.savedUsd || 0)}`
182
- : `measured ×${r.delegatedRuns} · err ${Math.round((r.delegatedErrRate || 0) * 100)}% · saved ~${signedUsd(r.savedUsd || 0)}`)
192
+ ? `실제 위임 ${r.delegatedRuns}건 · 에러율 ${Math.round((r.delegatedErrRate || 0) * 100)}%${base} · 절감 ~${signedUsd(r.savedUsd || 0)}`
193
+ : `measured ×${r.delegatedRuns} · err ${Math.round((r.delegatedErrRate || 0) * 100)}%${base} · saved ~${signedUsd(r.savedUsd || 0)}`)
183
194
  : (sessionRank !== null && !rs.worthDelegating(r.tier, sessionRank)
184
195
  ? (lang === 'ko'
185
196
  ? `이 규칙은 현재 기본 모델(${sessionModel}) 기준으로는 적용되지 않습니다. 세션 모델이 이미 위임 목표와 같은 급이어서 절감이 발생하지 않습니다.`
@@ -454,17 +465,18 @@ export async function run({ args, hasFlag, numArg }) {
454
465
  }
455
466
  if (reviewRules.length > 0) {
456
467
  lines.push(lang === 'ko'
457
- ? '[sprag rule-health] 사용자가 승인한 위임 룰 중, 위임 대상 유형의 최근 에러율이 기준(20%)을 넘어 재검토가 필요한 룰이 있습니다 — 사용자에게 브리핑하고 조건 좁히기/제거를 상의하세요:'
458
- : '[sprag rule-health] Some user-approved delegation rules now exceed the 20% error-rate threshold for their delegated category — brief the user and discuss narrowing or removing them:');
468
+ ? '[sprag rule-health] 사용자가 승인한 위임 룰 중, 위임 대상 유형의 최근 에러율이 룰별 기준을 넘어 재검토가 필요한 룰이 있습니다. 사용자에게 브리핑하고 조건 좁히기/제거를 상의하세요:'
469
+ : '[sprag rule-health] Some user-approved delegation rules now exceed their error-rate threshold for the delegated category — brief the user and discuss narrowing or removing them:');
459
470
  for (const r of reviewRules) {
460
471
  // Say WHICH signal tripped: a measured delegation failure rate is a
461
472
  // much stronger claim than the shape-based proxy, and the user's
462
473
  // decision (narrow vs. remove) depends on knowing which it is.
463
474
  const measured = r.healthSource === 'delegated';
464
475
  const rate = Math.round(((measured ? r.delegatedErrRate : r.errRate) || 0) * 100);
476
+ const bar = Math.round(mrHook.ruleReviewThreshold(r) * 100);
465
477
  const evidence = lang === 'ko'
466
- ? (measured ? `실제 위임 ${r.delegatedRuns}건 실측 에러율 ${rate}%` : `유형 에러율 ${rate}% (형태 기반 추정)`)
467
- : (measured ? `${rate}% measured across ${r.delegatedRuns} real delegations` : `${rate}% for the category (shape-based proxy)`);
478
+ ? (measured ? `실제 위임 ${r.delegatedRuns}건 실측 에러율 ${rate}% (기준 ${bar}%)` : `유형 에러율 ${rate}% (형태 기반 추정, 기준 ${bar}%)`)
479
+ : (measured ? `${rate}% measured across ${r.delegatedRuns} real delegations (threshold ${bar}%)` : `${rate}% for the category (shape-based proxy, threshold ${bar}%)`);
468
480
  lines.push(lang === 'ko'
469
481
  ? ` 룰 #${r.n} (${r.tier} ${rs.tierLabel(r.tier)} · ${rs.scopeLabel(r.scope)}) — ${evidence}`
470
482
  : ` rule #${r.n} (${r.tier} ${rs.tierLabel(r.tier, 'en')} · ${rs.scopeLabel(r.scope, 'en')}) — ${evidence}`);
@@ -155,7 +155,12 @@ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan
155
155
  : (ko ? `${fmtTime(marks[s])} 이후` : `since ${fmtTime(marks[s])}`);
156
156
  console.log(`${label(s)}: ${fmtTotal(t)} (${since})`);
157
157
  }
158
- if (agent !== 'codex') await printModelShare({ ko, dir, money });
158
+ if (agent !== 'codex') {
159
+ console.log(ko
160
+ ? '라우팅 절감은 위임하지 않고 직접 했을 때의 캐시 읽기와 쌓일 컨텍스트까지 반영해 계산합니다 (v3).'
161
+ : 'Routing saved is net of the cache re-reads and carried context the same work would have cost without delegating (v3).');
162
+ await printModelShare({ ko, dir, money });
163
+ }
159
164
  return;
160
165
  }
161
166
 
@@ -69,6 +69,28 @@ export function wilsonLowerBound(errs, n) {
69
69
  return Math.max(0, (center - margin) / denom);
70
70
  }
71
71
 
72
+ /**
73
+ * Error rate a delegated rule must clear before it goes to review. Failures
74
+ * the session model also hits on the same work are not the downgrade's fault:
75
+ * a combination of models cannot beat the rate at which all of them fail
76
+ * together (Co-Failure Ceiling, arXiv 2606.27288). So when the session model's
77
+ * own failure rate on this category is known from enough episodes, the bar is
78
+ * that rate, never lower than HEALTH_ERR_RATE. Without a baseline (Codex
79
+ * ledgers carry none, a fresh category has too few episodes) the floor alone
80
+ * applies, as before.
81
+ */
82
+ export function reviewThreshold(baselineErrRate, baselineSample = 0) {
83
+ if (!(baselineSample >= HEALTH_MIN_SAMPLE) || !Number.isFinite(baselineErrRate)) return HEALTH_ERR_RATE;
84
+ return Math.max(HEALTH_ERR_RATE, baselineErrRate);
85
+ }
86
+
87
+ /** The threshold a stored rule was judged against, for messages that quote it. */
88
+ export function ruleReviewThreshold(rule) {
89
+ return rule && rule.healthSource === 'delegated'
90
+ ? reviewThreshold(rule.baselineErrRate, rule.baselineSample)
91
+ : HEALTH_ERR_RATE;
92
+ }
93
+
72
94
  // Fallback budget for rules promoted before budgets were recorded — matches
73
95
  // route-scan's pre-calibration defaults. Kept as local constants rather than
74
96
  // imported: route-scan imports this module, and a static back-import would
@@ -649,9 +671,19 @@ export function refreshModelRules(episodeStats, delegatedStats = new Map(), { no
649
671
  // asks "does work SHAPED like this tend to fail?"; the measurement asks
650
672
  // "does this rule fail when it actually fires?" — only the second can
651
673
  // catch a rule that is mis-firing on requests it should never have taken.
674
+ // Baseline: how often the session model itself failed on work shaped like
675
+ // this rule, judged by isFailedRun's tool-error density just as delegated
676
+ // runs are. The proxy errRate above counts any tool error, so comparing
677
+ // the two would set a stricter test for the delegate than for the baseline.
678
+ const baseSample = s ? s.epCount : 0;
679
+ const baseRate = baseSample > 0 ? (s.failCount || 0) / baseSample : null;
680
+ if (r.baselineErrRate !== baseRate || r.baselineSample !== baseSample) {
681
+ r.baselineErrRate = baseRate;
682
+ r.baselineSample = baseSample;
683
+ }
652
684
  if (r.delegatedRuns >= HEALTH_MIN_SAMPLE_DELEGATED) {
653
685
  r.healthSource = 'delegated';
654
- r.status = wilsonLowerBound(d ? d.errRuns : 0, r.delegatedRuns) > HEALTH_ERR_RATE
686
+ r.status = wilsonLowerBound(d ? d.errRuns : 0, r.delegatedRuns) > reviewThreshold(baseRate, baseSample)
655
687
  ? 'review' : 'active';
656
688
  } else {
657
689
  r.healthSource = 'proxy';
@@ -0,0 +1,128 @@
1
+ /**
2
+ * net-saving — the v3 delegation counterfactual.
3
+ *
4
+ * v2 priced the subagent's own tokens at the session model's rates and called
5
+ * the difference the saving. That leaves out what makes a long-lived main
6
+ * session expensive: every call it makes re-reads its whole context from the
7
+ * cache, and everything a tool returns stays in that context for the rest of
8
+ * the session. It also leaves out what delegating costs the main session: the
9
+ * prompt it writes and the report that comes back and is then re-read.
10
+ *
11
+ * For one delegated run, with
12
+ * k subagent calls, ctx_i the context of call i, g_i = ctx_i - ctx_1
13
+ * G ctx_k - ctx_1 + the run's total output (what the main context would
14
+ * have gained)
15
+ * C context of the main call that issued the delegation
16
+ * N main calls that follow, up to the next compaction (capped)
17
+ * P tokens of the delegation prompt, R tokens of the report that returned
18
+ * the main model doing the work itself would have cost
19
+ * CF_work = sum_i (C + g_i) * cacheRead + sum_i (newIn_i * write + out_i * output)
20
+ * CF_carry = G * N * cacheRead
21
+ * and delegating actually cost
22
+ * Actual = what the run cost on its own model
23
+ * + P * output + R * write + R * N * cacheRead
24
+ * so saving = CF_work + CF_carry - Actual.
25
+ *
26
+ * Rates are the main model's, per token, from the same price paths as every
27
+ * other figure (list table, or the LiteLLM gateway table when one is set). A
28
+ * rate that is not known makes the saving null; nothing is filled in.
29
+ */
30
+
31
+ import { sessionCost } from './claude-price.js';
32
+ import { gatewayBase } from './gateway-auth.js';
33
+
34
+ // estimateCost rounds to cents. A per-token rate or a sub-cent run would vanish
35
+ // in that rounding, so both are priced at a larger quantity and scaled back
36
+ // (a run to 1e-8 USD, a rate to 1e-12 USD per token).
37
+ const RATE_SCALE = 1e9;
38
+ const COST_SCALE = 1e6;
39
+
40
+ const ZERO = { input: 0, cacheCreation: 0, cacheRead: 0, ephemeral5m: 0, ephemeral1h: 0, output: 0 };
41
+
42
+ /** Where a price came from: the Anthropic list table, or a LiteLLM gateway. */
43
+ export function priceSource(env = process.env) {
44
+ return gatewayBase(env) ? 'gateway' : 'list';
45
+ }
46
+
47
+ /**
48
+ * Per-token USD rates of a model for the three token classes the counterfactual
49
+ * touches. Cache writes are taken at the 5-minute rate, the cheaper of the two.
50
+ * null when any of them has no price.
51
+ */
52
+ export function unitRates(model, { env = process.env } = {}) {
53
+ if (!model) return null;
54
+ const rate = (totals) => {
55
+ let c;
56
+ try { c = sessionCost({ ...ZERO, ...totals }, model, { env }); } catch { return null; }
57
+ return c ? c.actual / RATE_SCALE : null;
58
+ };
59
+ const cacheRead = rate({ cacheRead: RATE_SCALE });
60
+ const write = rate({ cacheCreation: RATE_SCALE, ephemeral5m: RATE_SCALE });
61
+ const output = rate({ output: RATE_SCALE });
62
+ if (cacheRead === null || write === null || output === null) return null;
63
+ return { cacheRead, write, output };
64
+ }
65
+
66
+ /**
67
+ * What a run's tokens cost on a model, in USD, to better than a cent. null when
68
+ * the model has no price on this path.
69
+ */
70
+ export function exactCost(totals, model, { env = process.env } = {}) {
71
+ if (!model) return null;
72
+ const scale = (t) => {
73
+ const out = {};
74
+ for (const f of Object.keys(ZERO)) out[f] = (t[f] || 0) * COST_SCALE;
75
+ return out;
76
+ };
77
+ const scaled = scale(totals);
78
+ if (totals.long) scaled.long = scale(totals.long);
79
+ let c;
80
+ try { c = sessionCost(scaled, model, { env }); } catch { return null; }
81
+ return c ? c.actual / COST_SCALE : null;
82
+ }
83
+
84
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
85
+
86
+ /**
87
+ * The v3 saving of one delegated run, or null when an input is missing (the
88
+ * caller then falls back to the v2 formula).
89
+ *
90
+ * @param {object} p
91
+ * @param {Array<{ctx:number,newIn:number,out:number}>} p.calls subagent calls, in order
92
+ * @param {number} p.mainCtx C
93
+ * @param {number} p.followUps N
94
+ * @param {number} p.promptTokens P
95
+ * @param {number} p.resultTokens R
96
+ * @param {{cacheRead:number,write:number,output:number}} p.rates main model, USD per token
97
+ * @param {number} p.subActual what the run cost on its own model, USD
98
+ * @param {boolean} [p.skipFirstWrite] leave the first call's new input out of CF_work
99
+ * @returns {{usd:number,cfWork:number,cfCarry:number,overhead:number,actual:number}|null}
100
+ */
101
+ export function netSavingV3({ calls, mainCtx, followUps, promptTokens, resultTokens, rates, subActual, skipFirstWrite = false }) {
102
+ if (!Array.isArray(calls) || calls.length === 0) return null;
103
+ if (!calls.every((c) => c && isNum(c.ctx) && isNum(c.newIn) && isNum(c.out))) return null;
104
+ if (!isNum(mainCtx) || mainCtx <= 0) return null;
105
+ if (!isNum(followUps) || followUps < 0) return null;
106
+ if (!isNum(promptTokens) || promptTokens < 0) return null;
107
+ if (!isNum(resultTokens) || resultTokens < 0) return null;
108
+ if (!rates || !isNum(rates.cacheRead) || !isNum(rates.write) || !isNum(rates.output)) return null;
109
+ if (!isNum(subActual) || subActual < 0) return null;
110
+
111
+ const ctx1 = calls[0].ctx;
112
+ const grow = (c) => Math.max(0, c.ctx - ctx1);
113
+ let cfWork = 0;
114
+ let totalOut = 0;
115
+ calls.forEach((c, i) => {
116
+ cfWork += (mainCtx + grow(c)) * rates.cacheRead;
117
+ if (!(skipFirstWrite && i === 0)) cfWork += c.newIn * rates.write;
118
+ cfWork += c.out * rates.output;
119
+ totalOut += c.out;
120
+ });
121
+ const G = grow(calls[calls.length - 1]) + totalOut;
122
+ const cfCarry = G * followUps * rates.cacheRead;
123
+ const overhead = promptTokens * rates.output
124
+ + resultTokens * rates.write
125
+ + resultTokens * followUps * rates.cacheRead;
126
+ const actual = subActual + overhead;
127
+ return { usd: cfWork + cfCarry - actual, cfWork, cfCarry, overhead, actual };
128
+ }
@@ -47,6 +47,7 @@ import { aliasForRole, resolveModelAlias } from './model-alias.js';
47
47
  import { isRecognizedModelId, modelRank } from './cost.js';
48
48
  import { loadRecentSnapshot } from './caps-cache.js';
49
49
  import { getSessionModel } from './parser.js';
50
+ import { labelForKey } from './window-labels.js';
50
51
 
51
52
  const PASTE_MIN_LINES = 8;
52
53
  const LOG_SHAPE_RE = /^\s+at\s|\b(error|exception|traceback|warn(ing)?|fatal)\b|^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/im;
@@ -330,17 +331,43 @@ export function hintTarget(match, { lang = userLanguage(), root } = {}) {
330
331
  return target;
331
332
  }
332
333
 
334
+ /**
335
+ * The line a delegation hint ends with when a usage window is running low, or
336
+ * '' when there is nothing to add. It only changes how readily the model
337
+ * delegates; the target tier and the caps stay what the rule says.
338
+ *
339
+ * @param {{level: string, pct: number, key: string}|null|undefined} pressure a capPressure result
340
+ */
341
+ export function pressureLine(pressure, { lang = userLanguage() } = {}) {
342
+ if (!pressure || (pressure.level !== 'high' && pressure.level !== 'critical')) return '';
343
+ const label = labelForKey(pressure.key).short;
344
+ const pct = Math.round(pressure.pct);
345
+ const ko = lang === 'ko';
346
+ if (pressure.level === 'critical') {
347
+ return ko
348
+ ? `한도 위험: ${label} ${pct}%. 여러 단계 작업도 위임 대상으로 보고, 메인 모델을 바꾸는 것(/model)도 사용자에게 제안하십시오.`
349
+ : `Usage limit critical: ${label} ${pct}%. Treat multi-step work as delegable too, and suggest to the user switching the main model (/model).`;
350
+ }
351
+ return ko
352
+ ? `한도 압박: ${label} ${pct}%. 판단이 애매하면 위임하십시오.`
353
+ : `Usage limit pressure: ${label} ${pct}%. When in doubt, delegate.`;
354
+ }
355
+
333
356
  /**
334
357
  * @param {string} text the prompt just submitted
335
358
  * @param {object} [opts] as routeMatch, plus:
336
359
  * @param {string} [opts.lang] 'ko' | 'en'
360
+ * @param {object|null} [opts.pressure] a capPressure result. A delegation hint
361
+ * ends with one more line when it is high or critical; null or omitted leaves
362
+ * the hint exactly as it was. The caller passes it rather than this function
363
+ * reading the snapshot, so a hint stays a function of its arguments.
337
364
  * @param {string} [opts.root] project root used to look for a subagent's .md.
338
365
  * The hint names the agent when that file exists and only its model tier when
339
366
  * it does not, so a caller that needs a predictable phrase pins this.
340
367
  * @param {object|null} [opts.match] a routeMatch result the caller already has
341
368
  * @returns {string|null} the line to inject, or null to stay quiet
342
369
  */
343
- export function routeHint(text, { rules, lang = userLanguage(), root, sessionRank = null, match, env } = {}) {
370
+ export function routeHint(text, { rules, lang = userLanguage(), root, sessionRank = null, match, env, pressure = null } = {}) {
344
371
  const found = match === undefined ? routeMatch(text, { rules, sessionRank, root, env }) : match;
345
372
  if (!found) return null;
346
373
  const { t2, t1, t1h } = found;
@@ -355,9 +382,10 @@ export function routeHint(text, { rules, lang = userLanguage(), root, sessionRan
355
382
  ? (ko ? '상한 ' : 'cap ') + picked.map((r, i) => `${TIER_MODEL[r.tier]} ${caps[i]}`).join(' / ')
356
383
  : (ko ? `상한 ${caps[0]}` : `cap ${caps[0]}`);
357
384
 
385
+ const extra = pressureLine(pressure, { lang });
358
386
  // The marker line is the one in ratchet-model.md, so the user sees the same
359
387
  // string whichever path decided to delegate.
360
- return ko
388
+ const body = ko
361
389
  ? `[sprag] 이 요청은 사용자가 이미 승인한 위임 룰 "${label}" 에 해당합니다: ${target} 로 위임하십시오 (${capText}). `
362
390
  + `되묻지 말고 위임하고, 위임할 때 \`🔀 [sprag] 모델 피팅: "${label}" → <agent> (<모델> · effort <effort>) 위임\` 을 먼저 표시하십시오. `
363
391
  + `모델과 effort 값은 위 에이전트 표기에 적힌 그대로 쓰고, Agent 도구의 description 맨 앞에도 \`[<모델> · <effort>]\` 를 붙이십시오. `
@@ -366,4 +394,5 @@ export function routeHint(text, { rules, lang = userLanguage(), root, sessionRan
366
394
  + `Do not ask again; print \`🔀 [sprag] model fit: "${label}" → <agent> (<model> · effort <effort>)\` first, `
367
395
  + `with the model and effort the agent's phrase above gives, and start the Agent tool's description with \`[<model> · <effort>]\`. `
368
396
  + `If the run is likely to exceed its cap or hits an error, stop there and the main model takes over.`;
397
+ return extra ? `${body}\n${extra}` : body;
369
398
  }
package/src/route-scan.js CHANGED
@@ -21,7 +21,8 @@ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
21
21
  import { join } from 'node:path';
22
22
  import { userDataDir } from './paths.js';
23
23
  import { discoverSessionFiles } from './parser.js';
24
- import { collectSessionRecords } from './session-records.js';
24
+ import { collectSessionRecords, delegationContexts } from './session-records.js';
25
+ import { netSavingV3, unitRates, exactCost, priceSource } from './net-saving.js';
25
26
  import {
26
27
  collectSubagentRuns, indexRuns, exactRunsForEpisode, fallbackRunsForEpisode,
27
28
  } from './subagent-records.js';
@@ -387,15 +388,53 @@ export function worthDelegating(tier, rank) {
387
388
  * negative. null means a side has no price (a gateway session whose /model/info
388
389
  * table lacks the model), which is unpriced, not zero.
389
390
  */
390
- export function runSaving(run, mainModel) {
391
+ export function runSaving(run, mainModel, { env = process.env } = {}) {
391
392
  if (!run.model || !mainModel) return null;
392
393
  const totals = runTotals(run);
393
- const actual = sessionCost(totals, run.model);
394
- const counterfactual = sessionCost(totals, mainModel);
394
+ const actual = sessionCost(totals, run.model, { env });
395
+ const counterfactual = sessionCost(totals, mainModel, { env });
395
396
  if (!actual || !counterfactual) return null;
396
397
  return counterfactual.actual - actual.actual;
397
398
  }
398
399
 
400
+ /**
401
+ * The saving of one delegated run on the v3 basis (src/net-saving.js): the main
402
+ * model's cache re-reads and the context the run's findings would have added,
403
+ * against the run's own cost plus the main session's delegation overhead.
404
+ *
405
+ * `info` is this run's entry from delegationContexts (the main session around
406
+ * the Agent call). Anything v3 needs and cannot get (no info, no per-call data,
407
+ * no price on either side) sends the run to the v2 formula instead, tagged
408
+ * basis 'v2', so the figure is never invented. null still means unpriced.
409
+ *
410
+ * @returns {{usd:number, basis:'v3'|'v2', cfWork?:number, cfCarry?:number, overhead?:number}|null}
411
+ */
412
+ export function runSavingDetail(run, mainModel, info, { env = process.env } = {}) {
413
+ if (!run.model || !mainModel) return null;
414
+ const v3 = (() => {
415
+ if (!info || !Array.isArray(run.perCall) || run.perCall.length === 0) return null;
416
+ if (!Number.isFinite(info.resultChars)) return null;
417
+ const rates = unitRates(mainModel, { env });
418
+ const subActual = exactCost(runTotals(run), run.model, { env });
419
+ if (!rates || subActual === null) return null;
420
+ // A background launch returns only an acknowledgement; the report that
421
+ // follows is the run's final message.
422
+ const chars = info.resultChars + (info.async ? (run.finalChars || 0) : 0);
423
+ return netSavingV3({
424
+ calls: run.perCall,
425
+ mainCtx: info.C,
426
+ followUps: info.N,
427
+ promptTokens: info.P,
428
+ resultTokens: chars / 4,
429
+ rates,
430
+ subActual,
431
+ });
432
+ })();
433
+ if (v3) return { basis: 'v3', ...v3 };
434
+ const v2 = runSaving(run, mainModel, { env });
435
+ return Number.isFinite(v2) ? { usd: v2, basis: 'v2' } : null;
436
+ }
437
+
399
438
  /**
400
439
  * USD a delegated run cost on the model it ran on: the price side of
401
440
  * runSaving, recorded beside the saving so the statusline can show what the
@@ -537,7 +576,13 @@ export function tallyDelegatedRun(stats, key, run, saved, resetMark = null) {
537
576
  stats.set(key, d);
538
577
  }
539
578
 
540
- export async function runRouteScan({ days = 14 } = {}) {
579
+ /**
580
+ * @param {object} [opts]
581
+ * @param {number} [opts.days] scan window
582
+ * @param {Array|null} [opts.trace] when an array, each priced ledger event is
583
+ * pushed to it with both the v2 and the v3 figure (measurement; not stored)
584
+ */
585
+ export async function runRouteScan({ days = 14, trace = null } = {}) {
541
586
  const files = await discoverSessionFiles({ days });
542
587
 
543
588
  // Behind a Bedrock/LiteLLM gateway the transcripts carry an inference-profile
@@ -555,6 +600,7 @@ export async function runRouteScan({ days = 14 } = {}) {
555
600
  const all = []; // { ep, projectDir, sessionPath }
556
601
  const dataBytes = windowBytes(files); // window size snapshot — the rescan gate diffs against it
557
602
  const runIndexBySession = new Map(); // sessionPath → indexRuns() result
603
+ const delegationInfoBySession = new Map(); // sessionPath → Map(tool_use id → main-side context of that delegation)
558
604
  for (const f of files) {
559
605
  let records;
560
606
  try {
@@ -570,7 +616,10 @@ export async function runRouteScan({ days = 14 } = {}) {
570
616
  // delegation it made. Best-effort: sessions that never delegated have no
571
617
  // directory and cost one failed readdir.
572
618
  const runs = await collectSubagentRuns(f.path);
573
- if (runs.length > 0) runIndexBySession.set(f.path, indexRuns(runs));
619
+ if (runs.length > 0) {
620
+ runIndexBySession.set(f.path, indexRuns(runs));
621
+ delegationInfoBySession.set(f.path, delegationContexts(records));
622
+ }
574
623
  }
575
624
  const totalEpisodes = all.length;
576
625
  const thresholds = calibrateThresholds(all.map((x) => x.ep.out));
@@ -581,10 +630,13 @@ export async function runRouteScan({ days = 14 } = {}) {
581
630
  const episodeStats = new Map(); // "category|project" (+ "category|*") → outcome stats
582
631
  let tieredEpisodes = 0;
583
632
  const bumpStats = (key, ep) => {
584
- const s = episodeStats.get(key) || { count: 0, errCount: 0, epCount: 0, baselineModel: null, modelCounts: {} };
633
+ const s = episodeStats.get(key) || { count: 0, errCount: 0, failCount: 0, epCount: 0, baselineModel: null, modelCounts: {} };
585
634
  s.count += 1;
586
635
  s.epCount += 1;
587
636
  if (ep.errors > 0) s.errCount += 1;
637
+ // Same failure test a delegated run gets, so rule health can compare the
638
+ // delegate against the session model on equal terms (reviewThreshold).
639
+ if (isFailedRun({ toolErrors: ep.errors, calls: ep.calls })) s.failCount += 1;
588
640
  // Baseline model: what actually handled this category BEFORE any rule sent
589
641
  // it elsewhere. This is the only honest counterfactual for "routing saved
590
642
  // money" — the session's priciest model is not, since it may never have
@@ -747,7 +799,8 @@ export async function runRouteScan({ days = 14 } = {}) {
747
799
  if (run.model) unresolvedModels.add(run.model);
748
800
  }
749
801
  if (!runTier || !worthDelegating(runTier, mainRank)) continue;
750
- const saved = runSaving(run, mainModel);
802
+ const info = run.toolUseId ? delegationInfoBySession.get(sessionPath)?.get(run.toolUseId) : undefined;
803
+ const saved = runSavingDetail(run, mainModel, info)?.usd ?? null;
751
804
  bumpDelegated(`${runTier}|${cat.id}|${projectDir}`, run, saved);
752
805
  bumpDelegated(`${runTier}|${cat.id}|*`, run, saved);
753
806
  // Routing saving: priced against the episode's main model (before →
@@ -759,7 +812,7 @@ export async function runRouteScan({ days = 14 } = {}) {
759
812
  // Priced below, after this scan's baselines have been written back to
760
813
  // the registry — see the note at the ledger write.
761
814
  if (!isRecognizedModelId(run.model)) continue;
762
- ledgerEvents.push({ run, rule, tier: runTier, catId: cat.id, projectDir, mainModel });
815
+ ledgerEvents.push({ run, rule, tier: runTier, catId: cat.id, projectDir, mainModel, info });
763
816
  }
764
817
  }
765
818
  }
@@ -885,7 +938,8 @@ export async function runRouteScan({ days = 14 } = {}) {
885
938
  const rule = fresh.find((r) => r.signature === e.rule.signature) || e.rule;
886
939
  // The episode's main model is what would have done the work today; the
887
940
  // rule's promotion-time baseline only stands in when it is unpriced.
888
- const baseline = e.mainModel && isRecognizedModelId(e.mainModel)
941
+ const fromEpisode = !!(e.mainModel && isRecognizedModelId(e.mainModel));
942
+ const baseline = fromEpisode
889
943
  ? e.mainModel
890
944
  : baselineFor(rule, e.tier, e.catId, e.projectDir);
891
945
  // Both sides of the comparison must be ids the pricing table really
@@ -894,18 +948,39 @@ export async function runRouteScan({ days = 14 } = {}) {
894
948
  // erase a real one — worse than showing nothing. Map such ids in
895
949
  // profile-map.json's `modelAliases` to bring these runs back in.
896
950
  if (!baseline || !isRecognizedModelId(baseline)) continue;
897
- const usd = runSaving(e.run, baseline);
951
+ const detail = runSavingDetail(e.run, baseline, e.info);
898
952
  // A loss is recorded too; only an unpriced run (null) has nothing to record.
899
- if (!Number.isFinite(usd)) continue;
953
+ if (!detail || !Number.isFinite(detail.usd)) continue;
900
954
  priced.push({
901
955
  key: e.run.path,
902
956
  ts: e.run.endedAt ?? e.run.startedAt ?? Date.now(),
903
- usd,
957
+ usd: detail.usd,
904
958
  cost: runCost(e.run),
905
959
  rule: rule.signature,
906
960
  from: baseline,
907
961
  to: e.run.model,
962
+ basis: detail.basis,
963
+ priceSource: priceSource(),
964
+ baselineSource: fromEpisode ? 'episode' : 'rule',
908
965
  });
966
+ if (Array.isArray(trace)) {
967
+ trace.push({
968
+ key: e.run.path,
969
+ rule: rule.signature,
970
+ from: baseline,
971
+ to: e.run.model,
972
+ basis: detail.basis,
973
+ usd: detail.usd,
974
+ v2: runSaving(e.run, baseline),
975
+ cfWork: detail.cfWork,
976
+ cfCarry: detail.cfCarry,
977
+ overhead: detail.overhead,
978
+ firstWrite: detail.basis === 'v3' ? (e.run.perCall[0].newIn * (unitRates(baseline)?.write ?? 0)) : 0,
979
+ calls: e.run.calls,
980
+ C: e.info?.C ?? null,
981
+ N: e.info?.N ?? null,
982
+ });
983
+ }
909
984
  }
910
985
  recordDelegationEvents(priced);
911
986
  } catch {
@@ -9,8 +9,18 @@
9
9
  * upsert instead of double-counting.
10
10
  *
11
11
  * File: <userDataDir>/delegation-ledger.json
12
- * { "version": 2,
13
- * "events": { "<run path>": { "ts", "usd", "cost", "rule", "from", "to" } } }
12
+ * { "version": 3,
13
+ * "events": { "<run path>": { "ts", "usd", "cost", "rule", "from", "to",
14
+ * "basis", "priceSource", "baselineSource" } } }
15
+ *
16
+ * Version 3 prices a run on the net-saving basis (src/net-saving.js), and each
17
+ * event says how it was priced: `basis` 'v3' (cache re-reads and carried
18
+ * context counted) or 'v2' (run tokens repriced only, used when the main
19
+ * session's numbers could not be read), `priceSource` 'list' | 'gateway', and
20
+ * `baselineSource` 'episode' (the episode's own main model) | 'rule' (the
21
+ * rule's stored baseline, when that model had no price). Version 2 events keep
22
+ * their value and read as basis v2; a rescan reprices those still inside the
23
+ * scan window as v3 and leaves the older ones alone.
14
24
  *
15
25
  * `from`/`to` are the models the routing decision moved between, and `usd` is
16
26
  * the price difference between them for this run's tokens. `cost` is what the
@@ -42,7 +52,9 @@ export function ledgerPath() {
42
52
  return join(userDataDir(), 'delegation-ledger.json');
43
53
  }
44
54
 
45
- export const LEDGER_VERSION = 2;
55
+ export const LEDGER_VERSION = 3;
56
+ // Version 2 differs only in lacking the basis fields, so it is read as is.
57
+ const READABLE_VERSIONS = new Set([2, LEDGER_VERSION]);
46
58
 
47
59
  /**
48
60
  * Which run a ledger key names, wherever its transcript sits:
@@ -65,8 +77,10 @@ export function loadLedger() {
65
77
  }
66
78
  // Pre-v2 events were priced against a different counterfactual — drop them
67
79
  // instead of mixing two meanings into one total. The next scan rebuilds
68
- // whatever is still attributable.
69
- if (data.version !== LEDGER_VERSION) return { version: LEDGER_VERSION, events: {} };
80
+ // whatever is still attributable. v2 events are kept: they are the same
81
+ // kind of figure (basis v2), only unlabelled.
82
+ if (!READABLE_VERSIONS.has(data.version)) return { version: LEDGER_VERSION, events: {} };
83
+ data.version = LEDGER_VERSION;
70
84
  // One event per run: duplicates recorded from a second copy of the same
71
85
  // transcript are dropped here, so every reader sums each run once and the
72
86
  // next write persists the cleanup.
@@ -84,7 +98,7 @@ export function loadLedger() {
84
98
 
85
99
  /**
86
100
  * Upsert saving events. `events` is an array of
87
- * { key, ts, usd, cost, rule, from, to } where `key` is the run's transcript
101
+ * { key, ts, usd, cost, rule, from, to, basis, priceSource, baselineSource } where `key` is the run's transcript
88
102
  * path (unique per subagent run) and `from`/`to` name the models the routing
89
103
  * decision moved between. `usd` is signed: a run on a pricier model is a loss
90
104
  * and is recorded as a negative amount so it reduces the totals. Only
@@ -108,7 +122,10 @@ export function recordDelegationEvents(events) {
108
122
  const cost = Number.isFinite(e.cost) ? roundUsd(e.cost) : undefined;
109
123
  // An event recorded before `cost` existed compares unequal here, so the
110
124
  // first scan that still covers the run fills its cost in.
111
- if (prev && prev.ts === e.ts && prev.usd === usd && prev.cost === cost) continue;
125
+ // The same goes for the basis fields: a v2 event rescanned as v3 differs.
126
+ if (prev && prev.ts === e.ts && prev.usd === usd && prev.cost === cost
127
+ && prev.basis === (e.basis || undefined) && prev.priceSource === (e.priceSource || undefined)
128
+ && prev.baselineSource === (e.baselineSource || undefined)) continue;
112
129
  if (prevKey !== e.key) delete data.events[prevKey];
113
130
  keyOf.set(id, e.key);
114
131
  data.events[e.key] = {
@@ -118,6 +135,9 @@ export function recordDelegationEvents(events) {
118
135
  ...(e.rule ? { rule: e.rule } : {}),
119
136
  ...(e.from ? { from: e.from } : {}),
120
137
  ...(e.to ? { to: e.to } : {}),
138
+ ...(e.basis ? { basis: e.basis } : {}),
139
+ ...(e.priceSource ? { priceSource: e.priceSource } : {}),
140
+ ...(e.baselineSource ? { baselineSource: e.baselineSource } : {}),
121
141
  };
122
142
  changed = true;
123
143
  }
@@ -36,6 +36,7 @@ function contentText(content) {
36
36
  */
37
37
  const MUTATING_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash']);
38
38
  const DELEGATION_TOOLS = new Set(['Task', 'Agent']);
39
+ const HANDBACK_TOOL = 'SubagentHandback';
39
40
 
40
41
  // Permission rejections and harness policy denials arrive as is_error
41
42
  // tool_results, but they encode the user's choice / the permission system's
@@ -88,6 +89,7 @@ function isRealToolError(block) {
88
89
 
89
90
  export async function collectSessionRecords(filePath, { includeContent = true } = {}) {
90
91
  const records = new Map();
92
+ const delegationReq = new Map(); // Task/Agent tool_use id → requestId of the record that issued it
91
93
  let depth = 0;
92
94
  let lastUserText = '';
93
95
  let lastCwd = '';
@@ -114,6 +116,23 @@ export async function collectSessionRecords(filePath, { includeContent = true }
114
116
  if (isRealToolError(b)) lastRecord.toolErrors += 1;
115
117
  }
116
118
  }
119
+ // What a Task/Agent call handed back to this session: its size is what
120
+ // stays in the context for every later call (see delegationContexts).
121
+ // A background launch returns only an acknowledgement here; the report
122
+ // itself arrives later, so the entry is marked `async`.
123
+ if (Array.isArray(msg.content)) {
124
+ for (const b of msg.content) {
125
+ if (!b || b.type !== 'tool_result' || typeof b.tool_use_id !== 'string') continue;
126
+ const reqId = delegationReq.get(b.tool_use_id);
127
+ const owner = reqId !== undefined ? records.get(reqId) : null;
128
+ if (!owner) continue;
129
+ const tr = entry.toolUseResult;
130
+ owner.delegationResults[b.tool_use_id] = {
131
+ chars: toolResultText(b.content).length,
132
+ async: !!(tr && typeof tr === 'object' && (tr.isAsync === true || tr.status === 'async_launched')),
133
+ };
134
+ }
135
+ }
117
136
  continue;
118
137
  }
119
138
  if (entry.type !== 'assistant' || !msg) continue;
@@ -136,13 +155,21 @@ export async function collectSessionRecords(filePath, { includeContent = true }
136
155
  // transcripts under <session>/subagents/*.meta.json, which is how the
137
156
  // outcome of a delegation is measured (rule-health v2).
138
157
  const delegationToolUseIds = [...(prev?.delegationToolUseIds || [])];
158
+ let textChars = 0;
139
159
  if (Array.isArray(msg.content)) {
140
160
  for (const b of msg.content) {
161
+ if (b && b.type === 'text' && typeof b.text === 'string') textChars += b.text.length;
162
+ // A subagent that reports through the handback tool puts the report in
163
+ // the tool's `message`, not in a text block.
164
+ if (b && b.type === 'tool_use' && b.name === HANDBACK_TOOL && typeof b.input?.message === 'string') textChars += b.input.message.length;
141
165
  if (!b || b.type !== 'tool_use') continue;
142
166
  if (MUTATING_TOOLS.has(b.name)) mutatingToolCalls += 1;
143
167
  if (DELEGATION_TOOLS.has(b.name)) {
144
168
  delegationCalls += 1;
145
- if (typeof b.id === 'string') delegationToolUseIds.push(b.id);
169
+ if (typeof b.id === 'string') {
170
+ delegationToolUseIds.push(b.id);
171
+ delegationReq.set(b.id, reqId);
172
+ }
146
173
  }
147
174
  if (typeof b.name === 'string') toolCounts[b.name] = (toolCounts[b.name] || 0) + 1;
148
175
  }
@@ -174,9 +201,60 @@ export async function collectSessionRecords(filePath, { includeContent = true }
174
201
  delegationToolUseIds,
175
202
  toolErrors: prev?.toolErrors || 0,
176
203
  toolCounts,
204
+ // Characters of assistant text; for a subagent transcript the last
205
+ // record's value is the report it hands back to its parent.
206
+ textChars: (prev?.textChars || 0) + textChars,
207
+ // tool_use id → { chars, async } of the result the call received.
208
+ delegationResults: prev?.delegationResults || {},
177
209
  };
178
210
  records.set(reqId, lastRecord);
179
211
  }
180
212
 
181
213
  return [...records.values()];
182
214
  }
215
+
216
+ /** Later main calls counted for how long a delegation's result stays in context. */
217
+ export const CARRY_CAP = 50;
218
+ /** A call whose context falls below this share of the one before it follows a compaction. */
219
+ export const COMPACTION_RATIO = 0.5;
220
+
221
+ /**
222
+ * Per Task/Agent tool_use id, what the session around the delegation looked
223
+ * like, from the session's own call records (collectSessionRecords order):
224
+ * C context of the call that issued it (input + cache read + cache write)
225
+ * N main calls after it in the same session, stopping at the next
226
+ * compaction (context drops below COMPACTION_RATIO of the call
227
+ * before) or the end, capped at CARRY_CAP
228
+ * P output tokens that call spent writing the prompt (its output
229
+ * shared evenly between the delegations it issued)
230
+ * resultChars size of the tool_result that came back, null when none was seen
231
+ * async that result was only a background-launch acknowledgement
232
+ * A value that cannot be read stays null, and the caller then declines to use
233
+ * the entry rather than guess.
234
+ */
235
+ export function delegationContexts(records) {
236
+ const out = new Map();
237
+ for (let j = 0; j < records.length; j++) {
238
+ const r = records[j];
239
+ const ids = r.delegationToolUseIds || [];
240
+ if (ids.length === 0) continue;
241
+ let n = 0;
242
+ for (let k = j + 1; k < records.length && n < CARRY_CAP; k++) {
243
+ if (records[k].prompt_tokens < records[k - 1].prompt_tokens * COMPACTION_RATIO) break;
244
+ n += 1;
245
+ }
246
+ const ctx = r.prompt_tokens > 0 ? r.prompt_tokens : null;
247
+ const prompt = r.completion_tokens > 0 ? r.completion_tokens / ids.length : null;
248
+ for (const id of ids) {
249
+ const res = r.delegationResults?.[id];
250
+ out.set(id, {
251
+ C: ctx,
252
+ N: n,
253
+ P: prompt,
254
+ resultChars: res ? res.chars : null,
255
+ async: res ? res.async : false,
256
+ });
257
+ }
258
+ }
259
+ return out;
260
+ }
@@ -90,6 +90,16 @@ export async function collectSubagentRun(jsonlPath) {
90
90
  startedAt: null,
91
91
  endedAt: null,
92
92
  bytes: 0,
93
+ // One entry per API call, in order: the context it carried (ctx), the part
94
+ // of it that was not a cache read (newIn) and what it wrote (out). The
95
+ // net-saving counterfactual re-prices the run call by call from these.
96
+ perCall: records.map((r) => ({
97
+ ctx: r.prompt_tokens || 0,
98
+ newIn: (r.input_tokens || 0) + (r.cache_creation_tokens || 0),
99
+ out: r.completion_tokens || 0,
100
+ })),
101
+ // Size of the last text the run produced, i.e. the report it hands back.
102
+ finalChars: [...records].reverse().find((r) => (r.textChars || 0) > 0)?.textChars ?? 0,
93
103
  };
94
104
  const byModelOut = new Map();
95
105
  for (const r of records) {