@devries-cameron20 / composio Mirror · read-only / commits / a79c4b309
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, 07:15 UTC

docs: replace migration script with coding agent prompt

shashwatsnghcomposio committed Oct 29, 2026 at 10:50 UTC a79c4b309c10025c36d8f94eaabc5581ce9af881
7 files changed +44 -400
docs/AGENTS.md
-1
@@ -35,7 +35,6 @@ bun run check:code-examples
35 bun run check:api-snippets
36 bun run check:python-snippets
37 bun run test:python-snippets
38 -bun run test:migration-helper
38 bun run check:typescript-snippets
39 bun run inventory:code-examples
40 ```
docs/content/docs/migration-guide/no-auth-to-instant.mdx
+42 -67
@@ -4,14 +4,12 @@ description: Move shared-access workflows to Instant with your existing agents a
4 keywords: [No Auth, Instant, migration, Sessions, shared access]
5 ---
6
7 -From **13 November 2026**, the No Auth and shared-access routes for the toolkits below are being retired. This change supports growing usage while maintaining performance and quality for web search, browsing and AI tools via Composio.
7 +Move affected shared-access workflows to Instant before **13 November 2026**. On that date, Composio retires the No Auth and shared-access routes listed below.
8
9 -[Instant](/docs/instant-tools) replaces them. It runs supported tools on Composio's provider accounts and charges your organization's Composio balance, so your users don't need their own provider credentials for those tools.
9 +Use [Instant Tools](/docs/instant-tools) for supported actions, or provider credentials connected by your users where the toolkit supports them. This guide is for existing developer-platform integrations.
10
11 ## Choose a replacement
12
13 -All changes in this table take effect on **13 November 2026** for the developer platform.
14 -
13 | Toolkit | Change | Migration path |
14 | --- | --- | --- |
15 | Gemini (`gemini`) | No Auth/shared-key access ends; the toolkit remains | Use supported Gemini Instant tools or credentials connected by your users. |
@@ -22,57 +20,21 @@ All changes in this table take effect on **13 November 2026** for the developer
20 | WeatherMap (`weathermap`) | Toolkit removed | Use supported AccuWeather (`accu_weather`) Instant tools and update requests and response handling. |
21 | SeatGeek (`seat_geek`) | No Auth/shared-key access ends | SeatGeek will be available through Composio Instant. |
22
25 -These alternatives aren't interchangeable APIs, and Instant support is per tool. [Check each tool's support, rate, and input schema](/docs/instant-tools#find-supported-tools-and-rates) before replacing it.
23 +Instant support is per tool. [Check each tool's support, rate, and input schema](/docs/instant-tools#find-supported-tools-and-rates) before replacing it.
24
27 -## Update your Session
25 +## What carries over
26
29 -First, [enable Instant and check your organization's balance](/docs/instant-tools#enable-instant). If your agent already uses Sessions, keep your agent integration and change only the affected toolkit references.
27 +Keep your agent integration, application user IDs, and unaffected toolkits and connections. If you already use Sessions, you don't need to migrate to a different execution model.
28
31 -For example, replace the legacy `composio_search` toolkit with `exa`:
29 +## Update your application
30
33 -<Tabs groupId="language" items={['Python', 'TypeScript', 'API']} persist>
34 -<Tab value="Python">
35 -```python
36 -from composio import Composio
31 +First, [enable Instant and check your organization's balance](/docs/instant-tools#enable-instant). Then replace affected toolkit references, tool names, arguments, and response handling in your application.
32
38 -composio = Composio()
39 -session = composio.sessions.create(
40 - user_id="user_123",
41 - toolkits=["exa"],
42 -)
43 -tools = session.tools()
44 -```
45 -</Tab>
46 -<Tab value="TypeScript">
47 -```typescript
48 -import { Composio } from "@composio/core";
49 -
50 -const composio = new Composio();
51 -const session = await composio.create("user_123", {
52 - toolkits: ["exa"],
53 -});
54 -const tools = await session.tools();
55 -```
56 -</Tab>
57 -<Tab value="API">
58 -```bash
59 -SESSION_ID=$(curl -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
60 - -H "x-api-key: $COMPOSIO_API_KEY" \
61 - -H "Content-Type: application/json" \
62 - -d '{"user_id":"user_123","toolkits":{"enable":["exa"]}}' \
63 - | jq -r '.session_id')
64 -
65 -curl -X GET https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/tools \
66 - -H "x-api-key: $COMPOSIO_API_KEY"
67 -```
68 -</Tab>
69 -</Tabs>
33 +For example, replace `composio_search` with `exa` in your Session's toolkit filter, choose the replacement search action, and update any tool restrictions. Keep the other toolkits your agent needs. Use the existing [Session and agent examples](/docs/instant-tools#report-charges-and-use-instant-tools) for your framework.
34
71 -Pass `tools` to your existing agent as usual, using your framework's [provider adapter](/docs/providers). Keep your other required toolkits in the `toolkits` list.
35 +If your Session already permits eligible Instant tools, keep that policy. If it disables Instant, restricts it to other tools, or selects a provider account explicitly, follow [Control Instant usage](/docs/instant-tools#control-instant-usage) and [Know which account runs the tool](/docs/instant-tools#know-which-account-runs-the-tool).
36
73 -You don't need to add an `instant` setting; Sessions permit eligible Instant usage by default. If your Session sets `instant=false`, restricts Instant to other toolkits, or selects a provider account explicitly, update that policy. See [Control Instant usage](/docs/instant-tools#control-instant-usage) and [Know which account runs the tool](/docs/instant-tools#know-which-account-runs-the-tool).
74 -
75 -Enabling Instant doesn't rewrite tool slugs, arguments, or response handling. Update or recreate existing Sessions that still reference retired toolkits, and update saved Session configurations so future Sessions use the replacements.
37 +Update or recreate existing Sessions that reference retired toolkits, and update saved configurations for future Sessions. Enabling Instant doesn't rewrite these references.
38
39 ## If you call tools directly
40
@@ -91,24 +53,37 @@ Alternatively, follow [Migrate from Direct Tools to Sessions](/docs/migration-gu
53
54 After the cutoff, affected legacy executions will stop working. If you need help mapping a tool or adapting a workflow, contact [support@composio.dev](mailto:support@composio.dev).
55
94 -## Optional Session setup helper
95 -
96 -[Download the Python helper](/assets/migrations/migrate_no_auth_to_instant.py) to preview and create a replacement Session with explicit toolkit and tool allowlists. It requires Python 3.10 or later and uses only the standard library. It is for Sessions only.
97 -
98 -Save the file locally, inspect it, then preview a request:
99 -
100 -```bash
101 -python3 migrate_no_auth_to_instant.py --user-id user_123 --tool exa:EXA_SEARCH
102 -```
103 -
104 -Use your existing application user ID and repeat `--tool toolkit:TOOL_SLUG` for each required tool. The preview makes no network requests. The helper doesn't guess equivalents for retired tools or adapt their arguments and responses.
105 -
106 -After enabling Instant for the intended project, set `COMPOSIO_API_KEY` for that project. Review the selected tools and their published rates, then create the replacement Session:
107 -
108 -```bash
109 -python3 migrate_no_auth_to_instant.py --user-id user_123 --tool exa:EXA_SEARCH --apply
56 +## Migrate with your coding agent
57 +
58 +Open your application repository in your coding agent and paste this prompt. The prompt asks the agent to inspect your integration, update its code, and verify the affected workflows.
59 +
60 +```text
61 +Migrate this repository's affected Composio No Auth/shared-access workflows
62 +before 13 November 2026.
63 +
64 +Read these guides first:
65 +https://docs.composio.dev/docs/migration-guide/no-auth-to-instant
66 +https://docs.composio.dev/docs/instant-tools
67 +
68 +1. Inspect the repository and installed SDK version. Find affected toolkit
69 + and tool references in application code, saved configurations, tests,
70 + Session policies, and direct-execution version settings. Show the files
71 + and proposed replacements before editing.
72 +2. Check each replacement action's current schema, Instant eligibility, and
73 + published rate. Use the migration guide's toolkit mapping. Report missing
74 + coverage or unavailable replacements instead of guessing tool names.
75 +3. Update the affected code and tests. Preserve the current execution model,
76 + application user IDs, unrelated toolkits, and existing user connections.
77 + Adapt arguments and response handling to each replacement action. Follow
78 + the Instant guide for Session policies or direct-execution account selection.
79 +4. Run relevant local tests. Identify existing Sessions or project settings
80 + that need a separate update. Before creating or changing remote resources,
81 + or running paid tools, confirm the target project, test scope, and budget
82 + with me. Never print or commit credentials.
83 +5. Summarize the diff, tests run, remaining manual steps, and coverage gaps.
84 + Distinguish mocked tests from live execution. For any authorized live test,
85 + check execution logs for the credential source and charge. Do not claim
86 + migration is complete while affected workflows remain unverified.
87 ```
88
112 -`--apply` checks each tool's current identity, Instant support and published rate, then creates one Session. It doesn't run provider tools, edit existing Sessions, change project settings, or rewrite your application. Use the returned Session ID in your application and test the workflow separately.
113 -
114 -If creation times out or returns an ambiguous server error, check your project before trying again. The helper never retries automatically.
89 +Review the diff and the [verification checklist](#verify-before-the-cutoff) before deploying the changes.
docs/package.json
-1
@@ -40,7 +40,6 @@
40 "check:api-snippets": "bun scripts/check-api-snippets.ts",
41 "check:python-snippets": "bun scripts/check-python-snippets.ts",
42 "test:python-snippets": "bun scripts/python-snippets/test-helper.ts",
43 - "test:migration-helper": "python3 -I tests/migrations/test_migrate_no_auth_to_instant.py",
43 "check:typescript-snippets": "bun scripts/check-typescript-snippets.ts",
44 "pretest": "bun run generate:kb",
45 "test": "bun test tests/static/",
docs/public/assets/migrations/migrate_no_auth_to_instant.py deleted
-135
@@ -1,135 +0,0 @@
1 -#!/usr/bin/env python3
2 -"""Preview or create a replacement Session with explicitly selected Instant tools.
3 -
4 -Default: print a plan, with no network requests. --apply reads COMPOSIO_API_KEY,
5 -verifies current tool metadata, and creates one Session. No provider tool runs.
6 -"""
7 -import argparse
8 -import http.client
9 -import json
10 -import os
11 -import re
12 -import sys
13 -import urllib.error
14 -import urllib.parse
15 -import urllib.request
16 -
17 -BASE = "https://backend.composio.dev"
18 -RETIRED = {
19 - "browser_tool": "Choose supported browser_use tools.",
20 - "composio_search": "Choose supported exa, tavily, or serpapi tools.",
21 - "text_to_pdf": "Choose supported pdf_co tools. PDF.co Instant supports URL-based conversion.",
22 - "weathermap": "Choose supported accu_weather tools and adapt arguments and responses.",
23 -}
24 -
25 -
26 -def selected_tools(values):
27 - selected = {}
28 - for value in values:
29 - parts = value.split(":")
30 - if len(parts) != 2:
31 - raise ValueError("Each --tool must be TOOLKIT:TOOL_SLUG, for example exa:EXA_SEARCH.")
32 - toolkit, slug = parts
33 - if not re.fullmatch(r"[a-z][a-z0-9_]*", toolkit) or not re.fullmatch(r"[A-Z][A-Z0-9_]*", slug):
34 - raise ValueError("Use an exact lowercase toolkit slug and uppercase tool slug.")
35 - if toolkit in RETIRED:
36 - raise ValueError(toolkit + ": " + RETIRED[toolkit])
37 - if slug in selected.setdefault(toolkit, []):
38 - raise ValueError("Duplicate tool: " + value)
39 - if any(slug in tools for name, tools in selected.items() if name != toolkit):
40 - raise ValueError("A tool slug cannot be assigned to multiple toolkits.")
41 - selected[toolkit].append(slug)
42 - return {name: sorted(tools) for name, tools in sorted(selected.items())}
43 -
44 -
45 -def make_payload(user_id, selected):
46 - filters = {name: {"enable": tools} for name, tools in selected.items()}
47 - return {
48 - "user_id": user_id,
49 - "toolkits": {"enable": list(selected)},
50 - "tools": filters,
51 - "instant": {"toolkits": {"enable": list(selected)}, "tools": filters},
52 - }
53 -
54 -
55 -def request(method, path, key, body=None):
56 - data = None if body is None else json.dumps(body).encode("utf-8")
57 - req = urllib.request.Request(
58 - BASE + path,
59 - data=data,
60 - method=method,
61 - headers={"x-api-key": key, "Content-Type": "application/json"},
62 - )
63 - try:
64 - with urllib.request.urlopen(req, timeout=30) as response:
65 - return json.load(response)
66 - except urllib.error.HTTPError as error:
67 - if method == "POST" and (error.code >= 500 or error.code in (408, 429)):
68 - raise RuntimeError(f"POST returned HTTP {error.code}. Session creation outcome is unknown. Check your project before trying again. No automatic retry was made.") from None
69 - raise RuntimeError(f"{method} returned HTTP {error.code}. Check the project and permissions; no retry was made.") from None
70 - except (OSError, TimeoutError, http.client.HTTPException, json.JSONDecodeError, UnicodeError):
71 - message = "Session creation outcome is unknown. Check your project before trying again." if method == "POST" else "Metadata could not be read. No Session was created."
72 - raise RuntimeError(message + " No automatic retry was made.") from None
73 -
74 -
75 -def verify_tools(selected, key):
76 - for toolkit, slugs in selected.items():
77 - for slug in slugs:
78 - path = "/api/v3.1/tools/" + urllib.parse.quote(slug, safe="") + "?toolkit_versions=latest&include_pricing=true"
79 - tool = request("GET", path, key)
80 - if not isinstance(tool, dict):
81 - raise RuntimeError("Unexpected tool metadata; no Session was created.")
82 - toolkit_info = tool.get("toolkit")
83 - if not isinstance(toolkit_info, dict) or tool.get("slug") != slug or toolkit_info.get("slug") != toolkit:
84 - raise RuntimeError("Tool identity mismatch for " + slug + "; no Session was created.")
85 - instant = tool.get("instant") or {}
86 - if not isinstance(instant, dict) or instant.get("supported") is not True:
87 - raise RuntimeError(slug + " does not currently report Instant support; no Session was created.")
88 - price = instant.get("price") or {}
89 - if not isinstance(price, dict):
90 - raise RuntimeError("Invalid published price for " + slug + "; no Session was created.")
91 - description = price.get("description")
92 - if not isinstance(description, str) or not description.strip():
93 - raise RuntimeError("Missing published price for " + slug + "; no Session was created.")
94 - print(slug + ": " + description)
95 - if price.get("discount") is not None:
96 - print("Published discount: " + str(price["discount"]))
97 -
98 -
99 -def main(argv=None):
100 - parser = argparse.ArgumentParser(description=__doc__)
101 - parser.add_argument("--user-id", required=True, help="Your application's existing user ID.")
102 - parser.add_argument("--tool", action="append", required=True, help="Exact TOOLKIT:TOOL_SLUG; repeat for each allowed tool.")
103 - parser.add_argument("--apply", action="store_true", help="Verify metadata and create one replacement Session. Does not execute tools.")
104 - args = parser.parse_args(argv)
105 - if not args.user_id.strip():
106 - parser.error("--user-id must not be empty")
107 - try:
108 - selected = selected_tools(args.tool)
109 - except ValueError as error:
110 - parser.error(str(error))
111 - payload = make_payload(args.user_id, selected)
112 - print(json.dumps({"method": "POST", "url": BASE + "/api/v3.1/tool_router/session", "body": payload}, indent=2))
113 - if not args.apply:
114 - print("Preview only. No network requests made. Review tool schemas and published rates before using --apply.")
115 - return 0
116 - key = os.environ.get("COMPOSIO_API_KEY", "")
117 - if not key:
118 - parser.error("Set COMPOSIO_API_KEY for the intended project before using --apply.")
119 - try:
120 - verify_tools(selected, key)
121 - result = request("POST", "/api/v3.1/tool_router/session", key, payload)
122 - except RuntimeError as error:
123 - print(str(error), file=sys.stderr)
124 - return 1
125 - session_id = result.get("session_id") if isinstance(result, dict) else None
126 - if not isinstance(session_id, str) or not session_id:
127 - print("Session creation response did not include session_id. Outcome is unknown; inspect your project before retrying.", file=sys.stderr)
128 - return 1
129 - print("Created replacement Session: " + session_id)
130 - print("Use this Session in your application. Existing Sessions and application code were not changed. No provider tool was executed.")
131 - return 0
132 -
133 -
134 -if __name__ == "__main__":
135 - sys.exit(main())
docs/scripts/validate-links.ts
+2 -26
@@ -1,7 +1,6 @@
1 -import { statSync } from 'node:fs';
1 import { readFile } from 'node:fs/promises';
2 import { glob } from 'node:fs/promises';
4 -import { relative, resolve } from 'node:path';
3 +import { resolve } from 'node:path';
4 import { type FileObject, printErrors, scanURLs, validateFiles } from 'next-validate-link';
5 import GithubSlugger from 'github-slugger';
6 import { z } from 'zod';
@@ -31,29 +30,6 @@ type AnySource =
30
31 type PageOf = ReturnType<AnySource['getPages']>[number];
32
34 -/**
35 - * Static files in `public/` (such as downloadable `/assets/...` helpers) are
36 - * served at the site root but aren't pages, so `scanURLs` doesn't know them.
37 - */
38 -export function isPublicFileUrl(url: string, publicDir = 'public'): boolean {
39 - if (!url.startsWith('/') || url.startsWith('//')) return false;
40 - let pathname: string;
41 - try {
42 - pathname = decodeURI(url.split(/[?#]/, 1)[0]);
43 - } catch {
44 - return false;
45 - }
46 - const root = resolve(publicDir);
47 - const target = resolve(root, '.' + pathname);
48 - const inside = relative(root, target);
49 - if (!inside || inside.startsWith('..')) return false;
50 - try {
51 - return statSync(target, { throwIfNoEntry: false })?.isFile() ?? false;
52 - } catch {
53 - return false;
54 - }
55 -}
56 -
33 export function withoutFrontmatter(content: string): string {
34 return content.replace(/^(?:\uFEFF)?---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
35 }
@@ -273,7 +249,7 @@ async function checkLinks() {
249 const filteredErrors = errors
250 .map(fileError => ({
251 ...fileError,
276 - errors: fileError.errors.filter(e => !ignoredUrls.includes(e.url) && !isPublicFileUrl(e.url)),
252 + errors: fileError.errors.filter(e => !ignoredUrls.includes(e.url)),
253 detected: fileError.detected.filter(d => !ignoredUrls.includes(d[0] as string)),
254 }))
255 .filter(fileError => fileError.errors.length > 0);
docs/tests/migrations/test_migrate_no_auth_to_instant.py deleted
-158
@@ -1,158 +0,0 @@
1 -"""Offline regression and randomized tests for the downloadable No Auth migration helper.
2 -
3 -HTTP is mocked; no Composio or provider requests are made.
4 -Run from docs/: bun run test:migration-helper
5 -"""
6 -import contextlib, http.client, importlib.util, io, json, os, pathlib, random, socket, string, sys, unittest, urllib.error
7 -from unittest import mock
8 -
9 -sys.dont_write_bytecode = True
10 -PATH = pathlib.Path(__file__).resolve().parents[2] / "public/assets/migrations/migrate_no_auth_to_instant.py"
11 -spec = importlib.util.spec_from_file_location("helper", PATH)
12 -helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper)
13 -
14 -
15 -class Resp(io.BytesIO):
16 - def __enter__(self): return self
17 - def __exit__(self, *a): self.close()
18 -
19 -
20 -def tool_meta(slug, toolkit, supported=True, price="$0.01 per call", discount=None):
21 - t = {"slug": slug, "toolkit": {"slug": toolkit}}
22 - if supported is not None:
23 - t["instant"] = {"supported": supported, "price": {"description": price} if price is not None else None}
24 - if discount is not None: t["instant"]["price"]["discount"] = discount
25 - return t
26 -
27 -
28 -class Fake:
29 - def __init__(self, metas, post):
30 - self.metas, self.post, self.calls = metas, post, []
31 - def __call__(self, req, timeout=None):
32 - self.calls.append((req.get_method(), req.full_url, req.data))
33 - assert req.headers.get("X-api-key") == "k"
34 - if req.get_method() == "GET":
35 - slug = req.full_url.split("/tools/")[1].split("?")[0]
36 - m = self.metas[slug]
37 - if isinstance(m, BaseException): raise m
38 - return Resp(json.dumps(m).encode())
39 - if isinstance(self.post, BaseException): raise self.post
40 - return Resp(json.dumps(self.post).encode() if not isinstance(self.post, bytes) else self.post)
41 - def posts(self): return [c for c in self.calls if c[0] == "POST"]
42 -
43 -
44 -def run(argv, fake=None, key="k"):
45 - out, err = io.StringIO(), io.StringIO()
46 - env = {"COMPOSIO_API_KEY": key} if key else {}
47 - opener = fake or mock.Mock(side_effect=AssertionError("network used"))
48 - with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(helper.urllib.request, "urlopen", opener), \
49 - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
50 - try: code = helper.main(argv)
51 - except SystemExit as e: code = e.code
52 - return code, out.getvalue(), err.getvalue()
53 -
54 -
55 -def http_err(code): return urllib.error.HTTPError("u", code, "x", {}, io.BytesIO(b""))
56 -
57 -BASE = ["--user-id", "user_123", "--tool", "exa:EXA_SEARCH"]
58 -
59 -
60 -class Regression(unittest.TestCase):
61 - def test_preview_default_no_network(self):
62 - code, out, _ = run(BASE)
63 - self.assertEqual(code, 0); self.assertIn("Preview only", out)
64 - body = json.loads(out[: out.rindex("}") + 1])["body"]
65 - self.assertEqual(body, {"user_id": "user_123", "toolkits": {"enable": ["exa"]}, "tools": {"exa": {"enable": ["EXA_SEARCH"]}},
66 - "instant": {"toolkits": {"enable": ["exa"]}, "tools": {"exa": {"enable": ["EXA_SEARCH"]}}}})
67 -
68 - def test_retired_toolkits_rejected(self):
69 - for tk in ["browser_tool", "composio_search", "text_to_pdf", "weathermap"]:
70 - code, _, err = run(["--user-id", "u", "--tool", f"{tk}:X_Y"])
71 - self.assertEqual(code, 2, tk); self.assertIn(tk, err)
72 -
73 - def test_text_to_pdf_points_to_pdf_co(self):
74 - _, _, err = run(["--user-id", "u", "--tool", "text_to_pdf:X"])
75 - self.assertIn("pdf_co", err)
76 -
77 - def test_bad_inputs(self):
78 - for t in ["exa", "exa:EXA:X", "EXA:EXA_SEARCH", "exa:exa_search", ":X", "exa:"]:
79 - self.assertEqual(run(["--user-id", "u", "--tool", t])[0], 2, t)
80 - self.assertEqual(run(BASE + ["--tool", "exa:EXA_SEARCH"])[0], 2)
81 - self.assertEqual(run(BASE + ["--tool", "tavily:EXA_SEARCH"])[0], 2)
82 - self.assertEqual(run(["--user-id", " ", "--tool", "exa:EXA_SEARCH"])[0], 2)
83 -
84 - def test_apply_requires_key(self):
85 - self.assertEqual(run(BASE + ["--apply"], key=None)[0], 2)
86 -
87 - def test_apply_happy_path(self):
88 - f = Fake({"EXA_SEARCH": tool_meta("EXA_SEARCH", "exa", discount="10%")}, {"session_id": "trs_1"})
89 - code, out, _ = run(BASE + ["--apply"], f)
90 - self.assertEqual(code, 0); self.assertIn("trs_1", out); self.assertIn("Published discount: 10%", out)
91 - self.assertEqual([c[0] for c in f.calls], ["GET", "POST"])
92 - self.assertIn("toolkit_versions=latest&include_pricing=true", f.calls[0][1])
93 -
94 - def test_post_failures_never_retry(self):
95 - for exc in [http_err(500), http_err(502), http_err(408), http_err(429), socket.timeout(), TimeoutError(),
96 - http.client.RemoteDisconnected(), ConnectionResetError(), http.client.IncompleteRead(b"")]:
97 - f = Fake({"EXA_SEARCH": tool_meta("EXA_SEARCH", "exa")}, exc)
98 - code, _, err = run(BASE + ["--apply"], f)
99 - self.assertEqual(code, 1, exc); self.assertEqual(len(f.posts()), 1, exc); self.assertIn("No automatic retry", err)
100 -
101 - def test_post_ambiguous_message_for_5xx(self):
102 - f = Fake({"EXA_SEARCH": tool_meta("EXA_SEARCH", "exa")}, http_err(503))
103 - self.assertIn("outcome is unknown", run(BASE + ["--apply"], f)[2])
104 -
105 - def test_post_bad_json_or_missing_id(self):
106 - for post in [b"not json", {"id": "x"}, [], {"session_id": ""}]:
107 - f = Fake({"EXA_SEARCH": tool_meta("EXA_SEARCH", "exa")}, post)
108 - code, _, _ = run(BASE + ["--apply"], f)
109 - self.assertEqual(code, 1, post); self.assertEqual(len(f.posts()), 1)
110 -
111 - def test_metadata_gates_block_creation(self):
112 - bad = [tool_meta("EXA_SEARCH", "exa", supported=None), tool_meta("EXA_SEARCH", "exa", supported=False),
113 - tool_meta("EXA_SEARCH", "tavily"), tool_meta("OTHER", "exa"), tool_meta("EXA_SEARCH", "exa", price=None),
114 - tool_meta("EXA_SEARCH", "exa", price=" "), [], {"slug": "EXA_SEARCH", "toolkit": "exa"},
115 - http_err(404), http_err(500), socket.timeout()]
116 - for m in bad:
117 - f = Fake({"EXA_SEARCH": m}, {"session_id": "trs_1"})
118 - self.assertEqual(run(BASE + ["--apply"], f)[0], 1, m); self.assertEqual(f.posts(), [], m)
119 -
120 -
121 -class Randomized(unittest.TestCase):
122 - N = 2700
123 -
124 - def test_random(self):
125 - rng = random.Random(20261113)
126 - chars = string.ascii_letters + string.digits + "_:-. "
127 - for i in range(self.N):
128 - n = rng.randint(1, 4); tools = []
129 - for _ in range(n):
130 - if rng.random() < 0.6:
131 - tk = rng.choice(["exa", "tavily", "serpapi", "browser_use", "pdf_co", "accu_weather", "gemini", "yelp", "seat_geek", "browser_tool", "weathermap"])
132 - tools.append(f"{tk}:{tk.upper()}_{rng.choice(['SEARCH', 'GET', 'RUN'])}")
133 - else:
134 - tools.append("".join(rng.choice(chars) for _ in range(rng.randint(0, 12))))
135 - argv = ["--user-id", "u"] + sum((["--tool", t] for t in tools), [])
136 - outcome = rng.choice(["ok", "unsupported", "post_err", "get_err", "no_id"])
137 - metas = {}
138 - for t in tools:
139 - if ":" in t:
140 - tk, slug = t.split(":", 1)
141 - metas[slug] = http_err(500) if outcome == "get_err" else tool_meta(slug, tk, supported=outcome != "unsupported")
142 - post = {"ok": {"session_id": "trs"}, "no_id": {}}.get(outcome, rng.choice([http_err(500), socket.timeout(), http_err(429)]))
143 - apply = rng.random() < 0.5
144 - f = Fake(metas, post)
145 - code, out, _ = run(argv + (["--apply"] if apply else []), f if apply else None)
146 - self.assertLessEqual(len(f.posts()), 1)
147 - if not apply: self.assertEqual(f.calls, [])
148 - if code == 0 and apply: self.assertEqual(outcome, "ok"); self.assertIn("trs", out)
149 - if outcome in ("unsupported", "get_err") and apply: self.assertEqual(f.posts(), [])
150 - if code == 0:
151 - body = json.loads(out[: out.index("\n}") + 2])["body"]
152 - self.assertEqual(body["toolkits"]["enable"], body["instant"]["toolkits"]["enable"])
153 - self.assertEqual(body["tools"], body["instant"]["tools"])
154 - self.assertFalse(set(body["tools"]) & set(helper.RETIRED))
155 -
156 -
157 -if __name__ == "__main__":
158 - unittest.main(verbosity=1)
docs/tests/static/validate-links.test.ts
-12
@@ -13,18 +13,6 @@ describe('link validation', () => {
13 expect(withoutFrontmatter!(fixture)).toBe('Read [the guide](/kb/guide/example).\r\n');
14 });
15
16 - test('accepts links to files served from public/ and rejects missing or escaping paths', () => {
17 - expect(linkValidation.isPublicFileUrl('/assets/migrations/migrate_no_auth_to_instant.py')).toBe(true);
18 - expect(linkValidation.isPublicFileUrl('/assets/migrations/migrate_no_auth_to_instant.py#usage')).toBe(true);
19 - expect(linkValidation.isPublicFileUrl('/assets/migrations/missing.py')).toBe(false);
20 - expect(linkValidation.isPublicFileUrl('/assets/migrations')).toBe(false);
21 - expect(linkValidation.isPublicFileUrl('/../package.json')).toBe(false);
22 - expect(linkValidation.isPublicFileUrl('/%2e%2e/package.json')).toBe(false);
23 - expect(linkValidation.isPublicFileUrl('//example.com/robots.txt')).toBe(false);
24 - expect(linkValidation.isPublicFileUrl('/%E0%A4%A.py')).toBe(false);
25 - expect(linkValidation.isPublicFileUrl('/assets/file%00.py')).toBe(false);
26 - });
27 -
16 test('accepts redirecting toolkit knowledge routes as resolvable links', async () => {
17 const redirectingToolkit = (await getKnowledgeToolkitSummaries()).find(
18 toolkit => toolkit.knowledgeCount === 1,