@devries-cameron20 / composio Mirror · read-only / commits / be12ce16a
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 08:30 UTC

feat(core): warn once per deprecated toolkit version reported by the API (PLEN-4352) (#4883)

## What Adds `createToolkitDeprecationFetch()` (`ts/packages/core/src/utils/toolkitDeprecation.ts`), a `fetch` wrapper passed to the single `new ComposioClient({...})` in `ts/packages/core/src/composio.ts`. Every response is checked for the `Composio-Deprecated-Toolkits` header, an RFC 9651 structured-field list with one item per deprecated toolkit version (`"GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"`). Items are parsed by a hand-rolled parser for that subset and validated with zod; parse failures drop the item. Each `UPPER(slug)@version` is warned about once per process through the SDK logger, one line per toolkit: ``` [Deprecation] Toolkit GMAIL version 20250114_00 was deprecated on 2026-05-27 (lifecycle) and will stop working on 2026-08-27. Pin a newer version with toolkitVersions: { gmail: '<version>' } or COMPOSIO_TOOLKIT_VERSION_GMAIL. See https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset. ``` The reason and sunset clauses are omitted when the header omits them. The response is returned unchanged on every path and its body is never read or cloned. ## Why Phase 1 of toolkit version deprecation (PLEN-2553; platform #13516, #13517) emits the header; without this the SDK is silent until the Phase 2 410. ## Design decisions - Global response hook, not per call site: eight single-toolkit routes emit the header today and more may follow; one wrapper below the generated client covers them all, including retried attempts, without touching `src/models/*`. - Dedupe key UPPER(slug)@version per process: `tools.execute` and `triggers.create` each make two header-bearing requests, and a once-per-process boolean would hide a second deprecated toolkit. - Grouped formatter, five versions per line: every Phase 1 header carries one item, so this is one version per line today; the rule exists so a future listing emitter cannot produce a burst of lines. - Channel: `logger.warn` on the SDK singleton in `src/utils/logger.ts`; silence with `logLevel: 'error'` (or `'silent'`) or `COMPOSIO_LOG_LEVEL=error`. No new config flag, no telemetry event. - Listings never carry the header (platform decision); CLI, MCP, 410 mapping, telemetry are follow-ups. ## Owned-client facts verified Verified on the pinned `@composio/client@2.0.0-rc.14` as installed from `pnpm-lock.yaml` (the handoff cited rc.10; `next` moved to rc.14 and the same facts hold; rc.10 was also checked from `npm pack` with identical results at shifted lines): - `ClientOptions.fetch?: typeof globalThis.fetch | undefined`: `dist/session-configs-CtHZk-vG.d.mts:27117`. - Retries happen inside the wrapper: `makeRequest` (`dist/generated-operations-D8jOXj9j.mjs:1382`) loops `for (let numRetries = 0;; numRetries++)` (line 1400) and each attempt calls `config.fetch.call(void 0, url, init)` (line 1348). The wrapper therefore sees every attempt (dedupe makes that harmless) and must be `this`-independent, which it is. `withOptions()` keeps `#fetch` (`dist/index.mjs:203`) and the default is `globalThis.fetch` resolved per call (`dist/index.mjs:172`), which the wrapper mirrors when no base fetch is given. - Construction sites of the client in this package: 1, `ts/packages/core/src/composio.ts:526` (`grep -rn "ComposioClient(" ts/packages/core/src`). `createSession()` returns `new Composio({ ...this.config, defaultHeaders })`, so it goes through the same constructor and inherits the wrapper; a test covers it. ## Not changed src/models/*, generated surfaces, client pins, lockfiles, mocks. `test/utils/mocks/client.mock.ts` constructs the client without `fetch` and needs no change. `ts/packages/core/README.md` lists env vars, not logger emissions, so it was left alone. The CLI keeps its own `fetch: metrics.fetch` and is out of scope. ## Tests - `test/utils/toolkitDeprecation.test.ts` (25): parser goldens (full params; bare `"STRAVA";version="20240902_00"`; two items; escaped quote and backslash in a slug; whitespace around separators; garbage and empty string yield `[]`; unknown params ignored; missing `version` dropped while siblings are kept; wrong-typed known param and invalid escape drop the item); formatter with and without sunset and reason, default docs URL, six versions of one slug grouped into one line with "and 1 more", case-insensitive grouping; wrapper dedupes across calls and across wrapper instances, header name matched case-insensitively, no header and malformed header are silent, reset re-warns, global `fetch` resolved per call, rejections propagate untouched, a throwing `headers` getter logs at debug and still returns the response. - `test/core/toolkitDeprecationWarning.test.ts` (10), modelled on `test/core/loggerConfig.test.ts` with a real `Composio`, stubbed `globalThis.fetch` and a logger sink: `tools.getRawComposioToolBySlug` warns once; `tools.execute` with both responses carrying the item warns once; header only on the no-retry execute response still warns; no header, no warn; `logLevel: 'error'` and `'silent'` suppress; `Deprecation: @1688169599` plus our header yields the client's `tools.retrieve` warning and ours as two distinct messages; a malformed header never throws and the body is still returned; a second `Composio` and a `createSession()` clone do not re-warn, and do after `_resetToolkitDeprecationWarningsForTests()`; a clone warns when the parent has not seen the version. ## Checks run From the repo root with the mise toolchain (`pnpm 11.8.0`, `node 24.17.0`): - `pnpm install --frozen-lockfile`: `Done in 49.3s using pnpm v11.8.0`; `git status --short pnpm-lock.yaml` empty (lockfile unchanged). - `pnpm --filter @composio/core typecheck`: both `tsc --noEmit` passes clean. - `pnpm lint` (root `oxlint ts test tsdown.config.base.ts`; `@composio/core` has no package-level `lint` script): 4 pre-existing warnings in `ts/packages/cli/scripts` and `ts/examples`, none in changed files. `pnpm exec oxlint ts/packages/core`: 3 pre-existing warnings, none in changed files. - `pnpm exec prettier --check` on the five changed files: `All matched files use Prettier code style!` (there is no `format:check` script at the root; `format` is `prettier --write`). - `pnpm --filter @composio/core test`: `Tests 1852 passed | 2 expected fail (1854)`, including the 35 new tests. - `pnpm build:packages`: 19 turbo tasks successful, exit 0. - `pnpm --filter @composio/slim test`: `@composio/core` and `@composio/slim` provenance headers verified (slim copies core's `dist`, so it ships this change). - Diff grep for em dashes and `console.log`: none. Changeset: `.changeset/toolkit-deprecation-warning.md` bumps `@composio/core` and `@composio/slim` (patch); `.changeset/config.json` still has `fixed: [["@composio/core", "@composio/slim"]]` and ignores `@composio/cli`. ## Rollout and rollback No-op until Apollo #13517 is deployed; plain revert. ## Sibling PR - Python: https://github.com/ComposioHQ/composio/pull/4884 - Docs: https://github.com/ComposioHQ/composio/pull/4881 Linear: PLEN-4352 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com> Co-authored-by: jkomyno <alberto@composio.dev>

sankaran-lab committed Oct 17, 2026 at 02:00 UTC be12ce16a6a2c8543f1e36f85ec8ab98c04a1752
5 files changed +849 -1
.changeset/toolkit-deprecation-warning.md new
+6
@@ -0,0 +1,6 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/slim': patch
4 +---
5 +
6 +Warn once per toolkit version when the API reports it as deprecated through the `Composio-Deprecated-Toolkits` response header. The warning names the version, the sunset date and how to pin a newer version. Silence it with `logLevel: 'error'` or `COMPOSIO_LOG_LEVEL=error`.
ts/packages/core/src/composio.ts
+6 -1
@@ -1,6 +1,6 @@
1 import { getEnvVariable } from './utils/env';
2 import type { BaseComposioProvider } from './provider/BaseProvider';
3 -import ComposioClient from '@composio/client';
3 +import ComposioClient, { createFetchTransport } from '@composio/client';
4 import type { LogLevel as ClientLogLevel } from '@composio/client';
5 import { Tools } from './models/Tools';
6 import { Toolkits } from './models/Toolkits';
@@ -38,6 +38,7 @@ import { ToolRouter } from './models/ToolRouter';
38 import { Sessions } from './models/Sessions';
39 import { CONFIG_DEFAULTS } from './utils/config-defaults';
40 import { expandHomeAndResolve, expandHomeAndResolveMany } from './utils/fileDirs';
41 +import { createToolkitDeprecationFetch } from './utils/toolkitDeprecation';
42 export type ComposioConfig<
43 TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
44 > = {
@@ -554,6 +555,10 @@ export class Composio<
555 identity: getClientIdentity(this.provider),
556 logger: clientLogForwarder,
557 logLevel: toClientLogLevel(logger.getLevel()),
558 + // Warns once per deprecated toolkit version reported through the
559 + // `Composio-Deprecated-Toolkits` response header. `createSession()`
560 + // clones go through this same constructor and inherit it.
561 + transport: createFetchTransport({ fetch: createToolkitDeprecationFetch() }),
562 });
563
564 this.tools = new Tools(this.client, this.config);
ts/packages/core/src/utils/toolkitDeprecation.ts new
+271
@@ -0,0 +1,271 @@
1 +/**
2 + * Toolkit version deprecation warnings.
3 + *
4 + * When a request resolves to a deprecated toolkit version, the API adds a
5 + * `Composio-Deprecated-Toolkits` response header (an RFC 9651 structured-field
6 + * list). This module parses that header below the generated client, through a
7 + * `fetch` wrapper, and warns once per process for each deprecated toolkit
8 + * version it sees. The response itself is never read, cloned or altered.
9 + *
10 + * Example header:
11 + *
12 + * "GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"
13 + */
14 +import { z } from 'zod';
15 +import logger from './logger';
16 +import { normalizeToolkitSlug } from './toolkitVersion';
17 +
18 +/** Response header name. `Headers.get` is case-insensitive. */
19 +export const TOOLKIT_DEPRECATION_HEADER = 'composio-deprecated-toolkits';
20 +
21 +/** Anchor of the docs section every warning points at. */
22 +export const TOOLKIT_DEPRECATION_DOCS_URL =
23 + 'https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset';
24 +
25 +/** Versions named per toolkit before the formatter collapses the rest into "and N more". */
26 +const MAX_VERSIONS_PER_LINE = 5;
27 +
28 +/**
29 + * The three limits below mirror the `@composio/client` deprecation module,
30 + * which reads the same kind of server-controlled header.
31 + */
32 +/** A header longer than this is ignored whole rather than parsed. */
33 +const MAX_HEADER_LENGTH = 2048;
34 +/** A header holding any of these is ignored whole, so nothing partially cleaned reaches the log. */
35 +const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
36 +/** Keys the process will ever record; past this, new versions are neither recorded nor warned about. */
37 +const MAX_TRACKED_VERSIONS = 1024;
38 +
39 +const DeprecatedToolkitEntrySchema = z.object({
40 + slug: z.string().min(1),
41 + version: z.string().min(1),
42 + deprecatedAt: z.date().optional(),
43 + sunsetAt: z.date().optional(),
44 + reason: z.string().min(1).optional(),
45 +});
46 +
47 +export type DeprecatedToolkitEntry = z.infer<typeof DeprecatedToolkitEntrySchema>;
48 +
49 +/** Keys (`UPPER(slug)@version`) already warned about in this process. */
50 +const warnedToolkitVersions = new Set<string>();
51 +
52 +const dedupeKey = (entry: Pick<DeprecatedToolkitEntry, 'slug' | 'version'>): string =>
53 + `${entry.slug.toUpperCase()}@${entry.version}`;
54 +
55 +/**
56 + * Splits `value` on `delimiter` characters that sit outside double-quoted
57 + * strings, honouring backslash escapes inside the quotes. Empty pieces are
58 + * dropped and the rest are trimmed.
59 + */
60 +const splitOutsideQuotes = (value: string, delimiter: string): string[] => {
61 + const pieces: string[] = [];
62 + let current = '';
63 + let inString = false;
64 + for (let index = 0; index < value.length; index++) {
65 + const char = value[index];
66 + if (inString) {
67 + current += char;
68 + if (char === '\\' && index + 1 < value.length) {
69 + index += 1;
70 + current += value[index];
71 + } else if (char === '"') {
72 + inString = false;
73 + }
74 + } else if (char === '"') {
75 + inString = true;
76 + current += char;
77 + } else if (char === delimiter) {
78 + pieces.push(current);
79 + current = '';
80 + } else {
81 + current += char;
82 + }
83 + }
84 + pieces.push(current);
85 + return pieces.map(piece => piece.trim()).filter(piece => piece.length > 0);
86 +};
87 +
88 +/**
89 + * Decodes an sf-string (`"..."` with `\"` and `\\` escapes). Returns
90 + * `undefined` for anything that is not a complete, validly escaped sf-string.
91 + */
92 +const decodeSfString = (raw: string): string | undefined => {
93 + const match = /^"((?:[^"\\]|\\.)*)"$/.exec(raw);
94 + if (match === null) return undefined;
95 + let invalidEscape = false;
96 + const decoded = match[1].replace(/\\(.)/g, (_whole, escaped: string) => {
97 + if (escaped === '"' || escaped === '\\') return escaped;
98 + invalidEscape = true;
99 + return '';
100 + });
101 + return invalidEscape ? undefined : decoded;
102 +};
103 +
104 +/** Decodes an sf-date (`@` followed by Unix seconds). */
105 +const decodeSfDate = (raw: string): Date | undefined => {
106 + const match = /^@(-?\d{1,15})$/.exec(raw);
107 + if (match === null) return undefined;
108 + const date = new Date(Number(match[1]) * 1000);
109 + return Number.isNaN(date.getTime()) ? undefined : date;
110 +};
111 +
112 +/** Header parameters the SDK understands, by wire name. */
113 +const KNOWN_PARAMETERS = new Map<
114 + string,
115 + { name: Exclude<keyof DeprecatedToolkitEntry, 'slug'>; kind: 'string' | 'date' }
116 +>([
117 + ['version', { name: 'version', kind: 'string' }],
118 + ['reason', { name: 'reason', kind: 'string' }],
119 + ['deprecated', { name: 'deprecatedAt', kind: 'date' }],
120 + ['sunset', { name: 'sunsetAt', kind: 'date' }],
121 +]);
122 +
123 +/**
124 + * Parses one list item: an sf-string slug followed by `;key=value` parameters.
125 + * Unknown parameters are ignored; a known parameter with the wrong type drops
126 + * the item.
127 + */
128 +const parseItem = (item: string): DeprecatedToolkitEntry | undefined => {
129 + const [head, ...params] = splitOutsideQuotes(item, ';');
130 + if (head === undefined) return undefined;
131 + const candidate: Record<string, unknown> = { slug: decodeSfString(head) };
132 + for (const param of params) {
133 + const separator = param.indexOf('=');
134 + if (separator === -1) continue;
135 + const key = param.slice(0, separator).trim();
136 + const rawValue = param.slice(separator + 1).trim();
137 + const field = KNOWN_PARAMETERS.get(key);
138 + if (field === undefined) continue;
139 + const decoded = field.kind === 'string' ? decodeSfString(rawValue) : decodeSfDate(rawValue);
140 + if (decoded === undefined) return undefined;
141 + candidate[field.name] = decoded;
142 + }
143 + const parsed = DeprecatedToolkitEntrySchema.safeParse(candidate);
144 + return parsed.success ? parsed.data : undefined;
145 +};
146 +
147 +/**
148 + * Parses a `Composio-Deprecated-Toolkits` header value. Items that fail to
149 + * parse are dropped silently; garbage input yields an empty array. Never throws.
150 + */
151 +export function parseDeprecatedToolkitsHeader(value: string): DeprecatedToolkitEntry[] {
152 + try {
153 + const entries: DeprecatedToolkitEntry[] = [];
154 + for (const item of splitOutsideQuotes(value, ',')) {
155 + const entry = parseItem(item);
156 + if (entry !== undefined) entries.push(entry);
157 + }
158 + return entries;
159 + } catch {
160 + return [];
161 + }
162 +}
163 +
164 +const isoDate = (date: Date): string => date.toISOString().slice(0, 10);
165 +
166 +const pinHint = (slug: string, docsUrl: string): string => {
167 + const configKey = normalizeToolkitSlug(slug);
168 + const envVar = `COMPOSIO_TOOLKIT_VERSION_${slug.toUpperCase()}`;
169 + return `Pin a newer version with toolkitVersions: { ${configKey}: '<version>' } or ${envVar}. See ${docsUrl}.`;
170 +};
171 +
172 +const formatSingle = (entry: DeprecatedToolkitEntry, docsUrl: string): string => {
173 + let sentence = `[Deprecation] Toolkit ${entry.slug.toUpperCase()} version ${entry.version} was deprecated`;
174 + if (entry.deprecatedAt !== undefined) sentence += ` on ${isoDate(entry.deprecatedAt)}`;
175 + if (entry.reason !== undefined) sentence += ` (${entry.reason})`;
176 + if (entry.sunsetAt !== undefined)
177 + sentence += ` and will stop working on ${isoDate(entry.sunsetAt)}`;
178 + return `${sentence}. ${pinHint(entry.slug, docsUrl)}`;
179 +};
180 +
181 +const formatGroup = (slug: string, entries: DeprecatedToolkitEntry[], docsUrl: string): string => {
182 + const versions = entries.map(entry => entry.version);
183 + const named = versions.slice(0, MAX_VERSIONS_PER_LINE).join(', ');
184 + const remaining = versions.length - MAX_VERSIONS_PER_LINE;
185 + const list = remaining > 0 ? `${named} and ${remaining} more` : named;
186 + let sentence = `[Deprecation] Toolkit ${slug} versions ${list} are deprecated`;
187 + const sunsets = entries
188 + .map(entry => entry.sunsetAt)
189 + .filter((date): date is Date => date !== undefined)
190 + .sort((a, b) => a.getTime() - b.getTime());
191 + if (sunsets.length > 0) {
192 + sentence += ` and the earliest will stop working on ${isoDate(sunsets[0])}`;
193 + }
194 + return `${sentence}. ${pinHint(slug, docsUrl)}`;
195 +};
196 +
197 +/**
198 + * Renders one warning line per toolkit slug. A slug with a single deprecated
199 + * version gets the full sentence with its dates and reason; a slug with several
200 + * names at most five versions and collapses the rest into "and N more".
201 + */
202 +export function formatToolkitDeprecationWarnings(
203 + entries: DeprecatedToolkitEntry[],
204 + docsUrl: string = TOOLKIT_DEPRECATION_DOCS_URL
205 +): string[] {
206 + const groups = new Map<string, DeprecatedToolkitEntry[]>();
207 + for (const entry of entries) {
208 + const slug = entry.slug.toUpperCase();
209 + const group = groups.get(slug);
210 + if (group === undefined) groups.set(slug, [entry]);
211 + else group.push(entry);
212 + }
213 + return Array.from(groups, ([slug, group]) =>
214 + group.length === 1 ? formatSingle(group[0], docsUrl) : formatGroup(slug, group, docsUrl)
215 + );
216 +}
217 +
218 +/**
219 + * Parses the header on `response`, drops versions already warned about in this
220 + * process, records the new ones and warns once per formatted line.
221 + */
222 +const warnDeprecatedToolkits = (response: Response): void => {
223 + const value = response.headers.get(TOOLKIT_DEPRECATION_HEADER);
224 + if (value === null || value.length === 0) return;
225 + if (value.length > MAX_HEADER_LENGTH || CONTROL_CHARACTERS.test(value)) return;
226 + if (warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS) return;
227 + const fresh: DeprecatedToolkitEntry[] = [];
228 + for (const entry of parseDeprecatedToolkitsHeader(value)) {
229 + const key = dedupeKey(entry);
230 + if (warnedToolkitVersions.has(key) || warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS)
231 + continue;
232 + warnedToolkitVersions.add(key);
233 + fresh.push(entry);
234 + }
235 + for (const line of formatToolkitDeprecationWarnings(fresh)) {
236 + logger.warn(line);
237 + }
238 +};
239 +
240 +/**
241 + * Wraps a `fetch` implementation so every response is checked for the
242 + * `Composio-Deprecated-Toolkits` header. The wrapper is `this`-independent,
243 + * returns the response unchanged on every path and never fails a call over
244 + * the header: any error while inspecting it is logged at debug and swallowed.
245 + *
246 + * When no `baseFetch` is given, `globalThis.fetch` is resolved per call so a
247 + * runtime that installs or replaces `fetch` after construction still works.
248 + */
249 +export function createToolkitDeprecationFetch(
250 + baseFetch?: typeof globalThis.fetch
251 +): typeof globalThis.fetch {
252 + return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
253 + const target = baseFetch ?? globalThis.fetch;
254 + const response = await target(input, init);
255 + try {
256 + warnDeprecatedToolkits(response);
257 + } catch (error) {
258 + try {
259 + logger.debug('Failed to inspect the toolkit deprecation header', error);
260 + } catch {
261 + // The fallback is best-effort too: a sink that throws must not fail the call.
262 + }
263 + }
264 + return response;
265 + };
266 +}
267 +
268 +/** Clears the once-per-process record. Tests only. */
269 +export function _resetToolkitDeprecationWarningsForTests(): void {
270 + warnedToolkitVersions.clear();
271 +}
ts/packages/core/test/core/toolkitDeprecationWarning.test.ts new
+205
@@ -0,0 +1,205 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 +import { Composio } from '../../src/composio';
3 +import logger from '../../src/utils/logger';
4 +import { _resetToolkitDeprecationWarningsForTests } from '../../src/utils/toolkitDeprecation';
5 +import { toolMocks } from '../utils/mocks/data.mock';
6 +import { MockProvider } from '../utils/mocks/provider.mock';
7 +
8 +const HEADER = 'Composio-Deprecated-Toolkits';
9 +const GMAIL_ITEM =
10 + '"GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"';
11 +const CLIENT_DEPRECATION = '@1688169599';
12 +
13 +const jsonResponse = (body: unknown, headers: Record<string, string> = {}): Response =>
14 + new Response(JSON.stringify(body), {
15 + status: 200,
16 + headers: { 'content-type': 'application/json', ...headers },
17 + });
18 +
19 +const rawTool = { ...toolMocks.rawTool, toolkit: { ...toolMocks.rawTool.toolkit, slug: 'gmail' } };
20 +const executeBody = { data: { ok: true }, successful: true, error: null };
21 +
22 +const createSink = () => ({
23 + error: vi.fn(),
24 + warn: vi.fn(),
25 + info: vi.fn(),
26 + debug: vi.fn(),
27 +});
28 +
29 +const createComposio = (config: Partial<ConstructorParameters<typeof Composio>[0]> = {}) =>
30 + new Composio({
31 + apiKey: 'uak_test_secret',
32 + baseURL: 'https://backend.composio.test',
33 + provider: new MockProvider(),
34 + allowTracking: false,
35 + disableVersionCheck: true,
36 + ...config,
37 + });
38 +
39 +/** Serves the tool schema on GET and the execute body on POST, both with `headers`. */
40 +const routeByMethod =
41 + (headers: { retrieve?: Record<string, string>; execute?: Record<string, string> }) =>
42 + async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> =>
43 + init?.method === 'POST'
44 + ? jsonResponse(executeBody, headers.execute)
45 + : jsonResponse(rawTool, headers.retrieve);
46 +
47 +const warnMessages = (sink: ReturnType<typeof createSink>): string[] =>
48 + sink.warn.mock.calls.map(call => String(call[0]));
49 +
50 +describe('Composio toolkit deprecation warning', () => {
51 + let fetchMock: ReturnType<typeof vi.fn>;
52 +
53 + beforeEach(() => {
54 + _resetToolkitDeprecationWarningsForTests();
55 + fetchMock = vi.fn();
56 + vi.stubGlobal('fetch', fetchMock);
57 + });
58 +
59 + afterEach(() => {
60 + vi.unstubAllGlobals();
61 + vi.restoreAllMocks();
62 + _resetToolkitDeprecationWarningsForTests();
63 + logger.configure({ level: 'info', sink: console });
64 + });
65 +
66 + it('warns once when a tool retrieve response carries the header', async () => {
67 + const sink = createSink();
68 + fetchMock.mockResolvedValue(jsonResponse(rawTool, { [HEADER]: GMAIL_ITEM }));
69 + const composio = createComposio({ logger: sink });
70 +
71 + const tool = await composio.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
72 +
73 + expect(tool.slug).toBe('COMPOSIO_TOOL');
74 + expect(sink.warn).toHaveBeenCalledTimes(1);
75 + const [message] = warnMessages(sink);
76 + expect(message).toContain('[Deprecation] Toolkit GMAIL version 20250114_00');
77 + expect(message).toContain('deprecated on 2026-05-27 (lifecycle)');
78 + expect(message).toContain('stop working on 2026-08-27');
79 + expect(message).toContain("toolkitVersions: { gmail: '<version>' }");
80 + expect(message).toContain('COMPOSIO_TOOLKIT_VERSION_GMAIL');
81 + expect(message).toContain(
82 + 'https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset'
83 + );
84 + });
85 +
86 + it('warns once on the execute path even though both responses carry the item', async () => {
87 + const sink = createSink();
88 + fetchMock.mockImplementation(
89 + routeByMethod({ retrieve: { [HEADER]: GMAIL_ITEM }, execute: { [HEADER]: GMAIL_ITEM } })
90 + );
91 + const composio = createComposio({ logger: sink });
92 +
93 + const result = await composio.tools.execute('COMPOSIO_TOOL', {
94 + userId: 'user-1',
95 + arguments: { query: 'x' },
96 + version: '20250114_00',
97 + });
98 +
99 + expect(fetchMock).toHaveBeenCalledTimes(2);
100 + expect(result.successful).toBe(true);
101 + expect(sink.warn).toHaveBeenCalledTimes(1);
102 + });
103 +
104 + it('warns when only the no-retry execute response carries the header', async () => {
105 + const sink = createSink();
106 + fetchMock.mockImplementation(routeByMethod({ execute: { [HEADER]: GMAIL_ITEM } }));
107 + const composio = createComposio({ logger: sink });
108 +
109 + await composio.tools.execute('COMPOSIO_TOOL', {
110 + userId: 'user-1',
111 + arguments: { query: 'x' },
112 + version: '20250114_00',
113 + });
114 +
115 + expect(sink.warn).toHaveBeenCalledTimes(1);
116 + expect(warnMessages(sink)[0]).toContain('GMAIL version 20250114_00');
117 + });
118 +
119 + it('stays silent without the header', async () => {
120 + const sink = createSink();
121 + fetchMock.mockImplementation(routeByMethod({}));
122 + const composio = createComposio({ logger: sink });
123 +
124 + await composio.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
125 + await composio.tools.execute('COMPOSIO_TOOL', {
126 + userId: 'user-1',
127 + arguments: { query: 'x' },
128 + version: '20250114_00',
129 + });
130 +
131 + expect(sink.warn).not.toHaveBeenCalled();
132 + });
133 +
134 + it.each(['error', 'silent'] as const)("is suppressed when logLevel is '%s'", async level => {
135 + const sink = createSink();
136 + fetchMock.mockResolvedValue(jsonResponse(rawTool, { [HEADER]: GMAIL_ITEM }));
137 + const composio = createComposio({ logger: sink, logLevel: level });
138 +
139 + await composio.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
140 +
141 + expect(sink.warn).not.toHaveBeenCalled();
142 + expect(sink.info).not.toHaveBeenCalled();
143 + });
144 +
145 + it('emits the client Deprecation warning and ours as two distinct messages', async () => {
146 + const sink = createSink();
147 + fetchMock.mockResolvedValue(
148 + jsonResponse(rawTool, { Deprecation: CLIENT_DEPRECATION, [HEADER]: GMAIL_ITEM })
149 + );
150 + const composio = createComposio({ logger: sink });
151 +
152 + await composio.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
153 +
154 + expect(sink.warn).toHaveBeenCalledTimes(2);
155 + const messages = warnMessages(sink);
156 + const ours = messages.filter(message => message.includes('[Deprecation] Toolkit GMAIL'));
157 + const theirs = messages.filter(message => message.includes('tools.retrieve'));
158 + expect(ours).toHaveLength(1);
159 + expect(theirs).toHaveLength(1);
160 + expect(theirs[0]).toContain('deprecated');
161 + });
162 +
163 + it('never throws on a malformed header and still returns the body', async () => {
164 + const sink = createSink();
165 + fetchMock.mockResolvedValue(jsonResponse(rawTool, { [HEADER]: '"GMAIL;version=;;@@' }));
166 + const composio = createComposio({ logger: sink });
167 +
168 + const tool = await composio.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
169 +
170 + expect(tool.slug).toBe('COMPOSIO_TOOL');
171 + expect(tool.toolkit?.slug).toBe('gmail');
172 + expect(sink.warn).not.toHaveBeenCalled();
173 + expect(sink.error).not.toHaveBeenCalled();
174 + });
175 +
176 + it('does not re-warn from a second instance or a session clone, but does after reset', async () => {
177 + const sink = createSink();
178 + fetchMock.mockResolvedValue(jsonResponse(rawTool, { [HEADER]: GMAIL_ITEM }));
179 + const first = createComposio({ logger: sink });
180 + await first.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
181 + expect(sink.warn).toHaveBeenCalledTimes(1);
182 +
183 + const second = createComposio({ logger: sink });
184 + await second.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
185 + const clone = first.createSession({ headers: { 'x-request-id': 'r1' } });
186 + await clone.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
187 + expect(sink.warn).toHaveBeenCalledTimes(1);
188 +
189 + _resetToolkitDeprecationWarningsForTests();
190 + await clone.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
191 + expect(sink.warn).toHaveBeenCalledTimes(2);
192 + });
193 +
194 + it('warns through a createSession() clone when the parent has not seen the version', async () => {
195 + const sink = createSink();
196 + fetchMock.mockResolvedValue(jsonResponse(rawTool, { [HEADER]: GMAIL_ITEM }));
197 + const composio = createComposio({ logger: sink });
198 + const clone = composio.createSession({ headers: { 'x-request-id': 'r1' } });
199 +
200 + await clone.tools.getRawComposioToolBySlug('COMPOSIO_TOOL');
201 +
202 + expect(sink.warn).toHaveBeenCalledTimes(1);
203 + expect(warnMessages(sink)[0]).toContain('GMAIL version 20250114_00');
204 + });
205 +});
ts/packages/core/test/utils/toolkitDeprecation.test.ts new
+361
@@ -0,0 +1,361 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 +import logger from '../../src/utils/logger';
3 +import {
4 + _resetToolkitDeprecationWarningsForTests,
5 + createToolkitDeprecationFetch,
6 + formatToolkitDeprecationWarnings,
7 + parseDeprecatedToolkitsHeader,
8 + TOOLKIT_DEPRECATION_DOCS_URL,
9 + TOOLKIT_DEPRECATION_HEADER,
10 + type DeprecatedToolkitEntry,
11 +} from '../../src/utils/toolkitDeprecation';
12 +
13 +const FULL_ITEM =
14 + '"GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"';
15 +const BARE_ITEM = '"STRAVA";version="20240902_00"';
16 +const DOCS_URL = 'https://docs.example/deprecation';
17 +
18 +const entry = (overrides: Partial<DeprecatedToolkitEntry> = {}): DeprecatedToolkitEntry => ({
19 + slug: 'GMAIL',
20 + version: '20250114_00',
21 + ...overrides,
22 +});
23 +
24 +describe('parseDeprecatedToolkitsHeader', () => {
25 + it('parses an item with every parameter', () => {
26 + expect(parseDeprecatedToolkitsHeader(FULL_ITEM)).toEqual([
27 + {
28 + slug: 'GMAIL',
29 + version: '20250114_00',
30 + deprecatedAt: new Date(1779840000 * 1000),
31 + sunsetAt: new Date(1787788800 * 1000),
32 + reason: 'lifecycle',
33 + },
34 + ]);
35 + });
36 +
37 + it('parses a bare item that carries only the version', () => {
38 + expect(parseDeprecatedToolkitsHeader(BARE_ITEM)).toEqual([
39 + { slug: 'STRAVA', version: '20240902_00' },
40 + ]);
41 + });
42 +
43 + it('parses a two item list', () => {
44 + const entries = parseDeprecatedToolkitsHeader(`${FULL_ITEM}, ${BARE_ITEM}`);
45 + expect(entries.map(item => `${item.slug}@${item.version}`)).toEqual([
46 + 'GMAIL@20250114_00',
47 + 'STRAVA@20240902_00',
48 + ]);
49 + });
50 +
51 + it('decodes escaped quotes and backslashes inside a slug', () => {
52 + const entries = parseDeprecatedToolkitsHeader(
53 + '"ODD\\"SLUG\\\\";version="20250101_00", "GMAIL";version="20250114_00"'
54 + );
55 + expect(entries.map(item => item.slug)).toEqual(['ODD"SLUG\\', 'GMAIL']);
56 + });
57 +
58 + it('tolerates whitespace around separators', () => {
59 + const entries = parseDeprecatedToolkitsHeader(
60 + ' "GMAIL" ; version = "20250114_00" ; sunset = @1787788800 ,"STRAVA";version="20240902_00" '
61 + );
62 + expect(entries).toEqual([
63 + { slug: 'GMAIL', version: '20250114_00', sunsetAt: new Date(1787788800 * 1000) },
64 + { slug: 'STRAVA', version: '20240902_00' },
65 + ]);
66 + });
67 +
68 + it('returns an empty list for garbage and for an empty string', () => {
69 + expect(parseDeprecatedToolkitsHeader('')).toEqual([]);
70 + expect(parseDeprecatedToolkitsHeader(' ')).toEqual([]);
71 + expect(parseDeprecatedToolkitsHeader('not a structured field')).toEqual([]);
72 + expect(parseDeprecatedToolkitsHeader('GMAIL;version=20250114_00')).toEqual([]);
73 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version="unterminated')).toEqual([]);
74 + expect(parseDeprecatedToolkitsHeader(',,,;;;===')).toEqual([]);
75 + });
76 +
77 + it('ignores unknown parameters', () => {
78 + expect(
79 + parseDeprecatedToolkitsHeader('"GMAIL";version="20250114_00";severity=3;flag;note="x"')
80 + ).toEqual([{ slug: 'GMAIL', version: '20250114_00' }]);
81 + });
82 +
83 + it('ignores a parameter named after an inherited object property', () => {
84 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version="1";constructor="x"')).toEqual([
85 + { slug: 'GMAIL', version: '1' },
86 + ]);
87 + });
88 +
89 + it('drops an empty item but keeps its siblings', () => {
90 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version="1", ;;')).toEqual([
91 + { slug: 'GMAIL', version: '1' },
92 + ]);
93 + });
94 +
95 + it('drops an item without a version but keeps its siblings', () => {
96 + expect(parseDeprecatedToolkitsHeader(`"GMAIL";deprecated=@1779840000, ${BARE_ITEM}`)).toEqual([
97 + { slug: 'STRAVA', version: '20240902_00' },
98 + ]);
99 + });
100 +
101 + it('drops an item whose known parameter has the wrong type', () => {
102 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version=20250114_00')).toEqual([]);
103 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version="1";deprecated="2026-05-27"')).toEqual(
104 + []
105 + );
106 + expect(parseDeprecatedToolkitsHeader('"GMAIL";version="1";reason=lifecycle')).toEqual([]);
107 + });
108 +
109 + it('rejects invalid escapes in an sf-string', () => {
110 + expect(parseDeprecatedToolkitsHeader('"GM\\nAIL";version="1"')).toEqual([]);
111 + });
112 +});
113 +
114 +describe('formatToolkitDeprecationWarnings', () => {
115 + it('renders the full message with dates and reason', () => {
116 + const [line] = formatToolkitDeprecationWarnings(
117 + parseDeprecatedToolkitsHeader(FULL_ITEM),
118 + DOCS_URL
119 + );
120 + expect(line).toBe(
121 + '[Deprecation] Toolkit GMAIL version 20250114_00 was deprecated on 2026-05-27 (lifecycle) ' +
122 + 'and will stop working on 2026-08-27. ' +
123 + "Pin a newer version with toolkitVersions: { gmail: '<version>' } or " +
124 + `COMPOSIO_TOOLKIT_VERSION_GMAIL. See ${DOCS_URL}.`
125 + );
126 + });
127 +
128 + it('omits the reason and sunset clauses when the header omits them', () => {
129 + const [line] = formatToolkitDeprecationWarnings(
130 + [entry({ slug: 'STRAVA', version: '20240902_00' })],
131 + DOCS_URL
132 + );
133 + expect(line).toBe(
134 + '[Deprecation] Toolkit STRAVA version 20240902_00 was deprecated. ' +
135 + "Pin a newer version with toolkitVersions: { strava: '<version>' } or " +
136 + `COMPOSIO_TOOLKIT_VERSION_STRAVA. See ${DOCS_URL}.`
137 + );
138 + });
139 +
140 + it('keeps the deprecation date when only the sunset is missing', () => {
141 + const [line] = formatToolkitDeprecationWarnings(
142 + [entry({ deprecatedAt: new Date(1779840000 * 1000), reason: 'security' })],
143 + DOCS_URL
144 + );
145 + expect(line).toContain('was deprecated on 2026-05-27 (security). Pin');
146 + expect(line).not.toContain('stop working');
147 + });
148 +
149 + it('defaults to the published docs anchor', () => {
150 + const [line] = formatToolkitDeprecationWarnings([entry()]);
151 + expect(line).toContain(`See ${TOOLKIT_DEPRECATION_DOCS_URL}.`);
152 + expect(TOOLKIT_DEPRECATION_DOCS_URL).toBe(
153 + 'https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset'
154 + );
155 + });
156 +
157 + it('groups six versions of one slug into one line naming five', () => {
158 + const entries = ['01', '02', '03', '04', '05', '06'].map(suffix =>
159 + entry({
160 + version: `202501${suffix}_00`,
161 + sunsetAt: new Date(Date.UTC(2026, 7, Number(suffix) + 20)),
162 + })
163 + );
164 + const lines = formatToolkitDeprecationWarnings(entries, DOCS_URL);
165 + expect(lines).toHaveLength(1);
166 + expect(lines[0]).toBe(
167 + '[Deprecation] Toolkit GMAIL versions 20250101_00, 20250102_00, 20250103_00, 20250104_00, ' +
168 + '20250105_00 and 1 more are deprecated and the earliest will stop working on 2026-08-21. ' +
169 + "Pin a newer version with toolkitVersions: { gmail: '<version>' } or " +
170 + `COMPOSIO_TOOLKIT_VERSION_GMAIL. See ${DOCS_URL}.`
171 + );
172 + });
173 +
174 + it('renders one line per slug, grouping case-insensitively', () => {
175 + const lines = formatToolkitDeprecationWarnings(
176 + [
177 + entry({ slug: 'GMAIL', version: '1' }),
178 + entry({ slug: 'STRAVA', version: '1' }),
179 + entry({ slug: 'gmail', version: '2' }),
180 + ],
181 + DOCS_URL
182 + );
183 + expect(lines).toHaveLength(2);
184 + expect(lines[0]).toContain('Toolkit GMAIL versions 1, 2 are deprecated.');
185 + expect(lines[1]).toContain('Toolkit STRAVA version 1 was deprecated.');
186 + });
187 +
188 + it('returns no lines for no entries', () => {
189 + expect(formatToolkitDeprecationWarnings([], DOCS_URL)).toEqual([]);
190 + });
191 +});
192 +
193 +describe('createToolkitDeprecationFetch', () => {
194 + const response = (headers: Record<string, string> = {}): Response =>
195 + new Response('{"ok":true}', { status: 200, headers });
196 +
197 + beforeEach(() => {
198 + _resetToolkitDeprecationWarningsForTests();
199 + vi.spyOn(logger, 'warn').mockImplementation(() => undefined);
200 + vi.spyOn(logger, 'debug').mockImplementation(() => undefined);
201 + });
202 +
203 + afterEach(() => {
204 + vi.restoreAllMocks();
205 + _resetToolkitDeprecationWarningsForTests();
206 + });
207 +
208 + it('warns once per toolkit version across calls and returns the response unchanged', async () => {
209 + const base = vi.fn(async () => response({ [TOOLKIT_DEPRECATION_HEADER]: FULL_ITEM }));
210 + const wrapped = createToolkitDeprecationFetch(base);
211 +
212 + const first = await wrapped('https://backend.composio.test/api/v3/toolkits/gmail');
213 + const second = await wrapped('https://backend.composio.test/api/v3/toolkits/gmail');
214 +
215 + expect(base).toHaveBeenCalledTimes(2);
216 + expect(logger.warn).toHaveBeenCalledTimes(1);
217 + expect(String(vi.mocked(logger.warn).mock.calls[0]?.[0])).toContain(
218 + 'GMAIL version 20250114_00'
219 + );
220 + expect(await first.json()).toEqual({ ok: true });
221 + expect(await second.json()).toEqual({ ok: true });
222 + });
223 +
224 + it('matches the header name case-insensitively', async () => {
225 + const wrapped = createToolkitDeprecationFetch(async () =>
226 + response({ 'Composio-Deprecated-Toolkits': BARE_ITEM })
227 + );
228 + await wrapped('https://backend.composio.test/api/v3/toolkits/strava');
229 + expect(logger.warn).toHaveBeenCalledTimes(1);
230 + });
231 +
232 + it('warns for a second toolkit version even after the first was deduped', async () => {
233 + const wrapped = createToolkitDeprecationFetch(async () =>
234 + response({ [TOOLKIT_DEPRECATION_HEADER]: `${FULL_ITEM}, ${BARE_ITEM}` })
235 + );
236 + await wrapped('https://backend.composio.test/a');
237 + expect(logger.warn).toHaveBeenCalledTimes(2);
238 +
239 + const next = createToolkitDeprecationFetch(async () =>
240 + response({ [TOOLKIT_DEPRECATION_HEADER]: '"GMAIL";version="20250201_00"' })
241 + );
242 + await next('https://backend.composio.test/b');
243 + expect(logger.warn).toHaveBeenCalledTimes(3);
244 + });
245 +
246 + it('does nothing without the header and swallows a malformed value', async () => {
247 + const plain = createToolkitDeprecationFetch(async () => response());
248 + const garbage = createToolkitDeprecationFetch(async () =>
249 + response({ [TOOLKIT_DEPRECATION_HEADER]: '%%% nope' })
250 + );
251 + expect(await (await plain('https://backend.composio.test/a')).json()).toEqual({ ok: true });
252 + expect(await (await garbage('https://backend.composio.test/b')).json()).toEqual({ ok: true });
253 + expect(logger.warn).not.toHaveBeenCalled();
254 + });
255 +
256 + it('warns again after the test reset helper clears the record', async () => {
257 + const wrapped = createToolkitDeprecationFetch(async () =>
258 + response({ [TOOLKIT_DEPRECATION_HEADER]: BARE_ITEM })
259 + );
260 + await wrapped('https://backend.composio.test/a');
261 + _resetToolkitDeprecationWarningsForTests();
262 + await wrapped('https://backend.composio.test/a');
263 + expect(logger.warn).toHaveBeenCalledTimes(2);
264 + });
265 +
266 + it('resolves the global fetch per call when no base fetch is given', async () => {
267 + const wrapped = createToolkitDeprecationFetch();
268 + const stub = vi.fn(async () => response({ [TOOLKIT_DEPRECATION_HEADER]: BARE_ITEM }));
269 + vi.stubGlobal('fetch', stub);
270 + try {
271 + const result = await wrapped('https://backend.composio.test/a', { method: 'GET' });
272 + expect(stub).toHaveBeenCalledWith('https://backend.composio.test/a', { method: 'GET' });
273 + expect(result.status).toBe(200);
274 + expect(logger.warn).toHaveBeenCalledTimes(1);
275 + } finally {
276 + vi.unstubAllGlobals();
277 + }
278 + });
279 +
280 + it('propagates a rejection from the underlying fetch untouched', async () => {
281 + const failure = new TypeError('fetch failed');
282 + const wrapped = createToolkitDeprecationFetch(async () => {
283 + throw failure;
284 + });
285 + await expect(wrapped('https://backend.composio.test/a')).rejects.toBe(failure);
286 + expect(logger.warn).not.toHaveBeenCalled();
287 + });
288 +
289 + it('ignores a header longer than 2048 characters and still returns the body', async () => {
290 + const oversized = `"GMAIL";version="1";reason="${'x'.repeat(2048)}"`;
291 + const wrapped = createToolkitDeprecationFetch(async () =>
292 + response({ [TOOLKIT_DEPRECATION_HEADER]: oversized })
293 + );
294 + const result = await wrapped('https://backend.composio.test/a');
295 + expect(await result.json()).toEqual({ ok: true });
296 + expect(logger.warn).not.toHaveBeenCalled();
297 + });
298 +
299 + it('ignores a header carrying a control character and still returns the body', async () => {
300 + const wrapped = createToolkitDeprecationFetch(async () =>
301 + response({ [TOOLKIT_DEPRECATION_HEADER]: '"GMAIL";version="1";reason="\u001b[2J"' })
302 + );
303 + const result = await wrapped('https://backend.composio.test/a');
304 + expect(await result.json()).toEqual({ ok: true });
305 + expect(logger.warn).not.toHaveBeenCalled();
306 + });
307 +
308 + it('stops recording new versions after 1024 keys without evicting the old ones', async () => {
309 + let version = 0;
310 + const wrapped = createToolkitDeprecationFetch(async () =>
311 + response({ [TOOLKIT_DEPRECATION_HEADER]: `"GMAIL";version="${version}"` })
312 + );
313 + const send = async (next: number) => {
314 + version = next;
315 + await wrapped('https://backend.composio.test/a');
316 + };
317 +
318 + for (let next = 1; next <= 1024; next++) await send(next);
319 + expect(logger.warn).toHaveBeenCalledTimes(1024);
320 +
321 + await send(1025);
322 + expect(logger.warn).toHaveBeenCalledTimes(1024);
323 +
324 + for (let next = 1; next <= 1024; next++) await send(next);
325 + expect(logger.warn).toHaveBeenCalledTimes(1024);
326 + });
327 +
328 + it('still resolves when the logger sink throws from both warn and debug', async () => {
329 + vi.restoreAllMocks();
330 + const throwing = () => {
331 + throw new Error('sink is broken');
332 + };
333 + const sink = { error: vi.fn(), warn: vi.fn(throwing), info: vi.fn(), debug: vi.fn(throwing) };
334 + logger.configure({ level: 'debug', sink });
335 + const wrapped = createToolkitDeprecationFetch(async () =>
336 + response({ [TOOLKIT_DEPRECATION_HEADER]: BARE_ITEM })
337 + );
338 + try {
339 + const result = await wrapped('https://backend.composio.test/a');
340 + expect(await result.json()).toEqual({ ok: true });
341 + expect(sink.warn).toHaveBeenCalledTimes(1);
342 + expect(sink.debug).toHaveBeenCalledTimes(1);
343 + } finally {
344 + logger.configure({ level: 'info', sink: console });
345 + }
346 + });
347 +
348 + it('logs at debug and still returns the response when inspecting the header throws', async () => {
349 + const broken = response({ [TOOLKIT_DEPRECATION_HEADER]: BARE_ITEM });
350 + Object.defineProperty(broken, 'headers', {
351 + get() {
352 + throw new Error('headers unavailable');
353 + },
354 + });
355 + const wrapped = createToolkitDeprecationFetch(async () => broken);
356 + const result = await wrapped('https://backend.composio.test/a');
357 + expect(result).toBe(broken);
358 + expect(logger.debug).toHaveBeenCalledTimes(1);
359 + expect(logger.warn).not.toHaveBeenCalled();
360 + });
361 +});