@osfactory/otel-hook 0.12.0 → 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.
Files changed (39) hide show
  1. package/README.md +6 -4
  2. package/dist/{adapter-DQiPu8xF.d.ts → adapter-DyCb7y1N.d.ts} +1 -1
  3. package/dist/cli.js +137 -44
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-Bey2djRk.d.ts} +2 -2
  6. package/dist/{filesystem-store-CmnUlj1O.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  7. package/dist/{hook-vM_cgqS2.d.ts → hook-D5imE0Qc.d.ts} +3 -3
  8. package/dist/index.d.ts +10 -10
  9. package/dist/index.js +137 -44
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js +10 -1
  13. package/dist/install.js.map +1 -1
  14. package/dist/integration.d.ts +7 -7
  15. package/dist/integration.js +107 -41
  16. package/dist/integration.js.map +1 -1
  17. package/dist/lifecycle.d.ts +2 -2
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{memory-DdU1U91y.d.ts → memory-B3r6sZtC.d.ts} +1 -1
  21. package/dist/{metric-model-C9lLqqpI.d.ts → metric-model-CFIeUwqd.d.ts} +2 -1
  22. package/dist/{payload-BT19hiVZ.d.ts → payload-CdDKeRpH.d.ts} +1 -1
  23. package/dist/{ports-C3k_5eOQ.d.ts → ports-DhpSDIkp.d.ts} +8 -1
  24. package/dist/providers.d.ts +27 -11
  25. package/dist/providers.js +121 -41
  26. package/dist/providers.js.map +1 -1
  27. package/dist/{registry-gyJqaWmp.d.ts → registry-BKQhhIO3.d.ts} +1 -1
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +12 -2
  30. package/dist/runtime.js.map +1 -1
  31. package/dist/state.d.ts +3 -3
  32. package/dist/state.js.map +1 -1
  33. package/dist/telemetry.d.ts +3 -3
  34. package/dist/telemetry.js +4 -1
  35. package/dist/telemetry.js.map +1 -1
  36. package/dist/testing.d.ts +6 -6
  37. package/dist/testing.js +52 -6
  38. package/dist/testing.js.map +1 -1
  39. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { C as Clock, I as IdGenerator, j as StateStore, i as StateRecord, c as LogLevel, d as Logger, l as TelemetrySink } from './ports-C3k_5eOQ.js';
1
+ import { C as Clock, I as IdGenerator, j as StateStore, i as StateRecord, c as LogLevel, d as Logger, l as TelemetrySink } from './ports-DhpSDIkp.js';
2
2
  import { b as CanonicalEvent } from './events-fcomX6d5.js';
3
3
  import { b as Attributes } from './primitives-CJ8-rn-f.js';
4
4
 
@@ -296,7 +296,8 @@ type DeriveMetricObservationsInput = {
296
296
  * 2. a `generation.start` recorded by an *earlier* callback;
297
297
  * 3. the turn's start: the last `prompt.submitted` of the session, no later than
298
298
  * the end. For Claude Code and Codex a generation is a turn, so this is the
299
- * turn's wall-clock time, tool calls included.
299
+ * turn's wall-clock time, tool calls included. Not for a subagent's
300
+ * generation, which did not start with the parent's prompt.
300
301
  * A `generation.start` in the *same* batch as its end is not a start: an
301
302
  * adapter that emits both from one callback (Claude Code's `Stop`) synthesized
302
303
  * it, and measuring from it would record a zero.
@@ -1,7 +1,7 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
3
  import { g as ProviderId } from './primitives-CJ8-rn-f.js';
4
- import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-DQiPu8xF.js';
4
+ import { d as ProviderCapabilities, P as ProviderAdapter } from './adapter-DyCb7y1N.js';
5
5
 
6
6
  /** Stable, hyphenated provider id for Claude Code. */
7
7
  declare const CLAUDE_CODE_PROVIDER_ID: string & zod.$brand<"ProviderId">;
@@ -278,7 +278,7 @@ type ReadCursor = {
278
278
  type PayloadEnrichmentInput = {
279
279
  readonly payload: unknown;
280
280
  readonly sessionId: string;
281
- /** The cursor this enricher stored for this session last time, if any. */
281
+ /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */
282
282
  readonly cursor?: ReadCursor;
283
283
  };
284
284
  type PayloadEnrichment = {
@@ -305,6 +305,13 @@ interface PayloadEnricher {
305
305
  readonly id: string;
306
306
  /** The provider whose payloads it enriches. Others are never passed to it. */
307
307
  readonly providerId: string;
308
+ /**
309
+ * Which of the session's cursors this payload reads, when a session has more
310
+ * than one source (Claude Code writes each subagent to its own transcript).
311
+ * `undefined`, or no function, selects the session's own cursor. A scope is
312
+ * part of a state key, never exported; it must not hold a path.
313
+ */
314
+ cursorScope?(payload: unknown): string | undefined;
308
315
  enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;
309
316
  }
310
317
  /**
@@ -1,13 +1,13 @@
1
- import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-DQiPu8xF.js';
2
- export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-DQiPu8xF.js';
1
+ import { e as ProviderContext, P as ProviderAdapter, d as ProviderCapabilities, b as DeliveryIdentifierSupport, A as AdapterDescription } from './adapter-DyCb7y1N.js';
2
+ export { D as DELIVERY_COMPONENT_PATTERN, a as DELIVERY_GAP_REASON_PATTERN, M as MAX_DELIVERY_COMPONENTS, c as MAX_DELIVERY_GAPS, f as ProviderDeliveryClaim, g as ProviderDeliveryGaps, h as ProviderDetection, i as ProviderDetectionInput, j as ProviderHookResponse, k as ProviderHookResponseInput, l as ProviderIdentityInput, m as ProviderParseInput, n as ProviderParseResult, S as SILENT_HOOK_RESPONSE, o as adapterSupports, p as asProviderId, q as deliveryComponentSchema, r as deliveryGapReasonSchema, s as deliveryIdentifierSupportSchema, t as describeAdapter, u as providerCapabilitiesSchema, v as providerDeliveryClaimSchema, w as providerDeliveryGapsSchema, x as providerDetectionSchema, y as providerHookResponseSchema, z as readDeliveryClaim, B as readDeliveryGap, C as unknownDetection } from './adapter-DyCb7y1N.js';
3
3
  import { b as CanonicalEvent, u as TargetHint, q as SessionStartEvent, p as SessionEndEvent, P as PromptSubmittedEvent, l as GenerationStartEvent, G as GenerationEndEvent, A as ToolStartEvent, y as ToolEndEvent, t as SubagentStartEvent, r as SubagentEndEvent, g as CompactionPerformedEvent, i as ErrorRaisedEvent } from './events-fcomX6d5.js';
4
4
  import { d as InvocationIdentity } from './identity-BrVBs901.js';
5
5
  import { d as EventId } from './primitives-CJ8-rn-f.js';
6
- import { P as ProviderRegistry } from './registry-gyJqaWmp.js';
7
- export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-gyJqaWmp.js';
8
- import { v as ClaudeUsage } from './payload-BT19hiVZ.js';
9
- export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-BT19hiVZ.js';
10
- import { P as PayloadEnricher } from './ports-C3k_5eOQ.js';
6
+ import { P as ProviderRegistry } from './registry-BKQhhIO3.js';
7
+ export { B as BUILT_IN_PROVIDERS, D as DetectionCandidate, R as RegistryDetectionResult, c as createProviderRegistry } from './registry-BKQhhIO3.js';
8
+ import { v as ClaudeUsage } from './payload-CdDKeRpH.js';
9
+ export { A as ANTIGRAVITY_CAPABILITIES, a as ANTIGRAVITY_HOOK_EVENT_NAMES, b as ANTIGRAVITY_PROVIDER_ID, c as AntigravityAdapterOptions, d as AntigravityHookEventName, C as CLAUDE_CODE_PROVIDER_ID, e as CLAUDE_HOOK_EVENT_NAMES, f as CODEX_ADAPTER_VERSION, g as CODEX_HOOK_EVENT_NAMES, h as CODEX_PROVIDER_ID, i as CURSOR_DECISION_EVENTS, j as CURSOR_HOOK_EVENT_NAMES, k as CURSOR_PROVIDER_ID, l as CURSOR_UNMODELLED_HOOK_EVENT_NAMES, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, D as DEFAULT_GEMINI_CAPABILITIES, G as GEMINI_ADAPTER_VERSION, p as GEMINI_HOOK_EVENT_NAMES, q as GEMINI_PROVIDER_ID, r as GeminiAdapterOptions, s as GeminiHookEventName, t as createAntigravityAdapter, u as createGeminiCliAdapter } from './payload-CdDKeRpH.js';
10
+ import { P as PayloadEnricher } from './ports-DhpSDIkp.js';
11
11
  import 'zod';
12
12
  import './errors.js';
13
13
  import './taxonomy-DwhTtuWd.js';
@@ -194,10 +194,16 @@ type ReadClaudeTranscriptRangeOptions = {
194
194
  readonly maxRangeBytes?: number;
195
195
  /** Budget for the whole range read. Default 500 ms, clamped to 10 ms..5 s. */
196
196
  readonly rangeTimeoutMillis?: number;
197
+ /**
198
+ * Read subagent `agentId`'s requests (its sidechain records) instead of the
199
+ * main thread's. For a subagent's own transcript, `agent_transcript_path`.
200
+ */
201
+ readonly agentId?: string;
197
202
  };
198
203
  /**
199
- * Sum every main-thread model request written between `fromOffset` and the end
200
- * of the transcript. Never throws, never rejects.
204
+ * Sum every main-thread model request (or, with `agentId`, every request of that
205
+ * subagent) written between `fromOffset` and the end of the transcript. Never
206
+ * throws, never rejects.
201
207
  *
202
208
  * Records of one request share a `message.id` and each repeats its usage, so the
203
209
  * last record per id is the one counted; a record without an id counts alone.
@@ -218,11 +224,12 @@ declare const readClaudeTranscriptRange: (transcriptPath: string, fromOffset: nu
218
224
  * already carries is never overwritten. Never throws, never rejects.
219
225
  */
220
226
  declare const attachClaudeTranscriptTurn: (payload: unknown, options?: ReadClaudeTranscriptTurnOptions) => Promise<unknown>;
221
- type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions & ReadClaudeTranscriptRangeOptions;
227
+ type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions & Omit<ReadClaudeTranscriptRangeOptions, "agentId">;
222
228
  declare const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
223
229
  /**
224
230
  * The hook-runtime side of `providers.claudeCode.readTranscriptUsage`: attach
225
- * each turn's model and **summed** usage to its `Stop` / `StopFailure`.
231
+ * each turn's model and **summed** usage to its `Stop` / `StopFailure`, and each
232
+ * subagent run's to its `SubagentStop`.
226
233
  *
227
234
  * The runtime keeps a byte cursor per session (state value `read-cursor`):
228
235
  *
@@ -240,6 +247,15 @@ declare const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
240
247
  * the next turn's range includes this one: tokens are counted late, never
241
248
  * twice and never lost.
242
249
  *
250
+ * `SubagentStop` does the same over the subagent's own transcript
251
+ * (`agent_transcript_path`), with a cursor of its own per subagent (see
252
+ * {@link PayloadEnricher.cursorScope}), summing that agent's sidechain records.
253
+ * A subagent with no cursor yet is read from the start of its file: the file is
254
+ * that subagent's alone, so the first stop is its exact total, not a fallback.
255
+ * The parent's cursor is never touched, and the parent's `Stop` never counts
256
+ * sidechain records, so a subagent's requests are counted once, on its own
257
+ * generation (issue #68).
258
+ *
243
259
  * A payload that already carries `usage` (a wrapper attached it) is left as it
244
260
  * is, and the cursor moves past it so those tokens are not counted again.
245
261
  */
package/dist/providers.js CHANGED
@@ -1323,7 +1323,16 @@ var subagentStopPayloadSchema = z12.object({
1323
1323
  last_assistant_message: z12.string().optional(),
1324
1324
  /** True when this stop fired because a hook continued the subagent's turn. */
1325
1325
  stop_hook_active: z12.boolean().optional(),
1326
- usage: claudeUsageSchema.optional()
1326
+ /**
1327
+ * The subagent run's tokens since its previous stop — harness- or
1328
+ * enricher-supplied, never upstream. Reported on the subagent's own
1329
+ * generation, never on the parent turn (issue #68).
1330
+ */
1331
+ usage: claudeUsageSchema.optional(),
1332
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
1333
+ model: z12.string().min(1).max(256).optional().catch(void 0),
1334
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
1335
+ usage_partial: z12.boolean().optional().catch(void 0)
1327
1336
  });
1328
1337
  var preCompactPayloadSchema = z12.object({
1329
1338
  ...commonFields,
@@ -1968,6 +1977,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
1968
1977
  WebFetch: "network",
1969
1978
  WebSearch: "network",
1970
1979
  Task: "delegate",
1980
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
1981
+ Agent: "delegate",
1971
1982
  TodoWrite: "other",
1972
1983
  ExitPlanMode: "other",
1973
1984
  AskUserQuestion: "other",
@@ -2141,14 +2152,39 @@ var parseClaudeCode = (input, context) => {
2141
2152
  delegationDepth: 1
2142
2153
  });
2143
2154
  break;
2144
- case "SubagentStop":
2155
+ case "SubagentStop": {
2156
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
2157
+ if (usage.usage !== void 0 || payload.model !== void 0) {
2158
+ const generationId = context.ids.newOpaqueId([
2159
+ "claude-subagent-generation",
2160
+ payload.session_id,
2161
+ payload.agent_id,
2162
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
2163
+ ]);
2164
+ const models = generationModels(payload.model, void 0);
2165
+ factory.build({ type: "generation.start", generationId, model: models.request });
2166
+ factory.build({
2167
+ type: "generation.end",
2168
+ generationId,
2169
+ model: models.response,
2170
+ outcome: "ok",
2171
+ outputContent: [
2172
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
2173
+ kind: "response",
2174
+ role: "assistant",
2175
+ text: payload.last_assistant_message
2176
+ })
2177
+ ],
2178
+ ...usage
2179
+ });
2180
+ }
2145
2181
  factory.build({
2146
2182
  type: "subagent.end",
2147
2183
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
2148
- outcome: "ok",
2149
- ...withUsage(payload.usage)
2184
+ outcome: "ok"
2150
2185
  });
2151
2186
  break;
2187
+ }
2152
2188
  case "PreCompact":
2153
2189
  return {
2154
2190
  status: "ignored",
@@ -2268,7 +2304,8 @@ var clamp = (value, fallback, min, max) => {
2268
2304
  };
2269
2305
  var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2270
2306
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
2271
- var assistantRecordOf = (line) => {
2307
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
2308
+ var assistantRecordOf = (line, agentId) => {
2272
2309
  if (!line.includes('"assistant"')) {
2273
2310
  return void 0;
2274
2311
  }
@@ -2279,7 +2316,10 @@ var assistantRecordOf = (line) => {
2279
2316
  return void 0;
2280
2317
  }
2281
2318
  const record = asRecord5(parsed);
2282
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
2319
+ if (record === void 0 || record.type !== "assistant") {
2320
+ return void 0;
2321
+ }
2322
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
2283
2323
  return void 0;
2284
2324
  }
2285
2325
  const message = asRecord5(record.message);
@@ -2372,7 +2412,7 @@ var completeLinesEnd = (bytes, start) => {
2372
2412
  const lastNewline = bytes.lastIndexOf(10);
2373
2413
  return lastNewline < 0 ? start : start + lastNewline + 1;
2374
2414
  };
2375
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
2415
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
2376
2416
  const length = Math.min(size, maxTailBytes);
2377
2417
  const start = size - length;
2378
2418
  const bytes = await readBytes(handle, start, length);
@@ -2382,7 +2422,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
2382
2422
  lines.shift();
2383
2423
  }
2384
2424
  for (let index = lines.length - 1; index >= 0; index -= 1) {
2385
- const record = assistantRecordOf((lines[index] ?? "").trim());
2425
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
2386
2426
  if (record !== void 0) {
2387
2427
  return {
2388
2428
  turn: {
@@ -2396,10 +2436,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
2396
2436
  }
2397
2437
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
2398
2438
  });
2399
- var boundedTail = async (transcriptPath, options) => withTimeout(
2439
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
2400
2440
  readTail(
2401
2441
  transcriptPath,
2402
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
2442
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
2443
+ agentId
2403
2444
  ),
2404
2445
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
2405
2446
  { status: "unavailable", reason: "unreadable" }
@@ -2439,7 +2480,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
2439
2480
  let anonymous = 0;
2440
2481
  let model;
2441
2482
  for (const line of complete.split("\n")) {
2442
- const record = assistantRecordOf(line.trim());
2483
+ const record = assistantRecordOf(line.trim(), options.agentId);
2443
2484
  if (record === void 0) {
2444
2485
  continue;
2445
2486
  }
@@ -2501,6 +2542,20 @@ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
2501
2542
  };
2502
2543
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
2503
2544
  var sourceDigest = (transcriptPath) => createHash("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
2545
+ var SUBAGENT_STOP = "SubagentStop";
2546
+ var agentIdOf = (record) => {
2547
+ const agentId = record.agent_id ?? record.agentId;
2548
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
2549
+ };
2550
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
2551
+ var subagentCursorScope = (payload) => {
2552
+ const record = asRecord5(payload);
2553
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
2554
+ return void 0;
2555
+ }
2556
+ const agentId = agentIdOf(record);
2557
+ return agentId === void 0 ? void 0 : `agent-${createHash("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
2558
+ };
2504
2559
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
2505
2560
  const fileSize = async (transcriptPath) => {
2506
2561
  try {
@@ -2510,6 +2565,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2510
2565
  return thrown?.code === "ENOENT" ? "absent" : void 0;
2511
2566
  }
2512
2567
  };
2568
+ const readOptions = (agentId) => ({
2569
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
2570
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
2571
+ ...agentId === void 0 ? {} : { agentId }
2572
+ });
2573
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
2574
+ const source = sourceDigest(transcriptPath);
2575
+ const attach = (model, usage, partial) => ({
2576
+ ...record,
2577
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
2578
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
2579
+ });
2580
+ if (fromOffset !== void 0) {
2581
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
2582
+ if (range.status === "found") {
2583
+ return {
2584
+ payload: attach(range.model, range.usage, false),
2585
+ cursor: { source, offset: range.endOffset },
2586
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
2587
+ };
2588
+ }
2589
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
2590
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
2591
+ }
2592
+ }
2593
+ const tail = await boundedTail(transcriptPath, options, agentId);
2594
+ if (tail === TIMED_OUT || !("turn" in tail)) {
2595
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
2596
+ }
2597
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
2598
+ return {
2599
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
2600
+ cursor: { source, offset: tail.endOffset },
2601
+ notes: [`${why}; attached the last request only (usage_partial)`]
2602
+ };
2603
+ };
2604
+ const skipAttached = async (payload, transcriptPath) => {
2605
+ const size = await fileSize(transcriptPath);
2606
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
2607
+ };
2513
2608
  const enrich = async (input) => {
2514
2609
  const unchanged = { payload: input.payload };
2515
2610
  const record = asRecord5(input.payload);
@@ -2517,6 +2612,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2517
2612
  return unchanged;
2518
2613
  }
2519
2614
  const eventName = eventNameOf(record);
2615
+ if (eventName === SUBAGENT_STOP) {
2616
+ const agentTranscriptPath = agentTranscriptPathOf(record);
2617
+ const agentId = agentIdOf(record);
2618
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
2619
+ return unchanged;
2620
+ }
2621
+ if (hasUsage(record)) {
2622
+ return skipAttached(input.payload, agentTranscriptPath);
2623
+ }
2624
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
2625
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
2626
+ }
2520
2627
  const transcriptPath = transcriptPathOf(record);
2521
2628
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
2522
2629
  return unchanged;
@@ -2537,41 +2644,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2537
2644
  return unchanged;
2538
2645
  }
2539
2646
  if (hasUsage(record)) {
2540
- const size = await fileSize(transcriptPath);
2541
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
2542
- }
2543
- const attach = (model, usage, partial) => ({
2544
- ...record,
2545
- ...record.model === void 0 && model !== void 0 ? { model } : {},
2546
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
2547
- });
2548
- if (cursor !== void 0) {
2549
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
2550
- if (range.status === "found") {
2551
- return {
2552
- payload: attach(range.model, range.usage, false),
2553
- cursor: { source, offset: range.endOffset },
2554
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
2555
- };
2556
- }
2557
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
2558
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
2559
- }
2560
- }
2561
- const tail = await boundedTail(transcriptPath, options);
2562
- if (tail === TIMED_OUT || !("turn" in tail)) {
2563
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
2647
+ return skipAttached(input.payload, transcriptPath);
2564
2648
  }
2565
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
2566
- return {
2567
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
2568
- cursor: { source, offset: tail.endOffset },
2569
- notes: [`${why}; attached the last request only (usage_partial)`]
2570
- };
2649
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
2571
2650
  };
2572
2651
  return Object.freeze({
2573
2652
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
2574
2653
  providerId: CLAUDE_CODE_PROVIDER_ID,
2654
+ cursorScope: subagentCursorScope,
2575
2655
  enrich
2576
2656
  });
2577
2657
  };