@osfactory/otel-hook 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) 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 +260 -74
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{export-destinations-CI7z4n3i.d.ts → export-destinations-DUeQKr_C.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 +252 -66
  10. package/dist/index.js.map +1 -1
  11. package/dist/install.d.ts +3 -3
  12. package/dist/install.js +14 -2
  13. package/dist/install.js.map +1 -1
  14. package/dist/integration.d.ts +7 -7
  15. package/dist/integration.js +211 -58
  16. package/dist/integration.js.map +1 -1
  17. package/dist/lifecycle.d.ts +9 -2
  18. package/dist/lifecycle.js +10 -3
  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-B4lIuk6i.d.ts} +10 -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 +132 -43
  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 +20 -6
  33. package/dist/state.js.map +1 -1
  34. package/dist/telemetry.d.ts +3 -3
  35. package/dist/telemetry.js +72 -6
  36. package/dist/telemetry.js.map +1 -1
  37. package/dist/testing.d.ts +6 -6
  38. package/dist/testing.js +63 -8
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +2 -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
 
@@ -92,6 +92,14 @@ type SpanCorrelation = {
92
92
  * discriminator keeps them from claiming the same span id.
93
93
  */
94
94
  readonly spanIdDiscriminator?: string;
95
+ /**
96
+ * Set for a later *run* of a scope whose first run was already exported (a
97
+ * resumed session): mixed into the span id of this run's record, on the
98
+ * deferred start as well as on the end, so both edges agree and the id differs
99
+ * from the first run's. A resumed session span hangs under the first run's
100
+ * session span, so the trace stays one tree.
101
+ */
102
+ readonly runSpanIdDiscriminator?: string;
95
103
  /** Start recovered from state; authoritative over the batch's own start edge. */
96
104
  readonly startMillis?: number;
97
105
  /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */
@@ -296,7 +304,8 @@ type DeriveMetricObservationsInput = {
296
304
  * 2. a `generation.start` recorded by an *earlier* callback;
297
305
  * 3. the turn's start: the last `prompt.submitted` of the session, no later than
298
306
  * 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.
307
+ * turn's wall-clock time, tool calls included. Not for a subagent's
308
+ * generation, which did not start with the parent's prompt.
300
309
  * A `generation.start` in the *same* batch as its end is not a start: an
301
310
  * adapter that emits both from one callback (Claude Code's `Stop`) synthesized
302
311
  * 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
@@ -1299,7 +1299,10 @@ var postToolUseFailurePayloadSchema = z12.object({
1299
1299
  hook_event_name: z12.literal("PostToolUseFailure"),
1300
1300
  tool_name: z12.string().min(1),
1301
1301
  tool_input: z12.unknown().optional(),
1302
- tool_error: z12.unknown(),
1302
+ // Optional: a failure that names no message still ends its tool call. The
1303
+ // `error` spelling Claude Code 2.1.x sends is folded onto it by
1304
+ // `normalizeClaudeHookPayload`.
1305
+ tool_error: z12.unknown().optional(),
1303
1306
  tool_use_id: z12.string().min(1)
1304
1307
  });
1305
1308
  var permissionRequestPayloadSchema = z12.object({
@@ -1323,7 +1326,16 @@ var subagentStopPayloadSchema = z12.object({
1323
1326
  last_assistant_message: z12.string().optional(),
1324
1327
  /** True when this stop fired because a hook continued the subagent's turn. */
1325
1328
  stop_hook_active: z12.boolean().optional(),
1326
- usage: claudeUsageSchema.optional()
1329
+ /**
1330
+ * The subagent run's tokens since its previous stop — harness- or
1331
+ * enricher-supplied, never upstream. Reported on the subagent's own
1332
+ * generation, never on the parent turn (issue #68).
1333
+ */
1334
+ usage: claudeUsageSchema.optional(),
1335
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
1336
+ model: z12.string().min(1).max(256).optional().catch(void 0),
1337
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
1338
+ usage_partial: z12.boolean().optional().catch(void 0)
1327
1339
  });
1328
1340
  var preCompactPayloadSchema = z12.object({
1329
1341
  ...commonFields,
@@ -1659,7 +1671,13 @@ var normalizeClaudeHookPayload = (payload) => {
1659
1671
  if (record === void 0) {
1660
1672
  return payload;
1661
1673
  }
1662
- return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
1674
+ return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));
1675
+ };
1676
+ var applyToolFailureShape = (record) => {
1677
+ if (record.hook_event_name !== "PostToolUseFailure" || record.tool_error !== void 0 || record.error === void 0) {
1678
+ return record;
1679
+ }
1680
+ return { ...record, tool_error: record.error };
1663
1681
  };
1664
1682
  var applyUsageShape = (record) => {
1665
1683
  const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
@@ -1968,6 +1986,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
1968
1986
  WebFetch: "network",
1969
1987
  WebSearch: "network",
1970
1988
  Task: "delegate",
1989
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
1990
+ Agent: "delegate",
1971
1991
  TodoWrite: "other",
1972
1992
  ExitPlanMode: "other",
1973
1993
  AskUserQuestion: "other",
@@ -2141,14 +2161,39 @@ var parseClaudeCode = (input, context) => {
2141
2161
  delegationDepth: 1
2142
2162
  });
2143
2163
  break;
2144
- case "SubagentStop":
2164
+ case "SubagentStop": {
2165
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
2166
+ if (usage.usage !== void 0 || payload.model !== void 0) {
2167
+ const generationId = context.ids.newOpaqueId([
2168
+ "claude-subagent-generation",
2169
+ payload.session_id,
2170
+ payload.agent_id,
2171
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
2172
+ ]);
2173
+ const models = generationModels(payload.model, void 0);
2174
+ factory.build({ type: "generation.start", generationId, model: models.request });
2175
+ factory.build({
2176
+ type: "generation.end",
2177
+ generationId,
2178
+ model: models.response,
2179
+ outcome: "ok",
2180
+ outputContent: [
2181
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
2182
+ kind: "response",
2183
+ role: "assistant",
2184
+ text: payload.last_assistant_message
2185
+ })
2186
+ ],
2187
+ ...usage
2188
+ });
2189
+ }
2145
2190
  factory.build({
2146
2191
  type: "subagent.end",
2147
2192
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
2148
- outcome: "ok",
2149
- ...withUsage(payload.usage)
2193
+ outcome: "ok"
2150
2194
  });
2151
2195
  break;
2196
+ }
2152
2197
  case "PreCompact":
2153
2198
  return {
2154
2199
  status: "ignored",
@@ -2268,7 +2313,8 @@ var clamp = (value, fallback, min, max) => {
2268
2313
  };
2269
2314
  var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2270
2315
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
2271
- var assistantRecordOf = (line) => {
2316
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
2317
+ var assistantRecordOf = (line, agentId) => {
2272
2318
  if (!line.includes('"assistant"')) {
2273
2319
  return void 0;
2274
2320
  }
@@ -2279,7 +2325,10 @@ var assistantRecordOf = (line) => {
2279
2325
  return void 0;
2280
2326
  }
2281
2327
  const record = asRecord5(parsed);
2282
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
2328
+ if (record === void 0 || record.type !== "assistant") {
2329
+ return void 0;
2330
+ }
2331
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
2283
2332
  return void 0;
2284
2333
  }
2285
2334
  const message = asRecord5(record.message);
@@ -2372,7 +2421,7 @@ var completeLinesEnd = (bytes, start) => {
2372
2421
  const lastNewline = bytes.lastIndexOf(10);
2373
2422
  return lastNewline < 0 ? start : start + lastNewline + 1;
2374
2423
  };
2375
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
2424
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
2376
2425
  const length = Math.min(size, maxTailBytes);
2377
2426
  const start = size - length;
2378
2427
  const bytes = await readBytes(handle, start, length);
@@ -2382,7 +2431,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
2382
2431
  lines.shift();
2383
2432
  }
2384
2433
  for (let index = lines.length - 1; index >= 0; index -= 1) {
2385
- const record = assistantRecordOf((lines[index] ?? "").trim());
2434
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
2386
2435
  if (record !== void 0) {
2387
2436
  return {
2388
2437
  turn: {
@@ -2396,10 +2445,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
2396
2445
  }
2397
2446
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
2398
2447
  });
2399
- var boundedTail = async (transcriptPath, options) => withTimeout(
2448
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
2400
2449
  readTail(
2401
2450
  transcriptPath,
2402
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
2451
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
2452
+ agentId
2403
2453
  ),
2404
2454
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
2405
2455
  { status: "unavailable", reason: "unreadable" }
@@ -2439,7 +2489,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
2439
2489
  let anonymous = 0;
2440
2490
  let model;
2441
2491
  for (const line of complete.split("\n")) {
2442
- const record = assistantRecordOf(line.trim());
2492
+ const record = assistantRecordOf(line.trim(), options.agentId);
2443
2493
  if (record === void 0) {
2444
2494
  continue;
2445
2495
  }
@@ -2501,6 +2551,20 @@ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
2501
2551
  };
2502
2552
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
2503
2553
  var sourceDigest = (transcriptPath) => createHash("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
2554
+ var SUBAGENT_STOP = "SubagentStop";
2555
+ var agentIdOf = (record) => {
2556
+ const agentId = record.agent_id ?? record.agentId;
2557
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
2558
+ };
2559
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
2560
+ var subagentCursorScope = (payload) => {
2561
+ const record = asRecord5(payload);
2562
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
2563
+ return void 0;
2564
+ }
2565
+ const agentId = agentIdOf(record);
2566
+ return agentId === void 0 ? void 0 : `agent-${createHash("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
2567
+ };
2504
2568
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
2505
2569
  const fileSize = async (transcriptPath) => {
2506
2570
  try {
@@ -2510,6 +2574,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2510
2574
  return thrown?.code === "ENOENT" ? "absent" : void 0;
2511
2575
  }
2512
2576
  };
2577
+ const readOptions = (agentId) => ({
2578
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
2579
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
2580
+ ...agentId === void 0 ? {} : { agentId }
2581
+ });
2582
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
2583
+ const source = sourceDigest(transcriptPath);
2584
+ const attach = (model, usage, partial) => ({
2585
+ ...record,
2586
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
2587
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
2588
+ });
2589
+ if (fromOffset !== void 0) {
2590
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
2591
+ if (range.status === "found") {
2592
+ return {
2593
+ payload: attach(range.model, range.usage, false),
2594
+ cursor: { source, offset: range.endOffset },
2595
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
2596
+ };
2597
+ }
2598
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
2599
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
2600
+ }
2601
+ }
2602
+ const tail = await boundedTail(transcriptPath, options, agentId);
2603
+ if (tail === TIMED_OUT || !("turn" in tail)) {
2604
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
2605
+ }
2606
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
2607
+ return {
2608
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
2609
+ cursor: { source, offset: tail.endOffset },
2610
+ notes: [`${why}; attached the last request only (usage_partial)`]
2611
+ };
2612
+ };
2613
+ const skipAttached = async (payload, transcriptPath) => {
2614
+ const size = await fileSize(transcriptPath);
2615
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
2616
+ };
2513
2617
  const enrich = async (input) => {
2514
2618
  const unchanged = { payload: input.payload };
2515
2619
  const record = asRecord5(input.payload);
@@ -2517,6 +2621,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2517
2621
  return unchanged;
2518
2622
  }
2519
2623
  const eventName = eventNameOf(record);
2624
+ if (eventName === SUBAGENT_STOP) {
2625
+ const agentTranscriptPath = agentTranscriptPathOf(record);
2626
+ const agentId = agentIdOf(record);
2627
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
2628
+ return unchanged;
2629
+ }
2630
+ if (hasUsage(record)) {
2631
+ return skipAttached(input.payload, agentTranscriptPath);
2632
+ }
2633
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
2634
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
2635
+ }
2520
2636
  const transcriptPath = transcriptPathOf(record);
2521
2637
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
2522
2638
  return unchanged;
@@ -2537,41 +2653,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
2537
2653
  return unchanged;
2538
2654
  }
2539
2655
  if (hasUsage(record)) {
2540
- const size = await fileSize(transcriptPath);
2541
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
2656
+ return skipAttached(input.payload, transcriptPath);
2542
2657
  }
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})`] };
2564
- }
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
- };
2658
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
2571
2659
  };
2572
2660
  return Object.freeze({
2573
2661
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
2574
2662
  providerId: CLAUDE_CODE_PROVIDER_ID,
2663
+ cursorScope: subagentCursorScope,
2575
2664
  enrich
2576
2665
  });
2577
2666
  };