@struct-ai/sdk 0.3.0 → 0.3.17

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.
@@ -1,5 +1,5 @@
1
1
  import { SpanKind, SpanStatusCode, context as otelContext, trace, } from "@opentelemetry/api";
2
- import { ensurePendingToolCallsSlot, getAgentSpan, getSessionId, pushPendingToolCalls, runWithStore, snapshotStore, } from "../context.js";
2
+ import { ensurePendingToolCallsSlot, getAgentSpan, getSessionId, isGenAiSuppressed, pushPendingToolCalls, runWithContext, runWithStore, snapshotStore, } from "../context.js";
3
3
  function childParentContext() {
4
4
  const agentSpan = getAgentSpan();
5
5
  return agentSpan
@@ -97,12 +97,16 @@ function restoreMethod(proto, methodName) {
97
97
  proto[methodName] = current[STRUCT_ORIGINAL];
98
98
  }
99
99
  }
100
- function wrapCreate(original) {
100
+ export function wrapCreate(original) {
101
101
  return function wrappedCreate(params, opts) {
102
102
  const patchCtx = activePatchCtx.value;
103
103
  if (!patchCtx) {
104
104
  return original.call(this, params, opts);
105
105
  }
106
+ if (isGenAiSuppressed()) {
107
+ // A framework layer owns this chat span — run the call, emit no span.
108
+ return original.call(this, params, opts);
109
+ }
106
110
  // If params.stream is true, Messages.create delegates to the streaming path.
107
111
  // We still need to instrument the returned stream like we do in messages.stream.
108
112
  if (params && params.stream === true) {
@@ -132,27 +136,87 @@ function wrapCreate(original) {
132
136
  // user/system message logs back to the chat span.
133
137
  return otelContext.with(liveCtx, () => {
134
138
  safe(() => setChatRequestAttrs(liveSpan, params, sdk, logger), "anthropic.create.set_request_attrs", internalLogger);
135
- const promise = Promise.resolve(original.call(this, params, opts));
136
- return promise.then((result) => {
137
- safe(() => setChatResponseAttrs(liveSpan, sdk, result, logger), "anthropic.create.set_response_attrs", internalLogger);
138
- safe(() => liveSpan.setStatus({ code: SpanStatusCode.OK }), "anthropic.create.set_ok_status", internalLogger);
139
- safe(() => liveSpan.end(), "anthropic.create.span_end", internalLogger);
140
- return result;
141
- }, (err) => {
139
+ let rawResult;
140
+ try {
141
+ rawResult = original.call(this, params, opts);
142
+ }
143
+ catch (err) {
144
+ // Sync throw from the original call (e.g. a validation error thrown
145
+ // before any request goes out) would otherwise leak the span — no
146
+ // promise is ever created to drive the .then/.catch below.
142
147
  safe(() => recordErrorOnSpan(liveSpan, err), "anthropic.create.record_error", internalLogger);
143
148
  safe(() => liveSpan.end(), "anthropic.create.span_end_on_error", internalLogger);
144
- // User's API exception always propagates unchanged.
145
149
  throw err;
146
- });
150
+ }
151
+ // Observe the SDK's own return value (Anthropic's APIPromise) for
152
+ // telemetry, then hand it BACK UNCHANGED — replacing it with a native
153
+ // `Promise.resolve(...).then(...)` strips APIPromise methods
154
+ // (.withResponse/.asResponse), breaking customer code only when
155
+ // instrumentation is enabled. Our observer chain must not create an
156
+ // unhandled rejection. (The prior code returned a native Promise here;
157
+ // this is adjacent hardening of pre-existing behavior — the identity
158
+ // hazard predates the streaming work.)
159
+ //
160
+ // Both the `.then` PROPERTY READ (`rt.then`) and the `.then(...)` CALL
161
+ // that registers our observer run SYNCHRONOUSLY on the success path of
162
+ // a customer's `create()` call, and were previously unguarded — a
163
+ // hostile thenable (a `.then` accessor that throws on read, or a
164
+ // `.then` function that throws synchronously when invoked) would turn
165
+ // a SUCCESSFUL Anthropic request into a synchronous exception thrown
166
+ // out of `wrappedCreate`. Wrap the read + registration so a broken
167
+ // thenable degrades instead of crashing the host: close the span with
168
+ // no telemetry and hand back rawResult UNCHANGED — never
169
+ // `Promise.resolve(...)`, which would also strip APIPromise
170
+ // identity/methods.
171
+ try {
172
+ const rt = rawResult;
173
+ if (rt && typeof rt.then === "function") {
174
+ rawResult.then((result) => {
175
+ safe(() => setChatResponseAttrs(liveSpan, sdk, result, logger), "anthropic.create.set_response_attrs", internalLogger);
176
+ safe(() => liveSpan.setStatus({ code: SpanStatusCode.OK }), "anthropic.create.set_ok_status", internalLogger);
177
+ safe(() => liveSpan.end(), "anthropic.create.span_end", internalLogger);
178
+ }, (err) => {
179
+ safe(() => recordErrorOnSpan(liveSpan, err), "anthropic.create.record_error", internalLogger);
180
+ safe(() => liveSpan.end(), "anthropic.create.span_end_on_error", internalLogger);
181
+ // Observer branch only — do NOT rethrow; the original APIPromise
182
+ // still rejects to the customer independently.
183
+ });
184
+ return rawResult;
185
+ }
186
+ }
187
+ catch {
188
+ // Reading `.then` or invoking it threw (hostile thenable). The
189
+ // underlying call already succeeded (rawResult exists) — this is an
190
+ // instrumentation-only failure, not an API error. Degrade like the
191
+ // other host-crash guards in this file (e.g. wrapStream's dispatch
192
+ // region below): close the span with no telemetry, hand back
193
+ // rawResult untouched.
194
+ safe(() => liveSpan.setStatus({ code: SpanStatusCode.OK }), "anthropic.create.set_ok_status", internalLogger);
195
+ safe(() => liveSpan.end(), "anthropic.create.span_end", internalLogger);
196
+ return rawResult;
197
+ }
198
+ // Non-thenable return (a synchronous / mocked result, or any SDK shape
199
+ // that isn't a promise): run the response telemetry inline on it, close
200
+ // the span, and hand it back untouched — matching the prior
201
+ // `Promise.resolve(...).then(...)` behavior, which unified thenable and
202
+ // non-thenable returns.
203
+ safe(() => setChatResponseAttrs(liveSpan, sdk, rawResult, logger), "anthropic.create.set_response_attrs", internalLogger);
204
+ safe(() => liveSpan.setStatus({ code: SpanStatusCode.OK }), "anthropic.create.set_ok_status", internalLogger);
205
+ safe(() => liveSpan.end(), "anthropic.create.span_end", internalLogger);
206
+ return rawResult;
147
207
  });
148
208
  };
149
209
  }
150
- function wrapStream(original) {
210
+ export function wrapStream(original) {
151
211
  return function wrappedStream(params, opts) {
152
212
  const patchCtx = activePatchCtx.value;
153
213
  if (!patchCtx) {
154
214
  return original.call(this, params, opts);
155
215
  }
216
+ if (isGenAiSuppressed()) {
217
+ // A framework layer owns this chat span — run the call, emit no span.
218
+ return original.call(this, params, opts);
219
+ }
156
220
  const { tracer, sdk, logger } = patchCtx;
157
221
  const internalLogger = sdk.getInternalLogger();
158
222
  const model = params?.model ?? "unknown";
@@ -172,13 +236,6 @@ function wrapStream(original) {
172
236
  const liveSpan = span;
173
237
  const liveCtx = ctx;
174
238
  const storeSnapshot = snapshotStore();
175
- // Enter the span's context BEFORE request-side log emission so logs
176
- // link back to the chat span via TraceId. Same rationale as wrapCreate.
177
- // @anthropic-ai/sdk's `stream()` returns a MessageStream synchronously.
178
- const stream = otelContext.with(liveCtx, () => {
179
- safe(() => setChatRequestAttrs(liveSpan, params, sdk, logger), "anthropic.stream.set_request_attrs", internalLogger);
180
- return original.call(this, params, opts);
181
- });
182
239
  let finalized = false;
183
240
  const finalize = (result, err) => {
184
241
  if (finalized)
@@ -198,43 +255,407 @@ function wrapStream(original) {
198
255
  safe(() => liveSpan.end(), "anthropic.stream.span_end", internalLogger);
199
256
  });
200
257
  };
201
- const ee = stream;
202
- if (ee && typeof ee.on === "function") {
203
- ee.on("finalMessage", (msg) => {
204
- finalize(msg, undefined);
205
- });
206
- ee.on("error", (err) => {
207
- finalize(undefined, err);
258
+ // Enter the span's context BEFORE request-side log emission so logs
259
+ // link back to the chat span via TraceId. Same rationale as wrapCreate.
260
+ // @anthropic-ai/sdk's `stream()` returns a MessageStream synchronously,
261
+ // but `messages.create({stream:true})` (delegated here from wrapCreate)
262
+ // returns an APIPromise-like thenable resolving to a raw event Stream —
263
+ // both shapes are handled below.
264
+ //
265
+ // Suppress nested instrumentation: the real `Messages.prototype.stream()`
266
+ // (`original` here) internally calls `MessageStream.createMessage`, whose
267
+ // executor synchronously invokes `messages.create({ ...params, stream:
268
+ // true }, ...)` — on the SAME patched `Messages` prototype — before its
269
+ // first `await` yields control. That resolves to our `wrapCreate`
270
+ // wrapper, which would otherwise see `params.stream === true` and
271
+ // re-delegate to a brand-new `wrapStream(original)`, instrumenting the
272
+ // same underlying raw stream a second time (2 chat spans, same
273
+ // gen_ai.response.id). `runWithContext({ suppressGenAi: true }, ...)`
274
+ // scopes an ALS store patch around exactly this synchronous call (plus
275
+ // any promise chain it kicks off internally, since AsyncLocalStorage
276
+ // propagates into `.then` continuations created within the `run()`
277
+ // callback) — `wrapCreate` checks `isGenAiSuppressed()` before its
278
+ // `stream === true` branch and, when suppressed, falls through to
279
+ // calling the TRUE raw `create` directly (no span, no re-wrap). This
280
+ // must NOT leak into user code: the store patch is popped the instant
281
+ // `original.call(...)` returns (it returns the MessageStream
282
+ // synchronously), so by the time control returns to the caller of
283
+ // `.stream()`, suppression is already off again — user code that later
284
+ // iterates the stream, or that itself calls `messages.create`/`.stream`,
285
+ // runs with a clean (unsuppressed) ALS store.
286
+ let stream;
287
+ try {
288
+ stream = otelContext.with(liveCtx, () => {
289
+ safe(() => setChatRequestAttrs(liveSpan, params, sdk, logger), "anthropic.stream.set_request_attrs", internalLogger);
290
+ return runWithContext({ suppressGenAi: true }, () => original.call(this, params, opts));
208
291
  });
209
- // If the stream is created and never iterated / finalized, at least
210
- // don't hang on test exit — "end" fires after iteration completes.
211
- ee.on("end", () => {
212
- // Only fires if no finalMessage / error fired first (rare path).
292
+ }
293
+ catch (err) {
294
+ // Sync throw from the original call would otherwise leak the span —
295
+ // no stream/promise is ever produced to drive finalize() below.
296
+ finalize(undefined, err);
297
+ throw err;
298
+ }
299
+ // The entire branch-dispatch region below — reading `ee.on`/`.then`/
300
+ // `Symbol.asyncIterator`, registering `.on(...)` listeners, invoking
301
+ // `.then(...)`, and calling `instrumentSyncIterable` — runs SYNCHRONOUSLY
302
+ // on the success path of the customer's `.stream()`/`.create()` call, and
303
+ // was previously unguarded (round-4 only hardened the ASYNC observer
304
+ // callbacks registered inside it, e.g. the onFulfilled/onRejected
305
+ // handlers below). A hostile/broken stream-like object — a throwing
306
+ // `.on`/`.then`/`Symbol.asyncIterator` getter, or a `.on()` registration
307
+ // call that itself throws — would throw synchronously OUT of the
308
+ // customer's call. Wrap the whole dispatch in try/catch so a successful
309
+ // request never becomes a hard failure purely because OUR observer
310
+ // wiring couldn't attach: degrade to no telemetry and hand back the
311
+ // ORIGINAL stream object unchanged.
312
+ try {
313
+ const ee = stream;
314
+ // Emitter path wins first — a real MessageStream (`.on`) is never
315
+ // thenable, but check `.on` before `.then` defensively in case some
316
+ // future stream shape exposes both.
317
+ if (ee && typeof ee.on === "function") {
318
+ ee.on("finalMessage", (msg) => {
319
+ finalize(msg, undefined);
320
+ });
321
+ ee.on("error", (err) => {
322
+ finalize(undefined, err);
323
+ });
324
+ // Abort fires before "end" on an aborted stream — without this
325
+ // listener the "end" handler below finalizes with OK status even
326
+ // though the request was aborted. `finalized` makes the subsequent
327
+ // "end" a no-op.
328
+ ee.on("abort", (err) => {
329
+ finalize(undefined, err ?? new Error("aborted"));
330
+ });
331
+ // If the stream is created and never iterated / finalized, at least
332
+ // don't hang on test exit — "end" fires after iteration completes.
333
+ ee.on("end", () => {
334
+ // Only fires if no finalMessage / error / abort fired first (rare
335
+ // path for a healthy, fully-drained stream).
336
+ finalize(undefined, undefined);
337
+ });
338
+ }
339
+ else if (ee && typeof ee.then === "function") {
340
+ // `create({stream:true})` shape: an APIPromise-like thenable that
341
+ // resolves to a raw event Stream (no `.on`, no synchronous
342
+ // asyncIterator until resolved). Observe the resolution to instrument
343
+ // the resolved Stream BY MUTATION, but return the ORIGINAL thenable —
344
+ // Anthropic's APIPromise exposes methods like `.withResponse()` /
345
+ // `.asResponse()` that a native `Promise.resolve(...).then(...)` would
346
+ // strip, breaking customer code only when instrumentation is enabled.
347
+ // Our observer registers synchronously here, before the caller can
348
+ // await, so instrumentRawStream mutates the same resolved object the
349
+ // caller receives, before they iterate it.
350
+ const thenable = stream;
351
+ const observerChain = thenable.then((raw) => {
352
+ // instrumentRawStream can itself throw at points outside its OWN
353
+ // internal try/catch (e.g. a hostile `Symbol.asyncIterator`
354
+ // getter, read before that internal guard) — this must not
355
+ // escape THIS onFulfilled callback: an uncaught throw here
356
+ // becomes an unhandled rejection on the promise `.then()`
357
+ // returns, even though the customer's original APIPromise
358
+ // resolved successfully — a successful request must never crash
359
+ // the host. Degrade: end the span with no telemetry and swallow.
360
+ try {
361
+ instrumentRawStream(raw);
362
+ }
363
+ catch {
364
+ finalize(undefined, undefined);
365
+ }
366
+ }, (err) => {
367
+ // Observe the rejection to finalize the span, but do NOT rethrow:
368
+ // this observer branch must never surface as an unhandled
369
+ // rejection. The original thenable still rejects to the caller
370
+ // independently.
371
+ finalize(undefined, err);
372
+ });
373
+ // Belt-and-suspenders: both branches above are already guarded to
374
+ // never throw/reject, so this derived promise should never reject —
375
+ // but chain a no-op `.catch` anyway so this internal observer chain
376
+ // can NEVER become an unhandled-rejection source, even under future
377
+ // edits to the branches above.
378
+ observerChain.catch?.(() => { });
379
+ return stream;
380
+ }
381
+ else if (ee && typeof ee[Symbol.asyncIterator] === "function") {
382
+ // Wrap the async iterator so each .next() runs inside the captured
383
+ // ALS store.
384
+ instrumentSyncIterable(ee);
385
+ }
386
+ return stream;
387
+ }
388
+ catch {
389
+ finalize(undefined, undefined);
390
+ return stream;
391
+ }
392
+ function instrumentRawStream(raw) {
393
+ const it = raw;
394
+ if (!it || typeof it[Symbol.asyncIterator] !== "function") {
395
+ finalize(undefined, undefined); // not iterable — end the span rather than leak it
396
+ return raw;
397
+ }
398
+ // A raw stream that is awaited but never iterated would otherwise leak
399
+ // its span — finalize() only fires through the iterator hooks below.
400
+ // Anthropic's Stream carries an AbortController; close the span if the
401
+ // request is aborted before/without iteration. Residual (documented,
402
+ // accepted): a stream awaited, never iterated, AND never aborted stays
403
+ // open until process exit — no lifecycle signal exists to close it.
404
+ //
405
+ // This whole section reads a `controller` getter and calls
406
+ // `addEventListener` on whatever object the SDK (or a hostile/broken
407
+ // caller-supplied stand-in) hands us — both are fallible and, unlike
408
+ // the `Symbol.asyncIterator` assignment below, were previously
409
+ // unguarded. Wrap it so a throwing getter degrades to "no abort-driven
410
+ // finalize wiring" rather than aborting instrumentRawStream entirely
411
+ // (which would also skip the Symbol.asyncIterator instrumentation
412
+ // below and lose the whole stream's telemetry, not just the abort
413
+ // hook). The caller (the observer's onFulfilled, or the synchronous
414
+ // `.on()`/asyncIterator paths in wrapStream) also guards its own call
415
+ // to instrumentRawStream, so this is defense-in-depth, not the only
416
+ // guard.
417
+ try {
418
+ const ctrl = raw.controller;
419
+ const sig = ctrl?.signal;
420
+ if (sig) {
421
+ if (sig.aborted) {
422
+ finalize(undefined, sig.reason ?? new Error("aborted"));
423
+ }
424
+ else {
425
+ sig.addEventListener("abort", () => finalize(undefined, sig.reason ?? new Error("aborted")), { once: true });
426
+ }
427
+ }
428
+ }
429
+ catch {
430
+ // Swallow — no abort-driven finalize wiring for this stream, but
431
+ // fall through to installing the Symbol.asyncIterator override
432
+ // below so normal iteration still drives accumulate()/finalize().
433
+ }
434
+ const acc = {};
435
+ const originalIter = it[Symbol.asyncIterator].bind(it);
436
+ try {
437
+ it[Symbol.asyncIterator] = () => {
438
+ const inner = originalIter();
439
+ return {
440
+ next: () => runWithStore(storeSnapshot, () => inner.next().then((res) => {
441
+ // accumulate()/accToResponseMessage() inspect provider-owned
442
+ // values (a proxy getter can throw; accToResponseMessage
443
+ // JSON.parses input_json_delta, which may be malformed). A
444
+ // successfully yielded item must NEVER become a rejected
445
+ // next(): on any instrumentation failure, degrade telemetry
446
+ // (finalize with no result) and return the original res.
447
+ try {
448
+ if (!res.done)
449
+ accumulate(acc, res.value);
450
+ else
451
+ finalize(accToResponseMessage(acc), undefined);
452
+ }
453
+ catch {
454
+ finalize(undefined, undefined);
455
+ }
456
+ return res;
457
+ }, (err) => {
458
+ finalize(undefined, err);
459
+ throw err;
460
+ })),
461
+ return: (v) => runWithStore(storeSnapshot, () => {
462
+ // Settle the inner iterator's cleanup BEFORE finalizing, so a
463
+ // cleanup rejection is recorded as ERROR rather than the span
464
+ // being closed OK while the caller receives a rejection.
465
+ const ret = inner.return
466
+ ? inner.return(v)
467
+ : Promise.resolve({ value: v, done: true });
468
+ return Promise.resolve(ret).then((res) => {
469
+ finalize(accToResponseMessage(acc), undefined); // early break — close OK
470
+ return res;
471
+ }, (err) => {
472
+ finalize(undefined, err); // cleanup rejected — record ERROR
473
+ throw err; // propagate the original rejection unchanged
474
+ });
475
+ }),
476
+ throw: (e) => runWithStore(storeSnapshot, () => {
477
+ // The thrown value IS the error condition, so finalize ERROR
478
+ // with it regardless of the inner iterator's cleanup outcome.
479
+ finalize(undefined, e);
480
+ return inner.throw ? inner.throw(e) : Promise.reject(e);
481
+ }),
482
+ };
483
+ };
484
+ }
485
+ catch {
486
+ // The resolved stream object is frozen/sealed or the property is
487
+ // non-writable — assigning Symbol.asyncIterator threw. A successful
488
+ // request must never become a rejected promise because OUR
489
+ // instrumentation couldn't attach; degrade gracefully (end the span
490
+ // with no telemetry) and hand back the untouched object. No Proxy
491
+ // fallback — that would change the stream's identity, which is its
492
+ // own hazard.
213
493
  finalize(undefined, undefined);
214
- });
494
+ }
495
+ return raw;
215
496
  }
216
- // Wrap the async iterator so each .next() runs inside the captured ALS store.
217
- if (ee && typeof ee[Symbol.asyncIterator] === "function") {
218
- const originalIter = ee[Symbol.asyncIterator].bind(ee);
219
- ee[Symbol.asyncIterator] = () => {
220
- const inner = originalIter();
221
- const wrapped = {
222
- next() {
223
- return runWithStore(storeSnapshot, () => inner.next());
224
- },
225
- return(value) {
226
- return runWithStore(storeSnapshot, () => inner.return ? inner.return(value) : Promise.resolve({ value, done: true }));
227
- },
228
- throw(err) {
229
- return runWithStore(storeSnapshot, () => inner.throw
230
- ? inner.throw(err)
231
- : Promise.reject(err));
232
- },
497
+ function instrumentSyncIterable(target) {
498
+ const originalIter = target[Symbol.asyncIterator].bind(target);
499
+ try {
500
+ target[Symbol.asyncIterator] = () => {
501
+ const inner = originalIter();
502
+ const wrapped = {
503
+ next() {
504
+ return runWithStore(storeSnapshot, () => inner.next());
505
+ },
506
+ return(value) {
507
+ return runWithStore(storeSnapshot, () => inner.return
508
+ ? inner.return(value)
509
+ : Promise.resolve({ value, done: true }));
510
+ },
511
+ throw(err) {
512
+ return runWithStore(storeSnapshot, () => inner.throw ? inner.throw(err) : Promise.reject(err));
513
+ },
514
+ };
515
+ return wrapped;
233
516
  };
234
- return wrapped;
517
+ }
518
+ catch {
519
+ // Same hazard class as instrumentRawStream above: the target is
520
+ // frozen/sealed or the property is non-writable. This call happens
521
+ // synchronously inside wrapStream itself (not inside a promise
522
+ // callback), so an uncaught throw here would surface as a
523
+ // SYNCHRONOUS exception out of the user's `.stream()`/`.create()`
524
+ // call — turning a successful request into a hard failure. Degrade
525
+ // gracefully instead: end the span with no telemetry and leave the
526
+ // iterable completely untouched (the failed assignment never took
527
+ // effect).
528
+ finalize(undefined, undefined);
529
+ }
530
+ }
531
+ function accumulate(acc, ev) {
532
+ const e = ev;
533
+ if (e?.type === "message_start" && e.message) {
534
+ acc.id = e.message.id;
535
+ acc.model = e.message.model;
536
+ acc.inputTokens = e.message.usage?.input_tokens;
537
+ // Cached `create({stream:true})` requests carry cache token counts
538
+ // on message_start's usage (never on message_delta's) — without
539
+ // these, the synthesized ResponseMessage under-reports input usage
540
+ // (setChatResponseAttrs adds them into the total) and omits both
541
+ // cache attributes entirely, unlike the non-streaming and
542
+ // MessageStream (`.on("finalMessage")`) paths, which pass the SDK's
543
+ // own parsed usage straight through.
544
+ acc.cacheReadTokens = e.message.usage?.cache_read_input_tokens;
545
+ acc.cacheCreationTokens = e.message.usage?.cache_creation_input_tokens;
546
+ }
547
+ else if (e?.type === "content_block_start" && typeof e.index === "number") {
548
+ // Assemble content blocks so the synthesized response carries
549
+ // `content` — without it, setChatResponseAttrs's `if (response.content)`
550
+ // block never runs on this raw-stream path, dropping
551
+ // gen_ai.output.messages, the gen_ai.choice event, and (critically)
552
+ // recordPendingToolCalls, so a streamed tool_use never links to its
553
+ // execute_tool span. Mirrors MessageStream's finalMessage assembly,
554
+ // minimally: text blocks and tool_use blocks only.
555
+ const blocks = (acc.blocks ??= {});
556
+ const cb = e.content_block;
557
+ if (cb?.type === "tool_use") {
558
+ blocks[e.index] = {
559
+ type: "tool_use",
560
+ id: cb.id,
561
+ name: cb.name,
562
+ jsonBuf: "",
563
+ };
564
+ }
565
+ else if (cb?.type === "text") {
566
+ blocks[e.index] = { type: "text", text: cb.text ?? "" };
567
+ }
568
+ else if (cb?.type) {
569
+ blocks[e.index] = { type: cb.type };
570
+ }
571
+ }
572
+ else if (e?.type === "content_block_delta" && typeof e.index === "number") {
573
+ const blocks = (acc.blocks ??= {});
574
+ const b = blocks[e.index];
575
+ if (!b)
576
+ return;
577
+ if (e.delta?.type === "text_delta" && typeof e.delta.text === "string") {
578
+ b.text = (b.text ?? "") + e.delta.text;
579
+ }
580
+ else if (e.delta?.type === "input_json_delta" &&
581
+ typeof e.delta.partial_json === "string") {
582
+ b.jsonBuf = (b.jsonBuf ?? "") + e.delta.partial_json;
583
+ }
584
+ }
585
+ else if (e?.type === "content_block_stop" && typeof e.index === "number") {
586
+ const blocks = (acc.blocks ??= {});
587
+ const b = blocks[e.index];
588
+ if (b?.type === "tool_use") {
589
+ // Parse the accumulated partial_json into the tool_use input; fall
590
+ // back to the raw string if the model streamed malformed JSON (the
591
+ // block still links via id/name, which is what tool-call linkage
592
+ // needs).
593
+ try {
594
+ b.input = b.jsonBuf ? JSON.parse(b.jsonBuf) : {};
595
+ }
596
+ catch {
597
+ b.input = b.jsonBuf;
598
+ }
599
+ }
600
+ }
601
+ else if (e?.type === "message_delta") {
602
+ if (e.delta?.stop_reason)
603
+ acc.stopReason = e.delta.stop_reason;
604
+ if (e.usage?.output_tokens !== undefined) {
605
+ acc.outputTokens = e.usage.output_tokens;
606
+ }
607
+ }
608
+ }
609
+ // NOTE (parity, intentional divergence — self-audit round 5, item G):
610
+ // this synthesizes a FULL ResponseMessage (content, usage, stop_reason,
611
+ // id, model) from the raw SSE event stream, matching what the
612
+ // non-streaming `create()` path and `MessageStream`'s `finalMessage`
613
+ // event already carry. struct-sdk-python's `create(stream=True)` raw
614
+ // path does NOT do this reconstruction yet and emits none of these
615
+ // response-side attributes for that one call shape. This is TS being
616
+ // MORE complete than Python here, not a TS bug — do not remove it to
617
+ // "match" Python. Bringing Python's raw-stream path up to parity is a
618
+ // separate, independent follow-up.
619
+ function accToResponseMessage(acc) {
620
+ const blocks = acc.blocks;
621
+ if (acc.id === undefined && acc.inputTokens === undefined && !blocks) {
622
+ return undefined;
623
+ }
624
+ // Rebuild content in ascending block index, shaped like the SDK's own
625
+ // parsed message content so setChatResponseAttrs / iterToolUses read it
626
+ // identically to the non-streaming path.
627
+ let content;
628
+ if (blocks) {
629
+ content = Object.keys(blocks)
630
+ .map((k) => Number(k))
631
+ .sort((a, b) => a - b)
632
+ .map((i) => {
633
+ const b = blocks[i];
634
+ if (b.type === "tool_use") {
635
+ return { type: "tool_use", id: b.id, name: b.name, input: b.input ?? {} };
636
+ }
637
+ if (b.type === "text") {
638
+ return { type: "text", text: b.text ?? "" };
639
+ }
640
+ return { type: b.type };
641
+ });
642
+ }
643
+ return {
644
+ id: acc.id,
645
+ model: acc.model,
646
+ stop_reason: acc.stopReason,
647
+ content: content,
648
+ usage: {
649
+ input_tokens: acc.inputTokens,
650
+ output_tokens: acc.outputTokens,
651
+ // Raw fields only — setChatResponseAttrs remains the single place
652
+ // that adds these into the reported total, matching the
653
+ // non-streaming/MessageStream contract exactly.
654
+ cache_read_input_tokens: acc.cacheReadTokens,
655
+ cache_creation_input_tokens: acc.cacheCreationTokens,
656
+ },
235
657
  };
236
658
  }
237
- return stream;
238
659
  };
239
660
  }
240
661
  function setChatRequestAttrs(span, params, sdk, logger) {