@devries-cameron20 / composio-1 / commits / 1afd8be91
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.

fix(experimental): never re-send a workbench tool execution (#4727)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4718 and continues https://github.com/ComposioHQ/composio/issues/3654 - stops the workbench Python helper `run_composio_tool` from re-sending `/tool_router/session/{id}/execute` after a network failure. It retried a timeout or dropped connection up to three more times, so a tool the backend had already run could repeat its side effect (e.g. send the same email twice) - keeps the helper's rate-limit retries (HTTP 429 and a rate-limit `error` in the response body), where the tool did not run - regenerates `python-helpers.generated.ts` from the `.py` source - adds a helper regression test: a timed-out execution reaches the transport exactly once, while a 429 still retries. It fails without the fix (4 calls instead of 1) - adds the missing CLI assertion that `composio execute` passes `maxRetries: 0` for meta tools (`session.executeMeta`); dropping that argument previously left every CLI test green - records the CLI no-retry behavior from #4718 in `ts/packages/cli/CHANGELOG.md` ## Context #4718 disabled retries on every SDK-client execution path, but `@composio/experimental`'s workbench helper posts to the session execute endpoint with its own retry loop, so it was not covered. Checks run locally: `@composio/experimental` tests (46 passed), `typecheck`, and `build:python-helpers`; `@composio/cli` `tools.execute.cmd.test.ts` (58 passed) and `typecheck`; prettier and oxlint on the changed files.

Alberto Schiabel committed Oct 1, 2026 at 18:10 UTC 1afd8be91bd9590de5cdf520a71c54de26d3248b
6 files changed +98 -6
.changeset/workbench-helper-no-retry.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/experimental': patch
3 +---
4 +
5 +Stop re-sending a workbench tool execution after a network failure. The Python `run_composio_tool` helper retried a timed-out or dropped request up to three more times, so a tool the backend had already run could repeat its side effect, such as sending the same email twice. It now returns the error after the first attempt; rate-limited (429) requests still retry.
ts/packages/cli/CHANGELOG.md
+4
@@ -4,6 +4,10 @@
4
5 ### Patch Changes
6
7 +- `composio execute` (including meta tools) and `composio proxy` are never
8 + retried, so a request that timed out or failed after the backend already
9 + acted cannot repeat a side effect such as sending the same email twice.
10 +
11 - API requests and command analytics now report CLI product/version, language,
12 runtime/version, and the installed API client version separately.
13
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+16
@@ -347,6 +347,14 @@ describe('CLI: composio execute', () => {
347 log_id: 'log_gmail_default',
348 };
349 },
350 + executeMeta: async (_sessionId, params, options) => {
351 + recordedExecuteOptions.push(options);
352 + return {
353 + data: { slug: params.slug, arguments: params.arguments },
354 + error: null,
355 + log_id: 'log_meta_default',
356 + };
357 + },
358 },
359 })
360 )('[Given] default alias exists [Then] execute pins the default connected account', it => {
@@ -369,6 +377,14 @@ describe('CLI: composio execute', () => {
377 })
378 );
379
380 + it.effect('never retries a meta tool execution', () =>
381 + Effect.gen(function* () {
382 + yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']);
383 +
384 + expect(recordedExecuteOptions).toEqual([{ maxRetries: 0 }]);
385 + })
386 + );
387 +
388 it.effect('asks for the latest tool version once per execute on a schema cache hit', () =>
389 Effect.gen(function* () {
390 const latestVersion = vi
ts/packages/experimental/src/workbench/python-helpers.generated.ts
+1 -1
@@ -1,4 +1,4 @@
1 // GENERATED by scripts/build-python-helpers.ts — do not edit; edit the .py source.
2 // Source: src/workbench/python-helpers/composio_helper.py
3 export const PYTHON_WORKBENCH_HELPER_SOURCE =
4 - 'import json\nimport os\nimport random\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport uuid\nfrom typing import Any, Dict, Literal, Optional\n\n\n# Config is injected by the SDK via an `_INTERNAL` dict in a prologue prepended\n# at runtime. When running this file directly (e.g. pytest), default to empty.\ntry:\n _INTERNAL\nexcept NameError:\n _INTERNAL = {}\n\n\nDEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")\nRATE_LIMIT_PATTERNS = (\n "rate limit",\n "ratelimit",\n "too many requests",\n "quota exceeded",\n "resource exhausted",\n)\n\n\ndef _read_env(name, default=None):\n value = os.environ.get(name)\n return default if value is None or value == "" else value\n\n\ndef _require_value(value, label):\n if value is None or value == "":\n raise RuntimeError("%s is required" % label)\n return value\n\n\ndef _request_id():\n return str(uuid.uuid4())\n\n\ndef _session_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/execute" % (backend_url, encoded_session_id)\n\n\ndef _session_proxy_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/proxy_execute" % (\n backend_url,\n encoded_session_id,\n )\n\n\ndef _post_json(url, headers, payload, timeout=120):\n body = json.dumps(payload).encode("utf-8")\n request = urllib.request.Request(url, data=body, headers=headers, method="POST")\n try:\n with urllib.request.urlopen(request, timeout=timeout) as response:\n return response.status, dict(response.headers), response.read().decode("utf-8")\n except urllib.error.HTTPError as error:\n return error.code, dict(error.headers), error.read().decode("utf-8")\n\n\ndef _parse_json(text):\n if not text:\n return {}\n return json.loads(text)\n\n\ndef _safe_json(text):\n try:\n return _parse_json(text)\n except json.JSONDecodeError:\n return {"raw": text}\n\n\ndef _contains_rate_limit_error(payload):\n # Only inspect the API "error" field, not the whole body — otherwise benign\n # tool output mentioning "rate limit"/"quota" triggers spurious retries.\n if not isinstance(payload, dict):\n return False\n error = payload.get("error")\n if not error:\n return False\n text = json.dumps(error, default=str).lower()\n return any(pattern in text for pattern in RATE_LIMIT_PATTERNS)\n\n\ndef _retry_delay(attempt, delay_ms):\n base_delay = max(delay_ms, 0) / 1000.0\n if base_delay == 0:\n return\n # Exponential backoff: double the delay each attempt (parity with Apollo).\n backoff = base_delay * (2 ** attempt)\n jitter = random.uniform(0, min(backoff * 0.2, 0.5))\n time.sleep(backoff + jitter)\n\n\ndef _json_shape(value):\n if isinstance(value, dict):\n return {key: _json_shape(item) for key, item in value.items()}\n if isinstance(value, list):\n return [_json_shape(value[0])] if value else []\n if value is None:\n return "null"\n return type(value).__name__\n\n\ndef print_json_structure(value):\n print(json.dumps(_json_shape(value), indent=2, sort_keys=True))\n\n\ndef _track_helper_event(*_args, **_kwargs):\n return None\n\n\ndef run_composio_tool(\n tool_slug,\n arguments=None,\n retry_params=None,\n print_schema_for_tool=True,\n *,\n account=None,\n):\n if not tool_slug:\n return {}, "tool_slug is required"\n\n api_key = _require_value(_read_env("COMPOSIO_API_KEY"), "COMPOSIO_API_KEY")\n retry_config = {"max_retries": 3, "delay_ms": 2000}\n if retry_params:\n retry_config.update(retry_params)\n\n payload = {\n "tool_slug": str(tool_slug).strip().upper(),\n "arguments": arguments or {},\n }\n if account is not None:\n payload["account"] = account\n\n headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n max_retries = int(retry_config.get("max_retries", 3))\n delay_ms = int(retry_config.get("delay_ms", 2000))\n\n for attempt in range(max_retries + 1):\n try:\n status, _headers, text = _post_json(_session_execute_url(), headers, payload)\n except (urllib.error.URLError, TimeoutError) as error:\n # Network failure (timeout, connection/DNS error). Retry transient\n # failures, then surface as the error tuple instead of throwing.\n if attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n return {}, "Composio tool request failed: %s" % error\n\n if status == 429 and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n if status >= 400:\n response_data = _safe_json(text)\n return response_data, "Composio tool execution failed with HTTP %s" % status\n\n try:\n response_data = _parse_json(text)\n except json.JSONDecodeError as error:\n return {"raw": text}, "Failed to parse Composio tool response as JSON: %s" % error\n\n if _contains_rate_limit_error(response_data) and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n # A failed tool call returns HTTP 200 with a top-level "error" field;\n # surface it as the error tuple element so callers don\'t read it as success.\n if isinstance(response_data, dict) and response_data.get("error"):\n return response_data, str(response_data["error"])\n\n if print_schema_for_tool:\n print_json_structure(response_data)\n return response_data, ""\n\n return {}, "Composio tool execution failed after retries"\n\n\ndef _strip_code_fence(content):\n stripped = content.strip()\n code_fence = chr(96) * 3\n if stripped.startswith(code_fence):\n stripped = stripped[3:].strip()\n if stripped.lower().startswith("json"):\n stripped = stripped[4:].strip()\n if stripped.endswith(code_fence):\n stripped = stripped[:-3].strip()\n elif stripped.lower().startswith("json\\n"):\n stripped = stripped[5:].strip()\n return stripped.strip()\n\n\ndef invoke_llm(query, reasoning_effort=None):\n if not query:\n return "", "query is required"\n\n system_prompt = (\n "You are a generic, smart large language model. "\n "When asked to output a JSON, respond only with valid JSON - "\n "no other text / code fences / quotes around the JSON."\n )\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_GROQ_CHAT",\n {\n "model": DEFAULT_INVOKE_LLM_MODEL,\n "messages": [\n {"role": "system", "content": system_prompt},\n {"role": "user", "content": query},\n ],\n "temperature": 0.5,\n },\n None,\n False,\n )\n _track_helper_event("invoke_llm", {"reasoning_effort": reasoning_effort})\n\n if error:\n return "", error\n\n choices = (response.get("data") or {}).get("choices", "")\n if not choices:\n return "", "No choices returned from invoke_llm"\n\n first_choice = choices[0] if isinstance(choices, list) else choices\n content = (first_choice.get("message") or {}).get("content", "")\n if not content:\n return "", "No content returned from invoke_llm"\n return _strip_code_fence(content), ""\n\n\ndef web_search(query):\n if not query:\n return "", "query is required"\n\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_EXA_ANSWER",\n {"content": query},\n None,\n False,\n )\n _track_helper_event("web_search", {})\n\n if error:\n return "", error\n return (response.get("data") or {}).get("answer", ""), ""\n\n\ndef proxy_execute(\n method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"],\n endpoint: str,\n toolkit: str,\n query_params: Optional[Dict[str, str]] = None,\n body: Optional[object] = None,\n headers: Optional[Dict[str, str]] = None,\n) -> tuple[Any, str]:\n """Call a toolkit\'s API directly when no Composio tool exists.\n\n The session resolves the connected account and injects auth server-side, so\n your code never handles raw credentials.\n\n Args:\n method: HTTP method to use for the request. Example: "GET"\n endpoint: API endpoint to call. Example: "/repos/owner/repo"\n toolkit: Name of the toolkit. Example: "GITHUB"\n query_params: Query parameters as key-value pairs. Example: {"q": "is:unread"}\n body: The request body (required for POST, PUT, and PATCH requests)\n headers: HTTP headers as key-value pairs. Example: {"Accept": "application/json"}\n\n Returns:\n tuple[Any, str]:\n - data: Response data from the API (None if error)\n - error: Error message ("" if no error)\n """\n # Wrapped end-to-end so the helper always returns a (data, error) tuple\n # rather than raising.\n try:\n valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]\n if method.upper() not in valid_methods:\n return None, "Invalid HTTP method: " + method\n\n if not endpoint.strip():\n return None, "Endpoint cannot be empty"\n\n if not toolkit.strip():\n return None, "Toolkit cannot be empty"\n\n if query_params is not None and not isinstance(query_params, dict):\n return None, (\n "Invalid query_params type: expected dict or None, got "\n + type(query_params).__name__\n )\n\n if headers is not None and not isinstance(headers, dict):\n return None, (\n "Invalid headers type: expected dict or None, got "\n + type(headers).__name__\n )\n\n if method.upper() in ["POST", "PUT", "PATCH"] and body is None:\n return None, "Body is required for " + method.upper() + " requests"\n\n if method.upper() in ["GET", "DELETE"] and body is not None:\n return None, "Body should not be provided for " + method.upper() + " requests"\n\n api_key = _read_env("COMPOSIO_API_KEY")\n if not api_key:\n return None, "Missing environment variable COMPOSIO_API_KEY"\n if not _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"):\n return None, "Missing environment variable COMPOSIO_TOOLROUTER_SESSION_ID"\n\n # Convert query_params and headers dicts to the flat parameters array.\n parameters = []\n if query_params:\n for key, value in query_params.items():\n parameters.append({"name": key, "value": str(value), "type": "query"})\n if headers:\n for key, value in headers.items():\n parameters.append({"name": key, "value": str(value), "type": "header"})\n\n payload = {\n "toolkit_slug": toolkit.lower(),\n "endpoint": endpoint,\n "method": method.upper(),\n }\n if parameters:\n payload["parameters"] = parameters\n if body is not None:\n payload["body"] = body\n\n request_headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n\n status, _response_headers, text = _post_json(\n _session_proxy_execute_url(), request_headers, payload\n )\n\n # Handle HTTP errors explicitly. Always surface a non-empty message so a\n # >=400 response never looks like success (an empty error/message field\n # must not win over the default).\n if status >= 400:\n error_msg = "HTTP " + str(status) + " Error"\n try:\n error_data = json.loads(text)\n if isinstance(error_data, dict):\n error_msg = (\n error_data.get("error") or error_data.get("message") or error_msg\n )\n except (ValueError, TypeError):\n if text:\n sanitized = text[:200].replace("\\n", " ").strip()\n error_msg = "HTTP " + str(status) + ": " + sanitized\n return None, str(error_msg)\n\n response_data = json.loads(text)\n\n # The session wraps the proxied response as {data, status, headers}; the\n # toolkit\'s own API may still report a >=400 status inside that envelope.\n # `status` can arrive as a string or null, so coerce it before comparing\n # — a bare `>= 400` against a non-int would raise and mask a valid result.\n if isinstance(response_data, dict):\n try:\n api_status = int(response_data.get("status", 200))\n except (TypeError, ValueError):\n api_status = 200\n if api_status >= 400:\n error_msg = "API request failed"\n if isinstance(response_data.get("data"), dict):\n error_msg = response_data["data"].get(\n "message", response_data["data"].get("error", error_msg)\n )\n return response_data, "API returned status " + str(api_status) + ": " + str(error_msg)\n return response_data.get("data"), ""\n\n return response_data, ""\n except Exception as error:\n return None, "Failed to execute proxy request: " + str(error)\n';
4 + 'import json\nimport os\nimport random\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport uuid\nfrom typing import Any, Dict, Literal, Optional\n\n\n# Config is injected by the SDK via an `_INTERNAL` dict in a prologue prepended\n# at runtime. When running this file directly (e.g. pytest), default to empty.\ntry:\n _INTERNAL\nexcept NameError:\n _INTERNAL = {}\n\n\nDEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")\nRATE_LIMIT_PATTERNS = (\n "rate limit",\n "ratelimit",\n "too many requests",\n "quota exceeded",\n "resource exhausted",\n)\n\n\ndef _read_env(name, default=None):\n value = os.environ.get(name)\n return default if value is None or value == "" else value\n\n\ndef _require_value(value, label):\n if value is None or value == "":\n raise RuntimeError("%s is required" % label)\n return value\n\n\ndef _request_id():\n return str(uuid.uuid4())\n\n\ndef _session_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/execute" % (backend_url, encoded_session_id)\n\n\ndef _session_proxy_execute_url():\n backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")\n session_id = _require_value(\n _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),\n "COMPOSIO_TOOLROUTER_SESSION_ID",\n )\n encoded_session_id = urllib.parse.quote(session_id, safe="")\n return "%s/api/v3/tool_router/session/%s/proxy_execute" % (\n backend_url,\n encoded_session_id,\n )\n\n\ndef _post_json(url, headers, payload, timeout=120):\n body = json.dumps(payload).encode("utf-8")\n request = urllib.request.Request(url, data=body, headers=headers, method="POST")\n try:\n with urllib.request.urlopen(request, timeout=timeout) as response:\n return response.status, dict(response.headers), response.read().decode("utf-8")\n except urllib.error.HTTPError as error:\n return error.code, dict(error.headers), error.read().decode("utf-8")\n\n\ndef _parse_json(text):\n if not text:\n return {}\n return json.loads(text)\n\n\ndef _safe_json(text):\n try:\n return _parse_json(text)\n except json.JSONDecodeError:\n return {"raw": text}\n\n\ndef _contains_rate_limit_error(payload):\n # Only inspect the API "error" field, not the whole body — otherwise benign\n # tool output mentioning "rate limit"/"quota" triggers spurious retries.\n if not isinstance(payload, dict):\n return False\n error = payload.get("error")\n if not error:\n return False\n text = json.dumps(error, default=str).lower()\n return any(pattern in text for pattern in RATE_LIMIT_PATTERNS)\n\n\ndef _retry_delay(attempt, delay_ms):\n base_delay = max(delay_ms, 0) / 1000.0\n if base_delay == 0:\n return\n # Exponential backoff: double the delay each attempt (parity with Apollo).\n backoff = base_delay * (2 ** attempt)\n jitter = random.uniform(0, min(backoff * 0.2, 0.5))\n time.sleep(backoff + jitter)\n\n\ndef _json_shape(value):\n if isinstance(value, dict):\n return {key: _json_shape(item) for key, item in value.items()}\n if isinstance(value, list):\n return [_json_shape(value[0])] if value else []\n if value is None:\n return "null"\n return type(value).__name__\n\n\ndef print_json_structure(value):\n print(json.dumps(_json_shape(value), indent=2, sort_keys=True))\n\n\ndef _track_helper_event(*_args, **_kwargs):\n return None\n\n\ndef run_composio_tool(\n tool_slug,\n arguments=None,\n retry_params=None,\n print_schema_for_tool=True,\n *,\n account=None,\n):\n if not tool_slug:\n return {}, "tool_slug is required"\n\n api_key = _require_value(_read_env("COMPOSIO_API_KEY"), "COMPOSIO_API_KEY")\n retry_config = {"max_retries": 3, "delay_ms": 2000}\n if retry_params:\n retry_config.update(retry_params)\n\n payload = {\n "tool_slug": str(tool_slug).strip().upper(),\n "arguments": arguments or {},\n }\n if account is not None:\n payload["account"] = account\n\n headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n max_retries = int(retry_config.get("max_retries", 3))\n delay_ms = int(retry_config.get("delay_ms", 2000))\n\n for attempt in range(max_retries + 1):\n try:\n status, _headers, text = _post_json(_session_execute_url(), headers, payload)\n except (urllib.error.URLError, TimeoutError) as error:\n # Network failure (timeout, connection/DNS error). Never retry it:\n # the backend may already have run the tool and does not deduplicate\n # executions, so re-sending can repeat the side effect. Surface it as\n # the error tuple instead of throwing.\n return {}, "Composio tool request failed: %s" % error\n\n if status == 429 and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n if status >= 400:\n response_data = _safe_json(text)\n return response_data, "Composio tool execution failed with HTTP %s" % status\n\n try:\n response_data = _parse_json(text)\n except json.JSONDecodeError as error:\n return {"raw": text}, "Failed to parse Composio tool response as JSON: %s" % error\n\n if _contains_rate_limit_error(response_data) and attempt < max_retries:\n _retry_delay(attempt, delay_ms)\n continue\n\n # A failed tool call returns HTTP 200 with a top-level "error" field;\n # surface it as the error tuple element so callers don\'t read it as success.\n if isinstance(response_data, dict) and response_data.get("error"):\n return response_data, str(response_data["error"])\n\n if print_schema_for_tool:\n print_json_structure(response_data)\n return response_data, ""\n\n return {}, "Composio tool execution failed after retries"\n\n\ndef _strip_code_fence(content):\n stripped = content.strip()\n code_fence = chr(96) * 3\n if stripped.startswith(code_fence):\n stripped = stripped[3:].strip()\n if stripped.lower().startswith("json"):\n stripped = stripped[4:].strip()\n if stripped.endswith(code_fence):\n stripped = stripped[:-3].strip()\n elif stripped.lower().startswith("json\\n"):\n stripped = stripped[5:].strip()\n return stripped.strip()\n\n\ndef invoke_llm(query, reasoning_effort=None):\n if not query:\n return "", "query is required"\n\n system_prompt = (\n "You are a generic, smart large language model. "\n "When asked to output a JSON, respond only with valid JSON - "\n "no other text / code fences / quotes around the JSON."\n )\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_GROQ_CHAT",\n {\n "model": DEFAULT_INVOKE_LLM_MODEL,\n "messages": [\n {"role": "system", "content": system_prompt},\n {"role": "user", "content": query},\n ],\n "temperature": 0.5,\n },\n None,\n False,\n )\n _track_helper_event("invoke_llm", {"reasoning_effort": reasoning_effort})\n\n if error:\n return "", error\n\n choices = (response.get("data") or {}).get("choices", "")\n if not choices:\n return "", "No choices returned from invoke_llm"\n\n first_choice = choices[0] if isinstance(choices, list) else choices\n content = (first_choice.get("message") or {}).get("content", "")\n if not content:\n return "", "No content returned from invoke_llm"\n return _strip_code_fence(content), ""\n\n\ndef web_search(query):\n if not query:\n return "", "query is required"\n\n response, error = run_composio_tool(\n "COMPOSIO_SEARCH_EXA_ANSWER",\n {"content": query},\n None,\n False,\n )\n _track_helper_event("web_search", {})\n\n if error:\n return "", error\n return (response.get("data") or {}).get("answer", ""), ""\n\n\ndef proxy_execute(\n method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"],\n endpoint: str,\n toolkit: str,\n query_params: Optional[Dict[str, str]] = None,\n body: Optional[object] = None,\n headers: Optional[Dict[str, str]] = None,\n) -> tuple[Any, str]:\n """Call a toolkit\'s API directly when no Composio tool exists.\n\n The session resolves the connected account and injects auth server-side, so\n your code never handles raw credentials.\n\n Args:\n method: HTTP method to use for the request. Example: "GET"\n endpoint: API endpoint to call. Example: "/repos/owner/repo"\n toolkit: Name of the toolkit. Example: "GITHUB"\n query_params: Query parameters as key-value pairs. Example: {"q": "is:unread"}\n body: The request body (required for POST, PUT, and PATCH requests)\n headers: HTTP headers as key-value pairs. Example: {"Accept": "application/json"}\n\n Returns:\n tuple[Any, str]:\n - data: Response data from the API (None if error)\n - error: Error message ("" if no error)\n """\n # Wrapped end-to-end so the helper always returns a (data, error) tuple\n # rather than raising.\n try:\n valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]\n if method.upper() not in valid_methods:\n return None, "Invalid HTTP method: " + method\n\n if not endpoint.strip():\n return None, "Endpoint cannot be empty"\n\n if not toolkit.strip():\n return None, "Toolkit cannot be empty"\n\n if query_params is not None and not isinstance(query_params, dict):\n return None, (\n "Invalid query_params type: expected dict or None, got "\n + type(query_params).__name__\n )\n\n if headers is not None and not isinstance(headers, dict):\n return None, (\n "Invalid headers type: expected dict or None, got "\n + type(headers).__name__\n )\n\n if method.upper() in ["POST", "PUT", "PATCH"] and body is None:\n return None, "Body is required for " + method.upper() + " requests"\n\n if method.upper() in ["GET", "DELETE"] and body is not None:\n return None, "Body should not be provided for " + method.upper() + " requests"\n\n api_key = _read_env("COMPOSIO_API_KEY")\n if not api_key:\n return None, "Missing environment variable COMPOSIO_API_KEY"\n if not _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"):\n return None, "Missing environment variable COMPOSIO_TOOLROUTER_SESSION_ID"\n\n # Convert query_params and headers dicts to the flat parameters array.\n parameters = []\n if query_params:\n for key, value in query_params.items():\n parameters.append({"name": key, "value": str(value), "type": "query"})\n if headers:\n for key, value in headers.items():\n parameters.append({"name": key, "value": str(value), "type": "header"})\n\n payload = {\n "toolkit_slug": toolkit.lower(),\n "endpoint": endpoint,\n "method": method.upper(),\n }\n if parameters:\n payload["parameters"] = parameters\n if body is not None:\n payload["body"] = body\n\n request_headers = {\n "Content-Type": "application/json",\n "x-api-key": api_key,\n "x-request-id": _request_id(),\n }\n\n status, _response_headers, text = _post_json(\n _session_proxy_execute_url(), request_headers, payload\n )\n\n # Handle HTTP errors explicitly. Always surface a non-empty message so a\n # >=400 response never looks like success (an empty error/message field\n # must not win over the default).\n if status >= 400:\n error_msg = "HTTP " + str(status) + " Error"\n try:\n error_data = json.loads(text)\n if isinstance(error_data, dict):\n error_msg = (\n error_data.get("error") or error_data.get("message") or error_msg\n )\n except (ValueError, TypeError):\n if text:\n sanitized = text[:200].replace("\\n", " ").strip()\n error_msg = "HTTP " + str(status) + ": " + sanitized\n return None, str(error_msg)\n\n response_data = json.loads(text)\n\n # The session wraps the proxied response as {data, status, headers}; the\n # toolkit\'s own API may still report a >=400 status inside that envelope.\n # `status` can arrive as a string or null, so coerce it before comparing\n # — a bare `>= 400` against a non-int would raise and mask a valid result.\n if isinstance(response_data, dict):\n try:\n api_status = int(response_data.get("status", 200))\n except (TypeError, ValueError):\n api_status = 200\n if api_status >= 400:\n error_msg = "API request failed"\n if isinstance(response_data.get("data"), dict):\n error_msg = response_data["data"].get(\n "message", response_data["data"].get("error", error_msg)\n )\n return response_data, "API returned status " + str(api_status) + ": " + str(error_msg)\n return response_data.get("data"), ""\n\n return response_data, ""\n except Exception as error:\n return None, "Failed to execute proxy request: " + str(error)\n';
ts/packages/experimental/src/workbench/python-helpers/composio_helper.py
+4 -5
@@ -163,11 +163,10 @@ def run_composio_tool(
163 try:
164 status, _headers, text = _post_json(_session_execute_url(), headers, payload)
165 except (urllib.error.URLError, TimeoutError) as error:
166 - # Network failure (timeout, connection/DNS error). Retry transient
167 - # failures, then surface as the error tuple instead of throwing.
168 - if attempt < max_retries:
169 - _retry_delay(attempt, delay_ms)
170 - continue
166 + # Network failure (timeout, connection/DNS error). Never retry it:
167 + # the backend may already have run the tool and does not deduplicate
168 + # executions, so re-sending can repeat the side effect. Surface it as
169 + # the error tuple instead of throwing.
170 return {}, "Composio tool request failed: %s" % error
171
172 if status == 429 and attempt < max_retries:
ts/packages/experimental/test/workbench/shim.test.ts
+68
@@ -107,6 +107,74 @@ print(_json.dumps({
107 }
108 });
109
110 + it('never re-sends a tool execution after a network failure', () => {
111 + const source = experimental_createPythonWorkbenchHelperSource();
112 + const directory = mkdtempSync(join(tmpdir(), 'composio-helper-'));
113 + const scriptPath = join(directory, 'helper_retry_test.py');
114 + const testScript = `${source}
115 +
116 +import json as _json
117 +
118 +_timeout_calls = []
119 +
120 +def _post_json_timeout(url, headers, payload, timeout=120):
121 + # The backend may already have run the tool when the read times out.
122 + _timeout_calls.append(payload)
123 + raise TimeoutError("timed out")
124 +
125 +_post_json = _post_json_timeout
126 +timeout_data, timeout_error = run_composio_tool(
127 + "gmail_send_email", {"to": "a@example.com"}, {"delay_ms": 0}, False
128 +)
129 +
130 +_rate_limit_calls = []
131 +
132 +def _post_json_rate_limited(url, headers, payload, timeout=120):
133 + # A 429 is rejected before the tool runs, so it stays safe to retry.
134 + _rate_limit_calls.append(payload)
135 + if len(_rate_limit_calls) == 1:
136 + return 429, {}, _json.dumps({"error": "rate limited"})
137 + return 200, {}, _json.dumps({"data": {"ok": True}})
138 +
139 +_post_json = _post_json_rate_limited
140 +rate_limit_data, rate_limit_error = run_composio_tool(
141 + "gmail_send_email", {"to": "a@example.com"}, {"delay_ms": 0}, False
142 +)
143 +
144 +print(_json.dumps({
145 + "timeout_calls": len(_timeout_calls),
146 + "timeout_data": timeout_data,
147 + "timeout_error": timeout_error,
148 + "rate_limit_calls": len(_rate_limit_calls),
149 + "rate_limit_data": rate_limit_data,
150 + "rate_limit_error": rate_limit_error,
151 +}))
152 +`;
153 +
154 + try {
155 + writeFileSync(scriptPath, testScript);
156 + const output = execFileSync('python3', [scriptPath], {
157 + env: {
158 + ...process.env,
159 + BACKEND_URL: 'https://backend.test/',
160 + COMPOSIO_TOOLROUTER_SESSION_ID: 'session_123',
161 + COMPOSIO_API_KEY: 'project_key',
162 + },
163 + encoding: 'utf8',
164 + });
165 + const parsed = JSON.parse(output);
166 +
167 + expect(parsed.timeout_calls).toBe(1);
168 + expect(parsed.timeout_data).toEqual({});
169 + expect(parsed.timeout_error).toContain('Composio tool request failed');
170 + expect(parsed.rate_limit_calls).toBe(2);
171 + expect(parsed.rate_limit_data).toEqual({ data: { ok: true } });
172 + expect(parsed.rate_limit_error).toBe('');
173 + } finally {
174 + rmSync(directory, { recursive: true, force: true });
175 + }
176 + });
177 +
178 it('round-trips helper calls through the session execute endpoint shape', () => {
179 const source = experimental_createPythonWorkbenchHelperSource({
180 invokeLlmModel: 'test/model',