@animalabs/membrane 0.5.75 → 0.5.77

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/dist/formatters/native.d.ts.map +1 -1
  2. package/dist/formatters/native.js +13 -0
  3. package/dist/formatters/native.js.map +1 -1
  4. package/dist/membrane.d.ts.map +1 -1
  5. package/dist/membrane.js +282 -25
  6. package/dist/membrane.js.map +1 -1
  7. package/dist/providers/bedrock.d.ts +17 -0
  8. package/dist/providers/bedrock.d.ts.map +1 -1
  9. package/dist/providers/bedrock.js +95 -13
  10. package/dist/providers/bedrock.js.map +1 -1
  11. package/dist/types/config.d.ts +31 -1
  12. package/dist/types/config.d.ts.map +1 -1
  13. package/dist/types/config.js +8 -0
  14. package/dist/types/config.js.map +1 -1
  15. package/dist/types/errors.d.ts +12 -0
  16. package/dist/types/errors.d.ts.map +1 -1
  17. package/dist/types/errors.js +19 -0
  18. package/dist/types/errors.js.map +1 -1
  19. package/dist/types/index.d.ts +1 -1
  20. package/dist/types/index.d.ts.map +1 -1
  21. package/dist/types/index.js +1 -1
  22. package/dist/types/index.js.map +1 -1
  23. package/dist/types/response.d.ts +1 -1
  24. package/dist/types/response.d.ts.map +1 -1
  25. package/dist/types/response.js.map +1 -1
  26. package/dist/types/streaming.d.ts +10 -0
  27. package/dist/types/streaming.d.ts.map +1 -1
  28. package/dist/types/yielding-stream.d.ts +12 -0
  29. package/dist/types/yielding-stream.d.ts.map +1 -1
  30. package/dist/types/yielding-stream.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/formatters/native.ts +12 -0
  33. package/src/membrane.ts +308 -23
  34. package/src/providers/bedrock.ts +109 -13
  35. package/src/types/config.ts +48 -4
  36. package/src/types/errors.ts +18 -0
  37. package/src/types/index.ts +1 -0
  38. package/src/types/response.ts +5 -1
  39. package/src/types/streaming.ts +11 -0
  40. package/src/types/yielding-stream.ts +13 -0
@@ -49,6 +49,16 @@ export interface BedrockAdapterConfig {
49
49
 
50
50
  /** Anthropic API version header (defaults to 2023-06-01) */
51
51
  anthropicVersion?: string;
52
+
53
+ /**
54
+ * Endpoint override (no trailing slash), e.g. an inference gateway leg
55
+ * like `https://gate.animalabs.ai/bedrock/apse1`. Defaults to
56
+ * `https://bedrock-runtime.{region}.amazonaws.com`. When pointing at a
57
+ * gateway, set accessKeyId to the gate token — the gateway reads it from
58
+ * the SigV4 Credential field, discards the client signature, and re-signs
59
+ * with real AWS creds that never leave the gateway box.
60
+ */
61
+ baseURL?: string;
52
62
  }
53
63
 
54
64
  // ============================================================================
@@ -120,9 +130,25 @@ interface BedrockStreamEvent {
120
130
  usage?: {
121
131
  input_tokens: number;
122
132
  output_tokens: number;
133
+ cache_creation_input_tokens?: number | null;
134
+ cache_read_input_tokens?: number | null;
123
135
  };
124
136
  }
125
137
 
138
+ /**
139
+ * Bedrock accepts `cache_control: { type: 'ephemeral' }` but rejects the
140
+ * direct-API `ttl` extension ("cache_control.ttl: Extra inputs are not
141
+ * permitted"). Drop the ttl, keep the marker — the cache still works, at
142
+ * Bedrock's fixed default TTL.
143
+ */
144
+ function stripCacheTtl<T extends Record<string, any>>(block: T): T {
145
+ if (block?.cache_control && typeof block.cache_control === 'object' && 'ttl' in block.cache_control) {
146
+ const { ttl, ...cacheControl } = block.cache_control;
147
+ return { ...block, cache_control: cacheControl };
148
+ }
149
+ return block;
150
+ }
151
+
126
152
  // ============================================================================
127
153
  // AWS Signature V4 Implementation
128
154
  // ============================================================================
@@ -252,6 +278,7 @@ export class BedrockAdapter implements ProviderAdapter {
252
278
  private region: string;
253
279
  private defaultMaxTokens: number;
254
280
  private anthropicVersion: string;
281
+ private baseURL?: string;
255
282
 
256
283
  constructor(config: BedrockAdapterConfig = {}) {
257
284
  this.accessKeyId = config.accessKeyId ?? process.env.AWS_ACCESS_KEY_ID ?? '';
@@ -260,6 +287,7 @@ export class BedrockAdapter implements ProviderAdapter {
260
287
  this.region = config.region ?? process.env.AWS_REGION ?? 'us-west-2';
261
288
  this.defaultMaxTokens = config.defaultMaxTokens ?? 4096;
262
289
  this.anthropicVersion = config.anthropicVersion ?? 'bedrock-2023-05-31';
290
+ this.baseURL = config.baseURL?.replace(/\/$/, '');
263
291
 
264
292
  if (!this.accessKeyId || !this.secretAccessKey) {
265
293
  throw new Error('AWS credentials required: accessKeyId and secretAccessKey');
@@ -271,6 +299,18 @@ export class BedrockAdapter implements ProviderAdapter {
271
299
  return modelId.includes('claude') || modelId.startsWith('anthropic.');
272
300
  }
273
301
 
302
+ /**
303
+ * Cross-region inference-profile prefix for this adapter's region.
304
+ * Claude 4-era models on Bedrock reject on-demand invocation of the
305
+ * direct id ("Invocation ... with on-demand throughput isn't supported")
306
+ * and require the profile form — verified live 2026-07-31.
307
+ */
308
+ private inferenceProfilePrefix(): string {
309
+ if (this.region.startsWith('eu-')) return 'eu.';
310
+ if (this.region.startsWith('ap-')) return 'apac.';
311
+ return 'us.';
312
+ }
313
+
274
314
  /**
275
315
  * Convert a standard Claude model ID to Bedrock format if needed
276
316
  */
@@ -287,7 +327,13 @@ export class BedrockAdapter implements ProviderAdapter {
287
327
  return modelId;
288
328
  }
289
329
 
290
- // Map common Claude model IDs to Bedrock format
330
+ const profile = this.inferenceProfilePrefix();
331
+
332
+ // Map common Claude model IDs to Bedrock format. The 3.x entries keep
333
+ // their historical direct-id form (those models predate inference
334
+ // profiles; all are EOL on Bedrock as of 2026-07 anyway, so the exact
335
+ // shape is moot). 4-era entries use the profile form — the direct id
336
+ // no longer invokes.
291
337
  const modelMap: Record<string, string> = {
292
338
  'claude-3-5-sonnet-20241022': 'anthropic.claude-3-5-sonnet-20241022-v2:0',
293
339
  'claude-3-5-sonnet-latest': 'anthropic.claude-3-5-sonnet-20241022-v2:0',
@@ -296,13 +342,15 @@ export class BedrockAdapter implements ProviderAdapter {
296
342
  'claude-3-opus-20240229': 'anthropic.claude-3-opus-20240229-v1:0',
297
343
  'claude-3-sonnet-20240229': 'anthropic.claude-3-sonnet-20240229-v1:0',
298
344
  'claude-3-haiku-20240307': 'anthropic.claude-3-haiku-20240307-v1:0',
299
- 'claude-sonnet-4-20250514': 'anthropic.claude-sonnet-4-20250514-v1:0',
300
- 'claude-opus-4-20250514': 'anthropic.claude-opus-4-20250514-v1:0',
301
- // Haiku 4.5 aliases
302
- 'claude-haiku-4-5-20251001': 'anthropic.claude-3-5-haiku-20241022-v1:0',
345
+ 'claude-sonnet-4-20250514': `${profile}anthropic.claude-sonnet-4-20250514-v1:0`,
346
+ 'claude-opus-4-20250514': `${profile}anthropic.claude-opus-4-20250514-v1:0`,
347
+ // Haiku 4.5 previously aliased to 3.5 Haiku (a stand-in from before
348
+ // Haiku 4.5 reached Bedrock). 3.5 Haiku is EOL on Bedrock now, so the
349
+ // alias routed every plain-id caller to a guaranteed error.
350
+ 'claude-haiku-4-5-20251001': `${profile}anthropic.claude-haiku-4-5-20251001-v1:0`,
303
351
  };
304
352
 
305
- return modelMap[modelId] ?? `anthropic.${modelId}-v1:0`;
353
+ return modelMap[modelId] ?? `${profile}anthropic.${modelId}-v1:0`;
306
354
  }
307
355
 
308
356
  async complete(
@@ -347,7 +395,14 @@ export class BedrockAdapter implements ProviderAdapter {
347
395
 
348
396
  private buildRequest(request: ProviderRequest, bedrockModelId?: string): BedrockMessageRequest {
349
397
  // Strip provider-specific fields (e.g., sourceUrl for Gemini) from image blocks
350
- // before sending to Bedrock/Anthropic, which rejects extra inputs
398
+ // before sending to Bedrock/Anthropic, which rejects extra inputs.
399
+ //
400
+ // Same treatment for cache_control.ttl: Bedrock's prompt cache runs at the
401
+ // fixed default (5m) TTL — the ttl field is a direct-API extension and
402
+ // Bedrock rejects it as an extra input. The marker itself is fine and
403
+ // caching works without the field, so strip just the ttl and keep the
404
+ // breakpoint. Transport quirks belong to the transport, not to every
405
+ // caller that sets cacheTtl. (Connectome issue #35.)
351
406
  const sanitizedMessages = (request.messages as any[]).map((msg: any) => {
352
407
  if (!Array.isArray(msg.content)) return msg;
353
408
  return {
@@ -355,9 +410,9 @@ export class BedrockAdapter implements ProviderAdapter {
355
410
  content: msg.content.map((block: any) => {
356
411
  if (block.type === 'image' && block.sourceUrl !== undefined) {
357
412
  const { sourceUrl, ...rest } = block;
358
- return rest;
413
+ return stripCacheTtl(rest);
359
414
  }
360
- return block;
415
+ return stripCacheTtl(block);
361
416
  }),
362
417
  };
363
418
  });
@@ -377,6 +432,10 @@ export class BedrockAdapter implements ProviderAdapter {
377
432
  if (needsFlatten && Array.isArray(request.system)) {
378
433
  const blocks = request.system as Array<{ type: string; text: string }>;
379
434
  params.system = blocks.map(b => b.text).join('\n\n');
435
+ } else if (Array.isArray(request.system)) {
436
+ params.system = (request.system as Array<Record<string, any>>).map(
437
+ b => stripCacheTtl(b)
438
+ ) as BedrockMessageRequest['system'];
380
439
  } else {
381
440
  params.system = request.system as BedrockMessageRequest['system'];
382
441
  }
@@ -400,7 +459,7 @@ export class BedrockAdapter implements ProviderAdapter {
400
459
  }
401
460
 
402
461
  if (request.tools && request.tools.length > 0) {
403
- params.tools = request.tools;
462
+ params.tools = (request.tools as Array<Record<string, any>>).map(t => stripCacheTtl(t));
404
463
  }
405
464
 
406
465
  // Handle extended thinking
@@ -434,7 +493,7 @@ export class BedrockAdapter implements ProviderAdapter {
434
493
  signal?: AbortSignal
435
494
  ): Promise<BedrockMessageResponse> {
436
495
  const url = new URL(
437
- `https://bedrock-runtime.${this.region}.amazonaws.com/model/${encodeURIComponent(modelId)}/invoke`
496
+ `${this.baseURL ?? `https://bedrock-runtime.${this.region}.amazonaws.com`}/model/${encodeURIComponent(modelId)}/invoke`
438
497
  );
439
498
 
440
499
  const body = JSON.stringify(request);
@@ -477,7 +536,7 @@ export class BedrockAdapter implements ProviderAdapter {
477
536
  signal?: AbortSignal
478
537
  ): Promise<ProviderResponse> {
479
538
  const url = new URL(
480
- `https://bedrock-runtime.${this.region}.amazonaws.com/model/${encodeURIComponent(modelId)}/invoke-with-response-stream`
539
+ `${this.baseURL ?? `https://bedrock-runtime.${this.region}.amazonaws.com`}/model/${encodeURIComponent(modelId)}/invoke-with-response-stream`
481
540
  );
482
541
 
483
542
  const body = JSON.stringify(request);
@@ -516,7 +575,10 @@ export class BedrockAdapter implements ProviderAdapter {
516
575
  let finalMessage: BedrockMessageResponse | undefined;
517
576
  let inputTokens = 0;
518
577
  let outputTokens = 0;
578
+ let cacheCreationTokens: number | undefined;
579
+ let cacheReadTokens: number | undefined;
519
580
  let stopReason: string = 'end_turn';
581
+ let stopSequence: string | undefined;
520
582
  let fullText = '';
521
583
 
522
584
  const reader = response.body?.getReader();
@@ -629,7 +691,19 @@ export class BedrockAdapter implements ProviderAdapter {
629
691
  }
630
692
 
631
693
  if (eventData.type === 'message_start' && eventData.message) {
632
- inputTokens = eventData.message.usage?.input_tokens ?? 0;
694
+ // Cache metrics ride the same usage objects as on the direct
695
+ // API. Dropping them (pre-2026-07-31) made caching look
696
+ // permanently inert on Bedrock streams: complete() surfaced
697
+ // them, stream() zeroed them, and every ledger/pricing
698
+ // consumer downstream saw zeros. (Connectome issue #35.)
699
+ const startUsage = eventData.message.usage;
700
+ inputTokens = startUsage?.input_tokens ?? 0;
701
+ if (startUsage?.cache_creation_input_tokens != null) {
702
+ cacheCreationTokens = startUsage.cache_creation_input_tokens;
703
+ }
704
+ if (startUsage?.cache_read_input_tokens != null) {
705
+ cacheReadTokens = startUsage.cache_read_input_tokens;
706
+ }
633
707
  } else if (eventData.type === 'content_block_start') {
634
708
  currentBlockIndex = eventData.index ?? 0;
635
709
  contentBlocks[currentBlockIndex] = eventData.content_block as { type: string };
@@ -678,10 +752,29 @@ export class BedrockAdapter implements ProviderAdapter {
678
752
  } else if (eventData.type === 'message_delta') {
679
753
  if (eventData.usage) {
680
754
  outputTokens = eventData.usage.output_tokens;
755
+ // message_delta carries cumulative cache metrics — use as
756
+ // authoritative when present (same contract as the
757
+ // Anthropic adapter).
758
+ if (eventData.usage.cache_creation_input_tokens != null) {
759
+ cacheCreationTokens = eventData.usage.cache_creation_input_tokens;
760
+ }
761
+ if (eventData.usage.cache_read_input_tokens != null) {
762
+ cacheReadTokens = eventData.usage.cache_read_input_tokens;
763
+ }
681
764
  }
682
765
  if (eventData.delta?.stop_reason) {
683
766
  stopReason = eventData.delta.stop_reason;
684
767
  }
768
+ // WHICH stop sequence fired, not just that one did. Dropping
769
+ // this (pre-2026-07-26) broke prefill/XML tool use on
770
+ // Bedrock entirely: membrane's tool gate matches
771
+ // stopSequence === '</function_calls>', so calls were never
772
+ // parsed or executed, the close tag was never restored, and
773
+ // the turn continuation looped forever on the dangling
774
+ // block (~6 output tokens per full-prefill round).
775
+ if (eventData.delta?.stop_sequence) {
776
+ stopSequence = eventData.delta.stop_sequence;
777
+ }
685
778
  }
686
779
  }
687
780
  } catch (e) {
@@ -736,9 +829,12 @@ export class BedrockAdapter implements ProviderAdapter {
736
829
  }),
737
830
  model: modelId,
738
831
  stop_reason: stopReason as BedrockMessageResponse['stop_reason'],
832
+ stop_sequence: stopSequence ?? null,
739
833
  usage: {
740
834
  input_tokens: inputTokens,
741
835
  output_tokens: outputTokens,
836
+ ...(cacheCreationTokens != null ? { cache_creation_input_tokens: cacheCreationTokens } : {}),
837
+ ...(cacheReadTokens != null ? { cache_read_input_tokens: cacheReadTokens } : {}),
742
838
  },
743
839
  };
744
840
 
@@ -15,17 +15,53 @@ import type { PrefillFormatter } from '../formatters/types.js';
15
15
  export interface RetryConfig {
16
16
  /** Maximum number of retry attempts (default: 3) */
17
17
  maxRetries: number;
18
-
18
+
19
19
  /** Initial retry delay in milliseconds (default: 1000) */
20
20
  retryDelayMs: number;
21
-
21
+
22
22
  /** Backoff multiplier (default: 2) */
23
23
  backoffMultiplier: number;
24
-
24
+
25
25
  /** Maximum retry delay (default: 30000) */
26
26
  maxRetryDelayMs: number;
27
+
28
+ /**
29
+ * Separate, longer schedule for provider capacity errors (529
30
+ * overloaded_error). Capacity storms last minutes, not seconds — the
31
+ * standard schedule's 30s ceiling turns one into a dead turn. Overloaded
32
+ * retries are always attempted (mirroring the forced 429 retries), with
33
+ * jitter so a fleet backing off doesn't re-create the stampede in sync.
34
+ *
35
+ * maxRetries: 0 here disables this dedicated policy entirely: 529s then
36
+ * follow the base retry config like any other retryable server error
37
+ * (no forced retries, base schedule, no stream-path retry) — the exact
38
+ * pre-policy behavior.
39
+ */
40
+ overloaded: OverloadedRetryConfig;
27
41
  }
28
42
 
43
+ export interface OverloadedRetryConfig {
44
+ /** Attempt bound for overloaded errors, applied even when the base
45
+ * maxRetries is 0. Like the base maxRetries (and the forced 429 path),
46
+ * this bounds TOTAL attempts, not retries-after-the-first (default: 7) */
47
+ maxRetries: number;
48
+
49
+ /** Initial overloaded retry delay in milliseconds (default: 10000) */
50
+ retryDelayMs: number;
51
+
52
+ /** Backoff multiplier (default: 2) */
53
+ backoffMultiplier: number;
54
+
55
+ /** Maximum overloaded retry delay (default: 300000 — 5 minutes) */
56
+ maxRetryDelayMs: number;
57
+ }
58
+
59
+ /** Shape accepted by MembraneConfig.retry — every field optional, including
60
+ * inside the nested overloaded schedule. */
61
+ export type RetryConfigInput = Partial<Omit<RetryConfig, 'overloaded'>> & {
62
+ overloaded?: Partial<OverloadedRetryConfig>;
63
+ };
64
+
29
65
  // ============================================================================
30
66
  // Media Processing Config
31
67
  // ============================================================================
@@ -152,7 +188,7 @@ export interface MembraneConfig {
152
188
  formatter?: PrefillFormatter;
153
189
 
154
190
  /** Retry configuration */
155
- retry?: Partial<RetryConfig>;
191
+ retry?: RetryConfigInput;
156
192
 
157
193
  /** Media processing configuration */
158
194
  media?: Partial<MediaConfig>;
@@ -176,6 +212,14 @@ export const DEFAULT_RETRY_CONFIG: RetryConfig = {
176
212
  retryDelayMs: 1000,
177
213
  backoffMultiplier: 2,
178
214
  maxRetryDelayMs: 30000,
215
+ // 7 attempts = 6 waits: 10s → 20s → 40s → 80s → 160s → 300s, ~10 minutes
216
+ // of patience in total — the scale capacity storms actually resolve on.
217
+ overloaded: {
218
+ maxRetries: 7,
219
+ retryDelayMs: 10_000,
220
+ backoffMultiplier: 2,
221
+ maxRetryDelayMs: 300_000,
222
+ },
179
223
  };
180
224
 
181
225
  export const DEFAULT_MEDIA_CONFIG: MediaConfig = {
@@ -239,6 +239,24 @@ export function unsupportedError(message: string, rawRequest?: unknown): Membran
239
239
  // Error Classification
240
240
  // ============================================================================
241
241
 
242
+ /**
243
+ * Provider capacity exhaustion — Anthropic 529 overloaded_error, whichever
244
+ * path it arrived by (structured status from the provider handler, or the
245
+ * message-matched fallbacks in classifyError). Used only to CHOOSE the retry
246
+ * schedule among already-retryable errors, never to decide retryability.
247
+ * Matches the same deliberately narrow tokens as classifyError's fallback
248
+ * (status/`529`/exact `overloaded_error`) — a bare 'overloaded' in prose
249
+ * (e.g. "worker pool overloaded") must not put an unrelated error onto the
250
+ * ~10-minute schedule. The provider handlers' own bare-'overloaded' safety
251
+ * nets attach httpStatus 529, so those still land here via the status check.
252
+ */
253
+ export function isOverloadedError(info: ErrorInfo): boolean {
254
+ if (!info.retryable) return false;
255
+ if (info.httpStatus === 529) return true;
256
+ const m = info.message.toLowerCase();
257
+ return m.includes('529') || m.includes('overloaded_error');
258
+ }
259
+
242
260
  export function classifyError(error: unknown): ErrorInfo {
243
261
  if (error instanceof MembraneError) {
244
262
  return error.toErrorInfo();
@@ -165,6 +165,7 @@ export {
165
165
  safetyError,
166
166
  unsupportedError,
167
167
  classifyError,
168
+ isOverloadedError,
168
169
  } from './errors.js';
169
170
 
170
171
  // Config
@@ -15,7 +15,11 @@ export type StopReason =
15
15
  | 'stop_sequence' // Hit stop sequence
16
16
  | 'tool_use' // Stopped for tool use
17
17
  | 'refusal' // Content refused by safety
18
- | 'abort'; // Request was aborted
18
+ | 'abort' // Request was aborted
19
+ | 'no_progress' // Stall guard ended the turn (issue #39): consecutive
20
+ // automatic resumptions re-sent context without advancing
21
+ | 'round_limit'; // Resumption round cap ended the turn: the turn kept
22
+ // resuming (with progress) past maxResumptionRounds
19
23
 
20
24
  // ============================================================================
21
25
  // Usage Information
@@ -231,6 +231,17 @@ export interface StreamOptions {
231
231
  /** Maximum tool execution depth (default: 10) */
232
232
  maxToolDepth?: number;
233
233
 
234
+ /**
235
+ * Cap on AUTOMATIC false-positive stop-sequence resumptions per turn —
236
+ * membrane's own re-streams, not the caller's work. Tool rounds are
237
+ * deliberately not counted: they are governed by maxToolDepth and caller
238
+ * policy. Distinct from maxToolDepth on purpose: raising the tool budget
239
+ * for deep chains must not also raise how often a turn may re-send its
240
+ * full context on membrane's own initiative (issue #39). Exceeding it
241
+ * ends the turn with stopReason 'round_limit'. Default: 24.
242
+ */
243
+ maxResumptionRounds?: number;
244
+
234
245
  /** Timeout for each tool execution */
235
246
  toolTimeoutMs?: number;
236
247
 
@@ -237,6 +237,19 @@ export interface YieldingStreamOptions {
237
237
  */
238
238
  maxToolDepth?: number;
239
239
 
240
+ /**
241
+ * Cap on AUTOMATIC false-positive stop-sequence resumptions per turn —
242
+ * membrane's own re-streams, not the caller's tool work. Tool rounds are
243
+ * deliberately NOT counted: this path's uncapped-by-default tool-loop
244
+ * contract stands (the caller budgets its own work via maxToolDepth).
245
+ * What this bounds is membrane's own failure surface — how many times a
246
+ * turn may re-send its full context on membrane's initiative; an
247
+ * unlimited resumption bound is how the 43-round Ash spin happened
248
+ * (issue #39). Exceeding it ends the turn with stopReason 'round_limit'.
249
+ * Default: 24. `-1` for unlimited, at your own risk.
250
+ */
251
+ maxResumptionRounds?: number;
252
+
240
253
  /**
241
254
  * Whether to emit 'tokens' events.
242
255
  * Set to false if you only care about tool calls and final response.