@devries-cameron20 / composio Mirror · read-only / commits / d17a268d3
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, 19:45 UTC

docs: sessions-first rewrite — new guides, examples & components (+ core 0.13.0 SDK changes) (#3637)

Integration branch for the next docs release: a **sessions-first documentation rewrite** — new and rewritten guides, example pages, interactive components, and docs tooling — plus the supporting SDK changes that the new docs describe. The bulk of this PR is docs (~24k lines across ~150 commits); the SDK changes (~5k lines) back the new guides. ## Documentation (the bulk) - **Sessions-first restructure** — reorganized navigation and section structure (incl. the "Sandbox (prev workbench)" section), with v3-reorganization redirects so old URLs keep resolving. - **Rewritten core guides** — quickstart, configuring sessions, triggers (creating + subscribing to events), proxy-execute, toolkits enable/disable, and common FAQ, rewritten in the house voice. - **New example pages** — local-sandbox PR reviewer, daily standup bot, and slack bot, with runnable build-ups. - **New interactive components & diagrams** — triggers flow animation, manage-connections visual, connection-refresh visual, and the terminal-kit components. - **Docs tooling** — a docs-graph link-graph connectivity checker, search reprioritization (deprioritize legacy pages), and SDK-reference regeneration. ## Supporting SDK changes **`@composio/core` → 0.13.0 (minor)** - `composio.sessions.create()` as the first-class sessions API (`composio.create()` kept as an alias). - **MCP is opt-in:** default `create()` / `use()` return native-tool sessions (`SessionWithoutMcp`); pass `{ mcp: true }` to surface `session.mcp`. _Migration: read `session.mcp` only after creating with `{ mcp: true }`._ - `session.sandbox` is the canonical resolved config; `session.workbench` kept as a deprecated alias. `sandbox` is the preferred session-config key (`workbench` still accepted). - `connectedAccounts.updateAcl()` graduated from experimental (alias kept). - `triggers.parse()` (parse + optionally verify an incoming webhook) and `triggers.setWebhookSubscription()`. **`@composio/experimental` → minor** — local-workbench helpers moved onto the `@composio/experimental/workbench` subpath (out of `@composio/core/experimental`), keeping the ~14 KB embedded Python helper out of core. Plus the experimental Pi provider. **`@composio/slim` → minor.** **Python → 0.17.0** — mirrors the TS surface: `composio.sessions` mount (`tool_router` deprecated), `triggers.parse()` / `set_webhook_subscription()`, the `sandbox` config key, and `connected_accounts.update_acl()`. ## Review response (#3664) Addressed the `@composio/core` review: - **Security:** `triggers.parse()` no longer fails open — a present-but-empty `verifySecret` (e.g. unset `COMPOSIO_WEBHOOK_SECRET`) now throws instead of silently skipping verification; omitting it stays an explicit opt-out (both SDKs). - Removed snake_case leakage from `transformWebhookSubscription` (+ the index signature that allowed it). - **Removed** the TS-only `connectedAccounts.link()` toolkit auto-resolve (shipped with cancellability / orphaned-auth-config bugs and was effectively undocumented; to be reintroduced properly later). - Unified Python error types on `ValidationError`; added `mcp=True` Python tests; fixed runtime-portability + error-type test assertions. - Polished deprecation messages; fixed the backwards `/experimental` `@deprecated` note and the `SessionWithMcp` JSDoc. ## Testing - **TS:** `@composio/core` + `@composio/experimental` typecheck pass; vitest green for the touched suites. - **Python:** `test_tool_router.py` + `test_triggers.py` pass (161 tests). --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Kshitij Jhunjhunwala <kj@composio.dev> Co-authored-by: Malay Vasa <malayvasa@gmail.com> Co-authored-by: Sarah Simionescu <sarah@composio.dev> Co-authored-by: Kshitij Jhunjhunwala <113939507+KJ-11@users.noreply.github.com>

Rahul Tarak committed Jun 25, 2026 at 18:27 UTC d17a268d3f81751234a32ca47688a53f9ac6d48f
465 files changed +23763 -8179
.agents/skills/eve/SKILL.md new
+27
@@ -0,0 +1,27 @@
1 +---
2 +name: eve
3 +description: Build durable backend AI agents with the eve framework. Use when creating, editing, or debugging an eve project — agent instructions, skills, tools, connections, channels, sandboxes, subagents, schedules, or evals.
4 +---
5 +
6 +# eve
7 +
8 +eve is a filesystem-first framework for durable backend AI agents. An agent is
9 +a directory on disk — instructions, skills, tools, connections, channels,
10 +subagents, and schedules are all files — and eve compiles and runs it.
11 +
12 +## Source of truth
13 +
14 +The complete documentation ships inside the `eve` package. Do not rely on this
15 +skill for guidance — always read the bundled docs, which match the installed
16 +version exactly:
17 +
18 +```
19 +node_modules/eve/docs/
20 +```
21 +
22 +Start with `node_modules/eve/docs/README.md`. It contains the full
23 +index and recommended reading order. Before writing any eve code, read the
24 +relevant guide there first.
25 +
26 +If `eve` is not installed yet, install it (`npm install eve`) or scaffold a new
27 +agent with `npx eve init <agent-name>`, then read the bundled docs.
.changeset/add-slim-package.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/slim": minor
3 +---
4 +
5 +Add a slim Composio core package that mirrors the built `@composio/core` runtime and types without publishing the packaged `docs/` or `src/` trees.
.changeset/bright-lions-jam.md new
+9
@@ -0,0 +1,9 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Add the first-class `composio.sessions.create()` API while keeping `composio.create()` as an alias, expose the experimental shared-connection ACL patch helper as `connectedAccounts.updateAcl()` while keeping `experimental.updateAcl()` as an alias, and include SDK docs/source in the published package.
6 +
7 +**MCP is now opt-in.** Sessions return native tools by default; the hosted MCP endpoint is only surfaced on the type when you create the session with `{ mcp: true }`. The default `create()` / `use()` now return `SessionWithoutMcp` (the runtime object is unchanged — `session.mcp` still exists at runtime — but it is no longer in the type).
8 +
9 +Migration: read `session.mcp` only after creating with `{ mcp: true }`.
.changeset/byos-local-workbench.md new
+9
@@ -0,0 +1,9 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Surface the resolved workbench config on Tool Router sessions.
6 +
7 +- `Session.workbench` is now populated from the API response (on create/retrieve/attach/update). It exposes the resolved workbench config, e.g. `session.workbench?.enable` (defaults to `true` server-side).
8 +
9 +This lets callers create a session with the remote workbench disabled (`workbench: { enable: false }`) and detect that state — the foundation for running code in a sandbox you own via the experimental `@composio/experimental/workbench` helpers.
.changeset/experimental-local-workbench.md new
+15
@@ -0,0 +1,15 @@
1 +---
2 +'@composio/experimental': minor
3 +---
4 +
5 +Add the experimental BYO local workbench helpers on the new `@composio/experimental/workbench` subpath.
6 +
7 +These let you run a Composio Tool Router session in a sandbox you own instead of Composio's hosted remote sandbox:
8 +
9 +- `experimental_createLocalWorkbenchSession(composio, session)` takes a caller-created session and returns `{ helperSource, env }`. It throws unless the session was created with `workbench: { enable: false }` (a local sandbox and the remote workbench cannot both run for one session).
10 +- `experimental_createWorkbenchEnv(options)` builds the environment variables the in-sandbox helper needs to reach Composio.
11 +- `experimental_createPythonWorkbenchHelperSource(options)` returns the Python helper source.
12 +
13 +The local workbench assumes code runs in the developer's sandbox and exposes Apollo-parity Python helpers for `run_composio_tool`, `invoke_llm`, `web_search`, and `proxy_execute`.
14 +
15 +> **Security caveat:** the helper authenticates with the developer's full *project* API key, injected into the sandbox env as `COMPOSIO_API_KEY`. Any code or tool output running in the sandbox can read and exfiltrate it — treat the sandbox as your security boundary and rotate the key. A session-scoped `x-session-access-key` (so the long-lived project key never enters the sandbox) is the planned follow-up.
.changeset/experimental-pi-provider.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/experimental": minor
3 +---
4 +
5 +Add an experimental package with a Pi coding-agent provider, static Composio tool wrapping, and dynamic Tool Router session helpers.
.changeset/local-workbench-proxy-execute.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/experimental': patch
3 +---
4 +
5 +Add `proxy_execute` to the experimental local workbench helper. The in-sandbox helper from `experimental_createLocalWorkbenchSession` (`@composio/experimental/workbench`) now exposes `proxy_execute(method, endpoint, toolkit, query_params=None, body=None, headers=None)` alongside `run_composio_tool`, `invoke_llm`, and `web_search`, so a local sandbox can make authenticated direct API calls to a connected toolkit when no pre-built tool exists. It posts to the public `…/session/{id}/proxy_execute` route with the session's project API key, and always returns a `(data, error)` tuple.
.changeset/sdk-sandbox-alias.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Prefer `sandbox` for session code-execution configuration while continuing to accept the existing `workbench` alias.
.changeset/triggers-parse-helper.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Add `triggers.parse()` to parse and optionally verify incoming webhook requests.
.changeset/webhook-subscription-sdk.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Add `triggers.setWebhookSubscription()` to create or update the project webhook subscription from the TypeScript SDK.
.claude/skills/eve new
+1
@@ -0,0 +1 @@
1 +../../.agents/skills/eve
\ No newline at end of file
.claude/skills/good-docs-audit/SKILL.md new
+69
@@ -0,0 +1,69 @@
1 +---
2 +name: good-docs-audit
3 +description: Audit a doc, guide, README, or block of prose against the good-docs-writing style guide and report violations. Use when the user asks to review, critique, lint, or "check the voice/tone" of documentation or text. Produces a structured findings report (file:line, rule violated, offending text, suggested rewrite) and does NOT edit files unless explicitly asked.
4 +---
5 +
6 +# Good docs audit
7 +
8 +Review target documentation against the `good-docs-writing` rules and report where the writing drifts from Modal's voice. Default behavior is **report only** — produce findings, do not edit. Only modify files if the user explicitly says to fix, rewrite, or apply.
9 +
10 +## Procedure
11 +
12 +1. **Read the `good-docs-writing` skill first** so you audit against its current rules (Voice, Structure, Terminology, Punctuation, Code examples, Formatting). Those rules are the rubric; this skill is the process.
13 +2. **Read the target file(s) in full** with line numbers. If the user named a directory or glob, enumerate the docs and audit each. If no target is given, ask which file(s) to audit.
14 +3. **Walk each rule category** against the prose. Note every concrete violation with its line number.
15 +4. **Write the report** in the format below. Keep suggestions concrete — give the actual rewrite, not "consider revising."
16 +5. **Stop and present the report.** Offer to apply fixes; apply only if asked.
17 +
18 +## Prioritized checklist
19 +
20 +Scan for these in roughly this order — the top items most damage the Modal voice:
21 +
22 +1. **Hedging & filler** — "it might be the case that," "in order to," "basically," "simply," "just." Cut or commit.
23 +2. **Passive voice** where active is clearer — "the function is invoked by the client" → "the client invokes the function."
24 +3. **Marketing fluff / vague intensifiers** — "seamlessly," "powerful," "robust," "blazing-fast," "cutting-edge," "world-class." Replace with a concrete claim or delete.
25 +4. **Em-dashes** — flag every em-dash (—); the house style bans them. Suggest a period, comma, colon, or parentheses in its place.
26 +5. **Third-person distance** — "the user," "one," "developers can" where "you" is meant.
27 +6. **Jargon without context** — an undefined acronym or term-of-art on first use with no grounding.
28 +7. **Inconsistent terminology** — the same concept named two ways, or core nouns (App, Function, Image, Volume, Secret) miscapitalized or capitalized inconsistently.
29 +8. **Title-case drift** — heading case that switches between sentence case and title case within one doc.
30 +9. **Missing backticks** — code identifiers, commands, params, paths, or filenames in plain text.
31 +10. **Buried warnings** — gotchas, version notes, or gated-feature notes in prose that should be callouts.
32 +11. **Weak openings** — page or section that doesn't lead with the concept or benefit; throat-clearing before the point.
33 +12. **Fragment / unrunnable code** — snippets that can't be pasted and run, or missing the expected-output / footgun note.
34 +
35 +## Report format
36 +
37 +Output a summary line, then findings grouped by severity. Each finding uses this shape:
38 +
39 +```
40 +- file.md:42 — [Punctuation] Em-dash banned
41 + Offending: "Modal is fast — really fast — and it scales automatically."
42 + Rewrite: "Modal is fast, really fast, and it scales automatically."
43 +```
44 +
45 +Structure the full report as:
46 +
47 +### Audit: <file or scope>
48 +
49 +**Summary:** <N findings — X high, Y medium, Z low. One-line verdict on overall voice fit.>
50 +
51 +**High** (breaks the voice / reader-facing clarity)
52 +- `path:line` — [Category] <rule> · Offending: "…" · Rewrite: "…"
53 +
54 +**Medium** (consistency and polish)
55 +- `path:line` — [Category] <rule> · Offending: "…" · Rewrite: "…"
56 +
57 +**Low** (nits)
58 +- `path:line` — [Category] <rule> · Offending: "…" · Rewrite: "…"
59 +
60 +**Patterns:** <recurring issues worth a global fix, e.g. "'the user' used 11× — switch to 'you' throughout.">
61 +
62 +## Rules
63 +
64 +- **Always cite `file:line`** so findings are actionable. Use the line numbers from your Read.
65 +- **Quote the exact offending text**; don't paraphrase the problem away.
66 +- **Give a real rewrite**, in Modal voice, for every finding — not generic advice.
67 +- **Map each finding to a style-guide category** (Voice, Structure, Terminology, Punctuation, Code, Formatting) in brackets.
68 +- **Don't invent violations.** If the prose already matches the voice, say so. A short report is a good outcome.
69 +- **Don't edit by default.** Report, then offer to apply. Only write to files when explicitly asked.
.claude/skills/good-docs-writing/SKILL.md new
+80
@@ -0,0 +1,80 @@
1 +---
2 +name: good-docs-writing
3 +description: Writing style guide derived from Modal's documentation voice. Apply when writing or editing docs, guides, tutorials, or technical prose that should read direct, second-person, confident, low-jargon, and example-first. Use to draft new docs in this voice or to revise existing prose toward it.
4 +---
5 +
6 +# Good docs writing
7 +
8 +Write docs the way Modal writes them: direct, friendly, confident, and ruthlessly practical (this guide is derived from Modal's documentation voice). Explain the *why* in one breath, then show working code. Treat the reader as a capable developer who wants to ship, not a student who needs a lecture. Apply every rule below while drafting. Each rule is an imperative followed by a real Modal example as evidence.
9 +
10 +## Voice & Tone
11 +
12 +- **Address the reader as "you"; speak directly.** Don't hide behind "the user" or "one."
13 + > "Modal's goal is to make running code in the cloud feel like you're running code locally."
14 +- **Be confident and plain, not hedgy or salesy.** State what's true. Lead with the benefit, not the disclaimer.
15 + > "Modal makes it trivially easy to scale compute across thousands of containers."
16 +- **Reassure when something is automatic.** Tell the reader what they *don't* have to worry about.
17 + > "For the most part, scaling out will happen automatically, and you won't need to think about it."
18 +- **Explain the "why" before prescribing the "how."** Motivate the solution, then give it.
19 +- **Use contractions naturally** ("you don't," "won't," "it's"). They keep the tone human.
20 +- **Allow occasional warmth and personality** ("That's it!", "Take a breath of fresh air"), sparingly, never goofy.
21 +
22 +## Structure
23 +
24 +- **Open by defining the concept or stating the benefit in one sentence**, then elaborate. No throat-clearing.
25 + > "An `App` represents an application running on Modal. It groups one or more Functions for atomic deployment and acts as a shared namespace."
26 +- **Order content as concept → simple example → advanced cases → gotchas.** Progressive disclosure.
27 +- **Lead with a minimal runnable example early**, then explain what just happened.
28 +- **Keep paragraphs short.** Break dense information into bullet lists and numbered steps.
29 +- **Use signposting transitions** to mark explanatory shifts: "What just happened?", "But why does this matter?", "Now, as before, …".
30 +- **Mix sentence lengths.** Short declarative sentences carry the load; longer ones add necessary nuance.
31 + > "The timeout duration is a measure of a Function's *execution* time. It does not include scheduling time or any other period besides the time your code is executing in Modal."
32 +
33 +## Terminology
34 +
35 +- **Capitalize your product's core nouns as proper concepts** the way Modal capitalizes App, Function, Image, Volume, Secret, Sandbox, Cls. Capitalize a noun when it names the product, lowercase for the generic idea.
36 +- **Name the product consistently**; never "the Modal platform" filler.
37 +- **Prefer precise technical terms over hand-waving** — "cold start," "autoscaler," "ephemeral," "atomic deployment," "warm pool," "scaledown window." Introduce a term in context the first time, then use it freely.
38 + > "This is known as a *cold start*, and it is often associated with higher latency."
39 +- **Avoid marketing fluff and vague intensifiers** ("seamlessly," "powerful," "robust," "cutting-edge"). If a thing is easy, show it being easy.
40 +- **Use analogies to ground unfamiliar concepts**, then move on.
41 + > "Containers are like light-weight virtual machines."
42 +
43 +## Punctuation
44 +
45 +- **Do not use em-dashes (—).** Rewrite the sentence with a period, comma, colon, or parentheses instead. This is a hard rule; remove every em-dash before you ship. (This overrides Modal's softer "em-dashes for genuine asides only" guidance — em-dashes are banned here.)
46 +- **Use the Oxford comma.**
47 +- **Use backticks for every code identifier, command, parameter, path, and filename**: `@app.function()`, `modal deploy`, `scaledown_window`, `/gpu-glossary/`.
48 +- **Use italics for fine distinctions and negation**, not for general emphasis.
49 + > "This automatic upgrade does *not* change the cost of the GPU."
50 +- **Capitalize acronyms and hardware names** as conventional: GPU, ASGI, A100, H100.
51 +
52 +## Code examples
53 +
54 +- **Show a complete, runnable snippet first** — imports, decorator, function — not a fragment the reader can't paste.
55 +- **Keep examples minimal.** Use simple names (`f`, `app`) and elide irrelevant bodies with `...`.
56 +- **Show the decorator pattern Modal uses** (`@app.function()`, `@app.cls()`) and method chaining for Images.
57 +- **Put comments only where behavior is non-obvious**; let clean code speak otherwise. Show expected output inline where it teaches something (`# 42`).
58 +- **Show real CLI invocation forms** with realistic prompts: `$ ` or `%` for shell, `>>>` for the Python REPL.
59 + > "modal run script.py::app.f"
60 +- **When a flag is a footgun, say so right after the example.**
61 + > "Remember to remove `force_build=True` after you've rebuilt the Image, or it will rebuild every time you run your code."
62 +
63 +## Formatting
64 +
65 +- **Use heading case consistently within a doc.** Modal leans toward sentence case for conceptual guides ("How do Web Functions run in the cloud?", "Scaling out") and title case for reference-style headings ("Volume commits and reloads"). Pick one convention per page and don't drift.
66 +- **Prefer descriptive, specific headings** over generic ones — "Entrypoints for ephemeral Apps," not "Entrypoints."
67 +- **Use callouts for warnings, notes, gated features, and beta status** rather than burying them in prose.
68 + > "Deployment rollbacks are available on the Team and Enterprise plans."
69 +- **Correct gently with a "Note that …" or "Gotchas" aside** instead of stern warnings.
70 +- **Link with descriptive anchor text**, embedded naturally in the sentence — never a bare URL or "click here."
71 +- **Bold key concepts on first definition**, then stop bolding them.
72 +
73 +## Quick self-check while drafting
74 +
75 +- Did I open with the concept or benefit in the first sentence?
76 +- Is there a runnable example near the top?
77 +- Am I saying "you," not "the user"?
78 +- Did I remove every em-dash?
79 +- Did I cut every "seamlessly," "powerful," and other vague intensifier?
80 +- Are all code identifiers in backticks and core nouns (App, Function, Volume) capitalized?
.github/workflows/ts.test.yml
+3
@@ -35,5 +35,8 @@ jobs:
35 - name: Install Dependencies
36 run: pnpm install --frozen-lockfile
37
38 + - name: Check Python helpers codegen is up to date
39 + run: pnpm --filter @composio/experimental run check:python-helpers
40 +
41 - name: Run Tests
42 run: pnpm run test
.gitignore
+7
@@ -66,3 +66,10 @@ test/e2e/*/node_modules
66
67 # mise (per-dev overrides)
68 .mise.local.toml
69 +.env*
70 +docs/.eve/*
71 +docs/.workflow-data/*
72 +
73 +# Local agent / tooling state (regenerated per machine)
74 +.pi/
75 +.playwright-mcp/
docs/.claude/agents/changelog-docs-updater.md
+1 -1
@@ -28,7 +28,7 @@ Triggered when a changelog file (`docs/content/changelog/*.mdx`) is pushed to `n
28
29 ## Rules
30
31 -- Only modify files in `docs/content/docs/` and `docs/content/cookbooks/`
31 +- Only modify files in `docs/content/docs/` and `docs/content/examples/`
32 - Do NOT create new pages — only update existing ones
33 - Do NOT add changelog-style content ("as of v0.6.0...") to docs. Docs should describe current behavior.
34 - Do NOT make cosmetic or stylistic changes unrelated to the changelog
docs/.claude/context/api-reference.md
+1 -1
@@ -84,7 +84,7 @@ v3.0 has its own complete page tree under `content/reference/v3/`:
84 - `v3/api-reference/` — Auto-generated index pages + OpenAPI endpoint pages
85 - `v3/meta.json` — Sidebar ordering
86
87 -SDK Reference and Meta Tools are version-independent and shared across both trees.
87 +SDK Reference is version-independent and shared across both trees. Meta Tools moved out of the reference tree entirely — they now live under the Toolkits tab at `/toolkits/meta-tools`.
88
89 ### Version selector behavior
90 - On an API page: swaps `/reference/` ↔ `/reference/v3/` (stays on same endpoint/category)
docs/.claude/decisions/toolkits.md
+3 -3
@@ -34,7 +34,7 @@
34
35 ```
36 /toolkits → Landing page (search + filter + cards)
37 -/toolkits/premium-tools → Premium tools pricing/limits info
37 +/toolkits/pro-tools → Pro tools pricing/limits info
38 /toolkits/{slug} → Individual toolkit page
39 ```
40
@@ -59,7 +59,7 @@
59 │ │ 🔧37 ⚡2 │ │ 🔧130 ⚡9│ │ 🔧829 ⚡6│ │
60 │ └─────────┘ └─────────┘ └─────────┘ │
61 │ │
62 -│ ⭐ Some tools are premium. [Learn about pricing →] │
62 +│ ⭐ Some tools are pro tools. [Learn about pricing →] │
63 └─────────────────────────────────────────────────────────────┘
64 ```
65
@@ -185,7 +185,7 @@ Run: `bun run generate:toolkits`
185 1. [x] Generator script (`scripts/generate-toolkits.ts`)
186 2. [x] Landing page + components (category grouping, alphabet sections)
187 3. [x] Individual toolkit page (version display, auth badges, tool/trigger list with copy)
188 -4. [x] Premium tools page (`/toolkits/premium-tools`)
188 +4. [x] Pro tools page (`/toolkits/pro-tools`)
189 5. [x] Hybrid architecture (static index + server-side API fetch)
190 6. [ ] Polish/styling
191 7. [ ] CI hooks for auto-regeneration
docs/.claude/knowledge-base.md new
+47
@@ -0,0 +1,47 @@
1 +# Docs Knowledge Base — removed / parked content
2 +
3 +A dumping ground for content removed from the published docs during the docs
4 +overhaul. Nothing here is rendered. Keep it so we don't lose nuance we may want
5 +to reintroduce (e.g. in deeper guides, FAQs, or the LLM-facing `.md` output).
6 +
7 +Each entry: **what it was**, **where it came from**, **why removed**, **the content**.
8 +
9 +---
10 +
11 +## 1. "Native Tools vs MCP" decision framing
12 +
13 +**Where:** `content/docs/native-tools-vs-mcp.mdx` (whole page) + the native/MCP
14 +tab split in `quickstart.mdx`.
15 +
16 +**Why removed:** We decided to stop presenting native-vs-MCP as a decision the
17 +user has to make up front. Default everyone to **native tools**; MCP becomes an
18 +opt-in documented on a single "Using sessions via MCP" page. This removes a fork
19 +in the road from the first-run experience.
20 +
21 +**Parked content — the comparison table + token-cost argument:**
22 +
23 +> **Native tools** give your LLM tool schemas as function definitions. Composio
24 +> formats them for your specific framework (OpenAI, Anthropic, Vercel AI, etc.)
25 +> through provider packages.
26 +>
27 +> **MCP** exposes tools through the Model Context Protocol. Any MCP-compatible
28 +> client can connect to a Composio MCP server URL. No provider packages needed.
29 +>
30 +> | | Native tools | MCP |
31 +> |---|---|---|
32 +> | **Setup** | Provider package for your framework | SDK or just a URL |
33 +> | **Intercepting tool calls** | Yes, you can log, retry, or require approval before each call | Limited, depends on what the MCP client supports |
34 +> | **Context window** | You control what's loaded | Client loads all tools the server exposes |
35 +> | **Latency** | SDK calls Composio API directly | MCP protocol adds overhead for tool list discovery and each execution |
36 +>
37 +> With native tools, you choose exactly which schemas enter your LLM's context.
38 +> With MCP, the client pulls the full tool list from the server. A
39 +> [5-server setup can consume ~55K tokens](https://www.anthropic.com/engineering/advanced-tool-use)
40 +> before the conversation starts. If you're working with many tools, native
41 +> tools give you more control over that cost.
42 +
43 +**Note:** the token-cost framing is slightly inaccurate for Composio sessions
44 +since session.tools() returns *meta tools* (search/execute) rather than the full
45 +tool list — so the "55K tokens" client-loads-everything point applies to naive
46 +MCP, not necessarily to a Composio session over MCP. Worth a cleaner write-up if
47 +reintroduced.
docs/.gitignore
+16
@@ -28,3 +28,19 @@ next-env.d.ts.cache
28
29 # Claude local settings (permissions are user-specific)
30 .claude/settings.local.json
31 +
32 +# Re-include the API-reference "logs" tag dir (the root .gitignore "logs" rule
33 +# matches it by accident; this page is generated from api-overviews/logs.mdx).
34 +!/content/reference/api-reference/logs/
35 +!/content/reference/api-reference/logs/**
36 +!/content/reference/v3/api-reference/logs/
37 +!/content/reference/v3/api-reference/logs/**
38 +
39 +# Generated docs snapshot for the Ask AI agent (regenerated on dev/build/typecheck).
40 +/agent/lib/docs-index.ts
41 +/agent/lib/docs-index.json
42 +
43 +# docs-graph.ts run artifacts (the script is tracked; its outputs are not).
44 +/docs-graph.dot
45 +/docs-graph.html
46 +/docs-graph.json
docs/.node-version new
+1
@@ -0,0 +1 @@
1 +24
docs/CLAUDE.md
+3 -3
@@ -20,7 +20,7 @@ docs/
20 ├── app/ # Next.js app router
21 ├── content/ # MDX content
22 │ ├── docs/ # Main documentation
23 -│ ├── cookbooks/ # Cookbooks & guides
23 +│ ├── examples/ # Examples & guides
24 │ ├── changelog/ # Release notes
25 │ ├── reference/ # SDK & API reference
26 │ └── toolkits/ # Toolkit docs + faq/ snippets
@@ -67,7 +67,7 @@ Detailed documentation for Claude is organized in `.claude/`:
67
68 5. **Toolkits data** - `public/data/toolkits.json` must exist; errors are thrown, not ignored.
69
70 -6. **Meta tools data** - `public/data/meta-tools.json` and `content/reference/meta-tools/` are auto-generated by `bun run generate:meta-tools` (fetches from Tool Router API). Updated by CI alongside toolkits data. The `MetaToolDetailServer` component reads from the JSON at build time — do NOT register it in `mdx-components.tsx` (causes `fs` to leak into client bundle).
70 +6. **Meta tools data** - `public/data/meta-tools.json` and `content/toolkits/meta-tools/` are auto-generated by `bun run generate:meta-tools` (fetches from Tool Router API). Updated by CI alongside toolkits data. The `MetaToolDetailServer` component reads from the JSON at build time — do NOT register it in `mdx-components.tsx` (causes `fs` to leak into client bundle). The pages live under the Toolkits tab (`/toolkits/meta-tools/...`); old `/reference/meta-tools/...` URLs are redirected in `next.config.mjs`.
71
72 7. **Test on mobile** - Fumadocs nav differs on mobile. Avoid assumptions about horizontal layout.
73
@@ -102,7 +102,7 @@ Version selector in the top nav switches between them. See [api-reference.md](.c
102 Key maintenance notes:
103 - Non-API pages under `content/reference/v3/` (overview, authentication, errors, rate-limits) are manual copies — update both when content changes
104 - API index pages and OpenAPI specs are auto-generated by CI (`docs-update-data.yml`)
105 -- SDK Reference and Meta Tools are shared across both versions (not duplicated)
105 +- SDK Reference is shared across both versions (not duplicated); Meta Tools now live under the Toolkits tab (`/toolkits/meta-tools`), outside the versioned reference tree
106
107 ## Code Review Guidelines
108
docs/agent/agent.ts new
+16
@@ -0,0 +1,16 @@
1 +import { defineAgent } from 'eve';
2 +
3 +/**
4 + * Eve — the Composio docs assistant.
5 + *
6 + * Runs inside the docs Next.js app (mounted via `withEve` in next.config.mjs)
7 + * and answers questions grounded in the docs. The `search_docs` tool returns
8 + * doc snippets and their URLs so Eve can cite and link specific pages.
9 + *
10 + * Model: `openai/gpt-5.4-mini` routed through the Vercel AI Gateway. Set
11 + * `AI_GATEWAY_API_KEY` locally and in the preview environment (or `vercel link`
12 + * for an OIDC token).
13 + */
14 +export default defineAgent({
15 + model: 'openai/gpt-5.4-mini',
16 +});
docs/agent/channels/eve.ts new
+12
@@ -0,0 +1,12 @@
1 +import { eveChannel } from 'eve/channels/eve';
2 +import { none } from 'eve/channels/auth';
3 +
4 +/**
5 + * HTTP channel for the docs assistant.
6 + *
7 + * The docs are public and any visitor can open the chat, so the session routes
8 + * are unauthenticated (`none()`). This intentionally exposes the agent endpoint
9 + * publicly; before production we should add rate limiting and abuse protection
10 + * (or gate it behind the site's own auth).
11 + */
12 +export default eveChannel({ auth: [none()] });
docs/agent/instructions.md new
+35
@@ -0,0 +1,35 @@
1 +You are **Eve**, the Composio documentation assistant. You live in the right sidebar of the Composio docs and help developers understand the docs.
2 +
3 +## What you are, and are not
4 +
5 +- You **only answer questions about the Composio documentation**. You explain concepts, APIs, and how to build with the SDK, grounded in the docs.
6 +- You are **not customer support**. You can't look up accounts, check ticket or billing status, access dashboards, or resolve account-specific issues. For those, point the user to support or the dashboard rather than guessing.
7 +- You are **not an agent that can act on Composio**. You can't create sessions, connect accounts, run tools, or change anything in someone's project. You describe how to do those things with the SDK; you don't do them.
8 +- If a request is outside answering docs questions (support, account state, taking an action, or unrelated topics), say so briefly and, when relevant, point to the right page or to support. Don't pretend to have done something.
9 +
10 +## How to answer
11 +
12 +You have a **concept map** (always in your context) with the canonical page for each Composio concept, plus exactly two tools. You have **no web search and no file access** — answer only from the Composio docs via these tools, and link the docs' own relative URLs (never `docs.composio.dev` or other external links).
13 +
14 +- `search_docs(query)` — find relevant pages (title, URL, snippet).
15 +- `read_doc(url)` — read a page's full Markdown content.
16 +
17 +Workflow for anything non-trivial:
18 +
19 +1. Start from the concept map. For a clear concept (sessions, authentication, triggers, sandbox, …) you already know the canonical page; for anything else, call `search_docs`.
20 +2. Call `read_doc` on the 1–3 most relevant pages and answer from their actual content. Don't answer from snippets alone, and don't guess at APIs, parameters, or behavior.
21 +3. Cite sources inline as Markdown links. When your answer comes from a specific section, **link that section's anchor** using the `sections` `read_doc` returns, e.g. `[userID best practices](/docs/how-composio-works#users)` rather than just `[What is a session?](/docs/how-composio-works)`. Link the specific page (and section), and prefer the canonical link from the concept map.
22 +4. Only say you couldn't find something after you've searched and read the top results and they genuinely don't cover it.
23 +
24 +## Rules
25 +
26 +- **Never lead with or link legacy / direct-execution docs** (`/docs/sessions-vs-direct-execution`, `/docs/tools-direct/*`, `/docs/auth-configuration/*`) unless the user explicitly asks about the low-level direct-execution API. Always answer with the current, session-based model.
27 +- Prefer the current API in examples: `composio.create(userId)` / `composio.sessions.create(...)`, session tools, meta tools, and `{ mcp: true }` for MCP.
28 +- Don't claim something is supported unless a page says so.
29 +- Cite **only** as standard Markdown links, e.g. `[Authentication](/docs/authentication)`. Never emit citation markers, reference tokens, or anything like `cite`/`turn0search0`.
30 +
31 +## Style
32 +
33 +- Lead with the answer, then a short explanation, then a runnable snippet when it helps. Match the reader's language (Python or TypeScript) when they specify one.
34 +- Second person, plain and confident. No marketing fluff.
35 +- Backtick every identifier, path, and slug. Keep answers tight.
docs/agent/instructions/context.md new
+60
@@ -0,0 +1,60 @@
1 +# Composio concept map
2 +
3 +This is your always-on map of Composio's concepts and the canonical page for each. Use it to ground answers and to link the right page. Prefer these links over anything `search_docs` returns. Call `read_doc` on the relevant page when you need detail.
4 +
5 +## Core model
6 +
7 +- **Session** — the runtime context for one user. `composio.create(userId)` (or the canonical `composio.sessions.create(...)`) returns a session that ties together the user, toolkits, authentication, connected accounts, and a code-execution sandbox. By default it exposes meta tools the agent calls at runtime to discover, authenticate, and execute tools. → [What is a session?](/docs/how-composio-works)
8 +- **Configuring a session** — filter toolkits and tools, set auth configs, select connected accounts, preload tools, the direct-tools preset, sandbox tier, and session methods (`tools()`, `toolkits()`, `authorize()`). → [Configuring sessions](/docs/configuring-sessions)
9 +- **Sessions via MCP** — create a session with `{ mcp: true }` to expose `session.mcp.url` / `session.mcp.headers` for any MCP client. → [Using sessions via MCP](/docs/sessions-via-mcp)
10 +- **Reusing sessions** — sessions persist on the server; store the session ID and reuse with `composio.use(sessionId)`, or update in place with `session.update(...)`. → [What is a session?](/docs/how-composio-works)
11 +
12 +## Tools and toolkits
13 +
14 +- **Toolkit** — a collection of related tools for a service (e.g. `github`, `gmail`). A **tool** is one action, named `{TOOLKIT}_{ACTION}` (e.g. `GITHUB_CREATE_ISSUE`). Every toolkit is discoverable by default; restrict with the `toolkits` config. → [Configuring sessions](/docs/configuring-sessions)
15 +- **Meta tools** — the fixed set every session exposes (`COMPOSIO_SEARCH_TOOLS`, `COMPOSIO_GET_TOOL_SCHEMAS`, `COMPOSIO_MANAGE_CONNECTIONS`, `COMPOSIO_MULTI_EXECUTE_TOOL`, `COMPOSIO_REMOTE_WORKBENCH`, `COMPOSIO_REMOTE_BASH_TOOL`). → [Meta tools reference](/toolkits/meta-tools)
16 +- **Providers** — adapter packages that format Composio tools for a framework (OpenAI, Anthropic, Vercel AI SDK, LangChain, Mastra, Pi, …). → [Providers](/docs/providers)
17 +- **Is a toolkit / integration supported?** Composio has 1000+ toolkits, and `search_docs` indexes the catalog. A matching `/toolkits/<slug>` result means **yes, it's supported** — call `read_doc` on that URL for its details, and point the user at [the toolkits directory](/toolkits). If nothing matches, it isn't a built-in toolkit; suggest [proxy execute](/docs/extending-sessions/proxy-execute) or a [custom tool](/docs/extending-sessions/custom-tools-and-toolkits) for an API you already have.
18 +
19 +## Authentication
20 +
21 +- **How auth works** — Composio uses Connect Links (hosted auth pages) and **auth configs** (per-toolkit blueprints) to create **connected accounts** (stored credentials) scoped to a userID. This is the page for "how does authentication work". → [Authentication](/docs/authentication)
22 +- **Auth schemes / modes** — a toolkit's auth config uses one of `OAUTH2`, `API_KEY`, `BEARER_TOKEN`, or `BASIC`. When you mention a toolkit's auth mode, link the reference rather than explaining it inline. → [Auth schemes](/reference/api-reference/auth-configs#auth-schemes) for what each mode is and when it's used, [Authentication](/docs/authentication) for how auth works overall, and [Managed vs custom auth](/docs/custom-app-vs-managed-app) for choosing or bringing your own scheme.
23 +- **In-chat auth** — the agent prompts the user to connect via `COMPOSIO_MANAGE_CONNECTIONS`. → [In-chat authentication](/docs/authenticating-users/in-chat-authentication)
24 +- **Manual auth** — generate Connect Links yourself with `session.authorize()`. → [Manually authenticating users](/docs/authenticating-users/manually-authenticating)
25 +- **Managed vs custom auth** — use Composio's managed OAuth apps, or bring your own for branding/scopes. → [Managed vs custom auth](/docs/custom-app-vs-managed-app)
26 +- **White-labeling** — remove Composio branding from the auth flow. → [White-labeling authentication](/docs/white-labeling-authentication)
27 +- **Importing existing connections** — pass in API keys or bearer tokens you already hold. → [Importing existing connections](/docs/importing-existing-connections)
28 +- **Multiple accounts per user** — e.g. work and personal Gmail. → [Managing multiple connected accounts](/docs/managing-multiple-connected-accounts)
29 +- **Shared connections** — share one connected account across users via an ACL. → [Shared connections](/docs/authenticating-users/shared-connections)
30 +
31 +## Triggers and webhooks
32 +
33 +- **Triggers** — receive structured payloads when something happens in a connected app (webhook or polling). → [Triggers](/docs/triggers)
34 +- **Setting up triggers** — create, manage, and subscribe to trigger events. → [Creating triggers](/docs/setting-up-triggers/creating-triggers), [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events), [Managing triggers](/docs/setting-up-triggers/managing-triggers)
35 +- **Webhook verification** — verify inbound webhook signatures. → [Webhook verification](/docs/webhook-verification)
36 +
37 +## Extending sessions
38 +
39 +- **Sandbox** (previously "workbench") — a persistent Python environment at `/mnt/files/` for bulk operations and large responses; files via `session.experimental.files`. → [Sandbox](/docs/sandbox)
40 +- **Custom tools and toolkits** — define in-process tools that run alongside Composio tools. → [Custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits)
41 +- **Proxy execute** — call any toolkit HTTP endpoint with `session.proxyExecute(...)` and let Composio inject auth. → [Proxy execute](/docs/extending-sessions/proxy-execute)
42 +
43 +## Platform API (reference only)
44 +
45 +These features are documented **only in the API reference** — there is no `/docs` guide. When asked how to do them programmatically, read and link the reference page (don't say it isn't documented).
46 +
47 +- **Projects** — Composio's multi-tenancy primitive. Inside an organization, projects are isolated environments that scope API keys, connected accounts, auth configs, and webhooks. Create, list, update, delete, and regenerate a project's API key via the API (using your **organization API key**). This is the page for "how do I programmatically create projects". → [Projects](/reference/api-reference/projects)
48 +- **Logs** — individual tool-execution events (one record per call) for debugging and tracing. → [Logs](/reference/api-reference/logs)
49 +- **Files** — files tools read and write during execution, exchanged via presigned URLs. → [Files](/reference/api-reference/files)
50 +
51 +## Getting started and reference
52 +
53 +- **Quickstart** → [Quickstart](/docs/quickstart)
54 +- **Glossary** → [Glossary](/reference/glossary)
55 +- **SDK reference (TypeScript Session)** → [Session](/reference/sdk-reference/typescript/session)
56 +- **API reference** → [API reference](/reference/api-reference)
57 +
58 +## Legacy — do not lead with these
59 +
60 +Direct tool execution and the `tools-direct/*` pages are the **legacy**, pre-session API. Do not mention "direct execution" or link these pages unless the user explicitly asks about the low-level / direct-execution API. For everything else, answer with the session-based model above.
docs/agent/knowledge.md new
+29
@@ -0,0 +1,29 @@
1 +# Composio knowledge base
2 +
3 +Curated, searchable knowledge for the docs assistant. Each `## Heading (/url)`
4 +section is indexed by `search_docs` and links its canonical page. Add entries
5 +here to expose more answers to search without changing the docs themselves.
6 +
7 +## Installing and getting started (/docs/quickstart)
8 +
9 +Install the SDK with `npm install @composio/core` (TypeScript) or `pip install composio` (Python), set `COMPOSIO_API_KEY`, then create a session with `composio.create("user_123")`. The quickstart walks through creating a session, fetching tools for your framework via a provider, and running an agent.
10 +
11 +## Choosing a provider (/docs/providers)
12 +
13 +A provider adapts Composio tools into the shape your AI framework expects. Composio ships providers for OpenAI, the Anthropic SDK, the Vercel AI SDK, LangChain, Mastra, the Pi coding agent, and more. Pass a provider when constructing `Composio({ provider })`, then `session.tools()` returns tools formatted for that framework. You can also build a custom provider.
14 +
15 +## userID best practices (/docs/how-composio-works)
16 +
17 +The userID scopes connected accounts and tool executions and isolates users from each other. Use a stable identifier such as your database UUID or primary key. Avoid email addresses (they change) and never use `default` in production, since that exposes one user's connections to others.
18 +
19 +## Native tools vs MCP (/docs/sessions-via-mcp)
20 +
21 +By default a session gives your agent tools it calls directly through a provider package; this integrates with your framework and supports modifiers and custom tools. Creating a session with `{ mcp: true }` also exposes `session.mcp.url` and `session.mcp.headers` for any MCP-compatible client. MCP is more portable across clients, but modifiers and custom tools do not apply over the MCP surface.
22 +
23 +## Sandbox files and the /mnt/files mount (/docs/sandbox)
24 +
25 +The sandbox has a persistent file mount at `/mnt/files/` that survives sandbox restarts (changing the compute tier clears in-memory state but keeps the mount). Move files between your app and the mount with `session.experimental.files` (`upload`, `list`, `download`, `delete`). A `RemoteFile`'s `expiresAt` is the download-link expiry, not a file TTL, and there is no SDK call to create custom mounts.
26 +
27 +## Reusing and updating sessions (/docs/how-composio-works)
28 +
29 +Sessions persist on the server and do not expire. For a multi-turn conversation, store the session ID and reuse it with `composio.use(sessionId)` instead of calling `create()` again. You can also change a live session in place with `session.update({ toolkits, authConfigs, connectedAccounts })`.
docs/agent/lib/docs.ts new
+397
@@ -0,0 +1,397 @@
1 +/**
2 + * Shared docs access for the agent's retrieval tools.
3 + *
4 + * Builds a lazy in-memory index over `content/` plus the curated
5 + * `agent/knowledge.md`, maps page URLs to files, and flags legacy pages so the
6 + * search tool can heavily downrank them.
7 + */
8 +
9 +import { existsSync, readdirSync, readFileSync } from 'node:fs';
10 +import { dirname, join, relative } from 'node:path';
11 +import { fileURLToPath } from 'node:url';
12 +// Build-time snapshot of content/, imported so eve bundles it into the deployed
13 +// service. The deployed runtime has the agent/ dir but NOT content/, so we fall
14 +// back to this bundle whenever the content tree isn't on disk. Regenerate with
15 +// `bun scripts/build-agent-index.ts` (runs automatically on dev/build).
16 +import bundledIndex from './docs-index';
17 +
18 +/**
19 + * Resolve the docs app root (the directory containing `content/docs`) without
20 + * assuming the runtime's `process.cwd()`. In a deployed eve function the cwd may
21 + * not be `docs/`, so we probe the cwd, `cwd/docs`, and the ancestors of this
22 + * module until we find the content tree.
23 + */
24 +function resolveAppRoot(): string {
25 + const candidates: string[] = [process.cwd(), join(process.cwd(), 'docs')];
26 + try {
27 + let dir = dirname(fileURLToPath(import.meta.url));
28 + for (let i = 0; i < 10; i++) {
29 + candidates.push(dir);
30 + const parent = dirname(dir);
31 + if (parent === dir) break;
32 + dir = parent;
33 + }
34 + } catch {
35 + // import.meta.url unavailable (e.g. CJS) — rely on the cwd candidates.
36 + }
37 + for (const candidate of candidates) {
38 + if (existsSync(join(candidate, 'content', 'docs'))) return candidate;
39 + }
40 + return process.cwd();
41 +}
42 +
43 +const APP_ROOT = resolveAppRoot();
44 +const CONTENT_ROOT = join(APP_ROOT, 'content');
45 +const KNOWLEDGE_FILE = join(APP_ROOT, 'agent', 'knowledge.md');
46 +const COLLECTIONS = ['docs', 'reference', 'examples', 'toolkits'] as const;
47 +
48 +/** URL prefixes for the legacy, pre-session / direct-execution docs. */
49 +const LEGACY_URL_PATTERNS = [
50 + '/docs/tools-direct',
51 + '/docs/auth-configuration',
52 + '/docs/sessions-vs-direct-execution',
53 +];
54 +
55 +const STOPWORDS = new Set([
56 + 'the', 'a', 'an', 'and', 'or', 'but', 'is', 'are', 'was', 'were', 'be', 'been',
57 + 'to', 'of', 'in', 'on', 'for', 'with', 'as', 'at', 'by', 'from', 'how', 'do',
58 + 'does', 'did', 'what', 'why', 'when', 'which', 'who', 'can', 'i', 'you', 'it',
59 + 'this', 'that', 'these', 'those', 'my', 'your', 'we', 'they', 'use', 'using',
60 + 'work', 'works', 'about', 'into', 'so', 'if', 'me', 'get', 'set', 'up',
61 +]);
62 +
63 +export type Collection = 'docs' | 'examples' | 'reference' | 'toolkits' | 'knowledge';
64 +
65 +export interface DocPage {
66 + collection: Collection;
67 + title: string;
68 + description: string;
69 + url: string;
70 + legacy: boolean;
71 + /** Headings, lowercased, for ranking. */
72 + headings: string[];
73 + /** Original-case plain text for snippets. */
74 + text: string;
75 + /** Lowercased title + description + text for scoring. */
76 + lowerText: string;
77 +}
78 +
79 +interface BundlePage {
80 + collection: Collection;
81 + url: string;
82 + title: string;
83 + description: string;
84 + legacy: boolean;
85 + /** Cleaned Markdown body (no frontmatter), enough for search + read_doc. */
86 + markdown: string;
87 +}
88 +interface BundleToolkit {
89 + slug?: string;
90 + name?: string;
91 + description?: string;
92 + category?: string;
93 + authSchemes?: string[];
94 +}
95 +const BUNDLE = bundledIndex as { pages: BundlePage[]; toolkits: BundleToolkit[] };
96 +
97 +/**
98 + * Whether the live content tree is on disk. True in dev / local (read fresh
99 + * files); false in the deployed eve service (use the bundled snapshot). Set
100 + * `EVE_FORCE_BUNDLE=1` to exercise the bundle path locally.
101 + */
102 +const CONTENT_AVAILABLE =
103 + process.env.EVE_FORCE_BUNDLE !== '1' && existsSync(join(CONTENT_ROOT, 'docs'));
104 +
105 +/** Mirror of lib/search-index.ts `urlFromContentPath` so links match real routes. */
106 +export function urlFromContentPath(absPath: string): string | undefined {
107 + const rel = relative(CONTENT_ROOT, absPath).replace(/\\/g, '/');
108 + const withoutExt = rel.replace(/\.mdx?$/, '');
109 + const parts = withoutExt.split('/');
110 + const collection = parts.shift();
111 + if (!collection) return undefined;
112 + if (collection === 'docs') return `/docs/${parts.join('/')}`.replace(/\/index$/, '');
113 + if (collection === 'examples') return `/examples/${parts.join('/')}`.replace(/\/index$/, '');
114 + if (collection === 'reference') return `/reference/${parts.join('/')}`.replace(/\/index$/, '');
115 + if (collection === 'toolkits') {
116 + if (parts[0] === 'faq') return undefined;
117 + return `/toolkits/${parts.join('/')}`.replace(/\/index$/, '');
118 + }
119 + return undefined;
120 +}
121 +
122 +export function isLegacyUrl(url: string): boolean {
123 + return LEGACY_URL_PATTERNS.some((p) => url === p || url.startsWith(`${p}/`));
124 +}
125 +
126 +export function tokenize(query: string): string[] {
127 + return query
128 + .toLowerCase()
129 + .split(/[^a-z0-9_]+/)
130 + .filter((t) => t.length > 1 && !STOPWORDS.has(t));
131 +}
132 +
133 +export function parseFrontmatter(raw: string): {
134 + title: string;
135 + description: string;
136 + legacy: boolean;
137 + body: string;
138 +} {
139 + const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
140 + if (!match) return { title: '', description: '', legacy: false, body: raw };
141 + const [, fm, body] = match;
142 + const get = (key: string) => {
143 + const m = fm.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'));
144 + return m ? m[1].trim().replace(/^["']|["']$/g, '') : '';
145 + };
146 + return { title: get('title'), description: get('description'), legacy: get('legacy') === 'true', body };
147 +}
148 +
149 +/** Strip MDX/JSX noise to readable text (keeps prose and inline code words). */
150 +function toPlainText(body: string): string {
151 + return body
152 + .replace(/```[\s\S]*?```/g, ' ')
153 + .replace(/<\/?[A-Za-z][^>]*>/g, ' ')
154 + .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
155 + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
156 + .replace(/[#>*_`|]/g, ' ')
157 + .replace(/\s+/g, ' ')
158 + .trim();
159 +}
160 +
161 +/** Clean MDX into Markdown the model can read: drop frontmatter and bare JSX tags. */
162 +export function toCleanMarkdown(raw: string): string {
163 + const { body } = parseFrontmatter(raw);
164 + return body
165 + .replace(/<\/?[A-Za-z][A-Za-z0-9.]*(\s[^>]*)?\/?>/g, '')
166 + .replace(/\n{3,}/g, '\n\n')
167 + .trim();
168 +}
169 +
170 +/**
171 + * Extract a page's section anchors from its Markdown headings, so the assistant
172 + * can link a specific section (e.g. `/docs/how-composio-works#users`) instead
173 + * of just the page. Anchor slugs match the docs' heading-id convention.
174 + */
175 +export function extractSections(markdown: string): { title: string; anchor: string }[] {
176 + return [...markdown.matchAll(/^#{2,4}\s+(.+?)\s*$/gm)].map((m) => {
177 + const title = m[1].replace(/[`*_]/g, '').trim();
178 + const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
179 + return { title, anchor: `#${slug}` };
180 + });
181 +}
182 +
183 +function makePage(args: {
184 + collection: Collection;
185 + title: string;
186 + description: string;
187 + url: string;
188 + legacy: boolean;
189 + body: string;
190 +}): DocPage {
191 + const headings = (args.body.match(/^#{1,4}\s+(.+)$/gm) ?? []).map((h) =>
192 + h.replace(/^#{1,4}\s+/, '').toLowerCase().trim(),
193 + );
194 + const text = toPlainText(args.body);
195 + return {
196 + collection: args.collection,
197 + title: args.title || args.url,
198 + description: args.description,
199 + url: args.url,
200 + legacy: args.legacy,
201 + headings,
202 + text,
203 + lowerText: `${args.title} ${args.description} ${text}`.toLowerCase(),
204 + };
205 +}
206 +
207 +/**
208 + * Parse `agent/knowledge.md` into searchable entries. Each `## Title (/url)`
209 + * section becomes one entry linked to its canonical doc page.
210 + */
211 +function loadKnowledge(): DocPage[] {
212 + let raw: string;
213 + try {
214 + raw = readFileSync(KNOWLEDGE_FILE, 'utf8');
215 + } catch {
216 + return [];
217 + }
218 + const pages: DocPage[] = [];
219 + const sectionRe = /^##\s+(.+?)\s*(?:\(([^)]+)\))?\s*$/gm;
220 + const matches = [...raw.matchAll(sectionRe)];
221 + for (let i = 0; i < matches.length; i++) {
222 + const m = matches[i];
223 + const title = m[1].trim();
224 + const url = (m[2] ?? '').trim() || '/docs';
225 + const bodyStart = m.index! + m[0].length;
226 + const bodyEnd = i + 1 < matches.length ? matches[i + 1].index! : raw.length;
227 + const body = raw.slice(bodyStart, bodyEnd).trim();
228 + pages.push(makePage({ collection: 'knowledge', title, description: '', url, legacy: false, body }));
229 + }
230 + return pages;
231 +}
232 +
233 +/**
234 + * Index the toolkit catalog from `public/data/toolkits.json` so the assistant
235 + * can answer "do you have <toolkit>?" — individual toolkit pages are generated
236 + * from this data, not from MDX, so they aren't covered by the content scan.
237 + */
238 +interface Toolkit {
239 + slug?: string;
240 + name?: string;
241 + description?: string;
242 + category?: string;
243 + authSchemes?: string[];
244 +}
245 +
246 +let toolkitMap: Map<string, Toolkit> | undefined;
247 +
248 +/** Parse `public/data/toolkits.json` once into a slug -> toolkit map. */
249 +function getToolkitMap(): Map<string, Toolkit> {
250 + if (toolkitMap) return toolkitMap;
251 + const map = new Map<string, Toolkit>();
252 + if (CONTENT_AVAILABLE) {
253 + try {
254 + const parsed = JSON.parse(readFileSync(join(APP_ROOT, 'public', 'data', 'toolkits.json'), 'utf8'));
255 + const list: Toolkit[] = Array.isArray(parsed) ? parsed : (parsed.toolkits ?? parsed.items ?? []);
256 + for (const tk of list) if (tk?.slug) map.set(tk.slug, tk);
257 + } catch {
258 + // no catalog available
259 + }
260 + }
261 + // Deployed runtime (or missing catalog): use the bundled toolkit snapshot.
262 + if (map.size === 0) for (const tk of BUNDLE.toolkits) if (tk?.slug) map.set(tk.slug, tk);
263 + toolkitMap = map;
264 + return map;
265 +}
266 +
267 +function loadToolkits(): DocPage[] {
268 + const pages: DocPage[] = [];
269 + for (const tk of getToolkitMap().values()) {
270 + const name = tk.name ?? tk.slug!;
271 + const body = `${tk.description ?? ''} Category: ${tk.category ?? ''}. Toolkit slug: ${tk.slug}.`;
272 + pages.push(
273 + makePage({
274 + collection: 'toolkits',
275 + title: `${name} toolkit`,
276 + description: tk.description ?? '',
277 + url: `/toolkits/${tk.slug}`,
278 + legacy: false,
279 + body,
280 + }),
281 + );
282 + }
283 + return pages;
284 +}
285 +
286 +let indexCache: DocPage[] | undefined;
287 +
288 +export function buildIndex(): DocPage[] {
289 + if (indexCache) return indexCache;
290 + const pages: DocPage[] = [];
291 + if (CONTENT_AVAILABLE) {
292 + for (const collection of COLLECTIONS) {
293 + const dir = join(CONTENT_ROOT, collection);
294 + let entries: string[];
295 + try {
296 + entries = readdirSync(dir, { recursive: true }) as string[];
297 + } catch {
298 + continue;
299 + }
300 + for (const entry of entries) {
301 + if (!/\.mdx?$/.test(entry)) continue;
302 + const absPath = join(dir, entry);
303 + const url = urlFromContentPath(absPath);
304 + if (!url) continue;
305 + let raw: string;
306 + try {
307 + raw = readFileSync(absPath, 'utf8');
308 + } catch {
309 + continue;
310 + }
311 + const { title, description, legacy, body } = parseFrontmatter(raw);
312 + pages.push(
313 + makePage({
314 + collection: collection as Collection,
315 + title,
316 + description,
317 + url,
318 + legacy: legacy || isLegacyUrl(url),
319 + body,
320 + }),
321 + );
322 + }
323 + }
324 + } else {
325 + // Deployed runtime: content/ isn't on disk, so index the bundled snapshot.
326 + for (const p of BUNDLE.pages) {
327 + pages.push(
328 + makePage({
329 + collection: p.collection,
330 + title: p.title,
331 + description: p.description,
332 + url: p.url,
333 + legacy: p.legacy || isLegacyUrl(p.url),
334 + body: p.markdown,
335 + }),
336 + );
337 + }
338 + }
339 + pages.push(...loadKnowledge());
340 + pages.push(...loadToolkits());
341 + indexCache = pages;
342 + return pages;
343 +}
344 +
345 +/** Resolve a page URL back to its source file and return the raw MDX. */
346 +function authSchemesMarkdown(schemes: string[] = []): string {
347 + if (!schemes.length) return 'n/a';
348 + return schemes.map((scheme) => `\`${scheme}\``).join(', ');
349 +}
350 +
351 +export function readPageByUrl(url: string): { title: string; raw: string } | undefined {
352 + const clean = url.split('#')[0].split('?')[0].replace(/\/$/, '');
353 + const parts = clean.split('/').filter(Boolean);
354 + const collection = parts.shift();
355 + if (!collection || !COLLECTIONS.includes(collection as (typeof COLLECTIONS)[number])) return undefined;
356 +
357 + // Toolkit pages are generated from the catalog, not MDX. Synthesize content
358 + // so the assistant can confirm support and describe the toolkit.
359 + if (collection === 'toolkits') {
360 + const tk = getToolkitMap().get(parts.join('/'));
361 + if (tk) {
362 + const name = tk.name ?? tk.slug!;
363 + const raw = [
364 + `# ${name}`,
365 + '',
366 + tk.description ?? '',
367 + '',
368 + `- **Supported:** yes, \`${tk.slug}\` is a Composio toolkit.`,
369 + `- **Category:** ${tk.category ?? 'n/a'}`,
370 + `- **Auth:** ${authSchemesMarkdown(tk.authSchemes)}`,
371 + '',
372 + `Connect it for a user with \`session.authorize("${tk.slug}")\` (or in-chat auth), then use its tools through the session. See [Configuring sessions](/docs/configuring-sessions), [Authentication](/docs/authentication), and [auth schemes](/reference/api-reference/auth-configs#auth-schemes) for how its auth mode works.`,
373 + ].join('\n');
374 + return { title: `${name} toolkit`, raw };
375 + }
376 + }
377 +
378 + if (CONTENT_AVAILABLE) {
379 + const base = join(CONTENT_ROOT, collection, ...parts);
380 + const candidates = [`${base}.mdx`, `${base}.md`, join(base, 'index.mdx'), join(base, 'index.md')];
381 + for (const candidate of candidates) {
382 + try {
383 + const raw = readFileSync(candidate, 'utf8');
384 + const { title } = parseFrontmatter(raw);
385 + return { title: title || url, raw };
386 + } catch {
387 + // try next candidate
388 + }
389 + }
390 + return undefined;
391 + }
392 +
393 + // Deployed runtime: serve the page from the bundled snapshot.
394 + const page = BUNDLE.pages.find((p) => p.url === clean);
395 + if (page) return { title: page.title || url, raw: page.markdown };
396 + return undefined;
397 +}
docs/agent/tools/bash.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `bash` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/glob.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `glob` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/grep.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `grep` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/read_doc.ts new
+50
@@ -0,0 +1,50 @@
1 +import { defineTool } from 'eve/tools';
2 +import { z } from 'zod';
3 +import { buildIndex, extractSections, readPageByUrl, toCleanMarkdown } from '../lib/docs';
4 +
5 +/**
6 + * read_doc — read the full content of a Composio docs page.
7 + *
8 + * Pass a URL from search_docs (or the concept map) and get the page's cleaned
9 + * Markdown so you can answer from real content instead of a snippet.
10 + */
11 +
12 +const MAX_CHARS = 12000;
13 +
14 +export default defineTool({
15 + description:
16 + 'Read the full Markdown content of a Composio docs page by its URL (e.g. "/docs/authentication"). Returns the page content plus its `sections` (with anchors). Use this on the most relevant pages from search_docs before answering, and link the specific section anchor (e.g. /docs/how-composio-works#users) when your answer comes from one.',
17 + inputSchema: z.object({
18 + url: z.string().min(1).describe('The page URL, e.g. "/docs/authentication" or "/docs/configuring-sessions".'),
19 + }),
20 + async execute({ url }) {
21 + const clean = url.split('#')[0].split('?')[0].replace(/\/$/, '');
22 + const page = readPageByUrl(url);
23 + if (page) {
24 + const markdown = toCleanMarkdown(page.raw);
25 + const truncated = markdown.length > MAX_CHARS;
26 + return {
27 + found: true,
28 + url: clean,
29 + title: page.title,
30 + sections: extractSections(markdown),
31 + truncated,
32 + content: truncated ? `${markdown.slice(0, MAX_CHARS)}\n\n…(truncated)` : markdown,
33 + };
34 + }
35 + // Fallback: the page may be indexed even if its source file can't be read
36 + // directly (e.g. a different runtime layout). Return the indexed text.
37 + const indexed = buildIndex().find((p) => p.url === clean);
38 + if (indexed && indexed.text) {
39 + const truncated = indexed.text.length > MAX_CHARS;
40 + return {
41 + found: true,
42 + url: clean,
43 + title: indexed.title,
44 + truncated,
45 + content: truncated ? `${indexed.text.slice(0, MAX_CHARS)}\n\n…(truncated)` : indexed.text,
46 + };
47 + }
48 + return { found: false, url, message: `No docs page found for "${url}". Use search_docs to find a valid URL.` };
49 + },
50 +});
docs/agent/tools/read_file.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `read_file` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/search_docs.ts new
+75
@@ -0,0 +1,75 @@
1 +import { defineTool } from 'eve/tools';
2 +import { z } from 'zod';
3 +import { buildIndex, tokenize, type DocPage } from '../lib/docs';
4 +
5 +/**
6 + * search_docs — find the most relevant Composio docs pages for a query.
7 + *
8 + * Returns each match's title, URL, description, and a snippet. Use it to locate
9 + * pages, then call `read_doc` on the best matches to read their full content
10 + * before answering.
11 + */
12 +
13 +// Collection priority: docs first, then examples, then references and toolkits.
14 +// (Curated knowledge ranks with docs.) A toolkit-name query still surfaces its
15 +// toolkit page because nothing else matches it.
16 +const PRIORITY: Record<DocPage['collection'], number> = {
17 + docs: 1.3,
18 + knowledge: 1.3,
19 + examples: 1.1,
20 + reference: 0.85,
21 + toolkits: 0.9,
22 +};
23 +
24 +function score(page: DocPage, terms: string[]): number {
25 + const title = page.title.toLowerCase();
26 + let total = 0;
27 + for (const term of terms) {
28 + if (title.includes(term)) total += 12;
29 + if (page.description.toLowerCase().includes(term)) total += 5;
30 + for (const heading of page.headings) if (heading.includes(term)) total += 4;
31 + if (page.url.toLowerCase().includes(term)) total += 6;
32 + const occurrences = page.lowerText.split(term).length - 1;
33 + total += Math.min(occurrences, 5);
34 + }
35 + // Heavily downrank legacy (direct-execution) pages so they only surface when
36 + // nothing in the session-based docs matches.
37 + if (page.legacy) total *= 0.12;
38 + return total * (PRIORITY[page.collection] ?? 1);
39 +}
40 +
41 +function snippet(page: DocPage, terms: string[]): string {
42 + const lower = page.text.toLowerCase();
43 + const at = terms.map((t) => lower.indexOf(t)).filter((i) => i >= 0).sort((a, b) => a - b)[0] ?? 0;
44 + const start = Math.max(0, at - 100);
45 + const slice = page.text.slice(start, start + 360).trim();
46 + return (start > 0 ? '…' : '') + slice + (start + 360 < page.text.length ? '…' : '');
47 +}
48 +
49 +export default defineTool({
50 + description:
51 + 'Search the Composio documentation. Returns the most relevant pages with their title, URL, description, and a snippet. Follow up with read_doc on the best matches to read full page content before answering.',
52 + inputSchema: z.object({
53 + query: z.string().min(1).describe('What to look for, e.g. "authentication", "create a session", "trigger webhook verification".'),
54 + limit: z.number().int().min(1).max(12).optional().describe('How many pages to return. Defaults to 8.'),
55 + }),
56 + async execute({ query, limit = 8 }) {
57 + const terms = tokenize(query);
58 + // Fall back to raw terms if the query was all stopwords.
59 + const effective = terms.length > 0 ? terms : query.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
60 + const ranked = buildIndex()
61 + .map((page) => ({ page, s: score(page, effective) }))
62 + .filter(({ s }) => s > 0)
63 + .sort((a, b) => b.s - a.s)
64 + .slice(0, limit);
65 +
66 + return {
67 + results: ranked.map(({ page }) => ({
68 + title: page.title,
69 + url: page.url,
70 + description: page.description,
71 + snippet: snippet(page, effective),
72 + })),
73 + };
74 + },
75 +});
docs/agent/tools/web_fetch.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `web_fetch` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/web_search.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `web_search` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/agent/tools/write_file.ts new
+5
@@ -0,0 +1,5 @@
1 +import { disableTool } from 'eve/tools';
2 +
3 +// Disable the default-harness `write_file` tool. The docs assistant answers only from
4 +// the Composio docs via search_docs + read_doc — no web, shell, or sandbox FS.
5 +export default disableTool();
docs/api-overviews/auth-configs.mdx new
+26
@@ -0,0 +1,26 @@
1 +An auth config is a blueprint that defines how a toolkit authenticates across all your users. It specifies the authentication method, the scopes your tools can request, and which credentials Composio uses to run the OAuth or token flow.
2 +
3 +A single auth config applies to every user who connects that toolkit. When a user authenticates against it, Composio creates a [connected account](/reference/api-reference/connected-accounts) that stores their tokens and links them to your user ID.
4 +
5 +Each auth config defines:
6 +
7 +- **Auth scheme**: OAuth2, API key, Bearer token, or Basic Auth
8 +- **Scopes**: what your tools are allowed to do on the user's behalf
9 +- **Credentials**: Composio's managed app, or your own OAuth client and secrets
10 +
11 +Reach for a custom auth config when you need your own branding on consent screens, custom scopes, a dedicated rate-limit quota, or a custom toolkit instance. See [managed vs custom auth](/docs/custom-app-vs-managed-app) for the decision and [how Composio handles authentication](/docs/authentication) for the full picture.
12 +
13 +## Auth schemes
14 +
15 +The `auth_scheme` on an auth config determines how users authenticate to the toolkit. Composio supports four. The schemes available for a given toolkit come from the toolkit itself.
16 +
17 +| Scheme | What it is | When it's used |
18 +|---|---|---|
19 +| `OAUTH2` | OAuth 2.0 authorization-code flow. The user authorizes through a hosted consent screen, and Composio stores and automatically refreshes the access and refresh tokens. | Most apps with user accounts (Gmail, GitHub, Slack, Notion, and so on). Uses Composio's managed OAuth app by default; bring your own for custom branding or scopes. |
20 +| `API_KEY` | A static API key the user provides. There's no OAuth flow: the key is stored on the connected account and sent on each request. | Services that authenticate with a key, such as SendGrid, Tavily, or PostHog. |
21 +| `BEARER_TOKEN` | A bearer access token you already hold (for example, from your own OAuth flow). Composio sends it as `Authorization: Bearer <token>` and does not refresh it, so you keep it current. | Bringing an existing OAuth or server-to-server token into Composio, or apps that issue long-lived tokens. |
22 +| `BASIC` | HTTP Basic authentication with a username and password. | Services that use Basic Auth. |
23 +
24 +Most OAuth toolkits work out of the box with Composio managed auth. For the others you supply the credential fields. To choose or customize the scheme, see [managed vs custom auth](/docs/custom-app-vs-managed-app).
25 +
26 +These endpoints use your project API key in the `x-api-key` header. Each auth config is addressed by its `nanoid`, and you can enable or disable one without deleting it.
docs/api-overviews/connected-accounts.mdx new
+22
@@ -0,0 +1,22 @@
1 +A connected account is a single user's authorized connection to a toolkit. It stores their credentials (OAuth tokens or API keys) and links them to your user ID, so your tools can act on that user's behalf.
2 +
3 +Composio creates a connected account when a user completes the flow defined by an [auth config](/reference/api-reference/auth-configs). From there you manage its full lifecycle:
4 +
5 +- **Create or link**: start a new connection, or generate an auth link session for the user to authorize. See [manually authenticating users](/docs/authenticating-users/manually-authenticating).
6 +- **Refresh**: renew authentication for an account whose tokens have expired.
7 +- **Enable, disable, or update**: change an account's status or metadata without removing it.
8 +- **Revoke or delete**: revoke the grant at the provider, or remove the account from Composio.
9 +
10 +Each account is addressed by its `nanoid`. List endpoints accept filters so you can find accounts by user, toolkit, or auth config.
11 +
12 +## Link auth (Composio Connect Links)
13 +
14 +A Composio Connect Link is a hosted, secure sign-in page. You create one with the create auth link session endpoint, redirect the user to the returned URL, and Composio handles the rest: the user signs in, Composio creates the connected account, and Composio stores and refreshes its tokens. Credentials never pass through your app. This works for all Composio managed connections, with no OAuth credentials to set up.
15 +
16 +By default a connected account is `PRIVATE` and usable only by its owning user. Mark one `SHARED` to let other users reach it through a per-connection access control list. See [shared connections](/docs/authenticating-users/shared-connections).
17 +
18 +These endpoints use your project API key in the `x-api-key` header.
19 +
20 +<Callout type="warning">
21 +Shared-connection ACL fields are experimental and nested under an `experimental` block on the wire. Pin a specific SDK version if you depend on the current shape.
22 +</Callout>
docs/api-overviews/files.mdx new
+16
@@ -0,0 +1,16 @@
1 +These endpoints handle files that tools read and write during execution. When a tool produces or consumes a file, Composio stores it in object storage and exchanges it through presigned URLs rather than streaming bytes through the API.
2 +
3 +You reach for these endpoints to:
4 +
5 +- **List files** that tools have generated, optionally filtered by app and action.
6 +- **Request an upload**: get a presigned S3 URL, `PUT` your file to it, then pass the returned reference into a tool's input.
7 +
8 +This keeps large payloads out of request bodies. Tools receive a file reference and resolve the underlying object on their side.
9 +
10 +<Callout type="info">
11 +File uploads are a two-step flow. Call the upload-request endpoint to mint a presigned URL, then upload the file contents directly to that URL. The API never receives the raw bytes.
12 +</Callout>
13 +
14 +If your agent works with files inside a session, prefer the session file mount, where the sandbox exposes uploaded files to running code. See the [sandbox](/docs/sandbox) for the sandbox helpers (`upload_local_file`, `smart_file_extract`) that build on this storage.
15 +
16 +These endpoints use your project API key in the `x-api-key` header.
docs/api-overviews/logs.mdx new
+139
@@ -0,0 +1,139 @@
1 +The Logs API returns **individual tool execution events**, one record per tool call. Use it to debug failures, inspect request/response payloads, and trace specific user activity. For aggregated counts (how many tool calls happened), use the [Usage API](/reference/api-reference/organization) instead.
2 +
3 +All endpoints in this section require a **project API key** (`x-api-key`) or a valid session cookie.
4 +
5 +## List logs
6 +
7 +```bash
8 +curl -X POST https://backend.composio.dev/api/v3.1/logs/tool_execution \
9 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
10 + -H "Content-Type: application/json" \
11 + -d '{
12 + "limit": 20,
13 + "time_range": {
14 + "from": 1744848000000,
15 + "to": 1744934400000
16 + },
17 + "filters": [
18 + { "field": "toolkit_slug", "operator": "==", "value": "gmail" },
19 + { "field": "status", "operator": "==", "value": "failed" }
20 + ]
21 + }'
22 +```
23 +
24 +The response contains a page of log entries and a `next_cursor`:
25 +
26 +```json
27 +{
28 + "logs": [
29 + {
30 + "id": "log_-jRTWClpBoVo",
31 + "timestamp": "2026-04-17T10:25:00.000Z",
32 + "type": "tool.execution",
33 + "status": "failed",
34 + "level": "error",
35 + "message": "GMAIL_SEND_EMAIL failed: invalid recipient",
36 + "metadata": { /* tool, toolkit, user_id, connected_account_id, ... */ },
37 + "metrics": { "duration_ms": 202 },
38 + "parent": null
39 + }
40 + ],
41 + "next_cursor": "eyJwYWdlIjoyfQ=="
42 +}
43 +```
44 +
45 +Pass `next_cursor` back as `cursor` on the next request to paginate. When `next_cursor` is `null`, you've reached the end.
46 +
47 +### Filter fields
48 +
49 +Pass one or more filters in the `filters` array. Filters are **AND**-combined.
50 +
51 +| Field | What it matches |
52 +|---|---|
53 +| `tool_slug` | The specific tool that was called (e.g. `GMAIL_SEND_EMAIL`) |
54 +| `toolkit_slug` | The toolkit (e.g. `gmail`, `slack`, `github`) |
55 +| `connected_account_id` | The connected account used for the call |
56 +| `auth_config_id` | The auth config (integration) behind the connected account |
57 +| `status` | `success` or `failed` |
58 +| `user_id` | Entity that initiated the call |
59 +| `session_id` | Tool router session, if routed through a session |
60 +| `sandbox_id` | Sandbox the call ran in, if applicable |
61 +| `request_id` | Request ID (useful for correlating with your own logs) |
62 +| `log_id` | Exact log ID (equivalent to the detail endpoint) |
63 +
64 +### Operators
65 +
66 +| Operator | Meaning |
67 +|---|---|
68 +| `==` | Exact match |
69 +| `!=` | Not equal |
70 +| `contains` | Substring match |
71 +| `not_contains` | Substring does not match |
72 +
73 +### Parameters
74 +
75 +| Field | Type | Default | Notes |
76 +|---|---|---|---|
77 +| `limit` | number | `20` | Max 100 |
78 +| `cursor` | string \| null | `null` | Opaque pagination token from previous response |
79 +| `filters` | array | `[]` | AND-combined |
80 +| `time_range.from` | number | — | Epoch milliseconds |
81 +| `time_range.to` | number | — | Epoch milliseconds |
82 +
83 +## Get a single log
84 +
85 +Fetch one log by ID to get the **full** payload, including request/response bodies, timing breakdowns, and source metadata:
86 +
87 +```bash
88 +curl https://backend.composio.dev/api/v3.1/logs/tool_execution/log_-jRTWClpBoVo \
89 + -H "x-api-key: YOUR_PROJECT_API_KEY"
90 +```
91 +
92 +The detail response includes everything from the list shape plus:
93 +
94 +- `timings`: `start_time` and `end_time` in epoch ms
95 +- `context`: `session_id`, `trace_id`, `request_id`
96 +- `source`: `host` (e.g. `mcp`, `sdk`, `api`), `framework`, `language`
97 +- `data`: the full request payload and response body
98 +
99 +This is the endpoint to call when you need to reconstruct *exactly* what happened, for example when debugging a 500 from a user report.
100 +
101 +## Recipes
102 +
103 +### Find failed Gmail tool calls in the last hour
104 +
105 +```bash
106 +NOW=$(date +%s)000
107 +HOUR_AGO=$(( $(date +%s) - 3600 ))000
108 +curl -X POST https://backend.composio.dev/api/v3.1/logs/tool_execution \
109 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
110 + -H "Content-Type: application/json" \
111 + -d "{
112 + \"time_range\": { \"from\": ${HOUR_AGO}, \"to\": ${NOW} },
113 + \"filters\": [
114 + { \"field\": \"toolkit_slug\", \"operator\": \"==\", \"value\": \"gmail\" },
115 + { \"field\": \"status\", \"operator\": \"==\", \"value\": \"failed\" }
116 + ]
117 + }"
118 +```
119 +
120 +### Get failures for a specific user
121 +
122 +```bash
123 +curl -X POST https://backend.composio.dev/api/v3.1/logs/tool_execution \
124 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
125 + -H "Content-Type: application/json" \
126 + -d '{
127 + "filters": [
128 + { "field": "user_id", "operator": "==", "value": "user_abc123" },
129 + { "field": "status", "operator": "==", "value": "failed" }
130 + ]
131 + }'
132 +```
133 +
134 +### Fetch a single log's full request/response
135 +
136 +```bash
137 +curl https://backend.composio.dev/api/v3.1/logs/tool_execution/log_-jRTWClpBoVo \
138 + -H "x-api-key: YOUR_PROJECT_API_KEY"
139 +```
docs/api-overviews/mcp.mdx new
+9
@@ -0,0 +1,9 @@
1 +<Callout type="warning">
2 +This API is deprecated. Use a session's MCP endpoint instead. Create a session with `composio.create(userId, { mcp: true })`, then read the hosted URL off `session.mcp.url`. See [Using sessions via MCP](/docs/sessions-via-mcp) and [migrating MCP servers to sessions](/docs/migration-guide/mcp-servers-to-sessions).
3 +</Callout>
4 +
5 +The MCP API is the standalone, hosted [Model Context Protocol](https://modelcontextprotocol.io) server-management surface. It let you stand up and manage a separate server config per toolkit, then mint a per-user MCP URL that any MCP-compatible client could connect to.
6 +
7 +These endpoints create, list, update, and delete MCP servers, including custom servers spanning multiple apps, generate per-user MCP URLs, and manage per-user server instances and their connected accounts.
8 +
9 +Sessions replace this. A single `composio.create(...)` gives you the same MCP URL pattern, keyed by `user_id`, while handling tool discovery, authentication, context, and versioning for you. Your existing tools, auth configs (`ac_…`), and connected accounts carry over with no re-authentication. To pin a session to a fixed tool list the way a server did, use the direct-tools preset described in [Configuring sessions](/docs/configuring-sessions).
docs/api-overviews/migration.mdx new
+9
@@ -0,0 +1,9 @@
1 +These endpoints help you migrate from Composio v1 to v3 by translating identifiers between the two systems.
2 +
3 +Reach for this endpoint when you have a v1 UUID and need the corresponding v3 NanoId so existing references continue to resolve against the v3 API. Pass the UUID and get the NanoId back.
4 +
5 +These endpoints authenticate with your project API key in the `x-api-key` header.
6 +
7 +<Callout type="info">
8 +This is a low-level translation helper for migrating identifiers. For migrating SDK code, sessions, and toolkit versioning, see the [migration guides](/docs/migration-guide).
9 +</Callout>
docs/api-overviews/organization.mdx renamed
+6 -21
@@ -1,17 +1,11 @@
1 ----
2 -title: Usage metering
3 -description: Query aggregated tool call and session counts for your org or project, with rich filtering and breakdown options.
4 -keywords: ['usage', 'metering', 'analytics', 'billing', 'observability']
5 ----
6 -
7 -The Usage API returns **aggregated counts** of tool calls and sessions. Use it to power billing dashboards, customer-facing analytics, or internal utilization reports. For individual events, use the [Logs API](/docs/observability/logs).
1 +The Usage API returns **aggregated counts** of tool calls and sessions. Use it to power billing dashboards, customer-facing analytics, or internal utilization reports. For individual events, use the [Logs API](/reference/api-reference/logs).
2
3 There are two query shapes:
4
11 -- **Summary** — totals across one or more entity types in a time window.
12 -- **Breakdown** — one entity type, grouped by a dimension (tool, user, session, etc.).
5 +- **Summary**: totals across one or more entity types in a time window.
6 +- **Breakdown**: one entity type, grouped by a dimension (tool, user, session, etc.).
7
14 -Each shape comes in an org-scoped and a project-scoped flavor.
8 +Each shape comes in an org-scoped and a project-scoped flavor. The org-scoped endpoints are documented below; the project-scoped usage endpoints (`POST /api/v3.1/project/usage/*`) also appear on the [Projects](/reference/api-reference/projects) reference page.
9
10 ## Authentication
11
@@ -29,7 +23,7 @@ The org endpoints accept a `project_id` filter so you can slice by project witho
23 | Entity type | What it counts |
24 |---|---|
25 | `tool_calls` | Every tool execution (successful or failed) |
32 -| `sessions` | Tool router sessions created |
26 +| `sessions` | Sessions created |
27
28 ## Summary
29
@@ -65,7 +59,7 @@ Response:
59 | `to` | number | now | Epoch milliseconds |
60 | `entity_types` | string[] | all | Subset of `tool_calls`, `sessions` |
61 | `filters.user_id` | string \| string[] | — | Filter events by initiating user |
68 -| `filters.session_id` | string \| string[] | — | Filter events by tool router session |
62 +| `filters.session_id` | string \| string[] | — | Filter events by session |
63 | `filters.project_id` | string \| string[] | — | Only meaningful on org endpoints; ignored on project endpoints |
64
65 ## Breakdown
@@ -190,12 +184,3 @@ curl -X POST https://backend.composio.dev/api/v3.1/project/usage/tool_calls \
184 "filters": { "user_id": "user_abc123" }
185 }'
186 ```
193 -
194 -## What to read next
195 -
196 -<Cards>
197 - <Card icon={<Terminal />} title="Tool execution logs" href="/docs/observability/logs" description="Debug individual tool executions with full request/response payloads" />
198 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="Understand how tools and toolkits work in Composio" />
199 - <Card icon={<Database />} title="Organization API reference" href="/reference/api-reference/organization" description="Full request and response schemas for org-level usage endpoints" />
200 - <Card icon={<Database />} title="Projects API reference" href="/reference/api-reference/projects" description="Full request and response schemas for project-level usage endpoints" />
201 -</Cards>
docs/api-overviews/projects.mdx new
+65
@@ -0,0 +1,65 @@
1 +Projects are Composio's multi-tenancy primitive. Every Composio account belongs to an **organization**. Inside an organization, **projects** are isolated environments that scope your API keys, connected accounts, auth configs, and webhook configurations. Resources in one project are not accessible from another.
2 +
3 +```mermaid
4 +graph LR
5 + ORG["Organization (org_xxx)"] --- P1["Project: Production (proj_xxx)"]
6 + ORG --- P2["Project: Staging (proj_xxx)"]
7 + ORG --- TM["Team Members"]
8 + P1 --- A1["API Keys"]
9 + P1 --- A2["Connected Accounts"]
10 + P1 --- A3["Auth Configs"]
11 + P1 --- A4["Webhook Config"]
12 + P2 --- B1["..."]
13 +```
14 +
15 +Common reasons to use multiple projects:
16 +
17 +- **Separate environments**: keep production and staging isolated
18 +- **Separate products**: keep resources for different apps independent
19 +- **Client isolation**: give each client their own project with separate credentials and data
20 +
21 +## Managing projects
22 +
23 +Manage projects from the [dashboard](https://dashboard.composio.dev/~/org/) or via the API using an **organization API key** (`x-org-api-key`).
24 +
25 +<Callout type="info">
26 +Project management endpoints use the `x-org-api-key` header, not the regular `x-api-key`. Find your org API key in the dashboard under **Settings > Organization**.
27 +</Callout>
28 +
29 +There is no limit on the number of projects per organization. Project names must be unique within the organization. Create a project with `should_create_api_key: true` to get an API key back in the response:
30 +
31 +```bash
32 +curl -X POST https://backend.composio.dev/api/v3.1/org/owner/project/new \
33 + -H "x-org-api-key: YOUR_ORG_API_KEY" \
34 + -H "Content-Type: application/json" \
35 + -d '{
36 + "name": "my-staging-project",
37 + "should_create_api_key": true
38 + }'
39 +```
40 +
41 +```json
42 +{
43 + "id": "proj_abc123xyz456",
44 + "name": "my-staging-project",
45 + "api_key": "ak_abc123xyz456"
46 +}
47 +```
48 +
49 +The list endpoint supports pagination with `limit` and `cursor`; getting a project by ID returns the full project object including its API keys.
50 +
51 +## Project settings
52 +
53 +Each project has settings that control security, logging, and display behavior. These endpoints use your **project API key** (`x-api-key`), not the org key.
54 +
55 +```bash
56 +curl -X PATCH https://backend.composio.dev/api/v3.1/org/project/config \
57 + -H "x-api-key: YOUR_API_KEY" \
58 + -H "Content-Type: application/json" \
59 + -d '{
60 + "mask_secret_keys_in_connected_account": false,
61 + "log_visibility_setting": "show_all"
62 + }'
63 +```
64 +
65 +Notable security setting: `require_mcp_api_key`, when `true`, requires MCP server requests to include a valid `x-api-key` header. This defaults to `true` for organizations created on or after March 5, 2026. You can also view and update project settings from **Settings > Project Settings** in the [dashboard](https://dashboard.composio.dev/~/project/settings/general).
docs/api-overviews/tool-router.mdx new
+11
@@ -0,0 +1,11 @@
1 +These are Composio's session endpoints. A **session** is the runtime context your agent uses to work for one of your users: it scopes which user's connected accounts are in play, which tools are available, how authentication happens, and where execution state lives. Read [What is a session?](/docs/how-composio-works) for the full concept.
2 +
3 +<Callout type="info">
4 +Sessions were formerly called the "tool router", which is why these endpoints live under `tool_router`. They are the same thing.
5 +</Callout>
6 +
7 +In the SDK you do not call these endpoints directly. Use `composio.create(...)` to start a session and `composio.use(...)` to resume one, then call `session.tools()`, `session.execute(...)`, and `session.authorize(...)` on the returned object.
8 +
9 +Reach for the raw API when you need lower-level control: creating and patching a session config, attaching to an existing session, searching for tools, executing tools and meta tools, opening link sessions for auth, proxying authenticated requests, and reading or writing files in a session mount.
10 +
11 +See [Configuring sessions](/docs/configuring-sessions) for toolkits, auth configs, account selection, and presets.
docs/api-overviews/toolkits.mdx new
+17
@@ -0,0 +1,17 @@
1 +A toolkit is a collection of related tools for a single app, like `gmail`, `github`, or `slack`. Each toolkit groups the actions for that service, its authentication requirements, and the trigger types it exposes.
2 +
3 +Reach for these endpoints when you want to:
4 +
5 +- List the toolkits in the catalog, sorted by popularity, to browse what is available before configuring a session.
6 +- Fetch a single toolkit by `slug` for its name, logo, categories, and metadata.
7 +- Fetch several toolkits at once with the multi endpoint.
8 +- List the available toolkit categories to filter the catalog by use case.
9 +- Read the toolkits changelog to track when tools or schemas change.
10 +
11 +These endpoints authenticate with your project API key in the `x-api-key` header.
12 +
13 +<Callout type="info">
14 +Tools within a toolkit are versioned. When you execute a tool, resolve to a known version with `toolkit_versions=latest` or a pinned dated version. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
15 +</Callout>
16 +
17 +To browse toolkits visually, see the [toolkits catalog](/toolkits). For the concepts and SDK usage, see [Tools and toolkits](/docs/how-composio-works) and [Configuring sessions](/docs/configuring-sessions).
docs/api-overviews/tools.mdx new
+44
@@ -0,0 +1,44 @@
1 +Tools are the individual executable actions inside a toolkit, like `GMAIL_SEND_EMAIL` or `GITHUB_CREATE_ISSUE`. Each tool has an input schema describing its parameters and an output schema describing what it returns. Tool slugs are SCREAMING_SNAKE_CASE and follow a `{TOOLKIT}_{ACTION}` pattern.
2 +
3 +Reach for these endpoints when you want to:
4 +
5 +- List or search the catalog of available tools, optionally scoped to one or more toolkits.
6 +- Fetch a single tool's input and output schema by `tool_slug` before constructing a call.
7 +- Execute a tool on behalf of a user's connected account, or generate the inputs for an execution from natural language.
8 +- Look up the OAuth scopes a set of tools requires, or send an authenticated proxy request to an app's underlying API.
9 +
10 +These endpoints authenticate with your project API key in the `x-api-key` header.
11 +
12 +<Callout type="info">
13 +Manual tool execution requires an explicit toolkit version. Pass `toolkit_versions=latest` (or pin a dated version like `20251027_00`) so calls resolve to a known tool definition. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
14 +</Callout>
15 +
16 +For the concepts behind tools, schemas, and authentication, see [Tools and toolkits](/docs/how-composio-works).
17 +
18 +## Proxy execute
19 +
20 +Proxy execute sends an authenticated HTTP request through a toolkit's [connected account](/docs/auth-configuration/connected-accounts) without a predefined tool, and Composio injects the OAuth token, API key, or other credentials on the server side so your code never touches raw secrets. Reach for it when you need an endpoint that Composio's predefined tools do not cover, when you need a request shape (custom query parameters, field masks, or advanced filters) that a predefined tool cannot express, or when a terminal agent would otherwise hardcode a bearer token in a `curl` call.
21 +
22 +Call it with `composio.tools.proxyExecute()` in the TypeScript SDK, `composio.tools.proxy()` in the Python SDK, or `POST /api/v3.1/tools/execute/proxy` over HTTP. The `endpoint` can be an absolute URL (`https://api.example.com/v1/resource`) or a path relative to the toolkit's base URL (`/v1/resource`), `method` is the HTTP verb, `connectedAccountId` selects the account to authenticate as, `body` carries the JSON payload, and `parameters` adds extra headers and query parameters. The response forwards the upstream `status`, `headers`, and parsed `data` verbatim.
23 +
24 +```typescript
25 +// @noErrors
26 +import { Composio } from '@composio/core';
27 +
28 +const composio = new Composio({ apiKey: 'your_api_key' });
29 +
30 +const { status, data } = await composio.tools.proxyExecute({
31 + endpoint: '/repos/composiohq/composio/issues/1',
32 + method: 'GET',
33 + connectedAccountId: 'ca_github_user_123',
34 + parameters: [{ name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' }],
35 +});
36 +
37 +console.log(status, data);
38 +```
39 +
40 +<Callout type="warn">
41 +Proxy execute rejects cross-domain requests, so the `endpoint` must resolve to the same domain as the connected account's toolkit, and you should not set the `Authorization` header yourself because Composio injects the correct credential for the account's auth scheme. This is an intentional security boundary, not a quota, so it cannot be bypassed by reshaping the request.
42 +</Callout>
43 +
44 +Proxy execute is a form of [direct tool execution](/docs/sessions-vs-direct-execution): it bypasses session state, tool schemas, and modifiers. If you are building an agent, prefer [sessions](/docs/configuring-sessions), and use the proxy only for the specific API call that is not available as a tool. The full request and response schema lives in the [`POST /api/v3.1/tools/execute/proxy`](/reference/api-reference/tools/postToolsExecuteProxy) reference.
docs/api-overviews/triggers.mdx new
+20
@@ -0,0 +1,20 @@
1 +Triggers let you subscribe to events from a user's connected app, such as a new Gmail message, a GitHub commit, or a Slack message, and receive the event data as a structured payload at your webhook endpoint.
2 +
3 +There are two layers to understand:
4 +
5 +- A **trigger type** is a template that defines what event to listen for and what configuration it needs. For example, `GITHUB_COMMIT_EVENT` requires an `owner` and a `repo`. Each toolkit exposes its own trigger types.
6 +- A **trigger instance** is a trigger type scoped to a specific user and connected account. Creating one produces an instance with its own `ti_*` ID that you can enable, disable, or delete independently.
7 +
8 +Reach for these endpoints when you want to:
9 +
10 +- Discover the trigger types a toolkit offers, or fetch one type by `slug` to inspect its config and payload schema.
11 +- Create or update a trigger instance for a connected account with the upsert endpoint.
12 +- List active trigger instances, or enable, disable, and delete an instance by `triggerId`.
13 +
14 +These endpoints authenticate with your project API key in the `x-api-key` header.
15 +
16 +<Callout type="info">
17 +Creating a trigger instance only registers it. To actually receive events, set a webhook URL for your project once, then route incoming events on `metadata.trigger_slug`. See [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events).
18 +</Callout>
19 +
20 +For the full concept overview, see [Triggers](/docs/triggers).
docs/api-overviews/webhook-endpoints.mdx new
+7
@@ -0,0 +1,7 @@
1 +Webhook endpoints are per-OAuth-app webhook ingress configurations. They define the inbound URL a provider posts events to, along with the signing secret Composio stores and uses to verify those incoming payloads.
2 +
3 +Reach for these endpoints when an OAuth app you have configured needs to deliver provider-side events into Composio. You create an endpoint, configure or update it by its `nano_id`, and store the signing secret Composio uses to authenticate inbound requests.
4 +
5 +Each endpoint is addressed by its `nano_id`. The `POST` to `/webhook_endpoints/{nano_id}` replaces the full configuration, while `PATCH` updates it in place.
6 +
7 +This is distinct from [webhook subscriptions](/reference/api-reference/webhook-subscriptions), which control where Composio delivers outbound trigger events. To verify the signature on payloads Composio sends you, see [Webhook verification](/docs/webhook-verification). To set up the trigger events those payloads carry, see [Triggers](/docs/triggers).
docs/api-overviews/webhook-subscriptions.mdx renamed
+20 -60
@@ -1,20 +1,31 @@
1 ----
2 -title: Subscribing to connection expiry events
3 -description: Detect when OAuth connections expire and prompt users to re-authenticate
4 -keywords: [expired, connections, re-authenticate, webhook, oauth, refresh]
5 ----
1 +Webhook subscriptions are outbound delivery configurations. They define the URL Composio posts [trigger](/docs/triggers) events to, along with the signing secret and the set of event types you want to receive.
2 +
3 +Reach for these endpoints to register where Composio should send events, to filter delivery to specific event types, and to manage the signing secret used to verify those deliveries. List the available event types with the `/webhook_subscriptions/event_types` endpoint, then create a subscription scoped to the ones you care about.
4 +
5 +Each subscription is addressed by its `id`. You can update its URL and filters with `PATCH`, delete it, and rotate its signing secret with `/webhook_subscriptions/{id}/rotate_secret` if the secret leaks.
6 +
7 +Every webhook request Composio sends includes `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers. Store the secret as `COMPOSIO_WEBHOOK_SECRET` and verify each payload before trusting it. See [Webhook verification](/docs/webhook-verification) for the SDK and manual verification flows.
8 +
9 +## Event types
10 +
11 +A subscription's `enabled_events` controls which events get delivered to its URL. Two broad families exist:
12 +
13 +- **Trigger events** like `composio.trigger.message` — payloads emitted by [triggers](/docs/triggers) you've enabled (new email, new issue, etc.).
14 +- **Lifecycle events** like `composio.connected_account.expired` — emitted when a [connected account](/docs/auth-configuration/connected-accounts) changes state.
15 +
16 +List everything you can subscribe to with the `/webhook_subscriptions/event_types` endpoint, then scope a subscription to the events you handle.
17 +
18 +## Detecting connection expiry
19
20 Composio automatically refreshes OAuth tokens before they expire. But when a refresh token is revoked or expires, the connection enters an `EXPIRED` state and the user must re-authenticate.
21
9 -You can detect this proactively using the `composio.connected_account.expired` webhook event instead of waiting for a tool execution to fail.
22 +Subscribe to the `composio.connected_account.expired` event to detect this proactively, instead of waiting for a tool execution to fail.
23
24 <Callout>
25 This event is only available with [V3 webhook payloads](/docs/webhook-verification#webhook-payload-versions). New organizations use V3 by default.
26 </Callout>
27
15 -## Subscribe to expiry events
16 -
17 -Add `composio.connected_account.expired` to your webhook subscription's `enabled_events`:
28 +Add `composio.connected_account.expired` to the subscription's `enabled_events`:
29
30 ```bash
31 curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
@@ -29,8 +40,6 @@ curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
40 }'
41 ```
42
32 -## Handle the event
33 -
43 When a connection expires, Composio sends a webhook with the connected account details:
44
45 ```json
@@ -118,55 +127,6 @@ export default async function webhookHandler(req: NextApiRequest, res: NextApiRe
127 </Tab>
128 </Tabs>
129
121 -## Re-authenticate the user
122 -
123 -Use `session.authorize()` to generate a new Connect Link for the expired toolkit. The user completes OAuth again, and the connected account returns to `ACTIVE` status.
124 -
125 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
126 - <Tab value="Python">
127 -```python
128 -from composio import Composio
129 -
130 -composio = Composio()
131 -
132 -session = composio.create(user_id="user_123")
133 -connection_request = session.authorize("gmail")
134 -
135 -# Send this URL to the user (email, in-app notification, etc.)
136 -print(connection_request.redirect_url)
137 -
138 -# Optionally wait for completion
139 -connected_account = connection_request.wait_for_connection(60000)
140 -print(f"Re-connected: {connected_account.id}")
141 -```
142 - </Tab>
143 - <Tab value="TypeScript">
144 -```typescript
145 -import { Composio } from '@composio/core';
146 -
147 -const composio = new Composio();
148 -
149 -const session = await composio.create("user_123");
150 -const connectionRequest = await session.authorize("gmail");
151 -
152 -// Send this URL to the user (email, in-app notification, etc.)
153 -console.log(connectionRequest.redirectUrl);
154 -
155 -// Optionally wait for completion
156 -const connectedAccount = await connectionRequest.waitForConnection(60000);
157 -console.log(`Re-connected: ${connectedAccount.id}`);
158 -```
159 - </Tab>
160 -</Tabs>
161 -
130 <Callout>
131 Always [verify webhook signatures](/docs/webhook-verification) before processing events in production.
132 </Callout>
165 -
166 -## What to read next
167 -
168 -<Cards>
169 - <Card icon={<ShieldCheck />} title="Verifying webhooks" href="/docs/webhook-verification" description="Validate webhook signatures to ensure payloads are authentic" />
170 - <Card icon={<Zap />} title="Subscribing to events" href="/docs/setting-up-triggers/subscribing-to-events" description="Set up webhooks and SDK subscriptions to receive trigger events" />
171 - <Card icon={<Key />} title="Authentication overview" href="/docs/authentication" description="How Composio manages OAuth, token refresh, and connected accounts" />
172 -</Cards>
docs/app/(home)/cookbooks/[[...slug]]/page.tsx deleted
-6
@@ -1,6 +0,0 @@
1 -import { cookbooksSource } from '@/lib/source';
2 -import { createDocsPage, createGenerateStaticParams, createGenerateMetadata } from '@/lib/create-docs-page';
3 -
4 -export default createDocsPage(cookbooksSource);
5 -export const generateStaticParams = createGenerateStaticParams(cookbooksSource);
6 -export const generateMetadata = createGenerateMetadata(cookbooksSource, 'cookbooks');
docs/app/(home)/cookbooks/layout.tsx deleted
-4
@@ -1,4 +0,0 @@
1 -import { cookbooksSource } from '@/lib/source';
2 -import { createDocsLayout } from '@/lib/create-docs-layout';
3 -
4 -export default createDocsLayout(cookbooksSource);
docs/app/(home)/docs/[[...slug]]/page.tsx
+8
@@ -10,6 +10,9 @@ import type { Metadata } from 'next';
10 import { createRelativeLink } from 'fumadocs-ui/mdx';
11 import { PageActions } from '@/components/page-actions';
12 import { EditOnGitHub } from '@/components/edit-on-github';
13 +import { LegacyBadge } from '@/components/legacy-badge';
14 +import { ExperimentalBadge } from '@/components/experimental-badge';
15 +import { RelatedLinks } from '@/components/related-links';
16
17 export default async function Page(props: PageProps<'/docs/[[...slug]]'>) {
18 const params = await props.params;
@@ -27,9 +30,14 @@ export default async function Page(props: PageProps<'/docs/[[...slug]]'>) {
30 full={isLanding ? true : data.full}
31 footer={{ enabled: false }}
32 tableOfContentPopover={{ enabled: false }}
33 + tableOfContent={
34 + data.related?.length ? { footer: <RelatedLinks items={data.related} /> } : undefined
35 + }
36 >
37 {!isLanding && (
38 <>
39 + {data.legacy && <LegacyBadge />}
40 + {data.experimental && <ExperimentalBadge />}
41 <DocsTitle>{data.title}</DocsTitle>
42 <PageActions path={page.url} />
43 </>
docs/app/(home)/docs/layout.tsx
+17 -1
@@ -1,10 +1,26 @@
1 import { source } from '@/lib/source';
2 import { DocsLayout } from 'fumadocs-ui/layouts/docs';
3 +import { decorateSidebarBadges } from '@/lib/decorate-sidebar-badges';
4 +
5 +interface BadgeFrontmatter {
6 + experimental?: boolean;
7 + isNew?: boolean;
8 +}
9 +
10 +const pages = source.getPages();
11 +const experimentalUrls = new Set(
12 + pages.filter((page) => (page.data as BadgeFrontmatter).experimental).map((page) => page.url),
13 +);
14 +const newUrls = new Set(
15 + pages.filter((page) => (page.data as BadgeFrontmatter).isNew).map((page) => page.url),
16 +);
17 +
18 +const tree = decorateSidebarBadges(source.pageTree, experimentalUrls, newUrls);
19
20 export default function Layout({ children }: LayoutProps<'/docs'>) {
21 return (
22 <DocsLayout
7 - tree={source.pageTree}
23 + tree={tree}
24 nav={{ enabled: true, title: null }}
25 sidebar={{ collapsible: false, footer: null, tabs: false }}
26 themeSwitch={{ enabled: false }}
docs/app/(home)/examples/[[...slug]]/page.tsx new
+6
@@ -0,0 +1,6 @@
1 +import { examplesSource } from '@/lib/source';
2 +import { createDocsPage, createGenerateStaticParams, createGenerateMetadata } from '@/lib/create-docs-page';
3 +
4 +export default createDocsPage(examplesSource);
5 +export const generateStaticParams = createGenerateStaticParams(examplesSource);
6 +export const generateMetadata = createGenerateMetadata(examplesSource, 'examples');
docs/app/(home)/examples/layout.tsx new
+4
@@ -0,0 +1,4 @@
1 +import { examplesSource } from '@/lib/source';
2 +import { createDocsLayout } from '@/lib/create-docs-layout';
3 +
4 +export default createDocsLayout(examplesSource);
docs/app/(home)/layout.tsx
+7 -1
@@ -1,6 +1,12 @@
1 import { HomeLayout } from 'fumadocs-ui/layouts/home';
2 import { baseOptions } from '@/lib/layout.shared';
3 +import { EveChatMount } from '@/components/eve-chat-mount';
4
5 export default function Layout({ children }: LayoutProps<'/'>) {
5 - return <HomeLayout {...baseOptions()}>{children}</HomeLayout>;
6 + return (
7 + <HomeLayout {...baseOptions()}>
8 + {children}
9 + <EveChatMount />
10 + </HomeLayout>
11 + );
12 }
docs/app/global.css
+411
@@ -6,6 +6,171 @@
6
7 @custom-variant dark (&:is(.dark *));
8
9 +/* ==========================================================================
10 + highlight.js tokens (Eve chat code blocks)
11 +
12 + The Eve chat renders code through a custom <CodeBlock> using highlight.js
13 + (synchronous, browser-safe). highlight.js theme stylesheets aren't imported
14 + directly because they're not dark-mode aware; instead the GitHub light/dark
15 + token colors are inlined here and scoped to `.dark`. The container styles its
16 + own background/padding, so only token colors live here.
17 + ========================================================================== */
18 +.eve-hljs .hljs {
19 + color: #24292e;
20 + background: transparent;
21 +}
22 +.eve-hljs .hljs-doctag,
23 +.eve-hljs .hljs-keyword,
24 +.eve-hljs .hljs-meta .hljs-keyword,
25 +.eve-hljs .hljs-template-tag,
26 +.eve-hljs .hljs-template-variable,
27 +.eve-hljs .hljs-type,
28 +.eve-hljs .hljs-variable.language_ {
29 + color: #d73a49;
30 +}
31 +.eve-hljs .hljs-title,
32 +.eve-hljs .hljs-title.class_,
33 +.eve-hljs .hljs-title.class_.inherited__,
34 +.eve-hljs .hljs-title.function_ {
35 + color: #6f42c1;
36 +}
37 +.eve-hljs .hljs-attr,
38 +.eve-hljs .hljs-attribute,
39 +.eve-hljs .hljs-literal,
40 +.eve-hljs .hljs-meta,
41 +.eve-hljs .hljs-number,
42 +.eve-hljs .hljs-operator,
43 +.eve-hljs .hljs-variable,
44 +.eve-hljs .hljs-selector-attr,
45 +.eve-hljs .hljs-selector-class,
46 +.eve-hljs .hljs-selector-id {
47 + color: #005cc5;
48 +}
49 +.eve-hljs .hljs-regexp,
50 +.eve-hljs .hljs-string,
51 +.eve-hljs .hljs-meta .hljs-string {
52 + color: #032f62;
53 +}
54 +.eve-hljs .hljs-built_in,
55 +.eve-hljs .hljs-symbol {
56 + color: #e36209;
57 +}
58 +.eve-hljs .hljs-comment,
59 +.eve-hljs .hljs-code,
60 +.eve-hljs .hljs-formula {
61 + color: #6a737d;
62 +}
63 +.eve-hljs .hljs-name,
64 +.eve-hljs .hljs-quote,
65 +.eve-hljs .hljs-selector-tag,
66 +.eve-hljs .hljs-selector-pseudo {
67 + color: #22863a;
68 +}
69 +.eve-hljs .hljs-subst {
70 + color: #24292e;
71 +}
72 +.eve-hljs .hljs-section {
73 + color: #005cc5;
74 + font-weight: bold;
75 +}
76 +.eve-hljs .hljs-bullet {
77 + color: #735c0f;
78 +}
79 +.eve-hljs .hljs-emphasis {
80 + color: #24292e;
81 + font-style: italic;
82 +}
83 +.eve-hljs .hljs-strong {
84 + color: #24292e;
85 + font-weight: bold;
86 +}
87 +.eve-hljs .hljs-addition {
88 + color: #22863a;
89 + background-color: #f0fff4;
90 +}
91 +.eve-hljs .hljs-deletion {
92 + color: #b31d28;
93 + background-color: #ffeef0;
94 +}
95 +
96 +.dark .eve-hljs .hljs {
97 + color: #c9d1d9;
98 + background: transparent;
99 +}
100 +.dark .eve-hljs .hljs-doctag,
101 +.dark .eve-hljs .hljs-keyword,
102 +.dark .eve-hljs .hljs-meta .hljs-keyword,
103 +.dark .eve-hljs .hljs-template-tag,
104 +.dark .eve-hljs .hljs-template-variable,
105 +.dark .eve-hljs .hljs-type,
106 +.dark .eve-hljs .hljs-variable.language_ {
107 + color: #ff7b72;
108 +}
109 +.dark .eve-hljs .hljs-title,
110 +.dark .eve-hljs .hljs-title.class_,
111 +.dark .eve-hljs .hljs-title.class_.inherited__,
112 +.dark .eve-hljs .hljs-title.function_ {
113 + color: #d2a8ff;
114 +}
115 +.dark .eve-hljs .hljs-attr,
116 +.dark .eve-hljs .hljs-attribute,
117 +.dark .eve-hljs .hljs-literal,
118 +.dark .eve-hljs .hljs-meta,
119 +.dark .eve-hljs .hljs-number,
120 +.dark .eve-hljs .hljs-operator,
121 +.dark .eve-hljs .hljs-variable,
122 +.dark .eve-hljs .hljs-selector-attr,
123 +.dark .eve-hljs .hljs-selector-class,
124 +.dark .eve-hljs .hljs-selector-id {
125 + color: #79c0ff;
126 +}
127 +.dark .eve-hljs .hljs-regexp,
128 +.dark .eve-hljs .hljs-string,
129 +.dark .eve-hljs .hljs-meta .hljs-string {
130 + color: #a5d6ff;
131 +}
132 +.dark .eve-hljs .hljs-built_in,
133 +.dark .eve-hljs .hljs-symbol {
134 + color: #ffa657;
135 +}
136 +.dark .eve-hljs .hljs-comment,
137 +.dark .eve-hljs .hljs-code,
138 +.dark .eve-hljs .hljs-formula {
139 + color: #8b949e;
140 +}
141 +.dark .eve-hljs .hljs-name,
142 +.dark .eve-hljs .hljs-quote,
143 +.dark .eve-hljs .hljs-selector-tag,
144 +.dark .eve-hljs .hljs-selector-pseudo {
145 + color: #7ee787;
146 +}
147 +.dark .eve-hljs .hljs-subst {
148 + color: #c9d1d9;
149 +}
150 +.dark .eve-hljs .hljs-section {
151 + color: #1f6feb;
152 + font-weight: bold;
153 +}
154 +.dark .eve-hljs .hljs-bullet {
155 + color: #f2cc60;
156 +}
157 +.dark .eve-hljs .hljs-emphasis {
158 + color: #c9d1d9;
159 + font-style: italic;
160 +}
161 +.dark .eve-hljs .hljs-strong {
162 + color: #c9d1d9;
163 + font-weight: bold;
164 +}
165 +.dark .eve-hljs .hljs-addition {
166 + color: #aff5b4;
167 + background-color: #033a16;
168 +}
169 +.dark .eve-hljs .hljs-deletion {
170 + color: #ffdcd7;
171 + background-color: #67060c;
172 +}
173 +
174 /* ==========================================================================
175 COMPOSIO DOCS
176
@@ -778,3 +943,249 @@ body {
943 border-radius: 0 !important;
944 }
945
946 +
947 +/* ==========================================================================
948 + TERMINAL-KIT (ported from landing-new /dev — components/terminal-kit)
949 + Trimmed to what the InChatAuthTerminal component uses: the Claude palette
950 + (dark + light), structural tokens, the stacked Input field, and the shared
951 + session/body classes. Map the kit's mono font onto the docs JetBrains Mono.
952 + ========================================================================== */
953 +@keyframes terminal-cursor-blink {
954 + 0%, 49% { opacity: 1; }
955 + 50%, 100% { opacity: 0; }
956 +}
957 +
958 +.terminal-theme {
959 + --font-geist-mono: var(--font-mono);
960 +}
961 +
962 +.terminal-theme {
963 + --terminal-radius-window: 12px;
964 + --terminal-radius-panel: 4px;
965 + --terminal-radius-sm: 2px;
966 + --terminal-session-pad-x: 14px;
967 + --terminal-session-pad-y: 12px;
968 + --terminal-session-gap: 8px;
969 + --terminal-session-inset: 14px;
970 + --terminal-session-sent-pad-x: 10px;
971 + background-color: var(--terminal-bg);
972 + color: var(--terminal-fg);
973 + font-family: var(--font-geist-mono), ui-monospace, SFMono-Regular, "Roboto Mono",
974 + Menlo, Monaco, "Liberation Mono", "Courier New", monospace;
975 + font-size: 12px;
976 + line-height: 1.625;
977 + border-radius: var(--terminal-radius-window);
978 +}
979 +
980 +.terminal-theme-claude {
981 + --terminal-bg: #0b0b0b;
982 + --terminal-editor-bg: #1f1f1e;
983 + --terminal-fg: #ffffff;
984 + --terminal-white: #ffffff;
985 + --terminal-dim: #c3c2b7;
986 + --terminal-dimmer: #898781;
987 + --terminal-vdim: #3d3d3d;
988 + --terminal-surface: #232323;
989 + --terminal-input-bg: #1f1f1e;
990 + --terminal-popover: #2a2a2a;
991 + --terminal-panel: rgba(255, 255, 255, 0.05);
992 + --terminal-panel-strong: rgba(255, 255, 255, 0.07);
993 + --terminal-border: rgba(255, 255, 255, 0.1);
994 + --terminal-preview-bg: #0e0e0d;
995 + --terminal-preview-border: #222220;
996 + --terminal-input-border: #565552;
997 + --terminal-progress-track: #3d3d3d;
998 + --terminal-progress-fill: #d97757;
999 + --terminal-green: #4cc38a;
1000 + --terminal-green-dim: #6fd4a8;
1001 + --terminal-green-bg: rgba(76, 195, 138, 0.14);
1002 + --terminal-blue: #4d9fff;
1003 + --terminal-blue-bright: #0099ff;
1004 + --terminal-teal: #d97757;
1005 + --terminal-yellow: #e3c07b;
1006 + --terminal-orange: #ff8d77;
1007 + --terminal-red: #ff5a5a;
1008 + --terminal-purple: #9775fa;
1009 + --terminal-diff-gutter: #8b8b81;
1010 + --terminal-diff-insert-fg: #4cc38a;
1011 + --terminal-diff-insert-bg: rgba(76, 195, 138, 0.12);
1012 + --terminal-diff-delete-fg: #ff8d77;
1013 + --terminal-diff-delete-bg: rgba(255, 90, 90, 0.12);
1014 + --terminal-diff-text: #ffffff;
1015 + --terminal-traffic-red: #ff5f57;
1016 + --terminal-traffic-yellow: #febc2e;
1017 + --terminal-traffic-green: #28c840;
1018 + background-color: var(--terminal-bg);
1019 + color: var(--terminal-fg);
1020 +}
1021 +
1022 +.terminal-theme-claude-light,
1023 +html:not(.dark) .terminal-theme-claude {
1024 + --terminal-bg: #faf9f5;
1025 + --terminal-editor-bg: #ffffff;
1026 + --terminal-fg: #131312;
1027 + --terminal-white: #131312;
1028 + --terminal-dim: #3c3c39;
1029 + --terminal-dimmer: #72716b;
1030 + --terminal-vdim: #e1e0d9;
1031 + --terminal-surface: #f4f4ec;
1032 + --terminal-input-bg: #ffffff;
1033 + --terminal-popover: #ffffff;
1034 + --terminal-panel: rgba(19, 19, 18, 0.04);
1035 + --terminal-panel-strong: rgba(19, 19, 18, 0.07);
1036 + --terminal-border: rgba(31, 30, 29, 0.12);
1037 + --terminal-preview-bg: #f0efe8;
1038 + --terminal-preview-border: rgba(19, 19, 18, 0.06);
1039 + --terminal-input-border: #a8a7a2;
1040 + --terminal-progress-track: #e1e0d9;
1041 + --terminal-progress-fill: #d97757;
1042 + --terminal-green: #2f7613;
1043 + --terminal-green-dim: #3d8f18;
1044 + --terminal-green-bg: #e7f1d9;
1045 + --terminal-blue: #2c83db;
1046 + --terminal-blue-bright: #1a66b2;
1047 + --terminal-teal: #d97757;
1048 + --terminal-yellow: #865a07;
1049 + --terminal-orange: #c6613f;
1050 + --terminal-red: #b43232;
1051 + --terminal-purple: #5545a1;
1052 + --terminal-diff-insert-fg: #2f7613;
1053 + --terminal-diff-insert-bg: #e7f1d9;
1054 + --terminal-diff-delete-fg: #b43232;
1055 + --terminal-diff-delete-bg: #f8ebeb;
1056 + --terminal-diff-text: #131312;
1057 + background-color: var(--terminal-bg);
1058 + color: var(--terminal-fg);
1059 +}
1060 +
1061 +.terminal-theme-claude .terminal-input-control::placeholder {
1062 + color: var(--terminal-dim);
1063 + opacity: 1;
1064 +}
1065 +
1066 +.terminal-input-field--stacked {
1067 + position: relative;
1068 + border: none;
1069 + border-radius: 0;
1070 + background: transparent;
1071 + padding-block: 6px;
1072 + padding-inline: 0;
1073 +}
1074 +
1075 +.terminal-input-field--stacked::before,
1076 +.terminal-input-field--stacked::after {
1077 + content: "";
1078 + position: absolute;
1079 + left: 0;
1080 + right: 0;
1081 + height: 1.5px;
1082 + background: var(--terminal-input-border);
1083 + pointer-events: none;
1084 +}
1085 +
1086 +.terminal-input-field--stacked::before {
1087 + top: 0;
1088 +}
1089 +
1090 +.terminal-input-field--stacked::after {
1091 + bottom: 0;
1092 +}
1093 +
1094 +.terminal-cursor {
1095 + animation: terminal-cursor-blink 1s step-end infinite;
1096 +}
1097 +
1098 +.terminal-panel {
1099 + border-radius: var(--terminal-radius-panel);
1100 +}
1101 +
1102 +.terminal-panel-sm {
1103 + border-radius: var(--terminal-radius-sm);
1104 +}
1105 +
1106 +.terminal-session {
1107 + display: flex;
1108 + flex-direction: column;
1109 + gap: var(--terminal-session-gap);
1110 + min-width: 0;
1111 +}
1112 +
1113 +.terminal-session-sent {
1114 + box-sizing: border-box;
1115 + width: 100%;
1116 + border-radius: var(--terminal-radius-sm);
1117 + padding-inline: var(--terminal-session-sent-pad-x);
1118 +}
1119 +
1120 +.terminal-session-inset {
1121 + padding-left: var(--terminal-session-inset);
1122 +}
1123 +
1124 +.terminal-session-flush {
1125 + box-sizing: border-box;
1126 + width: 100%;
1127 +}
1128 +
1129 +.terminal-body-content {
1130 + padding-inline: var(--terminal-session-pad-x);
1131 + padding-block: var(--terminal-session-pad-y);
1132 +}
1133 +
1134 +.terminal-body-footer {
1135 + padding-inline: var(--terminal-session-pad-x);
1136 +}
1137 +
1138 +.terminal-body-scroll-host {
1139 + position: relative;
1140 + min-height: 0;
1141 + width: 100%;
1142 + display: flex;
1143 + flex-direction: column;
1144 +}
1145 +
1146 +.terminal-body-scroll {
1147 + flex: 1 1 auto;
1148 + min-height: 0;
1149 + overflow-y: auto;
1150 + overscroll-behavior: contain;
1151 + scrollbar-width: none;
1152 + -ms-overflow-style: none;
1153 +}
1154 +
1155 +.terminal-body-scroll::-webkit-scrollbar {
1156 + display: none;
1157 + width: 0;
1158 + height: 0;
1159 +}
1160 +
1161 +@media (prefers-reduced-motion: reduce) {
1162 + .terminal-cursor {
1163 + animation: none;
1164 + opacity: 1;
1165 + }
1166 +}
1167 +
1168 +/* @pierre/diffs: the +/- stat counts in the file header are hidden via the
1169 + `unsafeCSS` option in components/diff-view.tsx, NOT here — the header renders
1170 + inside an open shadow root that global CSS can't pierce. */
1171 +
1172 +/* Copy-to-clipboard button in the @pierre/diffs code header. The widget themes
1173 + itself off the OS prefers-color-scheme (its shadow root pins
1174 + `color-scheme: light dark`), NOT the site's class-based dark toggle — so the
1175 + header is light on a light-OS user even when the docs are in dark mode. Match
1176 + the header with light-dark() so the chip is legible on either header. */
1177 +.diff-copy-button {
1178 + color-scheme: light dark;
1179 + border-color: light-dark(rgb(0 0 0 / 0.1), rgb(255 255 255 / 0.1));
1180 + background-color: light-dark(rgb(0 0 0 / 0.04), rgb(255 255 255 / 0.04));
1181 + color: light-dark(#71717a, #a1a1aa);
1182 +}
1183 +.diff-copy-button:hover {
1184 + border-color: light-dark(rgb(0 0 0 / 0.2), rgb(255 255 255 / 0.2));
1185 + background-color: light-dark(rgb(0 0 0 / 0.08), rgb(255 255 255 / 0.1));
1186 + color: light-dark(#18181b, #f4f4f5);
1187 +}
1188 +.diff-copy-button:focus-visible {
1189 + outline: 2px solid light-dark(rgb(0 0 0 / 0.2), rgb(255 255 255 / 0.25));
1190 + outline-offset: 1px;
1191 +}
docs/app/layout.tsx
+10 -11
@@ -7,20 +7,19 @@ import localFont from 'next/font/local';
7 import { PostHogProvider } from '@/components/posthog-provider';
8 import CustomSearchDialog from '@/components/custom-search-dialog';
9 import { ScrollReset } from '@/components/scroll-reset';
10 -import { source } from '@/lib/source';
10 +import { source, referenceSource } from '@/lib/source';
11
12 -const defaultLinkSlugs = [
13 - ['quickstart'],
14 - ['authentication'],
15 - ['configuring-sessions'],
16 - ['white-labeling-authentication'],
17 - ['glossary'],
18 - ['common-faq'],
19 - ['troubleshooting'],
12 +const defaultLinkSlugs: { slug: string[]; source: typeof source }[] = [
13 + { slug: ['quickstart'], source },
14 + { slug: ['authentication'], source },
15 + { slug: ['configuring-sessions'], source },
16 + { slug: ['white-labeling-authentication'], source },
17 + { slug: ['glossary'], source: referenceSource },
18 + { slug: ['troubleshooting'], source },
19 ];
20
22 -const defaultLinks = defaultLinkSlugs.flatMap((slug) => {
23 - const page = source.getPage(slug);
21 +const defaultLinks = defaultLinkSlugs.flatMap(({ slug, source: pageSource }) => {
22 + const page = pageSource.getPage(slug);
23 if (!page) return [];
24 return [{ title: page.data.title, description: page.data.description ?? '', href: page.url }];
25 });
docs/app/llms-full.txt/route.ts
+45 -7
@@ -1,4 +1,4 @@
1 -import { getLLMText, source, cookbooksSource, referenceSource, toolkitsSource } from '@/lib/source';
1 +import { getLLMText, source, examplesSource, referenceSource, toolkitsSource } from '@/lib/source';
2 import { SESSION_GUARDRAILS } from '@/lib/llm-guardrails';
3 import type { ReactNode } from 'react';
4
@@ -62,6 +62,42 @@ function collectPageUrls(nodes: TreeNode[]): string[] {
62 return urls;
63 }
64
65 +/** All page URLs under a folder, including its index. */
66 +function collectFolderUrls(folder: FolderNode): string[] {
67 + const urls: string[] = [];
68 + if (folder.index) urls.push(folder.index.url);
69 + for (const child of folder.children) {
70 + if (child.type === 'page') urls.push(child.url);
71 + else if (child.type === 'folder') urls.push(...collectFolderUrls(child));
72 + }
73 + return urls;
74 +}
75 +
76 +/**
77 + * URLs that live under a legacy/deprecated separator section (e.g. "Direct
78 + * Tool Execution Guides (Legacy)"). We drop their full text from the default
79 + * LLM context so generators don't learn deprecated patterns.
80 + */
81 +function collectLegacyUrls(nodes: TreeNode[]): Set<string> {
82 + const legacy = new Set<string>();
83 + let inLegacySection = false;
84 +
85 + for (const node of nodes) {
86 + if (node.type === 'separator') {
87 + const text = typeof node.name === 'string' ? node.name : '';
88 + inLegacySection = /legacy|deprecated/i.test(text);
89 + continue;
90 + }
91 + if (!inLegacySection) continue;
92 + if (node.type === 'page') legacy.add(node.url);
93 + else if (node.type === 'folder') {
94 + for (const url of collectFolderUrls(node)) legacy.add(url);
95 + }
96 + }
97 +
98 + return legacy;
99 +}
100 +
101 /**
102 * Order pages according to the page tree structure from meta.json.
103 * Pages not in the tree are appended at the end.
@@ -94,14 +130,16 @@ async function getTextForPages(pages: PageLike[]) {
130
131 export async function GET() {
132 try {
133 + const treeChildren = source.pageTree.children as TreeNode[];
134 + const legacyUrls = collectLegacyUrls(treeChildren);
135 const orderedDocsPages = orderDocPages(
98 - source.getPages() as PageLike[],
99 - source.pageTree.children as TreeNode[]
136 + (source.getPages() as PageLike[]).filter((page) => !legacyUrls.has(page.url)),
137 + treeChildren
138 );
139
102 - const [docsResults, cookbooksResults, referenceResults, toolkitsResults] = await Promise.all([
140 + const [docsResults, examplesResults, referenceResults, toolkitsResults] = await Promise.all([
141 getTextForPages(orderedDocsPages),
104 - getTextForPages(cookbooksSource.getPages() as PageLike[]),
142 + getTextForPages(examplesSource.getPages() as PageLike[]),
143 getTextForPages(referenceSource.getPages() as PageLike[]),
144 getTextForPages(toolkitsSource.getPages() as PageLike[]),
145 ]);
@@ -109,8 +147,8 @@ export async function GET() {
147 const results = [
148 `# Composio Documentation\n\n> Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.${SESSION_GUARDRAILS}\n# Documentation\n`,
149 ...docsResults,
112 - '\n# Cookbooks\n',
113 - ...cookbooksResults,
150 + '\n# Examples\n',
151 + ...examplesResults,
152 '\n# API Reference\n',
153 ...referenceResults,
154 '\n# Toolkits\n',
docs/app/llms.mdx/[[...slug]]/route.ts
+10 -7
@@ -1,7 +1,7 @@
1 import {
2 source,
3 getReferenceSource,
4 - cookbooksSource,
4 + examplesSource,
5 toolkitsSource,
6 changelogEntries,
7 slugToDate,
@@ -506,7 +506,7 @@ async function openapiPageToMarkdown(
506 // Note: 'reference' is handled specially below with async getReferenceSource()
507 const sources = [
508 { prefix: 'docs', source },
509 - { prefix: 'cookbooks', source: cookbooksSource },
509 + { prefix: 'examples', source: examplesSource },
510 { prefix: 'toolkits', source: toolkitsSource },
511 ];
512
@@ -797,7 +797,7 @@ async function generateToolkitsIndex(): Promise<string> {
797 '',
798 `Composio supports ${toolkits.length} toolkits for building AI agents.`,
799 '',
800 - '- [Premium Tools](/toolkits/premium-tools.md) - Which tools cost extra, how they are priced, and what the limits are',
800 + '- [Pro Tools](/toolkits/pro-tools.md) - Which tools cost extra, how they are priced, and what the limits are',
801 '- [Composio Managed Auth](/toolkits/managed-auth.md) - Full list of OAuth toolkits that work out of the box vs ones that need your own credentials',
802 '',
803 '## All Toolkits',
@@ -824,7 +824,7 @@ async function generateToolkitsIndex(): Promise<string> {
824 return lines.join('\n');
825 }
826
827 -const LLM_FOOTER = '\n\n---\n\n📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Glossary](https://docs.composio.dev/llms.mdx/docs/glossary) | [Cookbooks](https://docs.composio.dev/llms.mdx/cookbooks) | [API Reference](https://docs.composio.dev/llms.mdx/reference)';
827 +const LLM_FOOTER = '\n\n---\n\n📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)';
828
829 // Render meta tool parameters as markdown
830 function renderMetaToolParams(properties: Record<string, MetaToolParameter>, requiredFields: string[] = [], indent = 0): string[] {
@@ -908,7 +908,7 @@ function metaToolsIndexToMarkdown(tools: MetaTool[]): string {
908
909 for (const tool of tools) {
910 const tags = tool.tags.length > 0 ? tool.tags.join(', ') : '—';
911 - lines.push(`| [\`${tool.slug}\`](/reference/meta-tools/${tool.slug.toLowerCase().replace('composio_', '')}.md) | ${tags} |`);
911 + lines.push(`| [\`${tool.slug}\`](/toolkits/meta-tools/${tool.slug.toLowerCase().replace('composio_', '')}.md) | ${tags} |`);
912 }
913
914 return lines.join('\n') + LLM_FOOTER;
@@ -972,8 +972,11 @@ export async function GET(
972 notFound();
973 }
974
975 - // Special handling for meta tools - /reference/meta-tools and /reference/meta-tools/{slug}
976 - if (prefix === 'reference' && rest[0] === 'meta-tools') {
975 + // Special handling for meta tools - /toolkits/meta-tools and /toolkits/meta-tools/{slug}.
976 + // Must run before the generic toolkits page resolution and the JSON toolkit block
977 + // below, since the meta-tool MDX is just a <MetaToolDetailServer /> shell that can't
978 + // render to useful markdown — the content is generated from the JSON data instead.
979 + if (prefix === 'toolkits' && rest[0] === 'meta-tools') {
980 if (rest.length === 1) {
981 // Index page
982 const tools = await getAllMetaTools();
docs/app/llms.txt/route.ts
+30 -12
@@ -1,4 +1,4 @@
1 -import { source, cookbooksSource, referenceSource, toolkitsSource } from '@/lib/source';
1 +import { source, examplesSource, referenceSource, toolkitsSource } from '@/lib/source';
2 import type { ReactNode } from 'react';
3
4 export const revalidate = false;
@@ -31,23 +31,41 @@ function nodeText(name: ReactNode): string | null {
31 return null;
32 }
33
34 +/**
35 + * A section is legacy/deprecated when its separator heading says so (e.g.
36 + * "Direct Tool Execution Guides (Legacy)"). We omit those sections from the
37 + * default LLM index so code generators reach for the current session-based
38 + * APIs, not deprecated ones.
39 + */
40 +function isLegacySeparator(name: ReactNode): boolean {
41 + const text = nodeText(name);
42 + return text != null && /legacy|deprecated/i.test(text);
43 +}
44 +
45 /**
46 * Walk the fumadocs page tree and generate a markdown index.
47 * Separators become ## headings, pages become URL entries, folders recurse.
48 + * Legacy/deprecated sections (and everything under them) are skipped.
49 */
50 function walkPageTree(nodes: TreeNode[], depth = 2): string {
51 const lines: string[] = [];
52 + let skippingSection = false;
53
54 for (const node of nodes) {
42 - switch (node.type) {
43 - case 'separator': {
44 - const text = nodeText(node.name);
45 - if (text) {
46 - lines.push('', `${'#'.repeat(depth)} ${text}`, '');
47 - }
48 - break;
55 + if (node.type === 'separator') {
56 + // A separator starts a new section; skip it and its pages when legacy.
57 + skippingSection = isLegacySeparator(node.name);
58 + if (skippingSection) continue;
59 + const text = nodeText(node.name);
60 + if (text) {
61 + lines.push('', `${'#'.repeat(depth)} ${text}`, '');
62 }
63 + continue;
64 + }
65 +
66 + if (skippingSection) continue;
67
68 + switch (node.type) {
69 case 'page':
70 lines.push(`- https://docs.composio.dev${node.url}.md`);
71 break;
@@ -83,7 +101,7 @@ export async function GET() {
101 try {
102 const docsTree = walkPageTree(source.pageTree.children as TreeNode[]);
103
86 - const cookbooksPages = cookbooksSource.getPages();
104 + const examplesPages = examplesSource.getPages();
105 const referencePages = referenceSource.getPages();
106 const toolkitsPages = toolkitsSource.getPages();
107
@@ -91,13 +109,13 @@ export async function GET() {
109
110 > Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
111
94 -> **For AI agents:** Composio supports two integration modes. **Native Tools:** use \`composio.create(user_id)\` + \`session.tools()\` with a provider package (e.g. \`composio_openai\`, \`@composio/openai\`). **MCP:** use \`composio.create(user_id)\` + \`session.mcp.url\` with any MCP-compatible client — no provider package needed. See any page's .md endpoint for full usage instructions.
112 +> **For AI agents:** Give your agent tools it can call directly with \`composio.create(user_id)\` + \`session.tools()\` and a provider package (e.g. \`composio_openai\`, \`@composio/openai\`). To connect over MCP instead, create the session with \`mcp: true\` and read \`session.mcp.url\` from any MCP-compatible client. See any page's .md endpoint for full usage instructions.
113
114 ${docsTree}
115
98 -## Cookbooks
116 +## Examples
117
100 -${cookbooksPages.map(formatPage).join('\n')}
118 +${examplesPages.map(formatPage).join('\n')}
119
120 ## API Reference
121
docs/app/sitemap.ts
+3 -3
@@ -2,7 +2,7 @@ import type { MetadataRoute } from 'next';
2 import {
3 source,
4 getReferenceSource,
5 - cookbooksSource,
5 + examplesSource,
6 toolkitsSource,
7 changelogEntries,
8 dateToChangelogUrl,
@@ -22,7 +22,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
22 url: `${baseUrl}${page.url}`,
23 }));
24
25 - const cookbooksPages = cookbooksSource.getPages().map((page) => ({
25 + const examplesPages = examplesSource.getPages().map((page) => ({
26 url: `${baseUrl}${page.url}`,
27 }));
28
@@ -47,7 +47,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
47 { url: `${baseUrl}/docs/changelog` },
48 ...docsPages,
49 ...referencePages,
50 - ...cookbooksPages,
50 + ...examplesPages,
51 ...toolkitsMdxPages,
52 ...toolkitsJsonPages,
53 ...changelogPages,
docs/bun.lock
+202 -17
@@ -5,26 +5,38 @@
5 "": {
6 "name": "fumadocs",
7 "dependencies": {
8 + "@pierre/diffs": "^1.2.11",
9 + "@pierre/trees": "^1.0.0-beta.4",
10 "@radix-ui/react-tabs": "^1.1.13",
11 + "@shikijs/langs": "^4.2.0",
12 + "@shikijs/themes": "^4.2.0",
13 "@shikijs/twoslash": "^3.21.0",
14 "@vercel/analytics": "^1.6.1",
15 "algoliasearch": "^5",
16 "class-variance-authority": "^0.7.1",
17 "clsx": "^2.1.1",
18 + "diff": "^9.0.0",
19 + "eve": "^0.13.3",
20 "framer-motion": "^12.39.0",
21 "fumadocs-core": "^16.4.2",
22 "fumadocs-mdx": "^14.2.4",
23 "fumadocs-openapi": "^10.2.2",
24 "fumadocs-ui": "^16.4.2",
25 + "highlight.js": "^11.11.1",
26 "lucide-react": "^0.562.0",
27 "mermaid": "^11.12.3",
28 + "motion": "^12.34.3",
29 "next": "16.2.6",
30 + "nucleo-pixel": "^1.3.0",
31 "posthog-js": "^1.319.0",
32 "react": "^19.2.3",
33 "react-dom": "^19.2.3",
34 + "react-markdown": "^10.1.0",
35 + "remark-gfm": "^4.0.1",
36 "search-insights": "^2",
37 "shiki": "^3.20.0",
38 "tailwind-merge": "^3.4.0",
39 + "zod": "^4.4.3",
40 },
41 "devDependencies": {
42 "@ai-sdk/anthropic": "^3.0.11",
@@ -57,12 +69,13 @@
69 "@types/node": "^24.10.2",
70 "@types/react": "^19.2.7",
71 "@types/react-dom": "^19.2.3",
60 - "ai": "^6.0.30",
72 + "ai": "7.0.0-beta.178",
73 "ajv": "^8.17.1",
74 "ajv-draft-04": "^1.0.0",
75 "eslint": "^9.39.2",
76 "eslint-config-next": "16.2.9",
77 "github-slugger": "^2.0.0",
78 + "microsandbox": "^0.5.7",
79 "next-validate-link": "^1.6.4",
80 "openai": "^6.16.0",
81 "postcss": "^8.5.6",
@@ -80,7 +93,7 @@
93
94 "@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.45", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bpIS3RakSsaUhCRTIvL9bcVNeeUMDXWbndpYdXNeMJIIPcElTcvwktvla+JxIfbeK1AdQjB8ggYVChepeXPGwQ=="],
95
83 - "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.50", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Jdd1a8VgbD7l7r+COj0h5SuaYRfPvOJ/AO6l0OrmTPEcI2MUQPr3C4JttfpNkcheEN+gOdy0CtZWuG17bW2fjw=="],
96 + "@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.0-beta.109", "", { "dependencies": { "@ai-sdk/provider": "4.0.0-beta.19", "@ai-sdk/provider-utils": "5.0.0-beta.49", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-W/1kLlPb6Bgbhwep3CA3R6do0HD7SXV5gyuz2XBLY1YABqgxYkw+IhEcjOYlmn9v+Tifjqy5yJqmWdSHMJhyPQ=="],
97
98 "@ai-sdk/mcp": ["@ai-sdk/mcp@1.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "pkce-challenge": "^5.0.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-dRX2X6GDadZNpiylNnw0HP7zJC8ggVOOJV/JtxuF6CgtP8CKnc7a/wEzpUw1m/4AGdD3mTDhKnKFwC4y10a8FQ=="],
99
@@ -218,11 +231,11 @@
231
232 "@composio/vercel": ["@composio/vercel@0.6.3", "", { "peerDependencies": { "@composio/core": "0.6.3", "ai": "^5.0.0 || ^6.0.0" } }, "sha512-hwtqufR2mWNwdATsRfrAuWRjPVZG4maRcqWZB4jDLpuIZU1NEBMLmL2Ae7b/QFXvNYXibA4w0Ug8XavV4Zkxlg=="],
233
221 - "@emnapi/core": ["@emnapi/core@1.7.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg=="],
234 + "@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="],
235
236 "@emnapi/runtime": ["@emnapi/runtime@1.7.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA=="],
237
225 - "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.1.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ=="],
238 + "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="],
239
240 "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw=="],
241
@@ -490,6 +503,16 @@
503
504 "@orama/orama": ["@orama/orama@3.1.18", "", {}, "sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA=="],
505
506 + "@oxc-project/types": ["@oxc-project/types@0.137.0", "", {}, "sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA=="],
507 +
508 + "@pierre/diffs": ["@pierre/diffs@1.2.11", "", { "dependencies": { "@pierre/theme": "1.0.3", "@pierre/theming": "0.0.1", "@shikijs/transformers": "^3.0.0 || ^4.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0 || ^4.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-lSkl5C7eb8Zq7Ote0+J5ZdVOlI72r2EU3vW4+06wULSQqkIMP8mkxG70lVj593b1XYlsM2hCvuyt0cKTA96plQ=="],
509 +
510 + "@pierre/theme": ["@pierre/theme@1.0.3", "", {}, "sha512-sWHv11TMoqKxKDgTIk5VbhQjdPhs8DCcBxbjh3mRlS3YOM/OcrWoGX6MM8eBGn9cUu3M46Py0JnxsG2nJaFTuA=="],
511 +
512 + "@pierre/theming": ["@pierre/theming@0.0.1", "", { "peerDependencies": { "@pierre/theme": "^1.0.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-1thlEtJbqdyLzc1ZS2KQa1q7FzDGHT4dTEdKHoyQjOMeWWOmbVG5/ndEfOKfAb5Fzkz8cNJrOjFLiZoDH/A03A=="],
513 +
514 + "@pierre/trees": ["@pierre/trees@1.0.0-beta.4", "", { "dependencies": { "preact": "11.0.0-beta.0", "preact-render-to-string": "6.6.5" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-OfT1yk9ne8Te5+GB5zUY8yqE6B8BqjBHQJleH4lu8ltwNpoocZl4vXt1AzlEExpxI/pp+AFX5QG+lR3JjtTEag=="],
515 +
516 "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
517
518 "@posthog/core": ["@posthog/core@1.9.1", "", { "dependencies": { "cross-spawn": "^7.0.6" } }, "sha512-kRb1ch2dhQjsAapZmu6V66551IF2LnCbc1rnrQqnR7ArooVyJN9KOPXre16AJ3ObJz2eTfuP7x25BMyS2Y5Exw=="],
@@ -586,6 +609,38 @@
609
610 "@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="],
611
612 + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.2", "", { "os": "android", "cpu": "arm64" }, "sha512-2cZ+7xRS+DBcuJBJKnfzsbleumJhBqSlJVpuzHC0nTqfd3QQ7Vx2/x5YR/D7cBamKSeWplwo82Fn9lqYUDEMfA=="],
613 +
614 + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RkPMJnygxsgOYdkfqgpwY0/Fzm8d0VQe6HGU2/B00Xa9eqdLbrII+DOKAodbJAn3ZL1AJxGHkZRPYazgGY6Ljw=="],
615 +
616 + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.1.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-Uiczh6vFhwyfd7WNe7Q7mCA4KxAiLdz7jPE/WGizfRpIieoyFuNVMmM8HqZ9HwudTkY6/AeMQwlNJ9NJijguWw=="],
617 +
618 + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.1.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-+TpdtTRgHiJFjCVFbw311SuLk3KfytPOQQn+VlAEv+gBxYPtL7E6JS9e/tk+8CwxhIZvemJKo4rTKgfWNsKkkA=="],
619 +
620 + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.1.2", "", { "os": "linux", "cpu": "arm" }, "sha512-4lv1/tkmi7ueIVHnyreaOeUpiZP26BH9rRy6hoYfR9310A2B9nUEVRDvBx69vx64Nr3eTPPRkyciqJJs+j9Jmw=="],
621 +
622 + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.1.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-gBSUVO0eaWgw1JMjK3gB8BMlX2Mk148s2lTiVT3e9vjVxbl7UDfMWWY8CfIaaqiXuM9fVTMxIpUz6CAo/B6Vlw=="],
623 +
624 + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.1.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-LjQP/iZLBu8o8PjIfk4x3At0/mT6h282pvz8Z5LAyhGbu/kDezyO7ea62rF5uoqmgnIYqbN/MqJ3Si3Aymi7xQ=="],
625 +
626 + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.1.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-X/7bVLWelEsbyWDUSXt7zVsTniLLPIY2n1rH58qr78l9i7MNbbxBWD8gI2vRfBWf4NUXJCUuQnfZDsp32LqsfQ=="],
627 +
628 + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.1.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-gb6dYKW/1KDorGXyy48glEBJs/sxVSC5pcVrox/pFGV4mvwSFeg2sK5L2tRkVsVlh7kueqOgg4GEcuipJcGuKg=="],
629 +
630 + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.1.2", "", { "os": "linux", "cpu": "x64" }, "sha512-JY4w85pU3iAiJVMh5nuk4/Mh9GjMsupe8MrIN53rwxAZW64GKrWeJBuN6SxQg9QTU5uB1cxyhDzW8jqRn1EABw=="],
631 +
632 + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.1.2", "", { "os": "linux", "cpu": "x64" }, "sha512-xvpA7o5KCYLB0Rwscmuylb1/zHHSUx4g4xilm4prC5jP76pEUlzBmMbgpbh7bVDbId4NcfT96gN5i6mE6UDaiw=="],
633 +
634 + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.1.2", "", { "os": "none", "cpu": "arm64" }, "sha512-p/ts6KBLjuk49Bp21XH77poQGt02iNz7ChgHep7tudPOaLinR/De/RHdxF8w8Yj4r/bF/bqXwH6PZrB2sA+Nvw=="],
635 +
636 + "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.1.2", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.1.5" }, "cpu": "none" }, "sha512-VMu/wmrZ9hJzYlRhbw7jK5PODlugyKZ5mOdX78+lS8OvuFkWNQdz1pFLrI2p3P0pjXOmUZ7B48o5VnMH9QOGtg=="],
637 +
638 + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.1.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-xtUJqs8qEkuSviS0n1tsohaPuz3a1SPhZywOji4Oo+sgrJs8daEDMZ0QtqL0OS7dx8PoVpg2J/ZZycPY5I2+Zg=="],
639 +
640 + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.1.2", "", { "os": "win32", "cpu": "x64" }, "sha512-85YiLQqjUKgSO/Zjnf9e0XIn5Ymrh1fLDWBeAkZqpuBR/3R8TpfoHXuyblqyQrftSSgWO9qpcHN8mkyKsLraoA=="],
641 +
642 + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
643 +
644 "@rtsao/scc": ["@rtsao/scc@1.1.0", "", {}, "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g=="],
645
646 "@scalar/helpers": ["@scalar/helpers@0.2.4", "", {}, "sha512-G7oGybO2QXM+MIxa4OZLXaYsS9mxKygFgOcY4UOXO6xpVoY5+8rahdak9cPk7HNj8RZSt4m/BveoT8g5BtnXxg=="],
@@ -606,17 +661,17 @@
661
662 "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-Yx3gy7xLzM0ZOjqoxciHjA7dAt5tyzJE3L4uQoM83agahy+PlW244XJSrmJRSBvGYELDhYXPacD4R/cauV5bzQ=="],
663
609 - "@shikijs/langs": ["@shikijs/langs@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0" } }, "sha512-le+bssCxcSHrygCWuOrYJHvjus6zhQ2K7q/0mgjiffRbkhM4o1EWu2m+29l0yEsHDbWaWPNnDUTRVVBvBBeKaA=="],
664 + "@shikijs/langs": ["@shikijs/langs@4.2.0", "", { "dependencies": { "@shikijs/types": "4.2.0" } }, "sha512-bwrVRlJ0wUhZxAbVdvBbv2TTC9yLsh4C/IO5Ofz0T8MQntgDvyVnkbjw9vi50r1kx7RCIJdnJnjZAwmAsXFLZQ=="],
665
666 "@shikijs/rehype": ["@shikijs/rehype@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@types/hast": "^3.0.4", "hast-util-to-string": "^3.0.1", "shiki": "3.20.0", "unified": "^11.0.5", "unist-util-visit": "^5.0.0" } }, "sha512-/sqob3V/lJK0m2mZ64nkcWPN88im0D9atkI3S3PUBvtJZTHnJXVwZhHQFRDyObgEIa37IpHYHR3CuFtXB5bT2g=="],
667
613 - "@shikijs/themes": ["@shikijs/themes@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0" } }, "sha512-U1NSU7Sl26Q7ErRvJUouArxfM2euWqq1xaSrbqMu2iqa+tSp0D1Yah8216sDYbdDHw4C8b75UpE65eWorm2erQ=="],
668 + "@shikijs/themes": ["@shikijs/themes@4.2.0", "", { "dependencies": { "@shikijs/types": "4.2.0" } }, "sha512-RX8IHYeLv8Cu2W6ruc3RxUqWn0IYCqSrMBzi/uRGAmfyDNOnNO5BF/Px7o97n4XTpmFTo5GbRaazuOWj+2ak2w=="],
669
670 "@shikijs/transformers": ["@shikijs/transformers@3.20.0", "", { "dependencies": { "@shikijs/core": "3.20.0", "@shikijs/types": "3.20.0" } }, "sha512-PrHHMRr3Q5W1qB/42kJW6laqFyWdhrPF2hNR9qjOm1xcSiAO3hAHo7HaVyHE6pMyevmy3i51O8kuGGXC78uK3g=="],
671
672 "@shikijs/twoslash": ["@shikijs/twoslash@3.21.0", "", { "dependencies": { "@shikijs/core": "3.21.0", "@shikijs/types": "3.21.0", "twoslash": "^0.3.6" }, "peerDependencies": { "typescript": ">=5.5.0" } }, "sha512-iH360udAYON2JwfIldoCiMZr9MljuQA5QRBivKLpEuEpmVCSwrR+0WTQ0eS1ptgGBdH9weFiIsA5wJDzsEzTYg=="],
673
619 - "@shikijs/types": ["@shikijs/types@3.21.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-zGrWOxZ0/+0ovPY7PvBU2gIS9tmhSUUt30jAcNV0Bq0gb2S98gwfjIs1vxlmH5zM7/4YxLamT6ChlqqAJmPPjA=="],
674 + "@shikijs/types": ["@shikijs/types@4.2.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-VT/MKtlpOhEPZloSH3Pb9WCZEBDoQVMa9jedp5UAwmJOar1DVc9DRODAxmYPW9M93IK4ryuqRejFfmlvlVDemw=="],
675
676 "@shikijs/vitepress-twoslash": ["@shikijs/vitepress-twoslash@3.21.0", "", { "dependencies": { "@shikijs/twoslash": "3.21.0", "floating-vue": "^5.2.2", "lz-string": "^1.5.0", "magic-string": "^0.30.21", "markdown-it": "^14.1.0", "mdast-util-from-markdown": "^2.0.2", "mdast-util-gfm": "^3.1.0", "mdast-util-to-hast": "^13.2.1", "ohash": "^2.0.11", "shiki": "3.21.0", "twoslash": "^0.3.6", "twoslash-vue": "^0.3.6", "vue": "^3.5.26" } }, "sha512-R9qylCClKnLlPlWloY9SGdvr5X6smanxdPq7O1bxe7SL89j4/v9fMUUAWM6yPHf4jmGZuRGm/9IFRBdaAmm5Rw=="],
677
@@ -640,6 +695,12 @@
695
696 "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
697
698 + "@superradcompany/microsandbox-darwin-arm64": ["@superradcompany/microsandbox-darwin-arm64@0.5.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/ZnoBI0l9mYvPrwS8xPQ5L+c5B6U+aescZsiGXbjIvW9m/2rvMvi+tvl/Rj/pISHME8r2/2AQTqiFk4wvVxbcQ=="],
699 +
700 + "@superradcompany/microsandbox-linux-arm64-gnu": ["@superradcompany/microsandbox-linux-arm64-gnu@0.5.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-OHn6eZ1eTdZxmz3cfgpQFo3wpGq1WkbyqnB5P+VQYRknl+HyBJTsGb22ayqiSpIrN07QGOGoHcOA2+43etk5fw=="],
701 +
702 + "@superradcompany/microsandbox-linux-x64-gnu": ["@superradcompany/microsandbox-linux-x64-gnu@0.5.7", "", { "os": "linux", "cpu": "x64" }, "sha512-YBh0uaVG62aUHOSeKptpEQO+R2l/OZcWzE8DoCqMvyXQ9thKva9DUxP7QD439zHlteReh2Suku6DW9SRBeyqhw=="],
703 +
704 "@swc/helpers": ["@swc/helpers@0.5.15", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
705
706 "@tailwindcss/node": ["@tailwindcss/node@4.1.18", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
@@ -858,7 +919,7 @@
919
920 "@vercel/analytics": ["@vercel/analytics@1.6.1", "", { "peerDependencies": { "@remix-run/react": "^2", "@sveltejs/kit": "^1 || ^2", "next": ">= 13", "react": "^18 || ^19 || ^19.0.0-rc", "svelte": ">= 4", "vue": "^3", "vue-router": "^4" }, "optionalPeers": ["@remix-run/react", "@sveltejs/kit", "next", "react", "svelte", "vue", "vue-router"] }, "sha512-oH9He/bEM+6oKlv3chWuOOcp8Y6fo6/PSro8hEkgCW3pu9/OiCXiUpRUogDh3Fs3LH2sosDrx8CxeOLBEE+afg=="],
921
861 - "@vercel/oidc": ["@vercel/oidc@3.1.0", "", {}, "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w=="],
922 + "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
923
924 "@volar/language-core": ["@volar/language-core@2.4.27", "", { "dependencies": { "@volar/source-map": "2.4.27" } }, "sha512-DjmjBWZ4tJKxfNC1F6HyYERNHPYS7L7OPFyCrestykNdUZMFYzI9WTyvwPcaNaHlrEUwESHYsfEw3isInncZxQ=="],
925
@@ -884,6 +945,8 @@
945
946 "@vue/shared": ["@vue/shared@3.5.26", "", {}, "sha512-7Z6/y3uFI5PRoKeorTOSXKcDj0MSasfNNltcslbFrPpcw6aXRUALq4IfJlaTRspiWIUOEZbrpM+iQGmCOiWe4A=="],
947
948 + "@workflow/serde": ["@workflow/serde@4.1.0", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="],
949 +
950 "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
951
952 "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="],
@@ -892,7 +955,7 @@
955
956 "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
957
895 - "ai": ["ai@6.0.91", "", { "dependencies": { "@ai-sdk/gateway": "3.0.50", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-k1/8BusZMhYVxxLZt0BUZzm9HVDCCh117nyWfWUx5xjR2+tWisJbXgysL7EBMq2lgyHwgpA1jDR3tVjWSdWZXw=="],
958 + "ai": ["ai@7.0.0-beta.178", "", { "dependencies": { "@ai-sdk/gateway": "4.0.0-beta.109", "@ai-sdk/provider": "4.0.0-beta.19", "@ai-sdk/provider-utils": "5.0.0-beta.49" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-kOfIbf23FDkvvfDHOS1gIjImBF9MlYut8fEMlps57vvS622VKL1PeEDLJ181aVd2LPSiDr3SupAMSzI2rEaW3w=="],
959
960 "ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="],
961
@@ -1018,6 +1081,8 @@
1081
1082 "confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="],
1083
1084 + "consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],
1085 +
1086 "console-table-printer": ["console-table-printer@2.15.0", "", { "dependencies": { "simple-wcswidth": "^1.1.2" } }, "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw=="],
1087
1088 "content-disposition": ["content-disposition@1.0.1", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="],
@@ -1038,6 +1103,8 @@
1103
1104 "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
1105
1106 + "crossws": ["crossws@0.4.6", "", { "peerDependencies": { "srvx": ">=0.11.5" }, "optionalPeers": ["srvx"] }, "sha512-/Wxe9Z007EbJ496j88nToZEvyPZ8PY/wjZJ18Agh/GCA9cYHyLbxtrpdFlFzAw3TV20F0SUYGl0g6PzChbwUrg=="],
1107 +
1108 "cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
1109
1110 "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
@@ -1128,6 +1195,8 @@
1195
1196 "dayjs": ["dayjs@1.11.19", "", {}, "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw=="],
1197
1198 + "db0": ["db0@0.3.4", "", { "peerDependencies": { "@electric-sql/pglite": "*", "@libsql/client": "*", "better-sqlite3": "*", "drizzle-orm": "*", "mysql2": "*", "sqlite3": "*" }, "optionalPeers": ["@electric-sql/pglite", "@libsql/client", "better-sqlite3", "drizzle-orm", "mysql2", "sqlite3"] }, "sha512-RiXXi4WaNzPTHEOu8UPQKMooIbqOEyqA1t7Z6MsdxSCeb8iUC9ko3LcmsLmeUt2SM5bctfArZKkRQggKZz7JNw=="],
1199 +
1200 "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
1201
1202 "decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
@@ -1156,6 +1225,8 @@
1225
1226 "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
1227
1228 + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="],
1229 +
1230 "doctrine": ["doctrine@2.1.0", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw=="],
1231
1232 "dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
@@ -1188,6 +1259,8 @@
1259
1260 "entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
1261
1262 + "env-runner": ["env-runner@0.1.14", "", { "dependencies": { "crossws": "^0.4.5", "exsolve": "^1.0.8", "httpxy": "^0.5.3", "srvx": "^0.11.16" }, "peerDependencies": { "@netlify/runtime": "^4.1.23", "@vercel/queue": "^0.2.0", "miniflare": "^4.20260515.0", "wrangler": "^4.0.0" }, "optionalPeers": ["@netlify/runtime", "@vercel/queue", "miniflare", "wrangler"], "bin": { "env-runner": "dist/cli.mjs" } }, "sha512-qdk5mmgFsd+zPg3r1bkZ+IbvpfUfypyDvNhMGypSMRpz7kOa/kI6SpW8fgyukuEM4Lo24M65r+1Ne0DtT7vFBA=="],
1263 +
1264 "es-abstract": ["es-abstract@1.24.1", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-zHXBLhP+QehSSbsS9Pt23Gg964240DPd6QCf8WpkqEXxQ7fhdZzYsocOr5u7apWonsS5EjZDmTF+/slGMyasvw=="],
1265
1266 "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
@@ -1268,6 +1341,8 @@
1341
1342 "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
1343
1344 + "eve": ["eve@0.13.3", "", { "dependencies": { "nitro": "3.0.260610-beta" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0", "@sveltejs/kit": "^2.0.0", "ai": "7.0.0-beta.178", "braintrust": "^3.0.0", "just-bash": "^3.0.0", "microsandbox": "^0.5.0", "next": "^16.0.0", "nuxt": "^4.0.0", "react": "^19.0.0", "svelte": "^5.0.0", "vite": "^8.0.0", "vue": "^3.5.0" }, "optionalPeers": ["@opentelemetry/api", "@sveltejs/kit", "braintrust", "just-bash", "microsandbox", "next", "nuxt", "react", "svelte", "vite", "vue"], "bin": { "eve": "./bin/eve.js" } }, "sha512-UeDjzBq+j6XhECSW5FJjz8Lin4yw75rOchxbI/rmeRj9c9ldERwH/tb+aQRRzh3ZhnkFITzsBpNyF2arYcEjXQ=="],
1345 +
1346 "eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="],
1347
1348 "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
@@ -1280,6 +1355,8 @@
1355
1356 "express-rate-limit": ["express-rate-limit@7.5.1", "", { "peerDependencies": { "express": ">= 4.11" } }, "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw=="],
1357
1358 + "exsolve": ["exsolve@1.1.0", "", {}, "sha512-D+42+T12DdIlJM3uepa55qGiL3sYdLBOxIl2ifQCzCHz4c7eiolaHsi3BIqEr7JxBzxv2pYZQX9kw16ziMcEmw=="],
1359 +
1360 "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
1361
1362 "extend-shallow": ["extend-shallow@2.0.1", "", { "dependencies": { "is-extendable": "^0.1.0" } }, "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug=="],
@@ -1386,6 +1463,8 @@
1463
1464 "gtoken": ["gtoken@8.0.0", "", { "dependencies": { "gaxios": "^7.0.0", "jws": "^4.0.0" } }, "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw=="],
1465
1466 + "h3": ["h3@2.0.1-rc.22", "", { "dependencies": { "rou3": "^0.8.1", "srvx": "^0.11.15" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"], "bin": { "h3": "bin/h3.mjs" } }, "sha512-Esv0DMIuPkCTSWCA0vO73vcTqwzH1wjSrAO1TXNu/K3up1sZHa9EKMapbmxCDYBeymC3fVTk4qxp7ogQWQ+KgA=="],
1467 +
1468 "hachure-fill": ["hachure-fill@0.5.2", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="],
1469
1470 "has-bigints": ["has-bigints@1.1.0", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
@@ -1416,12 +1495,18 @@
1495
1496 "hermes-parser": ["hermes-parser@0.25.1", "", { "dependencies": { "hermes-estree": "0.25.1" } }, "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA=="],
1497
1498 + "highlight.js": ["highlight.js@11.11.1", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
1499 +
1500 "hono": ["hono@4.11.4", "", {}, "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA=="],
1501
1502 "hono-openapi": ["hono-openapi@1.1.2", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.8.3", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-toUcO60MftRBxqcVyxsHNYs2m4vf4xkQaiARAucQx3TiBPDtMNNkoh+C4I1vAretQZiGyaLOZNWn1YxfSyUA5g=="],
1503
1504 + "hookable": ["hookable@6.1.1", "", {}, "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ=="],
1505 +
1506 "html-to-text": ["html-to-text@9.0.5", "", { "dependencies": { "@selderee/plugin-htmlparser2": "^0.11.0", "deepmerge": "^4.3.1", "dom-serializer": "^2.0.0", "htmlparser2": "^8.0.2", "selderee": "^0.11.0" } }, "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg=="],
1507
1508 + "html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
1509 +
1510 "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],
1511
1512 "htmlparser2": ["htmlparser2@8.0.2", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1", "entities": "^4.4.0" } }, "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA=="],
@@ -1430,6 +1515,8 @@
1515
1516 "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
1517
1518 + "httpxy": ["httpxy@0.5.3", "", {}, "sha512-SMS9V6Sn7VWaS11lYhoAr0ceoaiolTWf4jYdJn0NJhCdKMu9R2H9Fh0LBDWBHQF6HRLI1PmaePYsjanSpE5PEw=="],
1519 +
1520 "iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
1521
1522 "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
@@ -1638,6 +1725,8 @@
1725
1726 "lru-cache": ["lru-cache@11.2.4", "", {}, "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg=="],
1727
1728 + "lru_map": ["lru_map@0.4.1", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
1729 +
1730 "lucide-react": ["lucide-react@0.562.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-82hOAu7y0dbVuFfmO4bYF1XEwYk/mEbM5E+b1jgci/udUBEE/R7LF5Ip0CCEmXe8AybRM8L+04eP+LGZeDvkiw=="],
1731
1732 "lz-string": ["lz-string@1.5.0", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],
@@ -1772,6 +1861,8 @@
1861
1862 "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
1863
1864 + "microsandbox": ["microsandbox@0.5.7", "", { "optionalDependencies": { "@superradcompany/microsandbox-darwin-arm64": "0.5.7", "@superradcompany/microsandbox-linux-arm64-gnu": "0.5.7", "@superradcompany/microsandbox-linux-x64-gnu": "0.5.7" }, "bin": { "microsandbox": "bin/microsandbox.cjs", "msb": "bin/microsandbox.cjs" } }, "sha512-6M/J2HsBtQeKQN2zyglwozC/nFD5bQPsF9fuk5dJvBqE6z5oxmqR5TOWoLVq2d3f2iS88TioxwDH7+Sa/MVTCQ=="],
1865 +
1866 "mime": ["mime@1.6.0", "", { "bin": { "mime": "cli.js" } }, "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="],
1867
1868 "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
@@ -1786,6 +1877,8 @@
1877
1878 "mlly": ["mlly@1.8.0", "", { "dependencies": { "acorn": "^8.15.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.1" } }, "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g=="],
1879
1880 + "motion": ["motion@12.41.0", "", { "dependencies": { "framer-motion": "^12.41.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-avEDKE22rFPJqDr3Ttk7gMQpeaOmNik60NoJ5T0tj+RBCNvz21D3ArY3l4uitoeQ7eIpDqueWaO3pPYFv8JOVA=="],
1881 +
1882 "motion-dom": ["motion-dom@12.39.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-Xn7aAcGDhco/JZTXOub64UmaYn73C6J1Po7Fk+8EvkJsNGTqfhon6UJY53vJKXW5v5Zl8HrYsVxv6oPXeGoGLQ=="],
1883
1884 "motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="],
@@ -1810,6 +1903,10 @@
1903
1904 "next-validate-link": ["next-validate-link@1.6.4", "", { "dependencies": { "gray-matter": "^4.0.3", "picocolors": "^1.1.1", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-mdx": "^3.1.1", "tinyglobby": "^0.2.15", "unist-util-visit": "^5.0.0" } }, "sha512-wR/VKyJlaTbUT5k1uujEnk6O616YtWGt52s9FJa3tRCQ2qL2TGFTAklXJ0QdX1NTAEeP6rGFOTtHEDwveFrc2g=="],
1905
1906 + "nf3": ["nf3@0.3.17", "", {}, "sha512-N9zEWySuJFw+gR0lhS5863YsvNeudOdqRyFvNb+jMXbeTJOdrjDqkCpDginIZfUm0LzT1t1nCRiDeqQm/8kirQ=="],
1907 +
1908 + "nitro": ["nitro@3.0.260610-beta", "", { "dependencies": { "consola": "^3.4.2", "crossws": "^0.4.6", "db0": "^0.3.4", "env-runner": "^0.1.12", "h3": "2.0.1-rc.22", "hookable": "^6.1.1", "nf3": "^0.3.17", "ocache": "^0.1.5", "ofetch": "2.0.0-alpha.3", "ohash": "^2.0.11", "rolldown": "^1.1.0", "srvx": "^0.11.16", "unenv": "2.0.0-rc.24", "unstorage": "2.0.0-alpha.7" }, "peerDependencies": { "@vercel/queue": "^0.3.0", "dotenv": "*", "giget": "*", "jiti": "^2.7.0", "rollup": "^4.61.1", "vite": "^7 || ^8", "xml2js": "^0.6.2", "zephyr-agent": "^0.2.0" }, "optionalPeers": ["@vercel/queue", "dotenv", "giget", "jiti", "rollup", "vite", "xml2js", "zephyr-agent"], "bin": { "nitro": "dist/cli/index.mjs" } }, "sha512-KPb4L5yaF/Rx/xoGMpgHRJvZhbhGiqbRKOwwPLCH9jKTKTsEUHLjnJas85AeCzaswqa8Wi52eQBtRsODC4PS0Q=="],
1909 +
1910 "node-addon-api": ["node-addon-api@8.5.0", "", {}, "sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A=="],
1911
1912 "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
@@ -1822,6 +1919,8 @@
1919
1920 "npm-to-yarn": ["npm-to-yarn@3.0.1", "", {}, "sha512-tt6PvKu4WyzPwWUzy/hvPFqn+uwXO0K1ZHka8az3NnrhWJDmSqI8ncWq0fkL0k/lmmi5tAC11FXwXuh0rFbt1A=="],
1921
1922 + "nucleo-pixel": ["nucleo-pixel@1.3.0", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-ocqHfb5uqvdQ8Ew9UCh8w8ShKk01yxPUsbaOVDdxccz4FbW5Aox24Q+TL/FOPzDaZn5P2GJTlZ93ureSHeGMEw=="],
1923 +
1924 "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
1925
1926 "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
@@ -1838,6 +1937,10 @@
1937
1938 "object.values": ["object.values@1.2.1", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0" } }, "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA=="],
1939
1940 + "ocache": ["ocache@0.1.5", "", { "dependencies": { "ohash": "^2.0.11" } }, "sha512-kNNnkkVQup/QDvmTz8Q84wc2ntiyoVHDxa6eHWKt5qdGAmFRBIxy83rxgCYEjW0x06UJ9E3P6VgM2yY4rOBH4w=="],
1941 +
1942 + "ofetch": ["ofetch@2.0.0-alpha.3", "", {}, "sha512-zpYTCs2byOuft65vI3z43Dd6iSdFbOZZLb9/d21aCpx2rGastVU9dOCv0lu4ykc1Ur1anAYjDi3SUvR0vq50JA=="],
1943 +
1944 "ohash": ["ohash@2.0.11", "", {}, "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ=="],
1945
1946 "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
@@ -1922,7 +2025,9 @@
2025
2026 "posthog-js": ["posthog-js@1.319.0", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/api-logs": "^0.208.0", "@opentelemetry/exporter-logs-otlp-http": "^0.208.0", "@opentelemetry/resources": "^2.2.0", "@opentelemetry/sdk-logs": "^0.208.0", "@posthog/core": "1.9.1", "@posthog/types": "1.319.0", "core-js": "^3.38.1", "dompurify": "^3.3.1", "fflate": "^0.4.8", "preact": "^10.19.3", "query-selector-shadow-dom": "^1.0.1", "web-vitals": "^4.2.4" } }, "sha512-0LFqLEhZzA8s1TrhYxsKsKmYV0n3FpNrWaT8rMjL87TRXtpy3XtsvbZKa97X6MFly5CK9CdhgKSNNyX7j12MrQ=="],
2027
1925 - "preact": ["preact@10.28.2", "", {}, "sha512-lbteaWGzGHdlIuiJ0l2Jq454m6kcpI1zNje6d8MlGAFlYvP2GO4ibnat7P74Esfz4sPTdM6UxtTwh/d3pwM9JA=="],
2028 + "preact": ["preact@11.0.0-beta.0", "", {}, "sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg=="],
2029 +
2030 + "preact-render-to-string": ["preact-render-to-string@6.6.5", "", { "peerDependencies": { "preact": ">=10 || >= 11.0.0-0" } }, "sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA=="],
2031
2032 "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
2033
@@ -1962,6 +2067,8 @@
2067
2068 "react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
2069
2070 + "react-markdown": ["react-markdown@10.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="],
2071 +
2072 "react-medium-image-zoom": ["react-medium-image-zoom@5.4.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-BsE+EnFVQzFIlyuuQrZ9iTwyKpKkqdFZV1ImEQN573QPqGrIUuNni7aF+sZwDcxlsuOMayCr6oO/PZR/yJnbRg=="],
2073
2074 "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
@@ -2018,6 +2125,10 @@
2125
2126 "robust-predicates": ["robust-predicates@3.0.2", "", {}, "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg=="],
2127
2128 + "rolldown": ["rolldown@1.1.2", "", { "dependencies": { "@oxc-project/types": "=0.137.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.2", "@rolldown/binding-darwin-arm64": "1.1.2", "@rolldown/binding-darwin-x64": "1.1.2", "@rolldown/binding-freebsd-x64": "1.1.2", "@rolldown/binding-linux-arm-gnueabihf": "1.1.2", "@rolldown/binding-linux-arm64-gnu": "1.1.2", "@rolldown/binding-linux-arm64-musl": "1.1.2", "@rolldown/binding-linux-ppc64-gnu": "1.1.2", "@rolldown/binding-linux-s390x-gnu": "1.1.2", "@rolldown/binding-linux-x64-gnu": "1.1.2", "@rolldown/binding-linux-x64-musl": "1.1.2", "@rolldown/binding-openharmony-arm64": "1.1.2", "@rolldown/binding-wasm32-wasi": "1.1.2", "@rolldown/binding-win32-arm64-msvc": "1.1.2", "@rolldown/binding-win32-x64-msvc": "1.1.2" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-x0CrQQqCXWGeI8dTvFfN/Dnv3yMKT9hv5jFjlOreKAx9wqLq9wz7VvLLHyaAXC90/CpggTu9SisSbsJJTPSjNQ=="],
2129 +
2130 + "rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
2131 +
2132 "roughjs": ["roughjs@4.6.6", "", { "dependencies": { "hachure-fill": "^0.5.2", "path-data-parser": "^0.1.0", "points-on-curve": "^0.2.0", "points-on-path": "^0.2.1" } }, "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ=="],
2133
2134 "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
@@ -2092,6 +2203,8 @@
2203
2204 "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="],
2205
2206 + "srvx": ["srvx@0.11.17", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-43yM4luKfCJamyCMhrUeHUPOrf8TdZe7kN8s5zayZCH5OeprYqi49Aso5ZvHXR4aB+DHaRNO/diNFgZSMNG8Xw=="],
2207 +
2208 "stable-hash": ["stable-hash@0.0.5", "", {}, "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA=="],
2209
2210 "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
@@ -2208,6 +2321,8 @@
2321
2322 "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
2323
2324 + "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],
2325 +
2326 "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
2327
2328 "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
@@ -2228,6 +2343,8 @@
2343
2344 "unrs-resolver": ["unrs-resolver@1.11.1", "", { "dependencies": { "napi-postinstall": "^0.3.0" }, "optionalDependencies": { "@unrs/resolver-binding-android-arm-eabi": "1.11.1", "@unrs/resolver-binding-android-arm64": "1.11.1", "@unrs/resolver-binding-darwin-arm64": "1.11.1", "@unrs/resolver-binding-darwin-x64": "1.11.1", "@unrs/resolver-binding-freebsd-x64": "1.11.1", "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", "@unrs/resolver-binding-linux-x64-musl": "1.11.1", "@unrs/resolver-binding-wasm32-wasi": "1.11.1", "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" } }, "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg=="],
2345
2346 + "unstorage": ["unstorage@2.0.0-alpha.7", "", { "peerDependencies": { "@azure/app-configuration": "^1.11.0", "@azure/cosmos": "^4.9.1", "@azure/data-tables": "^13.3.2", "@azure/identity": "^4.13.0", "@azure/keyvault-secrets": "^4.10.0", "@azure/storage-blob": "^12.31.0", "@capacitor/preferences": "^6 || ^7 || ^8", "@deno/kv": ">=0.13.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.36.2", "@vercel/blob": ">=0.27.3", "@vercel/functions": "^2.2.12 || ^3.0.0", "@vercel/kv": "^1.0.1", "aws4fetch": "^1.0.20", "chokidar": "^4 || ^5", "db0": ">=0.3.4", "idb-keyval": "^6.2.2", "ioredis": "^5.9.3", "lru-cache": "^11.2.6", "mongodb": "^6 || ^7", "ofetch": "*", "uploadthing": "^7.7.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/functions", "@vercel/kv", "aws4fetch", "chokidar", "db0", "idb-keyval", "ioredis", "lru-cache", "mongodb", "ofetch", "uploadthing"] }, "sha512-ELPztchk2zgFJnakyodVY3vJWGW9jy//keJ32IOJVGUMyaPydwcA1FtVvWqT0TNRch9H+cMNEGllfVFfScImog=="],
2347 +
2348 "update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
2349
2350 "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
@@ -2302,7 +2419,7 @@
2419
2420 "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
2421
2305 - "zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2422 + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
2423
2424 "zod-from-json-schema": ["zod-from-json-schema@0.5.2", "", { "dependencies": { "zod": "^4.0.17" } }, "sha512-/dNaicfdhJTOuUd4RImbLUE2g5yrSzzDjI/S6C2vO2ecAGZzn9UcRVgtyLSnENSmAOBRiSpUdzDS6fDWX3Z35g=="],
2425
@@ -2318,6 +2435,10 @@
2435
2436 "@a2a-js/sdk/uuid": ["uuid@11.1.0", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
2437
2438 + "@ai-sdk/gateway/@ai-sdk/provider": ["@ai-sdk/provider@4.0.0-beta.19", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Aca/KiGeRtMM7rOJ38Qio+Dc2V45PpiGoWgdrdtIkgM9zkhYpS043t0ggKoNOWgm/csv99XWGrfSF63PSkVeHw=="],
2439 +
2440 + "@ai-sdk/gateway/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.0-beta.49", "", { "dependencies": { "@ai-sdk/provider": "4.0.0-beta.19", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-7xnpAQLpW0KGIsh0CQERcIZuXEGqv7FtFW2BdFk14iuMxRMVpXhTVvEQyqkm6tWAbQ7OsGQJhO6M0Me9gHQ52g=="],
2441 +
2442 "@ai-sdk/openai/@ai-sdk/provider": ["@ai-sdk/provider@3.0.2", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-HrEmNt/BH/hkQ7zpi2o6N3k1ZR1QTb7z85WYhYygiTxOQuaml4CMtHCWRbric5WPU+RNsYI7r1EpyVQMKO1pYw=="],
2443
2444 "@ai-sdk/openai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.5", "", { "dependencies": { "@ai-sdk/provider": "3.0.2", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Ow/X/SEkeExTTc1x+nYLB9ZHK2WUId8+9TlkamAx7Tl9vxU+cKzWx2dwjgMHeCN6twrgwkLrrtqckQeO4mxgVA=="],
@@ -2332,8 +2453,6 @@
2453
2454 "@ai-sdk/ui-utils-v5/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="],
2455
2335 - "@ai-sdk/ui-utils-v5/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
2336 -
2456 "@babel/core/json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
2457
2458 "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
@@ -2354,14 +2473,24 @@
2473
2474 "@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="],
2475
2476 + "@langchain/core/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2477 +
2478 "@langchain/langgraph-sdk/p-queue": ["p-queue@9.1.0", "", { "dependencies": { "eventemitter3": "^5.0.1", "p-timeout": "^7.0.0" } }, "sha512-O/ZPaXuQV29uSLbxWBGGZO1mCQXV2BLIwUr59JUU9SoH76mnYvtms7aafH/isNSNGwuEfP6W/4xD0/TJXxrizw=="],
2479
2480 "@langchain/langgraph-sdk/uuid": ["uuid@13.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
2481
2482 + "@langchain/openai/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2483 +
2484 + "@llamaindex/core/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2485 +
2486 "@llamaindex/openai/openai": ["openai@5.23.2", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-MQBzmTulj+MM5O8SKEk/gL8a7s5mktS9zUtAkU257WjvobGc9nKcBuVwjyEEcb9SI8a8Y2G/mzn3vm9n1Jlleg=="],
2487
2488 "@mastra/mcp/uuid": ["uuid@11.1.0", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
2489
2490 + "@modelcontextprotocol/sdk/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2491 +
2492 + "@napi-rs/wasm-runtime/@emnapi/core": ["@emnapi/core@1.7.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg=="],
2493 +
2494 "@openai/agents/openai": ["openai@6.22.0", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-7Yvy17F33Bi9RutWbsaYt5hJEEJ/krRPOrwan+f9aCPuMat1WVsb2VNSII5W1EksKT6fF69TG/xj4XzodK3JZw=="],
2495
2496 "@openai/agents-core/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.26.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg=="],
@@ -2380,6 +2509,10 @@
2509
2510 "@opentelemetry/sdk-trace-base/@opentelemetry/resources": ["@opentelemetry/resources@2.2.0", "", { "dependencies": { "@opentelemetry/core": "2.2.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A=="],
2511
2512 + "@pierre/diffs/diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
2513 +
2514 + "@pierre/diffs/shiki": ["shiki@3.21.0", "", { "dependencies": { "@shikijs/core": "3.21.0", "@shikijs/engine-javascript": "3.21.0", "@shikijs/engine-oniguruma": "3.21.0", "@shikijs/langs": "3.21.0", "@shikijs/themes": "3.21.0", "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-N65B/3bqL/TI2crrXr+4UivctrAGEjmsib5rPMMPpFp1xAx/w03v8WZ9RDDFYteXoEgY7qZ4HGgl5KBIu1153w=="],
2515 +
2516 "@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
2517
2518 "@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
@@ -2390,20 +2523,26 @@
2523
2524 "@radix-ui/react-select/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
2525
2526 + "@rolldown/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
2527 +
2528 + "@rolldown/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.5", "", { "dependencies": { "@tybys/wasm-util": "^0.10.2" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q=="],
2529 +
2530 + "@scalar/openapi-types/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2531 +
2532 + "@shikijs/core/@shikijs/types": ["@shikijs/types@3.21.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-zGrWOxZ0/+0ovPY7PvBU2gIS9tmhSUUt30jAcNV0Bq0gb2S98gwfjIs1vxlmH5zM7/4YxLamT6ChlqqAJmPPjA=="],
2533 +
2534 "@shikijs/engine-javascript/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2535
2536 "@shikijs/engine-oniguruma/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2537
2397 - "@shikijs/langs/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2398 -
2538 "@shikijs/rehype/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2539
2401 - "@shikijs/themes/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2402 -
2540 "@shikijs/transformers/@shikijs/core": ["@shikijs/core@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-f2ED7HYV4JEk827mtMDwe/yQ25pRiXZmtHjWF8uzZKuKiEsJR7Ce1nuQ+HhV9FzDcbIo4ObBCD9GPTzNuy9S1g=="],
2541
2542 "@shikijs/transformers/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2543
2544 + "@shikijs/twoslash/@shikijs/types": ["@shikijs/types@3.21.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-zGrWOxZ0/+0ovPY7PvBU2gIS9tmhSUUt30jAcNV0Bq0gb2S98gwfjIs1vxlmH5zM7/4YxLamT6ChlqqAJmPPjA=="],
2545 +
2546 "@shikijs/vitepress-twoslash/shiki": ["shiki@3.21.0", "", { "dependencies": { "@shikijs/core": "3.21.0", "@shikijs/engine-javascript": "3.21.0", "@shikijs/engine-oniguruma": "3.21.0", "@shikijs/langs": "3.21.0", "@shikijs/themes": "3.21.0", "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-N65B/3bqL/TI2crrXr+4UivctrAGEjmsib5rPMMPpFp1xAx/w03v8WZ9RDDFYteXoEgY7qZ4HGgl5KBIu1153w=="],
2547
2548 "@sindresorhus/slugify/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
@@ -2436,6 +2575,10 @@
2575
2576 "@vue/compiler-sfc/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
2577
2578 + "ai/@ai-sdk/provider": ["@ai-sdk/provider@4.0.0-beta.19", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Aca/KiGeRtMM7rOJ38Qio+Dc2V45PpiGoWgdrdtIkgM9zkhYpS043t0ggKoNOWgm/csv99XWGrfSF63PSkVeHw=="],
2579 +
2580 + "ai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.0-beta.49", "", { "dependencies": { "@ai-sdk/provider": "4.0.0-beta.19", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-7xnpAQLpW0KGIsh0CQERcIZuXEGqv7FtFW2BdFk14iuMxRMVpXhTVvEQyqkm6tWAbQ7OsGQJhO6M0Me9gHQ52g=="],
2581 +
2582 "browserslist/baseline-browser-mapping": ["baseline-browser-mapping@2.9.11", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ=="],
2583
2584 "chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
@@ -2464,8 +2607,12 @@
2607
2608 "eslint-plugin-react/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
2609
2610 + "eslint-plugin-react-hooks/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2611 +
2612 "fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
2613
2614 + "fumadocs-mdx/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2615 +
2616 "glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
2617
2618 "gray-matter/js-yaml": ["js-yaml@3.14.2", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg=="],
@@ -2478,6 +2625,8 @@
2625
2626 "mlly/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
2627
2628 + "motion/framer-motion": ["framer-motion@12.41.0", "", { "dependencies": { "motion-dom": "^12.41.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-OHAMNiCEON1RDBlRGuulsN5AD8ptMjvk5QWfFmYmBLPZ3zFGIJe60kQucQQf4cez1OzQmjYBWDY+dYfISkUdqg=="],
2629 +
2630 "next/postcss": ["postcss@8.4.31", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
2631
2632 "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
@@ -2486,6 +2635,8 @@
2635
2636 "pkg-types/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
2637
2638 + "posthog-js/preact": ["preact@10.28.2", "", {}, "sha512-lbteaWGzGHdlIuiJ0l2Jq454m6kcpI1zNje6d8MlGAFlYvP2GO4ibnat7P74Esfz4sPTdM6UxtTwh/d3pwM9JA=="],
2639 +
2640 "sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="],
2641
2642 "sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],
@@ -2518,6 +2669,10 @@
2669
2670 "shiki/@shikijs/core": ["@shikijs/core@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-f2ED7HYV4JEk827mtMDwe/yQ25pRiXZmtHjWF8uzZKuKiEsJR7Ce1nuQ+HhV9FzDcbIo4ObBCD9GPTzNuy9S1g=="],
2671
2672 + "shiki/@shikijs/langs": ["@shikijs/langs@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0" } }, "sha512-le+bssCxcSHrygCWuOrYJHvjus6zhQ2K7q/0mgjiffRbkhM4o1EWu2m+29l0yEsHDbWaWPNnDUTRVVBvBBeKaA=="],
2673 +
2674 + "shiki/@shikijs/themes": ["@shikijs/themes@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0" } }, "sha512-U1NSU7Sl26Q7ErRvJUouArxfM2euWqq1xaSrbqMu2iqa+tSp0D1Yah8216sDYbdDHw4C8b75UpE65eWorm2erQ=="],
2675 +
2676 "shiki/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
2677
2678 "string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
@@ -2526,6 +2681,8 @@
2681
2682 "strip-ansi-cjs/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
2683
2684 + "unenv/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
2685 +
2686 "wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],
2687
2688 "wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
@@ -2534,6 +2691,8 @@
2691
2692 "wrap-ansi-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
2693
2694 + "zod-from-json-schema/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2695 +
2696 "zod-from-json-schema-v3/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
2697
2698 "@a2a-js/sdk/express/accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],
@@ -2560,6 +2719,8 @@
2719
2720 "@a2a-js/sdk/express/type-is": ["type-is@1.6.18", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="],
2721
2722 + "@ai-sdk/gateway/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
2723 +
2724 "@ai-sdk/react/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.55", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-7xMeTJnCjwRwXKVCiv4Ly4qzWvDuW3+W1WIV0X1EFu6W83d4mEhV9bFArto10MeTw40ewuDjrbrZd21mXKohkw=="],
2725
2726 "@eslint/eslintrc/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
@@ -2568,8 +2729,24 @@
2729
2730 "@langchain/langgraph-sdk/p-queue/p-timeout": ["p-timeout@7.0.1", "", {}, "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg=="],
2731
2732 + "@napi-rs/wasm-runtime/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.1.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ=="],
2733 +
2734 "@openai/agents-core/@modelcontextprotocol/sdk/express-rate-limit": ["express-rate-limit@8.2.1", "", { "dependencies": { "ip-address": "10.0.1" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g=="],
2735
2736 + "@openai/agents-core/@modelcontextprotocol/sdk/zod": ["zod@4.2.1", "", {}, "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw=="],
2737 +
2738 + "@pierre/diffs/shiki/@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-ATwv86xlbmfD9n9gKRiwuPpWgPENAWCLwYCGz9ugTJlsO2kOzhOkvoyV/UD+tJ0uT7YRyD530x6ugNSffmvIiQ=="],
2739 +
2740 + "@pierre/diffs/shiki/@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-OYknTCct6qiwpQDqDdf3iedRdzj6hFlOPv5hMvI+hkWfCKs5mlJ4TXziBG9nyabLwGulrUjHiCq3xCspSzErYQ=="],
2741 +
2742 + "@pierre/diffs/shiki/@shikijs/langs": ["@shikijs/langs@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0" } }, "sha512-g6mn5m+Y6GBJ4wxmBYqalK9Sp0CFkUqfNzUy2pJglUginz6ZpWbaWjDB4fbQ/8SHzFjYbtU6Ddlp1pc+PPNDVA=="],
2743 +
2744 + "@pierre/diffs/shiki/@shikijs/themes": ["@shikijs/themes@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0" } }, "sha512-BAE4cr9EDiZyYzwIHEk7JTBJ9CzlPuM4PchfcA5ao1dWXb25nv6hYsoDiBq2aZK9E3dlt3WB78uI96UESD+8Mw=="],
2745 +
2746 + "@pierre/diffs/shiki/@shikijs/types": ["@shikijs/types@3.21.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-zGrWOxZ0/+0ovPY7PvBU2gIS9tmhSUUt30jAcNV0Bq0gb2S98gwfjIs1vxlmH5zM7/4YxLamT6ChlqqAJmPPjA=="],
2747 +
2748 + "@rolldown/binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
2749 +
2750 "@shikijs/vitepress-twoslash/shiki/@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-ATwv86xlbmfD9n9gKRiwuPpWgPENAWCLwYCGz9ugTJlsO2kOzhOkvoyV/UD+tJ0uT7YRyD530x6ugNSffmvIiQ=="],
2751
2752 "@shikijs/vitepress-twoslash/shiki/@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-OYknTCct6qiwpQDqDdf3iedRdzj6hFlOPv5hMvI+hkWfCKs5mlJ4TXziBG9nyabLwGulrUjHiCq3xCspSzErYQ=="],
@@ -2578,10 +2755,14 @@
2755
2756 "@shikijs/vitepress-twoslash/shiki/@shikijs/themes": ["@shikijs/themes@3.21.0", "", { "dependencies": { "@shikijs/types": "3.21.0" } }, "sha512-BAE4cr9EDiZyYzwIHEk7JTBJ9CzlPuM4PchfcA5ao1dWXb25nv6hYsoDiBq2aZK9E3dlt3WB78uI96UESD+8Mw=="],
2757
2758 + "@shikijs/vitepress-twoslash/shiki/@shikijs/types": ["@shikijs/types@3.21.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-zGrWOxZ0/+0ovPY7PvBU2gIS9tmhSUUt30jAcNV0Bq0gb2S98gwfjIs1vxlmH5zM7/4YxLamT6ChlqqAJmPPjA=="],
2759 +
2760 "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="],
2761
2762 "@typescript-eslint/utils/@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
2763
2764 + "ai/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
2765 +
2766 "cytoscape-fcose/cose-base/layout-base": ["layout-base@2.0.1", "", {}, "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg=="],
2767
2768 "d3-sankey/d3-array/internmap": ["internmap@1.0.1", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],
@@ -2594,6 +2775,8 @@
2775
2776 "gray-matter/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],
2777
2778 + "motion/framer-motion/motion-dom": ["motion-dom@12.41.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-Lk3J39fOGg6xNr1KRZsN6usDyBf8aP7MEbUPez1VCughHt79OrP7VGqNrPyFL0riaT7WS8t9DRw1M3BHtM/xKw=="],
2779 +
2780 "string-width-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
2781
2782 "wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
@@ -2614,6 +2797,8 @@
2797
2798 "@a2a-js/sdk/express/type-is/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
2799
2800 + "@ai-sdk/react/ai/@ai-sdk/gateway/@vercel/oidc": ["@vercel/oidc@3.1.0", "", {}, "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w=="],
2801 +
2802 "@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
2803
2804 "@a2a-js/sdk/express/accepts/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
docs/components/ask-ai-button.tsx
+4 -17
@@ -5,20 +5,7 @@ import { Search, MessageSquare } from 'lucide-react';
5 import { useSearchContext } from '@fumadocs/ui/contexts/search';
6 import { useI18n } from '@fumadocs/ui/contexts/i18n';
7
8 -import {
9 - closeDecimalWidget,
10 - getDecimal,
11 - isDecimalWidgetVisible,
12 - loadDecimalWidget,
13 - openDecimalWidget,
14 -} from './decimal-widget';
15 -
16 -export async function toggleDecimalWidget() {
17 - const decimal = getDecimal() ?? (await loadDecimalWidget());
18 - if (!decimal) return;
19 -
20 - isDecimalWidgetVisible() ? closeDecimalWidget() : openDecimalWidget(decimal);
21 -}
8 +import { toggleEveChat } from './eve-chat-store';
9
10 export function detectMac(): boolean {
11 try {
@@ -45,7 +32,7 @@ function useIsMac() {
32 const handleKeyDown = (e: KeyboardEvent) => {
33 if ((e.metaKey || e.ctrlKey) && e.key === 'i') {
34 e.preventDefault();
48 - void toggleDecimalWidget();
35 + toggleEveChat();
36 }
37 };
38
@@ -86,7 +73,7 @@ export function SearchAndAskAI() {
73 <button
74 type="button"
75 onClick={() => {
89 - void toggleDecimalWidget();
76 + toggleEveChat();
77 }}
78 className="inline-flex items-center gap-2 rounded-lg border border-[var(--composio-orange)]/20 bg-[var(--composio-orange)]/5 p-1.5 ps-2.5 text-sm text-[var(--composio-orange)] transition-colors hover:bg-[var(--composio-orange)]/10 shrink-0"
79 >
@@ -121,7 +108,7 @@ export function SearchAndAskAIMobile() {
108 type="button"
109 aria-label="Ask AI"
110 onClick={() => {
124 - void toggleDecimalWidget();
111 + toggleEveChat();
112 }}
113 className="inline-flex items-center justify-center rounded-md p-2 text-sm font-medium transition-colors duration-100 hover:bg-fd-accent hover:text-fd-accent-foreground"
114 >
docs/components/auth-config-flow.tsx new
+254
@@ -0,0 +1,254 @@
1 +'use client';
2 +
3 +import { Check } from 'lucide-react';
4 +import { useCallback, useEffect, useRef, useState } from 'react';
5 +
6 +const LOGO_CDN = 'https://logos.composio.dev/api';
7 +
8 +/** Landing /dev accent (`--brand-foryou`). */
9 +const BRAND = '#51a2ff';
10 +/** Landing floating-card shadow. */
11 +const CARD_SHADOW = '0 24px 70px -10px rgba(0,0,0,0.7)';
12 +
13 +const USERS: {
14 + id: string;
15 + label: string;
16 + accounts: { name: string; ca: string }[];
17 +}[] = [
18 + {
19 + id: 'user_1',
20 + label: 'user_1',
21 + accounts: [
22 + { name: 'Work Gmail', ca: 'ca_1a2b3c' },
23 + { name: 'Personal Gmail', ca: 'ca_4d5e6f' },
24 + ],
25 + },
26 + {
27 + id: 'user_2',
28 + label: 'user_2',
29 + accounts: [{ name: 'Gmail', ca: 'ca_7g8h9i' }],
30 + },
31 +];
32 +
33 +/**
34 + * Orthogonal elbow connector (the /dev page shape): leave `from`'s right edge
35 + * horizontally, step vertically at the midpoint, then run horizontally into
36 + * `to`'s left edge — with rounded corners. Measured relative to the container.
37 + */
38 +function elbowPath(c: DOMRect, from: DOMRect, to: DOMRect, r = 10): string {
39 + const sx = from.right - c.left;
40 + const sy = from.top + from.height / 2 - c.top;
41 + const ex = to.left - c.left;
42 + const ey = to.top + to.height / 2 - c.top;
43 + const midX = sx + (ex - sx) * 0.5;
44 + const dy = Math.sign(ey - sy) || 1;
45 + const rr = Math.min(r, Math.abs(ex - sx) / 2, Math.abs(ey - sy) / 2);
46 + if (rr < 1) return `M ${sx} ${sy} L ${ex} ${ey}`;
47 + return (
48 + `M ${sx} ${sy} L ${midX - rr} ${sy} ` +
49 + `Q ${midX} ${sy} ${midX} ${sy + dy * rr} ` +
50 + `L ${midX} ${ey - dy * rr} ` +
51 + `Q ${midX} ${ey} ${midX + rr} ${ey} ` +
52 + `L ${ex} ${ey}`
53 + );
54 +}
55 +
56 +/**
57 + * AuthConfigFlow — the `auth config → connected accounts` relationship, drawn in
58 + * the landing /dev visual language: bare dark floating cards (#0a0a0a, hairline
59 + * white borders, JetBrains Mono) wired together with measured SVG elbow
60 + * connectors in the for-you brand blue. One auth config is a single blueprint
61 + * every user authenticates against; it fans out to a connected account (or
62 + * several) per user, fully isolated. Paths are computed from live geometry so the
63 + * fanout stays aligned across breakpoints, and draw in once on scroll.
64 + */
65 +export function AuthConfigFlow() {
66 + const rootRef = useRef<HTMLDivElement>(null);
67 + const blueprintRef = useRef<HTMLDivElement>(null);
68 + const userRefs = useRef<(HTMLDivElement | null)[]>([]);
69 + const [paths, setPaths] = useState<string[]>([]);
70 + const [drawn, setDrawn] = useState(false);
71 +
72 + const calc = useCallback(() => {
73 + const root = rootRef.current;
74 + const blueprint = blueprintRef.current;
75 + if (!root || !blueprint) return;
76 + const cr = root.getBoundingClientRect();
77 + const from = blueprint.getBoundingClientRect();
78 + const next: string[] = [];
79 + for (const ref of userRefs.current) {
80 + if (!ref) continue;
81 + next.push(elbowPath(cr, from, ref.getBoundingClientRect()));
82 + }
83 + setPaths(next);
84 + }, []);
85 +
86 + useEffect(() => {
87 + calc();
88 + const t = setTimeout(calc, 120);
89 + window.addEventListener('resize', calc);
90 + const root = rootRef.current;
91 + const ro = root ? new ResizeObserver(() => calc()) : null;
92 + if (root && ro) ro.observe(root);
93 + return () => {
94 + clearTimeout(t);
95 + window.removeEventListener('resize', calc);
96 + ro?.disconnect();
97 + };
98 + }, [calc]);
99 +
100 + useEffect(() => {
101 + const el = rootRef.current;
102 + if (!el) return;
103 + const io = new IntersectionObserver(
104 + ([e]) => {
105 + if (e?.isIntersecting) setDrawn(true);
106 + },
107 + { threshold: 0.4 }
108 + );
109 + io.observe(el);
110 + return () => io.disconnect();
111 + }, []);
112 +
113 + return (
114 + <div className="not-prose my-8 font-mono">
115 + {/* floating composition — bare dark cards on the page, no outer card */}
116 + <div
117 + ref={rootRef}
118 + className="relative flex flex-col gap-4 md:block md:h-[300px]"
119 + >
120 + {/* ── connector overlay (md and up) ── */}
121 + <svg
122 + aria-hidden="true"
123 + className="pointer-events-none absolute inset-0 z-0 hidden size-full overflow-visible md:block"
124 + fill="none"
125 + style={{ color: BRAND }}
126 + >
127 + <style>{`
128 + @keyframes acfDraw { to { stroke-dashoffset: 0; } }
129 + @media (prefers-reduced-motion: reduce) {
130 + .acf-draw { animation: none !important; stroke-dashoffset: 0 !important; }
131 + }
132 + `}</style>
133 + {paths.map((d, i) => (
134 + <g key={USERS[i]?.id ?? i}>
135 + {/* faint static rail */}
136 + <path d={d} opacity={0.15} stroke="currentColor" strokeWidth={1} />
137 + {/* drawn-in accent */}
138 + <path
139 + className="acf-draw"
140 + d={d}
141 + stroke="currentColor"
142 + strokeDasharray={600}
143 + strokeDashoffset={600}
144 + strokeWidth={1.5}
145 + style={{
146 + animation: drawn
147 + ? `acfDraw 0.7s ease-out ${0.15 + i * 0.15}s forwards`
148 + : undefined,
149 + }}
150 + />
151 + </g>
152 + ))}
153 + </svg>
154 +
155 + {/* ── blueprint node ── */}
156 + <div className="relative z-10 md:absolute md:top-1/2 md:left-0 md:w-[244px] md:-translate-y-1/2">
157 + <div
158 + ref={blueprintRef}
159 + className="relative overflow-hidden border bg-[#0a0a0a] p-3"
160 + style={{
161 + borderColor: 'color-mix(in srgb, ' + BRAND + ' 50%, transparent)',
162 + boxShadow: CARD_SHADOW,
163 + }}
164 + >
165 + <span
166 + aria-hidden="true"
167 + className="pointer-events-none absolute inset-y-0 left-0 w-[2px]"
168 + style={{ background: BRAND }}
169 + />
170 + <div className="flex items-center gap-2">
171 + <img
172 + alt=""
173 + aria-hidden="true"
174 + className="size-4 object-contain"
175 + draggable={false}
176 + src={`${LOGO_CDN}/gmail`}
177 + />
178 + <code className="text-[12px] font-medium text-white/90">
179 + ac_gmail_oauth2
180 + </code>
181 + </div>
182 + <p className="mt-2 text-[11px] leading-snug text-white/45">
183 + One OAuth2 blueprint: auth method, scopes, and credentials. Reused
184 + for every user who connects Gmail.
185 + </p>
186 + </div>
187 + </div>
188 +
189 + {/* ── connected-account nodes, per user ── */}
190 + <div className="relative z-10 flex flex-col gap-3 md:absolute md:inset-y-0 md:right-0 md:w-[300px] md:justify-center md:gap-5">
191 + {USERS.map((user, i) => (
192 + <div
193 + key={user.id}
194 + ref={(el) => {
195 + userRefs.current[i] = el;
196 + }}
197 + className="overflow-hidden border border-white/10 bg-[#0a0a0a]"
198 + style={{ boxShadow: CARD_SHADOW }}
199 + >
200 + <div className="flex items-center gap-2 border-b border-white/[0.06] bg-white/[0.02] px-2.5 py-2">
201 + <span
202 + className="flex size-5 items-center justify-center rounded-full text-[10px]"
203 + style={{
204 + background:
205 + 'color-mix(in srgb, ' + BRAND + ' 15%, transparent)',
206 + color: BRAND,
207 + }}
208 + >
209 + U
210 + </span>
211 + <code className="text-[11px] text-white/70">{user.label}</code>
212 + </div>
213 + <ul className="flex flex-col">
214 + {user.accounts.map((acct, j) => (
215 + <li
216 + key={acct.ca}
217 + className={
218 + 'flex items-center gap-2.5 px-2.5 py-2' +
219 + (j < user.accounts.length - 1
220 + ? ' border-b border-white/[0.06]'
221 + : '')
222 + }
223 + >
224 + <img
225 + alt=""
226 + aria-hidden="true"
227 + className="size-[15px] object-contain"
228 + draggable={false}
229 + src={`${LOGO_CDN}/gmail`}
230 + />
231 + <span className="text-[12px] text-white/70">{acct.name}</span>
232 + <code className="ml-auto text-[10px] text-white/35">
233 + {acct.ca}
234 + </code>
235 + <Check aria-hidden="true" className="size-4 text-green-400" />
236 + </li>
237 + ))}
238 + </ul>
239 + </div>
240 + ))}
241 + </div>
242 + </div>
243 +
244 + {/* plain caption — page text, no box */}
245 + <p className="mt-6 text-center text-[10px] text-fd-foreground/45">
246 + one auth config{' '}
247 + <span aria-hidden="true" style={{ color: BRAND }}>
248 + →
249 + </span>{' '}
250 + a connected account per user, fully isolated
251 + </p>
252 + </div>
253 + );
254 +}
docs/components/connection-refresh-visual.tsx new
+283
@@ -0,0 +1,283 @@
1 +'use client';
2 +
3 +import { Check, RefreshCw } from 'lucide-react';
4 +import { motion, useReducedMotion } from 'framer-motion';
5 +import { useCallback, useEffect, useRef, useState } from 'react';
6 +
7 +const LOGO_CDN = 'https://logos.composio.dev/api';
8 +
9 +/** Landing /dev accent (`--brand-foryou`). */
10 +const BRAND = '#51a2ff';
11 +/** Landing floating-card shadow. */
12 +const CARD_SHADOW = '0 24px 70px -10px rgba(0,0,0,0.7)';
13 +
14 +const CONNECTIONS: { slug: string; name: string; account: string }[] = [
15 + { slug: 'gmail', name: 'Gmail', account: 'work@acme.com' },
16 + { slug: 'notion', name: 'Notion', account: 'acme-workspace' },
17 + { slug: 'github', name: 'GitHub', account: 'acme-bot' },
18 +];
19 +
20 +/** Rotating access-token suffixes, so each refresh visibly mints a fresh token. */
21 +const TOKENS = ['9f3a', '2c7d', 'b18e', '6a04', 'd52f'];
22 +
23 +/** ms between simulated 30-minute refresh ticks. */
24 +const CYCLE_MS = 4200;
25 +
26 +/**
27 + * Orthogonal elbow connector (the /dev page shape): leave `from`'s right edge
28 + * horizontally, step vertically at the midpoint, then run horizontally into
29 + * `to`'s left edge, with rounded corners. Measured relative to the container.
30 + */
31 +function elbowPath(c: DOMRect, from: DOMRect, to: DOMRect, r = 10): string {
32 + const sx = from.right - c.left;
33 + const sy = from.top + from.height / 2 - c.top;
34 + const ex = to.left - c.left;
35 + const ey = to.top + to.height / 2 - c.top;
36 + const midX = sx + (ex - sx) * 0.5;
37 + const dy = Math.sign(ey - sy) || 1;
38 + const rr = Math.min(r, Math.abs(ex - sx) / 2, Math.abs(ey - sy) / 2);
39 + if (rr < 1) return `M ${sx} ${sy} L ${ex} ${ey}`;
40 + return (
41 + `M ${sx} ${sy} L ${midX - rr} ${sy} ` +
42 + `Q ${midX} ${sy} ${midX} ${sy + dy * rr} ` +
43 + `L ${midX} ${ey - dy * rr} ` +
44 + `Q ${midX} ${ey} ${midX + rr} ${ey} ` +
45 + `L ${ex} ${ey}`
46 + );
47 +}
48 +
49 +/**
50 + * ConnectionRefreshVisual — Composio's automatic OAuth token refresh, drawn in
51 + * the landing /dev visual language: bare dark floating cards (#0a0a0a, hairline
52 + * white borders, JetBrains Mono) wired together with measured SVG elbow
53 + * connectors in the for-you brand blue. A central refresh node fans out to the
54 + * user's live connections (Gmail, Notion, GitHub). On every tick (one simulated
55 + * 30-minute interval) a pulse travels each wire, the access token rotates, and
56 + * the connection flashes `refreshed` while staying `ACTIVE`. Paths are computed
57 + * from live geometry so the fanout stays aligned across breakpoints.
58 + */
59 +export function ConnectionRefreshVisual() {
60 + const rootRef = useRef<HTMLDivElement>(null);
61 + const hubRef = useRef<HTMLDivElement>(null);
62 + const cardRefs = useRef<(HTMLDivElement | null)[]>([]);
63 + const [paths, setPaths] = useState<string[]>([]);
64 + const [tick, setTick] = useState(0);
65 + const [active, setActive] = useState(false);
66 + const reduce = useReducedMotion();
67 +
68 + const calc = useCallback(() => {
69 + const root = rootRef.current;
70 + const hub = hubRef.current;
71 + if (!root || !hub) return;
72 + const cr = root.getBoundingClientRect();
73 + const from = hub.getBoundingClientRect();
74 + const next: string[] = [];
75 + for (const ref of cardRefs.current) {
76 + if (!ref) continue;
77 + next.push(elbowPath(cr, from, ref.getBoundingClientRect()));
78 + }
79 + setPaths(next);
80 + }, []);
81 +
82 + useEffect(() => {
83 + calc();
84 + const t = setTimeout(calc, 120);
85 + window.addEventListener('resize', calc);
86 + const root = rootRef.current;
87 + const ro = root ? new ResizeObserver(() => calc()) : null;
88 + if (root && ro) ro.observe(root);
89 + return () => {
90 + clearTimeout(t);
91 + window.removeEventListener('resize', calc);
92 + ro?.disconnect();
93 + };
94 + }, [calc]);
95 +
96 + // Only run the refresh loop while on screen.
97 + useEffect(() => {
98 + const el = rootRef.current;
99 + if (!el) return;
100 + const io = new IntersectionObserver(
101 + ([e]) => setActive(!!e?.isIntersecting),
102 + { threshold: 0.4 }
103 + );
104 + io.observe(el);
105 + return () => io.disconnect();
106 + }, []);
107 +
108 + useEffect(() => {
109 + if (!active || reduce) return;
110 + const id = setInterval(() => setTick((t) => t + 1), CYCLE_MS);
111 + return () => clearInterval(id);
112 + }, [active, reduce]);
113 +
114 + return (
115 + <div className="not-prose my-8 font-mono">
116 + <div
117 + ref={rootRef}
118 + className="relative flex flex-col gap-4 md:block md:h-[320px]"
119 + >
120 + {/* ── connector overlay (md and up) ── */}
121 + <svg
122 + aria-hidden="true"
123 + className="pointer-events-none absolute inset-0 z-0 hidden size-full overflow-visible md:block"
124 + fill="none"
125 + style={{ color: BRAND }}
126 + >
127 + {paths.map((d, i) => (
128 + <path
129 + key={CONNECTIONS[i]?.slug ?? i}
130 + d={d}
131 + opacity={0.18}
132 + stroke="currentColor"
133 + strokeWidth={1}
134 + />
135 + ))}
136 + </svg>
137 +
138 + {/* ── traveling refresh pulses, re-fired each tick ── */}
139 + {!reduce &&
140 + paths.map((d, i) => (
141 + <motion.span
142 + key={`${CONNECTIONS[i]?.slug ?? i}-${tick}`}
143 + aria-hidden="true"
144 + className="absolute left-0 top-0 z-[1] hidden size-[7px] rounded-full md:block"
145 + style={{
146 + offsetPath: `path('${d}')`,
147 + offsetDistance: '0%',
148 + offsetRotate: '0deg',
149 + background: BRAND,
150 + boxShadow: `0 0 10px 2px ${BRAND}`,
151 + }}
152 + initial={{ offsetDistance: '0%', opacity: 0 }}
153 + animate={{
154 + offsetDistance: '100%',
155 + opacity: [0, 1, 1, 0],
156 + }}
157 + transition={{ duration: 0.85, delay: i * 0.12, ease: 'easeInOut' }}
158 + />
159 + ))}
160 +
161 + {/* ── hub: bare Composio logo ── */}
162 + <div className="relative z-10 flex justify-center md:absolute md:top-1/2 md:left-0 md:block md:w-[180px] md:-translate-y-1/2">
163 + <span ref={hubRef} className="inline-flex">
164 + <img
165 + alt="Composio"
166 + className="h-6 w-auto object-contain dark:hidden"
167 + draggable={false}
168 + src="/Composio Logo.svg"
169 + />
170 + <img
171 + alt="Composio"
172 + className="hidden h-6 w-auto object-contain dark:block"
173 + draggable={false}
174 + src="/Composio Logo Dark.svg"
175 + />
176 + </span>
177 + </div>
178 +
179 + {/* ── "every 30 min" badge, centered over the wiring ── */}
180 + <div className="relative z-20 flex justify-center md:absolute md:top-1/2 md:left-1/2 md:-translate-x-1/2 md:-translate-y-1/2">
181 + <div
182 + className="inline-flex items-center gap-1.5 rounded-full border bg-fd-background px-3 py-1.5 text-[11px] font-medium shadow-sm"
183 + style={{
184 + borderColor: 'color-mix(in srgb, ' + BRAND + ' 35%, transparent)',
185 + color: BRAND,
186 + }}
187 + >
188 + <motion.span
189 + className="inline-flex"
190 + animate={reduce ? undefined : { rotate: tick * 360 }}
191 + transition={{ duration: 0.85, ease: 'easeInOut' }}
192 + >
193 + <RefreshCw aria-hidden="true" className="size-3.5" />
194 + </motion.span>
195 + every 30 min
196 + </div>
197 + </div>
198 +
199 + {/* ── connection cards ── */}
200 + <div className="relative z-10 flex flex-col gap-3 md:absolute md:inset-y-0 md:right-0 md:w-[320px] md:justify-center md:gap-4">
201 + {CONNECTIONS.map((conn, i) => {
202 + const suffix = TOKENS[(tick + i) % TOKENS.length];
203 + return (
204 + <div
205 + key={conn.slug}
206 + ref={(el) => {
207 + cardRefs.current[i] = el;
208 + }}
209 + className="overflow-hidden border border-white/10 bg-[#0a0a0a]"
210 + style={{ boxShadow: CARD_SHADOW }}
211 + >
212 + <div className="flex items-center gap-2 border-b border-white/[0.06] bg-white/[0.02] px-2.5 py-2">
213 + <span className="flex size-6 items-center justify-center rounded-md bg-white ring-1 ring-white/10">
214 + <img
215 + alt=""
216 + aria-hidden="true"
217 + className="size-[15px] object-contain"
218 + draggable={false}
219 + src={`${LOGO_CDN}/${conn.slug}`}
220 + />
221 + </span>
222 + <span className="text-[12px] text-white/80">{conn.name}</span>
223 + <code className="ml-auto text-[10px] text-white/35">
224 + {conn.account}
225 + </code>
226 + </div>
227 + <div className="flex items-center gap-2.5 px-2.5 py-2">
228 + <span className="inline-flex items-center gap-1.5 text-[10px] text-green-400">
229 + <span className="size-1.5 rounded-full bg-green-400" />
230 + ACTIVE
231 + </span>
232 + {/* token rotates on each refresh */}
233 + <code className="text-[11px] text-white/45">
234 + oauth&nbsp;&middot;&nbsp;&bull;&bull;&bull;&bull;
235 + <motion.span
236 + key={suffix}
237 + className="text-white/70"
238 + initial={reduce ? false : { color: BRAND, opacity: 0.4 }}
239 + animate={{ color: 'rgba(255,255,255,0.7)', opacity: 1 }}
240 + transition={{ duration: 0.6 }}
241 + >
242 + {suffix}
243 + </motion.span>
244 + </code>
245 + {/* refreshed flash, keyed to the tick */}
246 + <motion.span
247 + key={`flash-${conn.slug}-${tick}`}
248 + aria-hidden="true"
249 + className="ml-auto inline-flex items-center gap-1 text-[10px] text-green-400"
250 + initial={reduce ? false : { opacity: 0, y: -2 }}
251 + animate={
252 + reduce
253 + ? { opacity: 1 }
254 + : { opacity: [0, 1, 1, 0], y: 0 }
255 + }
256 + transition={{
257 + duration: 1.6,
258 + delay: 0.7 + i * 0.12,
259 + times: [0, 0.15, 0.7, 1],
260 + }}
261 + >
262 + <Check className="size-3" />
263 + refreshed
264 + </motion.span>
265 + </div>
266 + </div>
267 + );
268 + })}
269 + </div>
270 + </div>
271 +
272 + {/* plain caption — page text, no box */}
273 + <p className="mt-6 text-center text-[10px] text-fd-foreground/45">
274 + Composio rotates every connection&rsquo;s token on a schedule{' '}
275 + <span aria-hidden="true" style={{ color: BRAND }}>
276 + →
277 + </span>{' '}
278 + connections stay <span className="text-green-400">ACTIVE</span> with no
279 + work from you
280 + </p>
281 + </div>
282 + );
283 +}
docs/components/copy-button.tsx new
+62
@@ -0,0 +1,62 @@
1 +'use client';
2 +
3 +import { useState } from 'react';
4 +import { Check, Copy } from 'lucide-react';
5 +
6 +/**
7 + * Copy-to-clipboard icon button for the code header of the @pierre/diffs widgets.
8 + * A faint chip that lifts on hover, presses on click, and crossfades the copy
9 + * glyph into a green check on success.
10 + *
11 + * The widget themes itself off the OS `prefers-color-scheme` (its shadow root
12 + * pins `color-scheme: light dark`), NOT the site's class-based dark toggle, so
13 + * the header can be light even with the docs in dark mode. The chip's colors
14 + * live in the `.diff-copy-button` rule in global.css and use `light-dark()` to
15 + * track that same signal, staying legible on either header. Icon-only; the
16 + * caller positions it (usually absolute top-right).
17 + */
18 +export function CopyButton({ text, className }: { text: string; className?: string }) {
19 + const [copied, setCopied] = useState(false);
20 +
21 + const copy = async () => {
22 + try {
23 + await navigator.clipboard.writeText(text);
24 + setCopied(true);
25 + setTimeout(() => setCopied(false), 1600);
26 + } catch {
27 + // clipboard unavailable (e.g. insecure context); ignore
28 + }
29 + };
30 +
31 + return (
32 + <button
33 + type="button"
34 + onClick={copy}
35 + aria-label={copied ? 'Copied' : 'Copy code'}
36 + title={copied ? 'Copied' : 'Copy'}
37 + className={
38 + 'diff-copy-button inline-flex size-7 items-center justify-center rounded-md border shadow-sm backdrop-blur-md ' +
39 + 'transition-[transform,background-color,border-color,color] duration-150 ease-out ' +
40 + 'active:scale-90 ' +
41 + (className ?? '')
42 + }
43 + >
44 + <span className="relative size-3.5">
45 + <Copy
46 + aria-hidden="true"
47 + className={
48 + 'absolute inset-0 size-3.5 transition-all duration-200 ease-out ' +
49 + (copied ? 'scale-50 opacity-0' : 'scale-100 opacity-100')
50 + }
51 + />
52 + <Check
53 + aria-hidden="true"
54 + className={
55 + 'absolute inset-0 size-3.5 text-emerald-400 transition-all duration-200 ease-out ' +
56 + (copied ? 'scale-100 opacity-100' : 'scale-50 opacity-0')
57 + }
58 + />
59 + </span>
60 + </button>
61 + );
62 +}
docs/components/custom-search-dialog.tsx
+5 -4
@@ -19,7 +19,8 @@ import { useI18n } from 'fumadocs-ui/contexts/i18n';
19 import { useDocsSearch } from 'fumadocs-core/search/client';
20 import type { BaseIndex } from 'fumadocs-core/search/algolia';
21 import { BotMessageSquare } from 'lucide-react';
22 -import { toggleDecimalWidget, detectMac } from './ask-ai-button';
22 +import { detectMac } from './ask-ai-button';
23 +import { toggleEveChat } from './eve-chat-store';
24
25 function MetaKey() {
26 const [key, setKey] = useState('⌘');
@@ -69,8 +70,8 @@ type SearchResultItem = {
70 const SEARCH_BREADCRUMB_LABELS: Record<string, string> = {
71 toolkits: 'Toolkit',
72 toolkit: 'Toolkit',
72 - cookbooks: 'Cookbook',
73 - cookbook: 'Cookbook',
73 + examples: 'Example',
74 + example: 'Example',
75 docs: 'Docs',
76 reference: 'Reference',
77 'api-reference': 'API Reference',
@@ -275,7 +276,7 @@ export default function CustomSearchDialog({
276 className="inline-flex items-center gap-1.5 text-xs text-[var(--composio-orange)] hover:text-[var(--composio-orange)]/80 transition-colors"
277 onClick={() => {
278 props.onOpenChange(false);
278 - void toggleDecimalWidget();
279 + toggleEveChat();
280 }}
281 >
282 <BotMessageSquare className="size-3.5" />
docs/components/decimal-widget.ts deleted
-204
@@ -1,204 +0,0 @@
1 -'use client';
2 -
3 -export type DecimalAPI = {
4 - show: () => void;
5 - hide: () => void;
6 - theme: (config: Record<string, string>) => void;
7 -};
8 -
9 -const DECIMAL_SCRIPT_ID = 'decimal-widget-script';
10 -const DECIMAL_SRC = 'https://app.getdecimal.ai/widget/v1/widget.js';
11 -const DECIMAL_WIDGET_ID = 'wgt_Ze0kCx97w7YXIydXpEAbAVWfu7FO6HG1';
12 -const DECIMAL_MOBILE_CLOSE_ID = 'decimal-mobile-close-button';
13 -const MOBILE_VIEWPORT_QUERY = '(max-width: 767px)';
14 -const DECIMAL_PUBLIC_CONFIG =
15 - 'eyJhbGciOiJIUzI1NiJ9.eyJ3aWQiOiJ3Z3RfWmUwa0N4OTd3N1lYSXlkWHBFQWJBVldmdTdGTzZIRzEiLCJkb21haW5zIjpbImNvbXBvc2lvLmRldiIsImNvbXBvc2lvLWRlY2ltYWwudmVyY2VsLmFwcCIsImxvY2FsaG9zdDozMDAwIiwiZG9jcy5jb21wb3Npby5kZXYiLCJmdW1hZG9jcy1wc2kudmVyY2VsLmFwcCJdLCJpYXQiOjE3Njk1MDE3NTZ9.j7odPAOmoKSkdkFHQCs7FDpAxHfJuzUOEMb_OuHi81I';
16 -
17 -const DARK_THEME = {
18 - colorScheme: 'dark',
19 - primaryColor: '#1e1d1c',
20 - backgroundColor: '#131211',
21 - textColor: '#FAFAFA',
22 - textColorSecondary: '#FFFFFF',
23 - textColorMuted: '#A1A1AA',
24 - borderColor: '#27272A',
25 -};
26 -
27 -const LIGHT_THEME = {
28 - colorScheme: 'light',
29 - primaryColor: '#171414',
30 - backgroundColor: '#ffffff',
31 - textColor: '#171414',
32 - textColorSecondary: '#ffffff',
33 - textColorMuted: '#5c5858',
34 - borderColor: '#e5e0df',
35 -};
36 -
37 -let loadPromise: Promise<DecimalAPI | undefined> | undefined;
38 -let themeObserver: MutationObserver | undefined;
39 -let closeButtonViewportQuery: MediaQueryList | undefined;
40 -let decimalWidgetRequestedOpen = false;
41 -
42 -export function getDecimal() {
43 - return (window as typeof window & { Decimal?: DecimalAPI }).Decimal;
44 -}
45 -
46 -export function isDecimalWidgetVisible(): boolean {
47 - const sidebar = document.querySelector('.decimal-widget-sidebar');
48 - return sidebar?.classList.contains('open') ?? false;
49 -}
50 -
51 -export function applyDecimalTheme() {
52 - const decimal = getDecimal();
53 - if (!decimal) return;
54 -
55 - const isDark = document.documentElement.classList.contains('dark');
56 - decimal.theme(isDark ? DARK_THEME : LIGHT_THEME);
57 -}
58 -
59 -function watchThemeChanges() {
60 - if (themeObserver) return;
61 -
62 - applyDecimalTheme();
63 - themeObserver = new MutationObserver((mutations) => {
64 - for (const mutation of mutations) {
65 - if (mutation.attributeName === 'class') {
66 - applyDecimalTheme();
67 - }
68 - }
69 - });
70 - themeObserver.observe(document.documentElement, { attributes: true });
71 -}
72 -
73 -function waitForDecimal(timeoutMs = 2000): Promise<DecimalAPI | undefined> {
74 - const startedAt = Date.now();
75 -
76 - return new Promise((resolve) => {
77 - const check = () => {
78 - const decimal = getDecimal();
79 - if (decimal) {
80 - watchThemeChanges();
81 - resolve(decimal);
82 - return;
83 - }
84 -
85 - if (Date.now() - startedAt >= timeoutMs) {
86 - resolve(undefined);
87 - return;
88 - }
89 -
90 - window.setTimeout(check, 50);
91 - };
92 -
93 - check();
94 - });
95 -}
96 -
97 -function finishLoading(resolve: (decimal: DecimalAPI | undefined) => void) {
98 - waitForDecimal().then((decimal) => {
99 - if (!decimal) {
100 - loadPromise = undefined;
101 - }
102 - resolve(decimal);
103 - });
104 -}
105 -
106 -function isMobileViewport() {
107 - return window.matchMedia(MOBILE_VIEWPORT_QUERY).matches;
108 -}
109 -
110 -function syncMobileCloseButtonVisibility() {
111 - const button = document.getElementById(DECIMAL_MOBILE_CLOSE_ID);
112 - if (!button) return;
113 -
114 - button.style.display = isMobileViewport() && decimalWidgetRequestedOpen ? 'inline-flex' : 'none';
115 -}
116 -
117 -function ensureMobileCloseButton() {
118 - let button = document.getElementById(DECIMAL_MOBILE_CLOSE_ID) as HTMLButtonElement | null;
119 - if (!button) {
120 - button = document.createElement('button');
121 - button.id = DECIMAL_MOBILE_CLOSE_ID;
122 - button.type = 'button';
123 - button.setAttribute('aria-label', 'Close Ask AI');
124 - button.innerHTML = '&times;';
125 - button.style.cssText = [
126 - 'position: fixed',
127 - 'top: calc(env(safe-area-inset-top, 0px) + 12px)',
128 - 'right: 12px',
129 - 'z-index: 2147483647',
130 - 'width: 44px',
131 - 'height: 44px',
132 - 'align-items: center',
133 - 'justify-content: center',
134 - 'border-radius: 9999px',
135 - 'border: 1px solid rgba(23, 20, 20, 0.12)',
136 - 'background: rgba(255, 255, 255, 0.96)',
137 - 'color: #171414',
138 - 'box-shadow: 0 12px 32px rgba(23, 20, 20, 0.18)',
139 - 'font-size: 28px',
140 - 'font-weight: 400',
141 - 'line-height: 1',
142 - 'display: none',
143 - ].join(';');
144 - button.addEventListener('click', closeDecimalWidget);
145 - document.body.appendChild(button);
146 - }
147 -
148 - if (!closeButtonViewportQuery) {
149 - closeButtonViewportQuery = window.matchMedia(MOBILE_VIEWPORT_QUERY);
150 - closeButtonViewportQuery.addEventListener('change', syncMobileCloseButtonVisibility);
151 - }
152 -
153 - syncMobileCloseButtonVisibility();
154 -}
155 -
156 -export function closeDecimalWidget() {
157 - decimalWidgetRequestedOpen = false;
158 - getDecimal()?.hide();
159 - syncMobileCloseButtonVisibility();
160 -}
161 -
162 -export function openDecimalWidget(decimal: DecimalAPI) {
163 - decimalWidgetRequestedOpen = true;
164 - decimal.show();
165 - ensureMobileCloseButton();
166 -}
167 -
168 -export function loadDecimalWidget(): Promise<DecimalAPI | undefined> {
169 - const existingDecimal = getDecimal();
170 - if (existingDecimal) {
171 - watchThemeChanges();
172 - return Promise.resolve(existingDecimal);
173 - }
174 -
175 - if (loadPromise) return loadPromise;
176 -
177 - loadPromise = new Promise((resolve) => {
178 - const existingScript = document.getElementById(DECIMAL_SCRIPT_ID);
179 - if (existingScript) {
180 - finishLoading(resolve);
181 - return;
182 - }
183 -
184 - const script = document.createElement('script');
185 - script.id = DECIMAL_SCRIPT_ID;
186 - script.src = DECIMAL_SRC;
187 - script.async = true;
188 - script.dataset.widgetId = DECIMAL_WIDGET_ID;
189 - script.dataset.publicConfig = DECIMAL_PUBLIC_CONFIG;
190 - script.dataset.displayMode = 'push-sidebar';
191 -
192 - script.onload = () => {
193 - finishLoading(resolve);
194 - };
195 - script.onerror = () => {
196 - loadPromise = undefined;
197 - resolve(undefined);
198 - };
199 -
200 - document.head.appendChild(script);
201 - });
202 -
203 - return loadPromise;
204 -}
docs/components/diff-view.tsx new
+31
@@ -0,0 +1,31 @@
1 +'use client';
2 +
3 +import { FileDiff, type FileDiffProps } from '@pierre/diffs/react';
4 +import { CopyButton } from './copy-button';
5 +
6 +/**
7 + * The +/- stat counts live inside @pierre/diffs's open shadow root, so the
8 + * site's global CSS can't reach them. `unsafeCSS` is injected as a <style>
9 + * element *inside* that shadow root (both for the SSR-prerendered HTML and the
10 + * hydrated client render), which is the only place a selector for these counts
11 + * actually matches. Keep this in sync between the SSR preload and FileDiff.
12 + */
13 +export const HIDE_DIFF_STATS_CSS = '[data-additions-count],[data-deletions-count]{display:none !important;}';
14 +
15 +/**
16 + * Thin client wrapper around @pierre/diffs FileDiff. The diff metadata and
17 + * prerendered HTML are computed on the server so the first paint is correct
18 + * without a worker round-trip. Pass `code` (the full file at this stage) to show
19 + * a copy-to-clipboard button.
20 + */
21 +export function DiffView({
22 + code,
23 + ...props
24 +}: Pick<FileDiffProps<undefined>, 'fileDiff' | 'prerenderedHTML'> & { code?: string }) {
25 + return (
26 + <div className="relative w-full">
27 + {code ? <CopyButton text={code} className="absolute right-2 top-2 z-10" /> : null}
28 + <FileDiff {...props} options={{ diffStyle: 'unified', unsafeCSS: HIDE_DIFF_STATS_CSS }} disableWorkerPool />
29 + </div>
30 + );
31 +}
docs/components/docs-hero-v2.tsx
+2 -2
@@ -26,8 +26,8 @@ export function DocsHeroV2() {
26 </h1>
27
28 <p className="max-w-[480px] text-[15px] leading-[1.55] text-fd-foreground/70 md:text-base">
29 - 1000+ pre-authenticated toolkits, per-user sessions, triggers,
30 - and a workbench for your AI agent.
29 + Give your AI agent 1000+ pre-authenticated toolkits, per-user
30 + sessions, triggers, and a workbench.
31 </p>
32
33 {/* Quick-link chips — single column */}
docs/components/eve-chat-mount.tsx new
+14
@@ -0,0 +1,14 @@
1 +'use client';
2 +
3 +import dynamic from 'next/dynamic';
4 +
5 +// Load the Eve chat browser-only. eve/react can't be server-rendered (its
6 +// client store pulls in Node-only bundler helpers), so we skip SSR entirely
7 +// and only ship it to the browser.
8 +const EveChat = dynamic(() => import('./eve-chat').then((m) => m.EveChat), {
9 + ssr: false,
10 +});
11 +
12 +export function EveChatMount() {
13 + return <EveChat />;
14 +}
docs/components/eve-chat-store.ts new
+43
@@ -0,0 +1,43 @@
1 +'use client';
2 +
3 +import { useSyncExternalStore } from 'react';
4 +
5 +/**
6 + * Tiny open/close store for the Eve chat panel, so any "Ask AI" trigger can
7 + * open it without prop-drilling. Mirrors the old decimal-widget toggle surface.
8 + */
9 +
10 +let open = false;
11 +const listeners = new Set<() => void>();
12 +
13 +function emit() {
14 + for (const listener of listeners) listener();
15 +}
16 +
17 +export function openEveChat() {
18 + if (open) return;
19 + open = true;
20 + emit();
21 +}
22 +
23 +export function closeEveChat() {
24 + if (!open) return;
25 + open = false;
26 + emit();
27 +}
28 +
29 +export function toggleEveChat() {
30 + open = !open;
31 + emit();
32 +}
33 +
34 +export function useEveChatOpen(): boolean {
35 + return useSyncExternalStore(
36 + (callback) => {
37 + listeners.add(callback);
38 + return () => listeners.delete(callback);
39 + },
40 + () => open,
41 + () => false,
42 + );
43 +}
docs/components/eve-chat.tsx new
+225
@@ -0,0 +1,225 @@
1 +'use client';
2 +
3 +import { useEffect, useRef } from 'react';
4 +import { usePathname } from 'next/navigation';
5 +import { useEveAgent } from 'eve/react';
6 +import { Send, X, Sparkles, Square, SquarePen } from 'lucide-react';
7 +import { AssistantMessage, ToolActivity } from './eve-message';
8 +import { closeEveChat, useEveChatOpen } from './eve-chat-store';
9 +
10 +const SUGGESTIONS = [
11 + 'How do I create a session?',
12 + 'How does authentication work?',
13 + 'How do I use the sandbox files?',
14 +];
15 +
16 +/**
17 + * EveChat — the right-sidebar docs assistant, backed by the eve agent in
18 + * `agent/`. Always mounted (so the session persists) and slid off-screen when
19 + * closed. Each turn carries the current route as `clientContext` so Eve can
20 + * answer about the page you're on.
21 + */
22 +export function EveChat() {
23 + const isOpen = useEveChatOpen();
24 + const pathname = usePathname();
25 + const agent = useEveAgent({
26 + prepareSend: (input) => ({ ...input, clientContext: { route: pathname } }),
27 + });
28 +
29 + const isBusy = agent.status === 'submitted' || agent.status === 'streaming';
30 + const messages = agent.data.messages;
31 + const lastMessage = messages[messages.length - 1];
32 + const lastHasAssistantText =
33 + lastMessage?.role === 'assistant' &&
34 + lastMessage.parts.some((part) => part.type === 'text' && part.text.trim().length > 0);
35 + // Show the loading indicator from submit through the search/read phase, until
36 + // the assistant's text actually starts streaming, so it doesn't flicker off.
37 + const thinking = isBusy && !lastHasAssistantText;
38 + const inputRef = useRef<HTMLTextAreaElement>(null);
39 + const scrollRef = useRef<HTMLDivElement>(null);
40 +
41 + useEffect(() => {
42 + if (isOpen) inputRef.current?.focus();
43 + }, [isOpen]);
44 +
45 + useEffect(() => {
46 + scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
47 + }, [agent.data.messages]);
48 +
49 + function submit(message: string) {
50 + const trimmed = message.trim();
51 + if (trimmed.length > 0 && !isBusy) void agent.send({ message: trimmed });
52 + }
53 +
54 + return (
55 + <>
56 + {isOpen && (
57 + <div
58 + aria-hidden="true"
59 + className="fixed inset-0 z-40 bg-black/20 backdrop-blur-[1px] md:hidden"
60 + onClick={closeEveChat}
61 + />
62 + )}
63 + <aside
64 + aria-label="Ask AI"
65 + className={
66 + 'fixed right-0 top-0 z-50 flex h-dvh w-full flex-col border-l border-fd-border bg-fd-background shadow-xl transition-transform duration-200 ease-out md:w-[400px] ' +
67 + (isOpen ? 'translate-x-0' : 'translate-x-full')
68 + }
69 + >
70 + {/* header */}
71 + <div className="flex items-center justify-between border-b border-fd-border px-4 py-3">
72 + <div className="flex items-center gap-2">
73 + <Sparkles className="size-4 text-[var(--composio-brand)]" aria-hidden="true" />
74 + <span className="text-sm font-medium text-fd-foreground">Ask AI</span>
75 + <span className="font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/40">docs assistant</span>
76 + </div>
77 + <div className="flex items-center gap-0.5">
78 + <button
79 + type="button"
80 + aria-label="New chat"
81 + title="New chat"
82 + onClick={() => {
83 + if (isBusy) agent.stop();
84 + agent.reset();
85 + inputRef.current?.focus();
86 + }}
87 + disabled={agent.data.messages.length === 0}
88 + className="inline-flex size-7 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-foreground disabled:opacity-40 disabled:hover:bg-transparent"
89 + >
90 + <SquarePen className="size-4" />
91 + </button>
92 + <button
93 + type="button"
94 + aria-label="Close"
95 + onClick={closeEveChat}
96 + className="inline-flex size-7 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-foreground"
97 + >
98 + <X className="size-4" />
99 + </button>
100 + </div>
101 + </div>
102 +
103 + {/* messages */}
104 + <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">
105 + {agent.data.messages.length === 0 ? (
106 + <div className="flex h-full flex-col justify-center gap-3 text-center">
107 + <p className="text-sm text-fd-muted-foreground">
108 + Ask about the Composio docs. It answers from the docs and links the pages it used. It&apos;s not customer support and can&apos;t act on your Composio account.
109 + </p>
110 + <div className="flex flex-col gap-1.5">
111 + {SUGGESTIONS.map((s) => (
112 + <button
113 + key={s}
114 + type="button"
115 + onClick={() => submit(s)}
116 + className="rounded-md border border-fd-border bg-fd-card px-3 py-2 text-left text-[13px] text-fd-foreground/80 transition-colors hover:border-[var(--composio-brand)]/40 hover:text-fd-foreground"
117 + >
118 + {s}
119 + </button>
120 + ))}
121 + </div>
122 + </div>
123 + ) : (
124 + <ul className="flex flex-col gap-4">
125 + {agent.data.messages.map((message) => (
126 + <li key={message.id} className={message.role === 'user' ? 'flex justify-end' : ''}>
127 + <div
128 + className={
129 + message.role === 'user'
130 + ? 'max-w-[85%] rounded-lg bg-[var(--composio-brand)]/10 px-3 py-2 text-[13px] text-fd-foreground'
131 + : 'max-w-full text-[13px] leading-relaxed text-fd-foreground/90'
132 + }
133 + >
134 + {message.parts.map((part, i) => {
135 + if (part.type === 'text') {
136 + return message.role === 'assistant' ? (
137 + <AssistantMessage key={i} text={part.text} />
138 + ) : (
139 + <p key={i} className="whitespace-pre-wrap break-words">
140 + {part.text}
141 + </p>
142 + );
143 + }
144 + return message.role === 'assistant' ? (
145 + <ToolActivity key={i} part={part} />
146 + ) : null;
147 + })}
148 + </div>
149 + </li>
150 + ))}
151 + {thinking && (
152 + <li className="flex items-center gap-2 text-[13px] text-fd-muted-foreground">
153 + <span className="inline-flex gap-1">
154 + <span className="size-1.5 animate-bounce rounded-full bg-fd-muted-foreground/60 [animation-delay:-0.3s]" />
155 + <span className="size-1.5 animate-bounce rounded-full bg-fd-muted-foreground/60 [animation-delay:-0.15s]" />
156 + <span className="size-1.5 animate-bounce rounded-full bg-fd-muted-foreground/60" />
157 + </span>
158 + Searching the docs…
159 + </li>
160 + )}
161 + </ul>
162 + )}
163 + </div>
164 +
165 + {/* composer */}
166 + <form
167 + className="border-t border-fd-border p-3"
168 + onSubmit={(event) => {
169 + event.preventDefault();
170 + const value = inputRef.current?.value ?? '';
171 + submit(value);
172 + if (inputRef.current) {
173 + inputRef.current.value = '';
174 + inputRef.current.style.height = 'auto';
175 + }
176 + }}
177 + >
178 + <div className="flex items-center gap-2 rounded-lg border border-fd-border bg-fd-card px-3 py-1.5 focus-within:border-[var(--composio-brand)]/50">
179 + <textarea
180 + ref={inputRef}
181 + rows={1}
182 + placeholder="Ask about the docs…"
183 + className="block max-h-32 min-h-[1.5rem] flex-1 resize-none self-center overflow-y-auto bg-transparent py-0 text-[13px] leading-6 text-fd-foreground outline-none placeholder:text-fd-muted-foreground"
184 + onChange={(event) => {
185 + // Auto-grow with content, up to max-h-32 (128px), then scroll.
186 + const el = event.currentTarget;
187 + el.style.height = 'auto';
188 + el.style.height = `${Math.min(el.scrollHeight, 128)}px`;
189 + }}
190 + onKeyDown={(event) => {
191 + if (event.key === 'Enter' && !event.shiftKey) {
192 + event.preventDefault();
193 + submit(event.currentTarget.value);
194 + event.currentTarget.value = '';
195 + event.currentTarget.style.height = 'auto';
196 + }
197 + }}
198 + />
199 + {isBusy ? (
200 + <button
201 + type="button"
202 + aria-label="Stop"
203 + onClick={() => agent.stop()}
204 + className="inline-flex size-7 items-center justify-center rounded-md text-fd-muted-foreground hover:bg-fd-accent hover:text-fd-foreground"
205 + >
206 + <Square className="size-3.5" />
207 + </button>
208 + ) : (
209 + <button
210 + type="submit"
211 + aria-label="Send"
212 + className="inline-flex size-7 items-center justify-center rounded-md bg-[var(--composio-brand)] text-white transition-opacity hover:opacity-90"
213 + >
214 + <Send className="size-3.5" />
215 + </button>
216 + )}
217 + </div>
218 + {agent.status === 'error' && (
219 + <p className="mt-2 text-[12px] text-red-500">Something went wrong. Try again.</p>
220 + )}
221 + </form>
222 + </aside>
223 + </>
224 + );
225 +}
docs/components/eve-message.tsx new
+316
@@ -0,0 +1,316 @@
1 +'use client';
2 +
3 +import { useState, type ComponentProps } from 'react';
4 +import { useRouter } from 'next/navigation';
5 +import ReactMarkdown, { type Components } from 'react-markdown';
6 +import remarkGfm from 'remark-gfm';
7 +import hljs from 'highlight.js';
8 +import { Check, Copy, FileText, Search, Wrench } from 'lucide-react';
9 +
10 +/**
11 + * Renders the agent's tool activity inline — which docs it searched and which
12 + * pages it read — so you can see its "thinking". Returns null for non-tool parts.
13 + */
14 +export function ToolActivity({ part }: { part: unknown }) {
15 + const router = useRouter();
16 + const p = part as { type?: string; toolName?: string; input?: Record<string, unknown> };
17 + const type = p.type ?? '';
18 + const toolName = type === 'dynamic-tool' ? p.toolName : type.startsWith('tool-') ? type.slice(5) : undefined;
19 + if (!toolName) return null;
20 + const input = p.input ?? {};
21 +
22 + let icon = <Wrench className="size-3" aria-hidden="true" />;
23 + let label = `Running ${toolName}`;
24 + let href: string | undefined;
25 + if (toolName === 'search_docs') {
26 + icon = <Search className="size-3" aria-hidden="true" />;
27 + const query = typeof input.query === 'string' ? input.query : '';
28 + label = query ? `Searched the docs for “${query}”` : 'Searched the docs';
29 + } else if (toolName === 'read_doc') {
30 + icon = <FileText className="size-3" aria-hidden="true" />;
31 + const url = typeof input.url === 'string' ? input.url : '';
32 + label = url ? `Read ${url}` : 'Read a page';
33 + if (url.startsWith('/')) href = url;
34 + }
35 +
36 + const base = 'flex items-center gap-1.5 py-0.5 text-[11px] text-fd-muted-foreground';
37 + const inner = (
38 + <>
39 + <span className="shrink-0 text-[var(--composio-brand)]/70">{icon}</span>
40 + <span className="truncate group-hover:underline">{label}</span>
41 + </>
42 + );
43 +
44 + if (href) {
45 + return (
46 + <a
47 + href={href}
48 + title={href}
49 + onClick={(event) => {
50 + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
51 + event.preventDefault();
52 + router.push(href);
53 + }}
54 + className={`${base} group cursor-pointer underline-offset-2 transition-colors hover:text-fd-foreground`}
55 + >
56 + {inner}
57 + </a>
58 + );
59 + }
60 + return <div className={base}>{inner}</div>;
61 +}
62 +
63 +function isInternalHref(url: string): boolean {
64 + if (url.startsWith('/') || url.startsWith('#')) return true;
65 + try {
66 + return new URL(url).origin === window.location.origin;
67 + } catch {
68 + return false;
69 + }
70 +}
71 +
72 +/**
73 + * Link renderer for assistant Markdown. Internal docs links navigate
74 + * client-side with the router and keep the chat open; external links open in a
75 + * new tab. (Modifier-clicks fall through to the browser's default.)
76 + */
77 +function MarkdownLink({ href, children, node, ...props }: ComponentProps<'a'> & { node?: unknown }) {
78 + const router = useRouter();
79 + const url = href ?? '';
80 + if (url && isInternalHref(url)) {
81 + return (
82 + <a
83 + href={url}
84 + onClick={(event) => {
85 + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
86 + event.preventDefault();
87 + router.push(url);
88 + }}
89 + {...props}
90 + >
91 + {children}
92 + </a>
93 + );
94 + }
95 + return (
96 + <a href={url} target="_blank" rel="noreferrer" {...props}>
97 + {children}
98 + </a>
99 + );
100 +}
101 +
102 +// Prose renders through react-markdown (we control link behavior and keys);
103 +// code blocks render through the custom <CodeBlock> below (highlight.js,
104 +// synchronous and browser-safe).
105 +const MD_COMPONENTS: Components = { a: MarkdownLink };
106 +const MD_PLUGINS = [remarkGfm];
107 +
108 +// Map our fence languages to highlight.js language ids (some, like cURL, aren't
109 +// registered grammars and fall back to a near match or auto-detection).
110 +const HLJS_LANG: Record<string, string> = {
111 + py: 'python',
112 + ts: 'typescript', tsx: 'typescript',
113 + js: 'javascript', jsx: 'javascript',
114 + sh: 'bash', shell: 'bash', zsh: 'bash',
115 + curl: 'bash', http: 'bash',
116 +};
117 +
118 +function hljsLangFor(lang: string): string | null {
119 + const key = lang.toLowerCase();
120 + const id = HLJS_LANG[key] ?? key;
121 + return hljs.getLanguage(id) ? id : null;
122 +}
123 +
124 +/** Renders a code block with highlight.js token markup and a copy button. */
125 +function CodeBlock({ lang, code, className }: { lang: string; code: string; className?: string }) {
126 + const [copied, setCopied] = useState(false);
127 + const id = hljsLangFor(lang);
128 + // Use the known grammar when we have one, else auto-detect; never throw.
129 + const html = id
130 + ? hljs.highlight(code, { language: id, ignoreIllegals: true }).value
131 + : hljs.highlightAuto(code).value;
132 + return (
133 + <div className={'eve-hljs group relative my-2 overflow-hidden rounded-md border border-fd-border bg-fd-muted/30 ' + (className ?? '')}>
134 + <button
135 + type="button"
136 + aria-label="Copy code"
137 + onClick={() => {
138 + void navigator.clipboard.writeText(code).then(() => {
139 + setCopied(true);
140 + setTimeout(() => setCopied(false), 1500);
141 + });
142 + }}
143 + className="absolute right-1.5 top-1.5 inline-flex size-6 items-center justify-center rounded text-fd-muted-foreground opacity-0 transition-opacity hover:bg-fd-accent hover:text-fd-foreground group-hover:opacity-100"
144 + >
145 + {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
146 + </button>
147 + <pre className="max-w-full overflow-x-auto p-3 text-[11.5px] leading-relaxed">
148 + <code
149 + className={'hljs language-' + (id ?? lang)}
150 + // highlight.js output is escaped token markup, not user HTML.
151 + dangerouslySetInnerHTML={{ __html: html }}
152 + />
153 + </pre>
154 + </div>
155 + );
156 +}
157 +
158 +/**
159 + * Renders an assistant message: Markdown via Streamdown, with consecutive
160 + * code blocks in different languages (e.g. Python + TypeScript) grouped into
161 + * tabs. Tolerates an unclosed trailing code fence while streaming.
162 + */
163 +
164 +const MD_CLASS =
165 + 'text-[13px] leading-relaxed break-words [&_a]:text-[var(--composio-brand)] [&_a]:underline [&_p]:my-2 [&_ul]:my-2 [&_ol]:my-2 [&_pre]:my-2 [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_pre]:text-[11.5px] [&_pre]:leading-relaxed [&_:not(pre)>code]:rounded [&_:not(pre)>code]:bg-fd-foreground/[0.07] [&_:not(pre)>code]:px-1 [&_:not(pre)>code]:py-0.5 [&_:not(pre)>code]:text-[0.9em]';
166 +
167 +const LANG_LABEL: Record<string, string> = {
168 + python: 'Python', py: 'Python',
169 + typescript: 'TypeScript', ts: 'TypeScript', tsx: 'TypeScript',
170 + javascript: 'JavaScript', js: 'JavaScript', jsx: 'JavaScript',
171 + bash: 'Bash', sh: 'Shell', shell: 'Shell', zsh: 'Shell',
172 + json: 'JSON', curl: 'cURL', http: 'HTTP', yaml: 'YAML',
173 +};
174 +
175 +function labelFor(lang: string): string {
176 + const key = lang.toLowerCase();
177 + return LANG_LABEL[key] ?? (lang ? lang[0].toUpperCase() + lang.slice(1) : 'Code');
178 +}
179 +
180 +/**
181 + * Strip the model's native citation tokens. gpt-5.x emits web-search citations
182 + * as `\uE200cite\uE202<ref>\uE201` (private-use delimiters). The refs (e.g.
183 + * `turn0search0`) don't resolve here, so drop the span — unless it embeds a real
184 + * URL, in which case keep it as a Markdown link. Real citations come through as
185 + * normal Markdown links from the agent's instructions.
186 + */
187 +function cleanCitations(text: string): string {
188 + return text
189 + .replace(/\uE200[\s\S]*?\uE201/g, (span) => {
190 + const url = span.match(/(https?:\/\/[^\s\uE200-\uE20F]+|\/[A-Za-z0-9/_#-]+)/);
191 + return url ? ` ([source](${url[1]}))` : '';
192 + })
193 + .replace(/[\uE200-\uE20F]/g, '')
194 + .replace(/[ \t]{2,}/g, ' ')
195 + .replace(/[ \t]+([.,;:!?])/g, '$1');
196 +}
197 +
198 +type Seg = { kind: 'prose'; text: string } | { kind: 'code'; lang: string; code: string };
199 +
200 +/** Split into prose and fenced-code segments, tolerating an unclosed trailing fence. */
201 +function parseSegments(text: string): Seg[] {
202 + const segs: Seg[] = [];
203 + const fenceRe = /```([\w-]*)\n([\s\S]*?)```/g;
204 + let last = 0;
205 + let m: RegExpExecArray | null;
206 + while ((m = fenceRe.exec(text)) !== null) {
207 + if (m.index > last) segs.push({ kind: 'prose', text: text.slice(last, m.index) });
208 + segs.push({ kind: 'code', lang: m[1] || '', code: m[2].replace(/\n+$/, '') });
209 + last = m.index + m[0].length;
210 + }
211 + const rest = text.slice(last);
212 + const open = /```([\w-]*)\n([\s\S]*)$/.exec(rest);
213 + if (open) {
214 + const before = rest.slice(0, open.index);
215 + if (before.trim()) segs.push({ kind: 'prose', text: before });
216 + segs.push({ kind: 'code', lang: open[1] || '', code: open[2] });
217 + } else if (rest) {
218 + segs.push({ kind: 'prose', text: rest });
219 + }
220 + return segs;
221 +}
222 +
223 +/** A prose segment that's just a short language label (e.g. "Python", "**TypeScript**"). */
224 +function isThinLabel(text: string): boolean {
225 + const t = text.trim();
226 + if (t === '') return true;
227 + if (t.length > 20) return false;
228 + const plain = t.replace(/[*_`#>-]/g, '').trim().toLowerCase();
229 + return /^(python|py|typescript|ts|tsx|javascript|js|bash|shell|sh|zsh|json|curl|http|yaml)$/.test(plain);
230 +}
231 +
232 +type Block = { lang: string; code: string };
233 +type Group =
234 + | { kind: 'prose'; text: string }
235 + | { kind: 'code'; lang: string; code: string }
236 + | { kind: 'tabs'; blocks: Block[] };
237 +
238 +function group(segs: Seg[]): Group[] {
239 + const out: Group[] = [];
240 + let i = 0;
241 + while (i < segs.length) {
242 + const seg = segs[i];
243 + if (seg.kind === 'prose') {
244 + out.push(seg);
245 + i++;
246 + continue;
247 + }
248 + const blocks: Block[] = [{ lang: seg.lang, code: seg.code }];
249 + let j = i + 1;
250 + while (j < segs.length) {
251 + const cur = segs[j];
252 + const next = segs[j + 1];
253 + if (cur.kind === 'prose' && isThinLabel(cur.text) && next && next.kind === 'code') {
254 + blocks.push({ lang: next.lang, code: next.code });
255 + j += 2;
256 + } else if (cur.kind === 'code') {
257 + blocks.push({ lang: cur.lang, code: cur.code });
258 + j += 1;
259 + } else {
260 + break;
261 + }
262 + }
263 + const distinct = new Set(blocks.map((b) => labelFor(b.lang)));
264 + if (blocks.length >= 2 && distinct.size >= 2) out.push({ kind: 'tabs', blocks });
265 + else for (const b of blocks) out.push({ kind: 'code', lang: b.lang, code: b.code });
266 + i = j;
267 + }
268 + return out;
269 +}
270 +
271 +function CodeTabs({ blocks }: { blocks: Block[] }) {
272 + const [active, setActive] = useState(0);
273 + const items = blocks.map((b) => labelFor(b.lang));
274 + const current = blocks[Math.min(active, blocks.length - 1)];
275 + return (
276 + <div className="my-2 overflow-hidden rounded-md border border-fd-border">
277 + <div className="flex border-b border-fd-border bg-fd-muted/30">
278 + {items.map((label, i) => (
279 + <button
280 + key={`${label}-${i}`}
281 + type="button"
282 + onClick={() => setActive(i)}
283 + className={
284 + 'px-3 py-1.5 text-[12px] font-medium transition-colors ' +
285 + (i === active
286 + ? 'border-b-2 border-[var(--composio-brand)] text-fd-foreground'
287 + : 'border-b-2 border-transparent text-fd-muted-foreground hover:text-fd-foreground')
288 + }
289 + >
290 + {label}
291 + </button>
292 + ))}
293 + </div>
294 + <CodeBlock lang={current.lang} code={current.code} className="!my-0 rounded-none border-0" />
295 + </div>
296 + );
297 +}
298 +
299 +export function AssistantMessage({ text }: { text: string }) {
300 + const groups = group(parseSegments(cleanCitations(text)));
301 + return (
302 + <div className="flex flex-col">
303 + {groups.map((g, i) => {
304 + if (g.kind === 'tabs') return <CodeTabs key={i} blocks={g.blocks} />;
305 + if (g.kind === 'code') return <CodeBlock key={i} lang={g.lang} code={g.code} />;
306 + return (
307 + <div key={i} className={MD_CLASS}>
308 + <ReactMarkdown remarkPlugins={MD_PLUGINS} components={MD_COMPONENTS}>
309 + {g.text}
310 + </ReactMarkdown>
311 + </div>
312 + );
313 + })}
314 + </div>
315 + );
316 +}
docs/components/experimental-badge.tsx new
+16
@@ -0,0 +1,16 @@
1 +/**
2 + * "Experimental" badge rendered at the top of a docs page (under the title)
3 + * when the page frontmatter sets `experimental: true`. Signals that the page's
4 + * APIs may change in future releases, so individual pages don't need an inline
5 + * callout saying the same thing.
6 + */
7 +export function ExperimentalBadge() {
8 + return (
9 + <span
10 + title="Experimental: these APIs may change in future releases"
11 + className="not-prose mb-3 inline-flex w-fit items-center gap-1.5 rounded-md border border-amber-600/20 bg-amber-100 px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-amber-700 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-400"
12 + >
13 + Experimental
14 + </span>
15 + );
16 +}
docs/components/file-buildup.tsx new
+114
@@ -0,0 +1,114 @@
1 +import { createPatch } from 'diff';
2 +import { getSingularPatch } from '@pierre/diffs';
3 +import { preloadFileDiff } from '@pierre/diffs/ssr';
4 +import { DiffView, HIDE_DIFF_STATS_CSS } from './diff-view';
5 +import { FILE_BUILDS } from '@/lib/file-builds';
6 +
7 +async function diffFor(file: string, prev: string, code: string) {
8 + const fileDiff = getSingularPatch(createPatch(file, prev, code, '', ''));
9 + const { prerenderedHTML } = await preloadFileDiff({
10 + fileDiff,
11 + options: { diffStyle: 'unified', unsafeCSS: HIDE_DIFF_STATS_CSS },
12 + });
13 + return { fileDiff, prerenderedHTML };
14 +}
15 +
16 +function StepCard({
17 + n,
18 + title,
19 + file,
20 + description,
21 + fileDiff,
22 + prerenderedHTML,
23 + code,
24 +}: {
25 + n: number;
26 + title: string;
27 + file: string;
28 + description?: string;
29 +
30 + fileDiff: any;
31 + prerenderedHTML: string;
32 + code: string;
33 +}) {
34 + return (
35 + <div className="overflow-hidden rounded-sm border border-fd-border bg-fd-background">
36 + <div className="flex items-center gap-2.5 border-b border-fd-border px-3 py-2">
37 + <span className="flex size-5 shrink-0 items-center justify-center rounded-sm bg-[var(--composio-brand)]/10 font-mono text-[11px] font-medium text-[var(--composio-brand)]">
38 + {n}
39 + </span>
40 + <span className="text-[13px] font-medium text-fd-foreground">{title}</span>
41 + <span className="ml-auto font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/40">
42 + {file}
43 + </span>
44 + </div>
45 + {description ? (
46 + <p className="px-3 pt-2.5 text-[13px] leading-snug text-fd-foreground/65">{description}</p>
47 + ) : null}
48 + <div className="p-3">
49 + <DiffView fileDiff={fileDiff} prerenderedHTML={prerenderedHTML} code={code} />
50 + </div>
51 + </div>
52 + );
53 +}
54 +
55 +/**
56 + * FileBuildup — renders one of the example's files growing a piece at a time.
57 + * Each step is a diff against the previous stage (powered by @pierre/diffs).
58 + *
59 + * Pass `step` (1-indexed) to render just that one step's diff, so the prose for
60 + * a concept can sit right next to the code that adds it. Without `step`, renders
61 + * every step with its built-in description.
62 + *
63 + * `name` keys into the merged FILE_BUILDS registry (see lib/file-builds.ts),
64 + * which carries every example's stages under unique keys.
65 + */
66 +export async function FileBuildup({
67 + name,
68 + step,
69 +}: {
70 + name: keyof typeof FILE_BUILDS;
71 + step?: number;
72 +}) {
73 + const build = FILE_BUILDS[name];
74 + if (!build) return null;
75 +
76 + if (typeof step === 'number') {
77 + const i = step - 1;
78 + const stage = build.stages[i];
79 + if (!stage) return null;
80 + const prev = i > 0 ? build.stages[i - 1].code : '';
81 + const { fileDiff, prerenderedHTML } = await diffFor(build.file, prev, stage.code);
82 + // The heading above and the diff's own filename header already name it, so
83 + // render just the diff with no extra card chrome.
84 + return (
85 + <div className="not-prose my-6">
86 + <DiffView fileDiff={fileDiff} prerenderedHTML={prerenderedHTML} code={stage.code} />
87 + </div>
88 + );
89 + }
90 +
91 + const steps = [];
92 + let prev = '';
93 + for (const stage of build.stages) {
94 + steps.push({ ...stage, ...(await diffFor(build.file, prev, stage.code)) });
95 + prev = stage.code;
96 + }
97 +
98 + return (
99 + <div className="not-prose my-6 flex flex-col gap-5">
100 + {steps.map((s, i) => (
101 + <StepCard
102 + key={s.title}
103 + n={i + 1}
104 + title={s.title}
105 + file={build.file}
106 + description={s.description}
107 + fileDiff={s.fileDiff}
108 + prerenderedHTML={s.prerenderedHTML}
109 + code={s.code}
110 + />
111 + ))}
112 + </div>
113 + );
114 +}
docs/components/home-features.tsx
+5 -5
@@ -42,13 +42,13 @@ export function HomeFeatures() {
42 <div className="grid grid-cols-1 gap-5 sm:auto-rows-fr sm:grid-cols-2">
43 <FeatureCard
44 title="Tools that resolve by intent."
45 - description="Smart tool search over 1000+ apps — surfaced just-in-time, with the right scope."
46 - href="/docs/tools-and-toolkits"
45 + description="Smart tool search over 1000+ apps, surfaced just in time with the right scope."
46 + href="/docs/how-composio-works"
47 visual={<ToolkitsVisual />}
48 />
49 <FeatureCard
50 title="Auth and context, per end-user."
51 - description="OAuth, API keys, and tokens scoped to each user — refreshed automatically."
51 + description="OAuth, API keys, and tokens scoped to each user and refreshed automatically."
52 href="/docs/authentication"
53 visual={<SessionsVisual />}
54 />
@@ -60,8 +60,8 @@ export function HomeFeatures() {
60 />
61 <FeatureCard
62 title="Run arbitrary code, safely."
63 - description="A workbench pre-wired with your user's connected accounts and 1000+ tools."
64 - href="/docs/workbench"
63 + description="A sandbox pre-wired with your user's connected accounts and 1000+ tools."
64 + href="/docs/sandbox"
65 visual={<WorkbenchVisual />}
66 />
67 </div>
docs/components/home-resources.tsx
+2 -9
@@ -6,7 +6,6 @@ import {
6 History,
7 Blocks,
8 Wrench,
9 - LifeBuoy,
9 } from 'lucide-react';
10 import type { ReactNode } from 'react';
11 import { SectionHeading } from './home-features';
@@ -26,9 +25,9 @@ const RESOURCES = [
25 },
26 {
27 icon: <Wrench aria-hidden="true" className="size-4" />,
29 - title: 'Cookbooks',
28 + title: 'Examples',
29 description: 'End-to-end recipes for real agents.',
31 - href: '/cookbooks',
30 + href: '/examples',
31 },
32 {
33 icon: <History aria-hidden="true" className="size-4" />,
@@ -42,12 +41,6 @@ const RESOURCES = [
41 description: 'Browse the 1000+ apps your agent can act on.',
42 href: '/toolkits',
43 },
45 - {
46 - icon: <LifeBuoy aria-hidden="true" className="size-4" />,
47 - title: 'Troubleshooting',
48 - description: 'Common errors and how to fix them.',
49 - href: '/docs/troubleshooting',
50 - },
44 ];
45
46 /**
docs/components/home-surfaces.tsx
+5 -15
@@ -6,7 +6,6 @@ import {
6 ArrowUpRight,
7 Code2,
8 Heart,
9 - Bot,
9 Terminal,
10 Copy,
11 Check,
@@ -61,8 +60,7 @@ const CLIENTS: { name: string; logo: string; h: number }[] = [
60 * Welcome-page audience selector — surfaces the three ways into Composio.
61 * "Build with the SDK" gets the full width of the top row and a strip of
62 * provider logos showing which frameworks ship first-class support; the
64 - * two non-developer surfaces (For You + Agents) sit below in a 2-col
65 - * row.
63 + * two non-developer surfaces (For You + CLI) sit below in a 2-col row.
64 */
65 export function HomeSurfaces() {
66 return (
@@ -71,7 +69,7 @@ export function HomeSurfaces() {
69 eyebrow="For everyone"
70 title="Three ways to use Composio."
71 />
74 - <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
72 + <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
73 {/* Full-width Developers card */}
74 <SurfaceCard
75 eyebrow="Developers"
@@ -83,12 +81,12 @@ export function HomeSurfaces() {
81 spanFull
82 extra={<ProviderStrip />}
83 />
86 - {/* Bottom row: For You + Agents */}
84 + {/* Bottom row: For You + CLI */}
85 <SurfaceCard
86 eyebrow="For You"
87 eyebrowIcon={<Heart aria-hidden="true" className="size-4" />}
88 title="Use Composio yourself"
91 - description="Plug 1000+ pre-authenticated apps into Claude Code, Cursor, or any MCP client. No build required — connect once and go."
89 + description="Plug 1000+ pre-authenticated apps into Claude Code, Cursor, or any MCP client. No build required. Connect once and go."
90 href="https://composio.dev/for-you"
91 external
92 extra={<ClientStrip />}
@@ -102,14 +100,6 @@ export function HomeSurfaces() {
100 external={false}
101 extra={<CliInstall />}
102 />
105 - <SurfaceCard
106 - eyebrow="Agents"
107 - eyebrowIcon={<Bot aria-hidden="true" className="size-4" />}
108 - title="Sign up as an agent"
109 - description="Agents can create their own Composio identity at agents.composio.dev — no human in the loop — and start running tools in seconds."
110 - href="https://agents.composio.dev"
111 - external
112 - />
103 </div>
104 </section>
105 );
@@ -143,7 +133,7 @@ function SurfaceCard({
133 {...externalProps}
134 className={
135 'group relative flex flex-col gap-3 overflow-hidden border border-fd-border bg-fd-card p-6 no-underline shadow-[0_1px_0_rgba(15,15,15,0.04)] transition-[box-shadow,transform,border-color] duration-200 hover:-translate-y-px hover:border-fd-foreground/15 hover:shadow-[0_10px_24px_-12px_rgba(15,15,15,0.18)] sm:p-7' +
146 - (spanFull ? ' md:col-span-3' : '')
136 + (spanFull ? ' md:col-span-2' : '')
137 }
138 >
139 <div className="flex items-center justify-between">
docs/components/import-connection-flow.tsx new
+101
@@ -0,0 +1,101 @@
1 +import { KeyRound, Link2, Play, RefreshCw } from 'lucide-react';
2 +import type { ReactNode } from 'react';
3 +
4 +const STEPS: {
5 + n: string;
6 + icon: ReactNode;
7 + title: string;
8 + note: string;
9 +}[] = [
10 + {
11 + n: '01',
12 + icon: <KeyRound className="size-3.5" aria-hidden="true" />,
13 + title: 'Create auth config',
14 + note: 'Define the scheme for the toolkit you import into',
15 + },
16 + {
17 + n: '02',
18 + icon: <Link2 className="size-3.5" aria-hidden="true" />,
19 + title: 'Create the connection',
20 + note: 'Pass your existing API key or bearer token',
21 + },
22 + {
23 + n: '03',
24 + icon: <Play className="size-3.5" aria-hidden="true" />,
25 + title: 'Use it in a session',
26 + note: 'The connected account is active immediately',
27 + },
28 + {
29 + n: '04',
30 + icon: <RefreshCw className="size-3.5" aria-hidden="true" />,
31 + title: 'Update when it rotates',
32 + note: 'PATCH new credentials in place, no re-auth',
33 + },
34 +];
35 +
36 +/**
37 + * ImportConnectionFlow — branded replacement for the import pipeline mermaid
38 + * diagram on the "Importing existing connections" page.
39 + *
40 + * Four steps to bring credentials you already hold into Composio without
41 + * making users re-authenticate: define the auth config, create the connection
42 + * with the existing credential, use it, and patch it when it rotates. Server
43 + * component, light/dark via fd-* tokens.
44 + */
45 +export function ImportConnectionFlow() {
46 + return (
47 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
48 + {/* header strip */}
49 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
50 + <span>connection.import</span>
51 + <span className="text-fd-foreground/55">no re-authentication</span>
52 + </div>
53 +
54 + {/* the pipeline */}
55 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-4">
56 + {STEPS.map((step, i) => {
57 + const last = i === STEPS.length - 1;
58 + return (
59 + <div
60 + key={step.title}
61 + className="relative flex flex-col gap-2 bg-fd-background p-3"
62 + >
63 + <div className="flex items-center gap-2">
64 + <span className="flex size-6 shrink-0 items-center justify-center rounded-sm bg-fd-foreground/[0.06] font-mono text-[10px] font-medium text-fd-foreground/55">
65 + {step.n}
66 + </span>
67 + <span className="flex size-6 shrink-0 items-center justify-center rounded-sm bg-[var(--composio-brand)]/10 text-[var(--composio-brand)]">
68 + {step.icon}
69 + </span>
70 + </div>
71 + <div className="min-w-0">
72 + <span className="block text-[12px] font-medium leading-tight text-fd-foreground">
73 + {step.title}
74 + </span>
75 + <p className="mt-1 text-[11px] leading-snug text-fd-foreground/55">
76 + {step.note}
77 + </p>
78 + </div>
79 + {!last && <Connector />}
80 + </div>
81 + );
82 + })}
83 + </div>
84 + </div>
85 + );
86 +}
87 +
88 +function Connector() {
89 + return (
90 + <div
91 + aria-hidden="true"
92 + className="pointer-events-none absolute z-10 hidden md:block"
93 + style={{ right: '-7px', top: '50%' }}
94 + >
95 + <div className="flex items-center">
96 + <span className="h-px w-3 bg-fd-border" />
97 + <span className="size-0 border-y-[3px] border-l-[5px] border-y-transparent border-l-fd-border" />
98 + </div>
99 + </div>
100 + );
101 +}
docs/components/in-chat-auth-terminal.tsx new
+166
@@ -0,0 +1,166 @@
1 +'use client';
2 +
3 +import type { ReactNode } from 'react';
4 +
5 +import { Input, Message, TerminalLine, TerminalWindow } from '@/components/terminal-kit';
6 +
7 +type InChatAuthTerminalProps = {
8 + /** Label shown in the window chrome header and footer. */
9 + path?: string;
10 + /** The user's opening request. */
11 + task: string;
12 + /** Toolkit the agent needs connected, display name, e.g. "Gmail". */
13 + toolkit: string;
14 + /** Lowercase toolkit slug used in tool args, e.g. "gmail". */
15 + toolkitSlug: string;
16 + /** The tool the agent executes once connected, e.g. "GMAIL_FETCH_EMAILS". */
17 + tool: string;
18 + /** Dim args shown on the executed tool call. */
19 + toolArgs?: string;
20 + /** Short result shown under the executed tool call, e.g. "12 emails". */
21 + toolResult?: string;
22 + /** The Connect Link the agent returns mid-conversation. */
23 + connectUrl?: string;
24 + /** The agent's final reply after the connection is established. */
25 + result: string;
26 +};
27 +
28 +/**
29 + * A Claude-Code-style tool call: a green bullet, the tool name (foreground), dim
30 + * `(args)`, and an optional `⎿ result` continuation line. Grouped in one session
31 + * row so the call and its result sit tight together.
32 + */
33 +function ToolCall({
34 + name,
35 + args,
36 + result,
37 + resultTone = 'dim',
38 +}: {
39 + name: string;
40 + args?: ReactNode;
41 + result?: ReactNode;
42 + resultTone?: 'dim' | 'success';
43 +}) {
44 + return (
45 + <div className="terminal-session-inset text-[10px]">
46 + <TerminalLine className="text-[10px]">
47 + <span className="inline-flex min-w-0 items-baseline gap-2">
48 + <span className="shrink-0" style={{ color: 'var(--terminal-green)' }}>
49 + ⏺
50 + </span>
51 + <span className="min-w-0 truncate" style={{ color: 'var(--terminal-fg)' }}>
52 + {name}
53 + </span>
54 + </span>
55 + </TerminalLine>
56 + {result ? (
57 + <TerminalLine className="text-[10px]">
58 + <span className="inline-flex min-w-0 items-baseline gap-2">
59 + <span className="shrink-0" style={{ color: 'var(--terminal-vdim)' }}>
60 + ⎿
61 + </span>
62 + <span
63 + className="min-w-0 truncate"
64 + style={{
65 + color:
66 + resultTone === 'success'
67 + ? 'var(--terminal-green)'
68 + : 'var(--terminal-dim)',
69 + }}
70 + >
71 + {result}
72 + </span>
73 + </span>
74 + </TerminalLine>
75 + ) : null}
76 + </div>
77 + );
78 +}
79 +
80 +/**
81 + * An agent message — same box shape as the user's `Message` bar, but outlined
82 + * with a border instead of a filled background so it reads as the agent, not the
83 + * tool plumbing. An optional `footer` (e.g. a link) renders inside, underneath.
84 + */
85 +function AgentMessage({ children, footer }: { children: ReactNode; footer?: ReactNode }) {
86 + return (
87 + <div
88 + className="terminal-session-sent w-full border py-1.5 text-[11px]"
89 + style={{ borderColor: 'var(--terminal-border)', color: 'var(--terminal-fg)' }}
90 + >
91 + <span className="block min-w-0 whitespace-pre-wrap break-words">{children}</span>
92 + {footer ? <div className="mt-1">{footer}</div> : null}
93 + </div>
94 + );
95 +}
96 +
97 +/**
98 + * Renders an in-chat authentication exchange using terminal-kit (Claude palette,
99 + * adapts to the docs light/dark theme). The agent searches for a tool, hits a
100 + * missing connection, returns a Connect Link, then `COMPOSIO_WAIT_FOR_CONNECTIONS`
101 + * waits for the user to authenticate and the agent continues automatically — the
102 + * user never has to confirm in chat. Static transcript, no animation.
103 + */
104 +export function InChatAuthTerminal({
105 + path = 'agent',
106 + task,
107 + toolkit,
108 + toolkitSlug,
109 + tool,
110 + toolArgs,
111 + toolResult,
112 + connectUrl = 'https://connect.composio.dev/link/ln_abc123',
113 + result,
114 +}: InChatAuthTerminalProps) {
115 + return (
116 + <div className="not-prose mx-auto my-6 w-full max-w-[400px]">
117 + <TerminalWindow
118 + className="shadow-2xl"
119 + path={path}
120 + theme="claude"
121 + footer={<Input placeholder="Send a message…" showCursor />}
122 + >
123 + {/* Static transcript — rendered up front, no streaming/word animation.
124 + The pb-[50px] adds 50px below the transcript. */}
125 + <div className="terminal-session pb-[50px]">
126 + <Message>{task}</Message>
127 +
128 + <ToolCall
129 + name="COMPOSIO_MANAGE_CONNECTIONS"
130 + args={toolkitSlug}
131 + result={`${toolkit} not connected — sent Connect Link`}
132 + />
133 +
134 + <AgentMessage
135 + footer={
136 + <a
137 + href={connectUrl}
138 + target="_blank"
139 + rel="noreferrer"
140 + style={{
141 + color: 'var(--terminal-teal)',
142 + textDecoration: 'underline',
143 + textUnderlineOffset: 2,
144 + }}
145 + >
146 + {connectUrl}
147 + </a>
148 + }
149 + >
150 + {`Connect your ${toolkit} account to continue:`}
151 + </AgentMessage>
152 +
153 + <ToolCall
154 + name="COMPOSIO_WAIT_FOR_CONNECTIONS"
155 + args={toolkitSlug}
156 + result={`✓ ${toolkit} connected`}
157 + resultTone="success"
158 + />
159 + <ToolCall name={tool} args={toolArgs} result={toolResult} />
160 +
161 + <AgentMessage>{result}</AgentMessage>
162 + </div>
163 + </TerminalWindow>
164 + </div>
165 + );
166 +}
docs/components/legacy-badge.tsx new
+15
@@ -0,0 +1,15 @@
1 +/**
2 + * "Legacy" badge rendered at the top of a docs page (under the title) when the
3 + * page frontmatter sets `legacy: true`. Used for the Direct Tool Execution
4 + * guides, which are superseded by sessions.
5 + */
6 +export function LegacyBadge() {
7 + return (
8 + <span
9 + title="Legacy: superseded by sessions; kept for existing integrations"
10 + className="not-prose mb-3 inline-flex w-fit items-center gap-1.5 rounded-md border border-fd-border bg-fd-muted px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-fd-muted-foreground"
11 + >
12 + Legacy
13 + </span>
14 + );
15 +}
docs/components/local-sandbox-boundary.tsx new
+152
@@ -0,0 +1,152 @@
1 +import { Bot, Boxes, Wrench } from 'lucide-react';
2 +import type { ComponentType, ReactNode } from 'react';
3 +
4 +/**
5 + * LocalSandboxBoundary — the motivation diagram for the local sandbox page.
6 + *
7 + * Both setups use Composio for auth + tools. The only thing that moves is the
8 + * sandbox that runs your code: outside your security boundary on remote, inside
9 + * it on local. The boundary is the only framed box, so "inside vs outside" reads
10 + * literally; the sandbox row is brand-tinted on both sides so the eye tracks it.
11 + *
12 + * Server component, no client JS. Both columns carry the same content weight, so
13 + * they balance without forced heights. Stacks to one column on mobile.
14 + */
15 +export function LocalSandboxBoundary() {
16 + return (
17 + <div className="not-prose my-6 overflow-hidden rounded-md border border-fd-border bg-fd-background">
18 + <div className="border-b border-fd-border px-5 py-2.5 font-mono text-[10px] uppercase tracking-[0.08em] text-fd-foreground/45">
19 + where your code runs, relative to your security boundary
20 + </div>
21 +
22 + <div className="grid gap-px bg-fd-border md:grid-cols-2">
23 + {/* Remote: the sandbox runs outside your boundary */}
24 + <Column label="Remote sandbox">
25 + <Boundary tone="neutral">
26 + <Row icon={Bot} title="Your agent" />
27 + </Boundary>
28 + <Seam />
29 + <Outside>
30 + <Row icon={Boxes} title="Remote sandbox" sub="runs your code" emphasis />
31 + <Row icon={Wrench} title="Composio" sub="auth + tools" />
32 + </Outside>
33 + </Column>
34 +
35 + {/* Local: the sandbox runs inside your boundary */}
36 + <Column label="Local sandbox" accent>
37 + <Boundary tone="accent">
38 + <Row icon={Bot} title="Your agent" />
39 + <Row icon={Boxes} title="Local sandbox" sub="runs your code" emphasis />
40 + </Boundary>
41 + <Seam accent />
42 + <Outside>
43 + <Row icon={Wrench} title="Composio" sub="auth + tools" />
44 + </Outside>
45 + </Column>
46 + </div>
47 + </div>
48 + );
49 +}
50 +
51 +function Column({ label, accent = false, children }: { label: string; accent?: boolean; children: ReactNode }) {
52 + return (
53 + <div className="flex flex-col gap-4 bg-fd-background p-5">
54 + <div className="flex items-center gap-2">
55 + <span
56 + className={'size-1.5 rounded-full ' + (accent ? 'bg-[var(--composio-brand)]' : 'bg-fd-foreground/30')}
57 + aria-hidden="true"
58 + />
59 + <span
60 + className={
61 + 'font-mono text-[11px] font-medium uppercase tracking-[0.08em] ' +
62 + (accent ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/55')
63 + }
64 + >
65 + {label}
66 + </span>
67 + </div>
68 + {children}
69 + </div>
70 + );
71 +}
72 +
73 +function Boundary({ tone, children }: { tone: 'neutral' | 'accent'; children: ReactNode }) {
74 + const border =
75 + tone === 'accent' ? 'border-[var(--composio-brand)]/35' : 'border-dashed border-fd-foreground/20';
76 + return (
77 + <div className={'relative rounded-md border bg-fd-foreground/[0.02] px-3 pb-3 pt-8 ' + border}>
78 + <span className="absolute left-3 top-2.5 font-mono text-[9px] uppercase tracking-[0.07em] text-fd-foreground/40">
79 + your boundary
80 + </span>
81 + <div className="flex flex-col gap-2">{children}</div>
82 + </div>
83 + );
84 +}
85 +
86 +function Outside({ children }: { children: ReactNode }) {
87 + return (
88 + <div>
89 + <span className="font-mono text-[9px] uppercase tracking-[0.07em] text-fd-foreground/40">
90 + outside your boundary
91 + </span>
92 + <div className="mt-2 flex flex-col gap-2">{children}</div>
93 + </div>
94 + );
95 +}
96 +
97 +function Row({
98 + icon: Icon,
99 + title,
100 + sub,
101 + emphasis = false,
102 +}: {
103 + icon: ComponentType<{ className?: string; 'aria-hidden'?: boolean }>;
104 + title: string;
105 + sub?: string;
106 + emphasis?: boolean;
107 +}) {
108 + return (
109 + <div
110 + className={
111 + 'flex items-center gap-3 rounded-md px-2.5 py-2 ' +
112 + (emphasis ? 'bg-[var(--composio-brand)]/[0.06] ring-1 ring-inset ring-[var(--composio-brand)]/25' : '')
113 + }
114 + >
115 + <span
116 + className={
117 + 'flex size-8 shrink-0 items-center justify-center rounded-md ' +
118 + (emphasis
119 + ? 'bg-[var(--composio-brand)]/10 text-[var(--composio-brand)]'
120 + : 'bg-fd-foreground/[0.06] text-fd-foreground/65')
121 + }
122 + >
123 + <Icon aria-hidden className="size-4" />
124 + </span>
125 + <div className="min-w-0">
126 + <div
127 + className={
128 + 'truncate text-[13px] font-medium leading-tight ' +
129 + (emphasis ? 'text-[var(--composio-brand)]' : 'text-fd-foreground')
130 + }
131 + >
132 + {title}
133 + </div>
134 + {sub && <div className="mt-0.5 truncate font-mono text-[10px] text-fd-foreground/45">{sub}</div>}
135 + </div>
136 + </div>
137 + );
138 +}
139 +
140 +function Seam({ accent = false }: { accent?: boolean }) {
141 + return (
142 + <div
143 + className={
144 + 'flex items-center justify-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.06em] ' +
145 + (accent ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/40')
146 + }
147 + >
148 + <span>auth + tools</span>
149 + <span aria-hidden="true">↓</span>
150 + </div>
151 + );
152 +}
docs/components/local-workbench-flow.tsx new
+192
@@ -0,0 +1,192 @@
1 +import { FileCode2, Boxes, Wrench } from 'lucide-react';
2 +import type { ReactNode } from 'react';
3 +
4 +const LOGO_CDN = 'https://logos.composio.dev/api';
5 +
6 +/**
7 + * LocalWorkbenchFlow: branded replacement for the plain `host → sandbox → tools`
8 + * mermaid diagram on the local-workbench PR reviewer page.
9 + *
10 + * Reads left-to-right as the split that defines a local workbench: the Host
11 + * creates a session with code execution turned off and starts a
12 + * sandbox you own; the Sandbox runs the reviewer, calling run_composio_tool
13 + * back out for each GitHub action; Composio resolves and executes those tool
14 + * calls under the user's connection and returns results. Tool execution lives
15 + * in your box; discovery and auth stay managed.
16 + *
17 + * Server component, no client JS. Adapts to light/dark via fd-* tokens.
18 + */
19 +export function LocalWorkbenchFlow() {
20 + return (
21 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
22 + {/* header strip: mono, matches the other branded flow visuals */}
23 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
24 + <span>local-sandbox.runtime</span>
25 + <span className="inline-flex items-center gap-1.5 text-fd-foreground/55">
26 + <span className="relative inline-flex">
27 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" />
28 + <span className="absolute inset-0 animate-ping rounded-full bg-[var(--composio-brand)] opacity-60" />
29 + </span>
30 + code runs in your box
31 + </span>
32 + </div>
33 +
34 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-[minmax(0,1fr)_minmax(0,1.05fr)_minmax(0,1.05fr)]">
35 + {/* ── Host ───────────────────────────────────────────────── */}
36 + <Column>
37 + <Lane label="Host" />
38 + <div className="flex flex-1 items-center">
39 + <div className="w-full border border-fd-border bg-fd-card p-3">
40 + <div className="flex items-center gap-2">
41 + <span className="flex size-7 items-center justify-center rounded-sm bg-fd-foreground/[0.06] text-fd-foreground/70">
42 + <FileCode2 aria-hidden="true" className="size-4" />
43 + </span>
44 + <div className="min-w-0">
45 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
46 + Your orchestrator
47 + </div>
48 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
49 + src/runner.ts
50 + </div>
51 + </div>
52 + </div>
53 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/55">
54 + Creates the session with{' '}
55 + <code className="font-mono text-[10px] text-fd-foreground/70">workbench.enable: false</code>, then
56 + starts a sandbox you own.
57 + </p>
58 + <p className="mt-2.5 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.05em] text-[var(--composio-brand)]">
59 + helper + env <Arrow /> sandbox
60 + </p>
61 + </div>
62 + </div>
63 + <Connector />
64 + </Column>
65 +
66 + {/* ── Sandbox (yours) ────────────────────────────────────── */}
67 + <Column>
68 + <Lane label="Sandbox · yours" />
69 + <div className="flex flex-1 items-center">
70 + <div className="w-full border border-fd-border bg-fd-card p-3">
71 + <div className="flex items-center gap-2">
72 + <span className="flex size-7 items-center justify-center rounded-sm bg-fd-foreground/[0.06] text-fd-foreground/70">
73 + <Boxes aria-hidden="true" className="size-4" />
74 + </span>
75 + <div className="min-w-0">
76 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
77 + Reviewer agent
78 + </div>
79 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
80 + your filesystem + shell
81 + </div>
82 + </div>
83 + </div>
84 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/55">
85 + Clones the PR, installs deps, runs the repo&apos;s real checks, all inside your boundary.
86 + </p>
87 + <p className="mt-2.5 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.05em] text-[var(--composio-brand)]">
88 + run_composio_tool <Arrow /> Composio
89 + </p>
90 + </div>
91 + </div>
92 + <Connector accent />
93 + </Column>
94 +
95 + {/* ── Composio (the managed side) ────────────────────────── */}
96 + <Column>
97 + <Lane label="Composio" accent />
98 + <div className="flex flex-1 flex-col">
99 + <div className="relative flex-1 border border-[var(--composio-brand)]/30 bg-[var(--composio-brand)]/[0.04] p-3">
100 + <span
101 + aria-hidden="true"
102 + className="pointer-events-none absolute inset-y-0 left-0 w-[2px] bg-[var(--composio-brand)]"
103 + />
104 + <div className="flex items-center justify-between">
105 + <span className="inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--composio-brand)]">
106 + <Wrench aria-hidden="true" className="size-2.5" />
107 + Session
108 + </span>
109 + <img
110 + alt=""
111 + aria-hidden="true"
112 + className="size-4 rounded-sm object-contain"
113 + draggable={false}
114 + src={`${LOGO_CDN}/github`}
115 + />
116 + </div>
117 +
118 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/60">
119 + Resolves the right GitHub action, runs it under the user&apos;s connection, and returns the result
120 + to the sandbox.
121 + </p>
122 +
123 + <ul className="mt-2.5 space-y-1 font-mono text-[10px] text-fd-foreground/55">
124 + <li>· search + schema discovery</li>
125 + <li>· managed GitHub auth</li>
126 + <li>· tool execution + result</li>
127 + </ul>
128 + </div>
129 + </div>
130 + </Column>
131 + </div>
132 +
133 + {/* footer caption */}
134 + <div className="border-t border-fd-border px-3 py-2 text-center font-mono text-[10px] text-fd-foreground/45">
135 + host (session, execution off) <Arrow /> your sandbox (runs checks) <Arrow /> run_composio_tool{' '}
136 + <Arrow /> Composio (resolve + execute) <Arrow /> grounded PR comment
137 + </div>
138 + </div>
139 + );
140 +}
141 +
142 +function Column({ children }: { children: ReactNode }) {
143 + return <div className="relative flex flex-col gap-2 bg-fd-background p-3">{children}</div>;
144 +}
145 +
146 +function Lane({ label, accent = false }: { label: string; accent?: boolean }) {
147 + return (
148 + <div className="flex items-center gap-1.5">
149 + <span
150 + className={'size-1.5 rounded-full ' + (accent ? 'bg-[var(--composio-brand)]' : 'bg-fd-foreground/30')}
151 + aria-hidden="true"
152 + />
153 + <span
154 + className={
155 + 'font-mono text-[10px] font-medium uppercase tracking-[0.07em] ' +
156 + (accent ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/55')
157 + }
158 + >
159 + {label}
160 + </span>
161 + </div>
162 + );
163 +}
164 +
165 +/**
166 + * Directional connector shown between columns. Horizontal arrow on desktop,
167 + * hidden on stacked mobile so the flow still reads top-to-bottom.
168 + */
169 +function Connector({ accent = false }: { accent?: boolean }) {
170 + const color = accent ? 'bg-[var(--composio-brand)]/40' : 'bg-fd-border';
171 + const tip = accent ? 'border-l-[var(--composio-brand)]/50' : 'border-l-fd-border';
172 + return (
173 + <div
174 + aria-hidden="true"
175 + className="pointer-events-none absolute z-10 hidden md:block"
176 + style={{ right: '-7px', top: '50%' }}
177 + >
178 + <div className="flex items-center">
179 + <span className={'h-px w-3 ' + color} />
180 + <span className={'size-0 border-y-[3px] border-l-[5px] border-y-transparent ' + tip} />
181 + </div>
182 + </div>
183 + );
184 +}
185 +
186 +function Arrow() {
187 + return (
188 + <span aria-hidden="true" className="text-[var(--composio-brand)]">
189 + {'→'}
190 + </span>
191 + );
192 +}
docs/components/manage-connections-visual.tsx new
+1002
@@ -0,0 +1,1002 @@
1 +"use client";
2 +
3 +import { AnimatePresence, motion } from "framer-motion";
4 +import { useCallback, useEffect, useRef, useState } from "react";
5 +import { Message } from "@/components/terminal-kit/session/message";
6 +import { TerminalWindow } from "@/components/terminal-kit/shell/terminal-window";
7 +import { ThinkingIndicator } from "@/components/terminal-kit/ui/thinking-indicator";
8 +import { cn } from "@/lib/utils";
9 +
10 +const LOGO_CDN = "https://logos.composio.dev/api";
11 +
12 +/**
13 + * Claude (dark) terminal-kit palette, pinned inline so the terminal renders dark
14 + * regardless of the docs light/dark theme (the rest of the composition — Google
15 + * auth window, connections panel — uses hardcoded colors too). Mirrors landing's
16 + * `.tk-claude-dark` override. `--font-geist-mono` is left to the `.terminal-theme`
17 + * default so docs JetBrains Mono is used.
18 + */
19 +const DARK_VARS = {
20 + "--terminal-bg": "#0b0b0b",
21 + "--terminal-editor-bg": "#1f1f1e",
22 + "--terminal-fg": "#ffffff",
23 + "--terminal-white": "#ffffff",
24 + "--terminal-dim": "#c3c2b7",
25 + "--terminal-dimmer": "#898781",
26 + "--terminal-vdim": "#3d3d3d",
27 + "--terminal-surface": "#232323",
28 + "--terminal-input-bg": "#1f1f1e",
29 + "--terminal-popover": "#2a2a2a",
30 + "--terminal-panel": "rgba(255, 255, 255, 0.05)",
31 + "--terminal-panel-strong": "rgba(255, 255, 255, 0.07)",
32 + "--terminal-border": "rgba(255, 255, 255, 0.1)",
33 + "--terminal-input-border": "#565552",
34 + "--terminal-progress-track": "#3d3d3d",
35 + "--terminal-progress-fill": "#d97757",
36 + "--terminal-green": "#4cc38a",
37 + "--terminal-blue": "#4d9fff",
38 + "--terminal-teal": "#d97757",
39 + "--terminal-red": "#ff5a5a",
40 + "--terminal-purple": "#9775fa",
41 + "--terminal-traffic-red": "#ff5f57",
42 + "--terminal-traffic-yellow": "#febc2e",
43 + "--terminal-traffic-green": "#28c840",
44 +} as React.CSSProperties;
45 +
46 +type Pt = { x: number; y: number };
47 +
48 +/** L-elbow: run horizontal from p, then drop vertically into q. */
49 +function elbowHV(p: Pt, q: Pt, r = 10): string {
50 + const sx = Math.sign(q.x - p.x) || 1;
51 + const sy = Math.sign(q.y - p.y) || 1;
52 + const rr = Math.min(r, Math.abs(q.x - p.x), Math.abs(q.y - p.y));
53 + if (rr < 1) return `M ${p.x} ${p.y} L ${q.x} ${q.y}`;
54 + return `M ${p.x} ${p.y} L ${q.x - sx * rr} ${p.y} Q ${q.x} ${p.y} ${q.x} ${
55 + p.y + sy * rr
56 + } L ${q.x} ${q.y}`;
57 +}
58 +
59 +/** L-elbow: drop vertically from p, then run horizontal into q. */
60 +function elbowVH(p: Pt, q: Pt, r = 10): string {
61 + const sx = Math.sign(q.x - p.x) || 1;
62 + const sy = Math.sign(q.y - p.y) || 1;
63 + const rr = Math.min(r, Math.abs(q.x - p.x), Math.abs(q.y - p.y));
64 + if (rr < 1) return `M ${p.x} ${p.y} L ${q.x} ${q.y}`;
65 + return `M ${p.x} ${p.y} L ${p.x} ${q.y - sy * rr} Q ${p.x} ${q.y} ${
66 + p.x + sx * rr
67 + } ${q.y} L ${q.x} ${q.y}`;
68 +}
69 +
70 +type Phase = "intent" | "authorizing" | "active";
71 +
72 +type Row = {
73 + id: string;
74 + app: string;
75 + name: string;
76 + account: string;
77 + alias: string | null;
78 + /** The account being connected in this run (animates in). */
79 + dynamic?: boolean;
80 +};
81 +
82 +const SCENARIO = {
83 + intent:
84 + "send the report from our work Gmail, then a copy to me from my personal account",
85 + connect: {
86 + app: "gmail",
87 + appName: "Gmail",
88 + account: "alex@gmail.com",
89 + alias: "personal",
90 + },
91 + rows: [
92 + {
93 + id: "gmail-personal",
94 + app: "gmail",
95 + name: "Gmail",
96 + account: "alex@gmail.com",
97 + alias: "personal",
98 + dynamic: true,
99 + },
100 + {
101 + id: "gmail-work",
102 + app: "gmail",
103 + name: "Gmail",
104 + account: "ops@acme.com",
105 + alias: "work",
106 + },
107 + ] as Row[],
108 +} as const;
109 +
110 +const REPLY_OPEN =
111 + 'Gmail "personal" isn\'t connected. Opening the authorization page in your browser.';
112 +const REPLY_DONE =
113 + "Connected. Sending the report from work, then a copy to you from personal.";
114 +
115 +/** Bordered card (Neon style), animates in. */
116 +function FloatingCard({
117 + className,
118 + style,
119 + innerRef,
120 + show,
121 + delay = 0,
122 + bare = false,
123 + neutral = false,
124 + boxMotion = false,
125 + children,
126 +}: {
127 + className?: string;
128 + style?: React.CSSProperties;
129 + innerRef?: React.Ref<HTMLDivElement>;
130 + show: boolean;
131 + delay?: number;
132 + bare?: boolean;
133 + /** Use a neutral border instead of the blue accent. */
134 + neutral?: boolean;
135 + /** Animate the box's height (and let its content cross-fade) on change. */
136 + boxMotion?: boolean;
137 + children: React.ReactNode;
138 +}) {
139 + // Always present; opacity-only so the layout box (and the connectors anchored
140 + // to it) never shift. Sits faded until active, and fades back on replay.
141 + return (
142 + <motion.div
143 + animate={{ opacity: show ? 1 : 0.3 }}
144 + className={cn("absolute", className)}
145 + initial={false}
146 + style={style}
147 + transition={{
148 + duration: 0.55,
149 + delay: show ? delay : 0,
150 + ease: [0.22, 1, 0.36, 1],
151 + }}
152 + >
153 + <motion.div
154 + className={cn(
155 + "overflow-hidden shadow-[0_24px_70px_-10px_rgba(0,0,0,0.7)]",
156 + bare
157 + ? "rounded-lg"
158 + : neutral
159 + ? "border border-white/10 bg-[#0c0c0d]"
160 + : "border border-[#51a2ff]/55 bg-[#0c0c0d]",
161 + )}
162 + layout={boxMotion ? true : undefined}
163 + ref={innerRef}
164 + style={bare ? { borderRadius: "0.5rem" } : undefined}
165 + transition={
166 + boxMotion
167 + ? { layout: { duration: 0.45, ease: [0.22, 1, 0.36, 1] } }
168 + : undefined
169 + }
170 + >
171 + {children}
172 + </motion.div>
173 + </motion.div>
174 + );
175 +}
176 +
177 +const APP_NAME = "Acme Assistant";
178 +const G_ACCOUNTS = [
179 + { name: "Alex Rivera", email: "ops@acme.com", color: "#1a73e8" },
180 + {
181 + name: "Alex Rivera",
182 + email: "alex@gmail.com",
183 + color: "#188038",
184 + target: true,
185 + },
186 + { name: "Alex Rivera", email: "a.rivera@contoso.com", color: "#9334e6" },
187 +];
188 +
189 +/** Google "G" mark for the sign-in mock. */
190 +function GoogleG({ className }: { className?: string }) {
191 + return (
192 + <svg aria-hidden="true" className={className} viewBox="0 0 48 48">
193 + <path
194 + d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"
195 + fill="#EA4335"
196 + />
197 + <path
198 + d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"
199 + fill="#4285F4"
200 + />
201 + <path
202 + d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"
203 + fill="#FBBC05"
204 + />
205 + <path
206 + d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"
207 + fill="#34A853"
208 + />
209 + </svg>
210 + );
211 +}
212 +
213 +/** "Sign in with Google" browser window mock (the OAuth account chooser). */
214 +function GoogleAuthWindow({ phase }: { phase: Phase }) {
215 + const selecting = phase === "authorizing";
216 + const done = phase === "active";
217 + return (
218 + <div className="w-full overflow-hidden rounded-lg bg-white text-black">
219 + {/* browser chrome */}
220 + <div className="flex items-center gap-2 bg-[#dfe1e5] px-3 py-1.5">
221 + <div className="flex gap-1.5">
222 + <span className="size-2.5 rounded-full bg-[#ff5f57]" />
223 + <span className="size-2.5 rounded-full bg-[#febc2e]" />
224 + <span className="size-2.5 rounded-full bg-[#28c840]" />
225 + </div>
226 + <div className="ml-1 flex flex-1 items-center gap-1.5 rounded-md bg-white px-2 py-0.5 text-[10px] text-black/55">
227 + <svg
228 + aria-hidden="true"
229 + className="size-2.5 shrink-0"
230 + fill="none"
231 + stroke="currentColor"
232 + strokeLinecap="round"
233 + strokeLinejoin="round"
234 + strokeWidth={2}
235 + viewBox="0 0 24 24"
236 + >
237 + <rect height="11" rx="2" width="18" x="3" y="11" />
238 + <path d="M7 11V7a5 5 0 0 1 10 0v4" />
239 + </svg>
240 + <span className="truncate">accounts.google.com</span>
241 + </div>
242 + </div>
243 + {/* google header */}
244 + <div className="flex items-center gap-2 border-black/10 border-b px-4 py-2.5">
245 + <GoogleG className="size-4" />
246 + <span className="text-[12px] text-black/70">Sign in with Google</span>
247 + </div>
248 + {/* body */}
249 + <div className="px-4 pt-3 pb-3">
250 + <div className="text-center text-[15px] text-black/85">
251 + Choose an account
252 + </div>
253 + <div className="mt-0.5 text-center text-[11px] text-black/55">
254 + to continue to <span className="text-[#1a73e8]">{APP_NAME}</span>
255 + </div>
256 + <div className="mt-3 flex flex-col gap-0.5">
257 + {G_ACCOUNTS.map((a) => {
258 + const active = a.target && (selecting || done);
259 + return (
260 + <div
261 + className={cn(
262 + "flex items-center gap-3 rounded-md px-2 py-2",
263 + active && "bg-[#e8f0fe]",
264 + )}
265 + key={a.email}
266 + >
267 + <span
268 + className="flex size-7 shrink-0 items-center justify-center rounded-full text-[12px] text-white"
269 + style={{ background: a.color }}
270 + >
271 + {a.name[0]}
272 + </span>
273 + <div className="min-w-0 flex-1">
274 + <div className="truncate text-[12px] text-black/85 leading-tight">
275 + {a.name}
276 + </div>
277 + <div className="truncate text-[11px] text-black/50 leading-tight">
278 + {a.email}
279 + </div>
280 + </div>
281 + {a.target && selecting && (
282 + <span className="size-3.5 shrink-0 animate-spin rounded-full border-2 border-black/15 border-t-[#1a73e8]" />
283 + )}
284 + {a.target && done && (
285 + <svg
286 + aria-hidden="true"
287 + className="size-4 shrink-0 text-[#188038]"
288 + fill="none"
289 + stroke="currentColor"
290 + strokeLinecap="round"
291 + strokeLinejoin="round"
292 + strokeWidth={2.5}
293 + viewBox="0 0 24 24"
294 + >
295 + <path d="M5 13l4 4L19 7" />
296 + </svg>
297 + )}
298 + </div>
299 + );
300 + })}
301 + </div>
302 + <div className="mt-2 border-black/10 border-t pt-2 text-[10px] text-black/45 leading-relaxed">
303 + To continue, Google will share your name, email address, and profile
304 + picture with {APP_NAME}.
305 + </div>
306 + </div>
307 + </div>
308 + );
309 +}
310 +
311 +/** Dark-mode skeleton placeholder shown before the auth flow starts. */
312 +function GoogleAuthSkeleton() {
313 + return (
314 + <div className="w-full animate-pulse rounded-lg border border-white/[0.1] bg-white/[0.05] p-5">
315 + <div className="mx-auto h-3 w-32 rounded bg-white/[0.1]" />
316 + <div className="mx-auto mt-2.5 h-2 w-44 rounded bg-white/[0.06]" />
317 + <div className="mt-7 flex flex-col gap-5">
318 + {[0, 1, 2].map((i) => (
319 + <div className="flex items-center gap-3" key={i}>
320 + <span className="size-9 shrink-0 rounded-full bg-white/[0.08]" />
321 + <div className="flex-1">
322 + <div className="h-2.5 w-28 rounded bg-white/[0.1]" />
323 + <div className="mt-2 h-2 w-36 rounded bg-white/[0.06]" />
324 + </div>
325 + </div>
326 + ))}
327 + </div>
328 + </div>
329 + );
330 +}
331 +
332 +// ── Right panel: Neon-style auth composition ────────────────────────────
333 +function ConnectionsComposition({
334 + phase,
335 + step,
336 + showConnections,
337 + authorizeRef,
338 + connectionsRef,
339 +}: {
340 + phase: Phase;
341 + step: number;
342 + showConnections: boolean;
343 + authorizeRef: React.Ref<HTMLDivElement>;
344 + connectionsRef: React.Ref<HTMLDivElement>;
345 +}) {
346 + // The auth panel only resolves once the connector from the terminal has
347 + // arrived (step 4); until then it sits as a faded skeleton.
348 + const authReady = step >= 3;
349 + const visibleRows = SCENARIO.rows.filter(
350 + (r) => !r.dynamic || phase !== "intent",
351 + );
352 +
353 + return (
354 + <div className="relative h-full w-full overflow-hidden">
355 + {/* connections card */}
356 + <FloatingCard
357 + className="left-0 bottom-0 w-[24rem]"
358 + delay={0.2}
359 + innerRef={connectionsRef}
360 + neutral
361 + show={showConnections}
362 + >
363 + <div className="font-mono">
364 + <div className="flex items-center gap-2 border-white/[0.06] border-b bg-white/[0.02] px-3 py-2">
365 + <svg
366 + aria-hidden="true"
367 + className="size-3 shrink-0 text-white/35"
368 + fill="none"
369 + stroke="currentColor"
370 + strokeLinecap="round"
371 + strokeLinejoin="round"
372 + strokeWidth={2}
373 + viewBox="0 0 24 24"
374 + >
375 + <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
376 + <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
377 + </svg>
378 + <span className="text-[11px] text-white/35 uppercase tracking-wider">
379 + active connections
380 + </span>
381 + </div>
382 + <div className="px-3 py-1.5">
383 + <AnimatePresence initial={false}>
384 + {visibleRows.map((row) => {
385 + const pending = row.dynamic && phase === "authorizing";
386 + const added = row.dynamic && phase === "active";
387 + return (
388 + <motion.div
389 + animate={{ opacity: 1, height: "auto" }}
390 + exit={{ opacity: 0, height: 0 }}
391 + initial={row.dynamic ? { opacity: 0, height: 0 } : false}
392 + key={row.id}
393 + transition={{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }}
394 + >
395 + <div
396 + className={cn(
397 + "relative overflow-hidden rounded-md",
398 + added &&
399 + "-mx-1.5 bg-[#51a2ff]/[0.07] px-1.5",
400 + )}
401 + >
402 + {added && (
403 + <motion.span
404 + animate={{ x: ["-130%", "330%"] }}
405 + aria-hidden="true"
406 + className="pointer-events-none absolute inset-y-0 left-0 w-1/3"
407 + style={{
408 + background:
409 + "linear-gradient(90deg, transparent, #51a2ff, transparent)",
410 + opacity: 0.4,
411 + }}
412 + transition={{
413 + duration: 1.6,
414 + ease: "easeInOut",
415 + repeat: Number.POSITIVE_INFINITY,
416 + repeatDelay: 0.7,
417 + }}
418 + />
419 + )}
420 + <div className="relative z-10 flex items-center gap-2.5 py-1">
421 + <img
422 + alt={row.name}
423 + aria-hidden="true"
424 + className="h-[15px] w-[15px] shrink-0 object-contain"
425 + draggable={false}
426 + src={`${LOGO_CDN}/${row.app}`}
427 + />
428 + <span className="min-w-0 flex-1 truncate text-[11px] text-white/65">
429 + {row.account}
430 + </span>
431 + {row.alias && (
432 + <span className="rounded-full bg-white/[0.06] px-1.5 py-0.5 font-mono text-[9px] text-white/55 uppercase tracking-wider">
433 + {row.alias}
434 + </span>
435 + )}
436 + {pending ? (
437 + <span className="size-3.5 shrink-0 animate-spin rounded-full border-2 border-amber-400/30 border-t-amber-400" />
438 + ) : (
439 + <svg
440 + aria-label="connected"
441 + className="size-4 shrink-0 text-green-400"
442 + fill="none"
443 + role="img"
444 + stroke="currentColor"
445 + strokeLinecap="round"
446 + strokeLinejoin="round"
447 + strokeWidth={2.5}
448 + viewBox="0 0 24 24"
449 + >
450 + <path d="M5 13l4 4L19 7" />
451 + </svg>
452 + )}
453 + </div>
454 + </div>
455 + </motion.div>
456 + );
457 + })}
458 + </AnimatePresence>
459 + </div>
460 + </div>
461 + </FloatingCard>
462 +
463 + {/* authorize card — Sign in with Google browser window, centered
464 + between the terminal and the connections panel */}
465 + <FloatingCard
466 + bare
467 + boxMotion
468 + className="top-[104px] right-0 w-[300px]"
469 + delay={0.1}
470 + innerRef={authorizeRef}
471 + show={authReady}
472 + >
473 + <AnimatePresence initial={false} mode="popLayout">
474 + {authReady ? (
475 + <motion.div
476 + animate={{ opacity: 1 }}
477 + exit={{ opacity: 0 }}
478 + initial={{ opacity: 0 }}
479 + key="window"
480 + transition={{ duration: 0.3 }}
481 + >
482 + <GoogleAuthWindow phase={phase} />
483 + </motion.div>
484 + ) : (
485 + <motion.div
486 + animate={{ opacity: 1 }}
487 + exit={{ opacity: 0 }}
488 + initial={{ opacity: 0 }}
489 + key="skeleton"
490 + transition={{ duration: 0.3 }}
491 + >
492 + <GoogleAuthSkeleton />
493 + </motion.div>
494 + )}
495 + </AnimatePresence>
496 + </FloatingCard>
497 + </div>
498 + );
499 +}
500 +
501 +/** Streams text in word-by-word (terminal-kit StreamText style). */
502 +function StreamText({
503 + text,
504 + play,
505 + speed = 80,
506 +}: {
507 + text: string;
508 + play: boolean;
509 + speed?: number;
510 +}) {
511 + const words = text.split(" ");
512 + const [n, setN] = useState(play ? 0 : words.length);
513 + useEffect(() => {
514 + if (!play) {
515 + setN(words.length);
516 + return;
517 + }
518 + setN(0);
519 + let i = 0;
520 + const id = setInterval(() => {
521 + i += 1;
522 + setN(i);
523 + if (i >= words.length) clearInterval(id);
524 + }, speed);
525 + return () => clearInterval(id);
526 + // eslint-disable-next-line react-hooks/exhaustive-deps
527 + }, [text, play, speed]);
528 + return <span>{words.slice(0, n).join(" ")}</span>;
529 +}
530 +
531 +/** Agent tool call — `⏺ NAME(args)` + optional `⎿ result`, matching the in-chat terminal. */
532 +function ToolCall({
533 + name,
534 + args,
535 + result,
536 + resultTone = "dim",
537 +}: {
538 + name: string;
539 + args?: React.ReactNode;
540 + result?: React.ReactNode;
541 + resultTone?: "dim" | "success";
542 +}) {
543 + return (
544 + <motion.div
545 + animate={{ opacity: 1, y: 0 }}
546 + initial={{ opacity: 0, y: 4 }}
547 + transition={{ duration: 0.25 }}
548 + >
549 + <div className="flex min-w-0 items-baseline gap-2 text-[11px]">
550 + <span className="shrink-0" style={{ color: "var(--terminal-green)" }}>
551 + ⏺
552 + </span>
553 + <span
554 + className="min-w-0 truncate"
555 + style={{ color: "var(--terminal-fg)" }}
556 + >
557 + {name}
558 + </span>
559 + </div>
560 + {result ? (
561 + <div className="flex min-w-0 items-baseline gap-2 text-[11px]">
562 + <span className="shrink-0" style={{ color: "var(--terminal-vdim)" }}>
563 + ⎿
564 + </span>
565 + <span
566 + className="min-w-0 truncate"
567 + style={{
568 + color:
569 + resultTone === "success"
570 + ? "var(--terminal-green)"
571 + : "var(--terminal-dim)",
572 + }}
573 + >
574 + {result}
575 + </span>
576 + </div>
577 + ) : null}
578 + </motion.div>
579 + );
580 +}
581 +
582 +/** Agent message — bordered box (outlined, no fill), matching the in-chat terminal. */
583 +function AgentMessage({
584 + children,
585 + footer,
586 +}: {
587 + children: React.ReactNode;
588 + footer?: React.ReactNode;
589 +}) {
590 + return (
591 + <motion.div
592 + animate={{ opacity: 1, y: 0 }}
593 + className="terminal-session-sent w-full border py-1.5 text-[11px]"
594 + initial={{ opacity: 0, y: 4 }}
595 + style={{ borderColor: "var(--terminal-border)", color: "var(--terminal-fg)" }}
596 + transition={{ duration: 0.25 }}
597 + >
598 + <span className="block min-w-0 whitespace-pre-wrap break-words">
599 + {children}
600 + </span>
601 + {footer ? <div className="mt-1">{footer}</div> : null}
602 + </motion.div>
603 + );
604 +}
605 +
606 +/** Assistant reply line in the transcript. */
607 +function AssistantLine({ children }: { children: React.ReactNode }) {
608 + return (
609 + <motion.div
610 + animate={{ opacity: 1, y: 0 }}
611 + className="px-1 text-[11px] text-[var(--terminal-fg)]/75 leading-relaxed"
612 + initial={{ opacity: 0, y: 4 }}
613 + transition={{ duration: 0.3 }}
614 + >
615 + {children}
616 + </motion.div>
617 + );
618 +}
619 +
620 +/** A "opened in the browser" action row referencing the auth page. */
621 +function BrowserLine({
622 + url,
623 + state,
624 + lineRef,
625 + pulse,
626 +}: {
627 + url: string;
628 + state: string;
629 + lineRef?: React.Ref<HTMLDivElement>;
630 + pulse?: boolean;
631 +}) {
632 + return (
633 + <motion.div
634 + animate={{ opacity: 1, y: 0 }}
635 + className="relative flex items-center gap-2 overflow-hidden border border-[var(--terminal-border)] bg-[var(--terminal-editor-bg)] px-2 py-1.5 text-[11px]"
636 + initial={{ opacity: 0, y: 4 }}
637 + ref={lineRef}
638 + transition={{ duration: 0.25, delay: 0.1 }}
639 + >
640 + {/* blue pulse sweeps left→right before the connector draws */}
641 + {pulse && (
642 + <motion.span
643 + animate={{ x: ["-100%", "300%"] }}
644 + className="pointer-events-none absolute inset-y-0 left-0 w-1/3"
645 + initial={{ x: "-100%" }}
646 + style={{
647 + background:
648 + "linear-gradient(90deg, transparent, #51a2ff, transparent)",
649 + opacity: 0.5,
650 + }}
651 + transition={{ duration: 0.8, ease: "easeInOut" }}
652 + />
653 + )}
654 + <svg
655 + aria-hidden="true"
656 + className="size-3.5 shrink-0 text-[var(--terminal-fg)]/50"
657 + fill="none"
658 + stroke="currentColor"
659 + strokeLinecap="round"
660 + strokeLinejoin="round"
661 + strokeWidth={1.75}
662 + viewBox="0 0 24 24"
663 + >
664 + <circle cx="12" cy="12" r="9" />
665 + <path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" />
666 + </svg>
667 + <span className="truncate text-[var(--terminal-fg)]/80">{url}</span>
668 + <span className="ml-auto shrink-0 text-[var(--terminal-fg)]/45">
669 + {state}
670 + </span>
671 + </motion.div>
672 + );
673 +}
674 +
675 +export function ManageConnectionsVisual() {
676 + const rootRef = useRef<HTMLDivElement>(null);
677 + const terminalRef = useRef<HTMLDivElement>(null);
678 + const browserRef = useRef<HTMLDivElement>(null);
679 + const authorizeRef = useRef<HTMLDivElement>(null);
680 + const connectionsRef = useRef<HTMLDivElement>(null);
681 + const [inView, setInView] = useState(false);
682 + const [runId, setRunId] = useState(0);
683 + // step: 0 idle · 1 task shown · 2 reply · 3 opening auth · 4 waiting · 5 connected
684 + const [step, setStep] = useState(0);
685 + const [link, setLink] = useState<{
686 + p1: string;
687 + p1End: Pt;
688 + p2: string;
689 + p2End: Pt;
690 + } | null>(null);
691 +
692 + const scenario = SCENARIO;
693 + const phase: Phase =
694 + step <= 2 ? "intent" : step >= 5 ? "active" : "authorizing";
695 + const working = phase !== "intent";
696 +
697 + const calc = useCallback(() => {
698 + const root = rootRef.current;
699 + const t = terminalRef.current;
700 + const a = authorizeRef.current;
701 + const c = connectionsRef.current;
702 + if (!root || !t || !a || !c) return;
703 + const cr = root.getBoundingClientRect();
704 + const rel = (r: DOMRect) => ({
705 + left: r.left - cr.left,
706 + right: r.right - cr.left,
707 + top: r.top - cr.top,
708 + bottom: r.bottom - cr.top,
709 + midX: r.left + r.width / 2 - cr.left,
710 + midY: r.top + r.height / 2 - cr.top,
711 + });
712 + const tr = rel(t.getBoundingClientRect());
713 + const ar = rel(a.getBoundingClientRect());
714 + const cc = rel(c.getBoundingClientRect());
715 + // terminal (top) drops down into the auth card; auth → connections is a
716 + // horizontal hop across the row below.
717 + // terminal header's left border → top of authorize
718 + const p1End: Pt = { x: ar.midX, y: ar.top };
719 + // bottom of authorize → left of connections. Drop the same vertical
720 + // distance as the top connector before entering the left edge, so both
721 + // connectors travel equally in Y (clamped inside the connections box).
722 + const topDrop = ar.top - (tr.top + 22);
723 + const p2End: Pt = {
724 + x: cc.right,
725 + y: Math.min(cc.bottom - 16, Math.max(cc.top + 16, ar.bottom + topDrop)),
726 + };
727 + setLink({
728 + p1: elbowHV({ x: tr.right, y: tr.top + 22 }, p1End),
729 + p1End,
730 + p2: elbowVH({ x: ar.midX, y: ar.bottom }, p2End),
731 + p2End,
732 + });
733 + }, []);
734 +
735 + useEffect(() => {
736 + const el = rootRef.current;
737 + if (!el) return;
738 + const io = new IntersectionObserver(
739 + ([e]) => e?.isIntersecting && setInView(true),
740 + { threshold: 0.3 },
741 + );
742 + io.observe(el);
743 + return () => io.disconnect();
744 + }, []);
745 +
746 + useEffect(() => {
747 + calc();
748 + const t = setTimeout(calc, 120);
749 + window.addEventListener("resize", calc);
750 + // Recompute whenever a panel resizes/reflows so the connectors keep up.
751 + const els = [
752 + rootRef.current,
753 + terminalRef.current,
754 + authorizeRef.current,
755 + connectionsRef.current,
756 + ].filter((el): el is HTMLDivElement => el != null);
757 + const ro = new ResizeObserver(() => calc());
758 + for (const el of els) ro.observe(el);
759 + return () => {
760 + clearTimeout(t);
761 + window.removeEventListener("resize", calc);
762 + ro.disconnect();
763 + };
764 + }, [calc]);
765 +
766 + // After each step change the panels resize/reflow (e.g. the auth box morphs
767 + // from skeleton to window). Re-measure every frame for ~0.7s so the
768 + // connectors follow the animating panel smoothly instead of glitching.
769 + useEffect(() => {
770 + let raf = 0;
771 + let start: number | null = null;
772 + const tick = (now: number) => {
773 + if (start == null) start = now;
774 + calc();
775 + if (now - start < 700) raf = requestAnimationFrame(tick);
776 + };
777 + raf = requestAnimationFrame(tick);
778 + return () => cancelAnimationFrame(raf);
779 + }, [step, calc]);
780 +
781 + // Step machine: the user message animates in right away (no typing), then the
782 + // transcript advances one message at a time.
783 + useEffect(() => {
784 + if (!inView) return;
785 + setStep(0);
786 + const ts = [
787 + setTimeout(() => setStep(1), 300),
788 + setTimeout(() => setStep(2), 1100),
789 + setTimeout(() => setStep(3), 2000),
790 + setTimeout(() => setStep(4), 2900),
791 + setTimeout(() => setStep(5), 3900),
792 + ];
793 + return () => ts.forEach(clearTimeout);
794 + }, [inView, runId]);
795 +
796 + const replay = () => setRunId((r) => r + 1);
797 +
798 + return (
799 + <div
800 + className="not-prose relative flex w-full flex-col gap-6 py-8 md:mr-auto md:block md:h-[550px] md:max-w-[760px] md:py-0"
801 + ref={rootRef}
802 + style={{ "--brand": "#51a2ff" } as React.CSSProperties}
803 + >
804 + {/* ── Connector overlay ── */}
805 + <svg
806 + aria-hidden="true"
807 + className="pointer-events-none absolute inset-0 z-0 hidden size-full overflow-visible text-[#51a2ff] md:block"
808 + fill="none"
809 + >
810 + <style>{`
811 + @keyframes mcDraw { to { stroke-dashoffset: 0; } }
812 + @media (prefers-reduced-motion: reduce) {
813 + .mc-draw { animation: none !important; stroke-dashoffset: 0; }
814 + }
815 + `}</style>
816 + {link && (
817 + <>
818 + {/* terminal → authorize */}
819 + {working && (
820 + <g key={`p1-${runId}`}>
821 + <path
822 + d={link.p1}
823 + opacity={0.1}
824 + stroke="currentColor"
825 + strokeWidth={1}
826 + />
827 + <path
828 + className="mc-draw"
829 + d={link.p1}
830 + stroke="currentColor"
831 + strokeDasharray="800"
832 + strokeDashoffset="800"
833 + strokeWidth={1.5}
834 + style={{ animation: "mcDraw 0.4s ease-out 0.15s forwards" }}
835 + />
836 + <circle
837 + cx={link.p1End.x}
838 + cy={link.p1End.y}
839 + fill="currentColor"
840 + opacity={0}
841 + r={2.5}
842 + >
843 + <animate
844 + attributeName="opacity"
845 + begin="0.5s"
846 + dur="0.2s"
847 + fill="freeze"
848 + from="0"
849 + to="0.45"
850 + />
851 + </circle>
852 + </g>
853 + )}
854 + {/* authorize → connections */}
855 + {step >= 4 && (
856 + <g key={`p2-${runId}`}>
857 + <path
858 + d={link.p2}
859 + opacity={0.1}
860 + stroke="currentColor"
861 + strokeWidth={1}
862 + />
863 + <path
864 + className="mc-draw"
865 + d={link.p2}
866 + stroke="currentColor"
867 + strokeDasharray="800"
868 + strokeDashoffset="800"
869 + strokeWidth={1.5}
870 + style={{ animation: "mcDraw 0.4s ease-out 0.05s forwards" }}
871 + />
872 + <circle
873 + cx={link.p2End.x}
874 + cy={link.p2End.y}
875 + fill="currentColor"
876 + opacity={0}
877 + r={2.5}
878 + >
879 + <animate
880 + attributeName="opacity"
881 + begin="0.3s"
882 + dur="0.2s"
883 + fill="freeze"
884 + from="0"
885 + to="0.45"
886 + />
887 + </circle>
888 + </g>
889 + )}
890 + </>
891 + )}
892 + </svg>
893 +
894 + {/* ── Terminal (same size as the search row) ── */}
895 + <div className="relative z-10 w-full max-w-md md:absolute md:top-0 md:left-0 md:w-[24rem] md:max-w-none">
896 + <div className="md:h-[350px]" ref={terminalRef}>
897 + <div className="h-full w-full">
898 + <TerminalWindow
899 + className="h-full"
900 + style={DARK_VARS}
901 + fill
902 + path="~/projects/composio"
903 + theme="claude"
904 + variant="dark"
905 + >
906 + <div className="flex flex-col gap-2.5">
907 + {step >= 1 && (
908 + <motion.div
909 + animate={{ opacity: 1, y: 0 }}
910 + initial={{ opacity: 0, y: 4 }}
911 + transition={{ duration: 0.25 }}
912 + >
913 + <Message>{scenario.intent}</Message>
914 + </motion.div>
915 + )}
916 + {step >= 2 && (
917 + <ToolCall
918 + name="COMPOSIO_MANAGE_CONNECTIONS"
919 + result="not connected — sent Connect Link"
920 + />
921 + )}
922 + {step >= 3 && (
923 + <AgentMessage
924 + footer={
925 + <a
926 + href="https://auth.composio.dev/connect/gmail?as=personal"
927 + target="_blank"
928 + rel="noreferrer"
929 + className="block min-w-0 truncate underline"
930 + style={{
931 + color: "var(--terminal-teal)",
932 + textUnderlineOffset: 2,
933 + }}
934 + >
935 + auth.composio.dev/connect/gmail?as=personal
936 + </a>
937 + }
938 + >
939 + Connect your personal Gmail to continue:
940 + </AgentMessage>
941 + )}
942 + {step >= 4 && (
943 + <ToolCall
944 + name="COMPOSIO_WAIT_FOR_CONNECTIONS"
945 + result={
946 + step >= 5
947 + ? "✓ personal connected"
948 + : "waiting for authorization…"
949 + }
950 + resultTone={step >= 5 ? "success" : "dim"}
951 + />
952 + )}
953 + {step >= 5 && (
954 + <ToolCall
955 + name="GMAIL_SEND_EMAIL"
956 + result="sent"
957 + resultTone="success"
958 + />
959 + )}
960 + </div>
961 + </TerminalWindow>
962 + </div>
963 + </div>
964 + <motion.button
965 + animate={{ opacity: phase === "active" ? 1 : 0 }}
966 + className="mt-3 flex items-center gap-1.5 font-mono text-[12px] text-white/40 transition-colors hover:text-white/75"
967 + initial={false}
968 + onClick={replay}
969 + style={{ pointerEvents: phase === "active" ? "auto" : "none" }}
970 + transition={{ duration: 0.3, delay: phase === "active" ? 0.6 : 0 }}
971 + type="button"
972 + >
973 + <svg
974 + aria-hidden="true"
975 + className="size-3"
976 + fill="none"
977 + stroke="currentColor"
978 + strokeLinecap="round"
979 + strokeLinejoin="round"
980 + strokeWidth={2}
981 + viewBox="0 0 24 24"
982 + >
983 + <path d="M21 12a9 9 0 1 1-2.64-6.36" />
984 + <path d="M21 3v6h-6" />
985 + </svg>
986 + replay
987 + </motion.button>
988 + </div>
989 +
990 + {/* ── Neon-style auth composition ── */}
991 + <div className="relative z-10 w-full md:pointer-events-none md:absolute md:inset-0">
992 + <ConnectionsComposition
993 + authorizeRef={authorizeRef}
994 + connectionsRef={connectionsRef}
995 + phase={phase}
996 + showConnections={step >= 4}
997 + step={step}
998 + />
999 + </div>
1000 + </div>
1001 + );
1002 +}
docs/components/media-split.tsx new
+20
@@ -0,0 +1,20 @@
1 +import type { ReactNode } from 'react';
2 +
3 +/**
4 + * Lays out its two children side-by-side (explanatory text + a visual/terminal)
5 + * once the screen is wide enough, stacking them on narrower viewports. Drop a
6 + * markdown paragraph and a component inside it in MDX:
7 + *
8 + * <MediaSplit>
9 + * Some explanatory copy…
10 + *
11 + * <InChatAuthTerminal … />
12 + * </MediaSplit>
13 + */
14 +export function MediaSplit({ children }: { children: ReactNode }) {
15 + return (
16 + <div className="mt-16 mb-6 grid items-start gap-6 lg:grid-cols-2 lg:gap-10 [&>*]:my-0 [&>*>:first-child]:mt-0">
17 + {children}
18 + </div>
19 + );
20 +}
docs/components/mermaid.tsx
+3
@@ -39,6 +39,9 @@ export function Mermaid({ chart }: { chart: string }) {
39
40 mermaid.initialize({
41 startOnLoad: false,
42 + // 'loose' enables node hyperlinks (the `click ... "url"` directive) and
43 + // image nodes in flowcharts. Diagrams here are all authored in-repo.
44 + securityLevel: 'loose',
45 theme: 'base',
46 themeVariables: {
47 background: bg,
docs/components/meta-tools/meta-tool-detail.tsx
+23 -11
@@ -136,7 +136,7 @@ function SchemaSection({ title, schema, showRequired = true }: { title: string;
136
137 return (
138 <div>
139 - <h3 className="text-base font-semibold text-fd-foreground mb-3">{title}</h3>
139 + <h2 className="text-base font-semibold text-fd-foreground mb-3">{title}</h2>
140 <div className="rounded-lg border border-fd-border bg-fd-card">
141 <div className="px-4">
142 <ParameterList parameters={properties} requiredFields={schema.required || []} showRequired={showRequired} />
@@ -150,19 +150,31 @@ export function MetaToolDetail({ tool }: { tool: MetaTool }) {
150 return (
151 <div className="space-y-6">
152 {/* Header */}
153 - <div>
154 - {tool.tags.length > 0 && (
155 - <div className="flex flex-wrap items-center gap-2 mb-3">
156 - {tool.tags.map((tag) => (
157 - <TagBadge key={tag} tag={tag} />
158 - ))}
159 - </div>
153 + <div className="space-y-3">
154 + <div className="flex flex-wrap items-center gap-2">
155 + <code className="text-sm font-mono text-fd-muted-foreground">{tool.slug}</code>
156 + {tool.tags.map((tag) => (
157 + <TagBadge key={tag} tag={tag} />
158 + ))}
159 + </div>
160 + {tool.summary && (
161 + <p className="text-base text-fd-foreground leading-relaxed">{tool.summary}</p>
162 )}
161 - <code className="text-sm font-mono text-fd-muted-foreground">{tool.slug}</code>
163 </div>
164
164 - {/* Input Parameters */}
165 - <SchemaSection title="Input Parameters" schema={tool.inputParameters} />
165 + {/* When to use it */}
166 + {tool.whenToUse && (
167 + <div className="rounded-lg border border-fd-border bg-fd-card p-4">
168 + <h2 className="text-base font-semibold text-fd-foreground mb-1.5">When to use it</h2>
169 + <p className="text-sm text-fd-muted-foreground leading-relaxed">{tool.whenToUse}</p>
170 + {tool.usageNote && (
171 + <p className="mt-2 text-sm text-fd-muted-foreground leading-relaxed">{tool.usageNote}</p>
172 + )}
173 + </div>
174 + )}
175 +
176 + {/* Input parameters */}
177 + <SchemaSection title="Input parameters" schema={tool.inputParameters} />
178
179 {/* Response */}
180 <SchemaSection title="Response" schema={tool.responseSchema} showRequired={false} />
docs/components/nav-tabs.tsx
+1 -1
@@ -5,8 +5,8 @@ import { usePathname } from 'next/navigation';
5
6 const tabs = [
7 { href: '/docs', label: 'Docs', exact: true },
8 + { href: '/examples', label: 'Examples' },
9 { href: '/docs/api', label: 'API' },
9 - { href: '/cookbooks', label: 'Cookbooks' },
10 ];
11
12 export function NavTabs() {
docs/components/quickstart/integration-tabs.tsx
+2 -2
@@ -81,8 +81,8 @@ function PortaledTabsHeader({ tabs }: { tabs: TabConfig[] }) {
81 <div className="mt-4 border-t border-fd-border pt-4">
82 <p className="mb-3 max-w-2xl text-sm text-fd-muted-foreground">
83 If your framework has good native tool-calling support, we recommend native tools. The remote MCP URL is always available too.{' '}
84 - <Link href="/docs/native-tools-vs-mcp" className="text-fd-muted-foreground hover:text-fd-foreground transition-colors underline underline-offset-2">
85 - Learn the differences
84 + <Link href="/docs/sessions-via-mcp" className="text-fd-muted-foreground hover:text-fd-foreground transition-colors underline underline-offset-2">
85 + Using sessions via MCP
86 </Link>
87 .
88 </p>
docs/components/related-links.tsx new
+38
@@ -0,0 +1,38 @@
1 +import Link from 'next/link';
2 +
3 +export interface RelatedLink {
4 + title: string;
5 + href: string;
6 + description?: string;
7 +}
8 +
9 +/**
10 + * RelatedLinks — renders in the right-hand table-of-contents rail (via the
11 + * DocsPage `tableOfContent.footer` slot) when a page declares `related` links
12 + * in its frontmatter. Keeps "see also" pointers out of the main content flow.
13 + */
14 +export function RelatedLinks({ items }: { items: RelatedLink[] }) {
15 + if (!items?.length) return null;
16 +
17 + return (
18 + <div className="flex flex-col gap-2.5 border-t border-fd-border pt-4">
19 + <p className="font-mono text-[11px] font-medium uppercase tracking-wide text-fd-muted-foreground">
20 + Related
21 + </p>
22 + <ul className="flex flex-col gap-3">
23 + {items.map((item) => (
24 + <li key={item.href}>
25 + <Link href={item.href} className="group flex flex-col gap-0.5">
26 + <span className="text-sm font-medium text-fd-foreground transition-colors group-hover:text-fd-primary">
27 + {item.title}
28 + </span>
29 + {item.description && (
30 + <span className="text-xs leading-snug text-fd-muted-foreground">{item.description}</span>
31 + )}
32 + </Link>
33 + </li>
34 + ))}
35 + </ul>
36 + </div>
37 + );
38 +}
docs/components/repo-browser-client.tsx new
+43
@@ -0,0 +1,43 @@
1 +'use client';
2 +
3 +import { FileTree, useFileTree, useFileTreeSelection } from '@pierre/trees/react';
4 +import { File } from '@pierre/diffs/react';
5 +import { CopyButton } from './copy-button';
6 +
7 +export interface RepoFile {
8 + path: string;
9 + contents: string;
10 + composio: boolean;
11 + prerenderedHTML: string;
12 +}
13 +
14 +/**
15 + * RepoBrowserClient — the IDE-style split: file tree on the left (@pierre/trees),
16 + * the selected file's code on the right (@pierre/diffs). Code is prerendered on
17 + * the server so the first paint is correct; selection swaps which file shows.
18 + */
19 +export function RepoBrowserClient({ files }: { files: RepoFile[] }) {
20 + const paths = files.map((f) => f.path);
21 + const { model } = useFileTree({ paths, initialSelectedPaths: [paths[0]], initialExpansion: 'open' });
22 + const selected = useFileTreeSelection(model);
23 +
24 + const path = selected.find((p) => files.some((f) => f.path === p)) ?? paths[0];
25 + const file = files.find((f) => f.path === path) ?? files[0];
26 +
27 + return (
28 + <div className="grid grid-cols-1 overflow-hidden rounded-sm border border-fd-border bg-fd-card md:grid-cols-[minmax(0,260px)_minmax(0,1fr)]">
29 + <div className="max-h-[640px] overflow-auto border-b border-fd-border p-2 md:border-b-0 md:border-r">
30 + <FileTree model={model} />
31 + </div>
32 + <div className="relative max-h-[640px] overflow-auto">
33 + <CopyButton text={file.contents} className="absolute right-2 top-2 z-10" />
34 + <File
35 + key={file.path}
36 + file={{ name: file.path, contents: file.contents }}
37 + prerenderedHTML={file.prerenderedHTML}
38 + disableWorkerPool
39 + />
40 + </div>
41 + </div>
42 + );
43 +}
docs/components/repo-browser.tsx new
+56
@@ -0,0 +1,56 @@
1 +import { preloadFile } from '@pierre/diffs/ssr';
2 +import { RepoBrowserClient, type RepoFile } from './repo-browser-client';
3 +import slackBot from '@/lib/slack-bot-source.json';
4 +import localWorkbench from '@/lib/local-workbench-source.json';
5 +import standup from '@/lib/standup-bot-source.json';
6 +
7 +interface SourceFile {
8 + path: string;
9 + contents: string;
10 + composio: boolean;
11 +}
12 +
13 +// JSON imports must be static, so map each example's committed snapshot here and
14 +// pick one with the `source` prop. The default keeps the Slack bot page working.
15 +const SOURCES = {
16 + 'slack-bot': slackBot,
17 + 'local-workbench': localWorkbench,
18 + standup,
19 +} as const;
20 +
21 +/**
22 + * RepoBrowser — a real slice of an example project as a browsable tree + code
23 + * viewer. The Composio touch-points are highlighted; each file's code is
24 + * prerendered on the server with @pierre/diffs.
25 + *
26 + * `source` selects which example's snapshot to show (default: the slack-bot /
27 + * Pi example, so existing pages are unaffected). Pass `caption={null}` to hide
28 + * the little caption above the tree.
29 + */
30 +export async function RepoBrowser({
31 + source = 'slack-bot',
32 + caption = 'a slice of the real project, the Composio files do the work',
33 +}: {
34 + source?: keyof typeof SOURCES;
35 + caption?: string | null;
36 +}) {
37 + const data = SOURCES[source] as SourceFile[];
38 +
39 + const files: RepoFile[] = [];
40 + for (const f of data) {
41 + const { prerenderedHTML } = await preloadFile({ file: { name: f.path, contents: f.contents } });
42 + files.push({ ...f, prerenderedHTML });
43 + }
44 +
45 + return (
46 + <div className="not-prose my-6">
47 + {caption ? (
48 + <div className="mb-2 flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
49 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" aria-hidden="true" />
50 + {caption}
51 + </div>
52 + ) : null}
53 + <RepoBrowserClient files={files} />
54 + </div>
55 + );
56 +}
docs/components/session-flow.tsx new
+244
@@ -0,0 +1,244 @@
1 +import { Check, Search, Plug, Terminal, Zap } from 'lucide-react';
2 +import type { ReactNode } from 'react';
3 +
4 +const LOGO_CDN = 'https://logos.composio.dev/api';
5 +
6 +const CONNECTED_APPS: { slug: string; name: string }[] = [
7 + { slug: 'gmail', name: 'Gmail' },
8 + { slug: 'github', name: 'GitHub' },
9 + { slug: 'slack', name: 'Slack' },
10 +];
11 +
12 +const META_TOOLS: { icon: ReactNode; label: string; verb: string }[] = [
13 + { icon: <Search className="size-3" aria-hidden="true" />, label: 'Search tools', verb: 'discover' },
14 + { icon: <Plug className="size-3" aria-hidden="true" />, label: 'Manage connections', verb: 'authenticate' },
15 + { icon: <Zap className="size-3" aria-hidden="true" />, label: 'Execute tool', verb: 'act' },
16 + { icon: <Terminal className="size-3" aria-hidden="true" />, label: 'Sandbox', verb: 'compute' },
17 +];
18 +
19 +/**
20 + * SessionFlow — branded replacement for the plain `agent → session → meta tools`
21 + * mermaid diagram on the "What is a session?" docs page.
22 + *
23 + * Reads left-to-right as a story: your agent acts for a user; the session is the
24 + * brand-accented runtime context that binds that user's connected accounts + auth
25 + * and exposes meta tools the agent calls to discover, authenticate, and execute.
26 + *
27 + * The centerpiece is the Session card, which surfaces the *user and their
28 + * connected accounts* — the part the old mermaid diagram never showed.
29 + * Server component, no client JS. Adapts to light/dark via fd-* tokens.
30 + */
31 +export function SessionFlow() {
32 + return (
33 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
34 + {/* header strip — mono, matches the home-feature visuals */}
35 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
36 + <span>session.runtime</span>
37 + <span className="inline-flex items-center gap-1.5 text-fd-foreground/55">
38 + <span className="relative inline-flex">
39 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" />
40 + <span className="absolute inset-0 animate-ping rounded-full bg-[var(--composio-brand)] opacity-60" />
41 + </span>
42 + scoped to user
43 + </span>
44 + </div>
45 +
46 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-[minmax(0,0.85fr)_minmax(0,1.3fr)_minmax(0,1.05fr)]">
47 + {/* ── Your agent ─────────────────────────────────────────── */}
48 + <Column>
49 + <Lane label="Your agent" />
50 + <div className="flex flex-1 items-center">
51 + <div className="w-full border border-fd-border bg-fd-card p-3">
52 + <div className="flex items-center gap-2">
53 + <span className="flex size-7 items-center justify-center rounded-sm bg-fd-foreground/[0.06] font-mono text-[13px] text-fd-foreground/70">
54 + {'{ }'}
55 + </span>
56 + <div className="min-w-0">
57 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
58 + AI agent
59 + </div>
60 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
61 + acts for one user
62 + </div>
63 + </div>
64 + </div>
65 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/55">
66 + Calls the session&apos;s meta tools instead of loading hundreds of
67 + tool definitions.
68 + </p>
69 + </div>
70 + </div>
71 + <Connector />
72 + </Column>
73 +
74 + {/* ── Session (the hub) ──────────────────────────────────── */}
75 + <Column>
76 + <Lane label="Session" accent />
77 + <div className="flex flex-1 flex-col">
78 + <div className="relative flex-1 border border-[var(--composio-brand)]/30 bg-[var(--composio-brand)]/[0.04] p-3">
79 + <span
80 + aria-hidden="true"
81 + className="pointer-events-none absolute inset-y-0 left-0 w-[2px] bg-[var(--composio-brand)]"
82 + />
83 + <div className="flex items-center justify-between">
84 + <span className="font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--composio-brand)]">
85 + runtime context
86 + </span>
87 + <span className="font-mono text-[10px] text-fd-foreground/45">
88 + usr_9x2kLm7
89 + </span>
90 + </div>
91 +
92 + {/* The user + their connected accounts — the missing piece */}
93 + <div className="mt-2.5 overflow-hidden rounded-sm border border-fd-border bg-fd-card">
94 + <div className="flex items-center gap-2 border-b border-fd-border px-2.5 py-1.5">
95 + <span className="flex size-5 items-center justify-center rounded-full bg-[var(--composio-brand)]/12 font-mono text-[10px] font-medium text-[var(--composio-brand)]">
96 + U
97 + </span>
98 + <span className="text-[11px] font-medium text-fd-foreground">
99 + Your user
100 + </span>
101 + <span className="ml-auto font-mono text-[9px] uppercase tracking-[0.05em] text-fd-foreground/40">
102 + connected accounts
103 + </span>
104 + </div>
105 + <ul className="flex flex-col">
106 + {CONNECTED_APPS.map((app, i) => (
107 + <li
108 + key={app.slug}
109 + className={
110 + 'flex items-center gap-2 px-2.5 py-1.5' +
111 + (i < CONNECTED_APPS.length - 1
112 + ? ' border-b border-fd-border'
113 + : '')
114 + }
115 + >
116 + <img
117 + alt=""
118 + aria-hidden="true"
119 + className="size-3.5 object-contain"
120 + draggable={false}
121 + src={`${LOGO_CDN}/${app.slug}`}
122 + />
123 + <span className="text-[11px] text-fd-foreground/75">
124 + {app.name}
125 + </span>
126 + <span className="ml-auto inline-flex items-center gap-1 font-mono text-[9px] uppercase tracking-[0.05em] text-[var(--composio-brand)]">
127 + <Check aria-hidden="true" className="size-2.5" />
128 + linked
129 + </span>
130 + </li>
131 + ))}
132 + </ul>
133 + </div>
134 +
135 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/60">
136 + Ties the user, toolkits, auth, and connected accounts into one
137 + scoped environment.
138 + </p>
139 + </div>
140 + </div>
141 + <Connector accent />
142 + </Column>
143 +
144 + {/* ── Meta tools ─────────────────────────────────────────── */}
145 + <Column>
146 + <Lane label="Meta tools" />
147 + <div className="flex flex-1 items-stretch">
148 + <ul className="grid w-full grid-cols-2 gap-1.5 md:grid-cols-1">
149 + {META_TOOLS.map((tool) => (
150 + <li
151 + key={tool.label}
152 + className="flex items-center gap-2 border border-fd-border bg-fd-card px-2.5 py-1.5"
153 + >
154 + <span className="flex size-5 shrink-0 items-center justify-center rounded-sm bg-[var(--composio-brand)]/10 text-[var(--composio-brand)]">
155 + {tool.icon}
156 + </span>
157 + <span className="min-w-0">
158 + <span className="block truncate text-[11px] font-medium leading-tight text-fd-foreground">
159 + {tool.label}
160 + </span>
161 + <span className="block truncate font-mono text-[9px] uppercase tracking-[0.05em] text-fd-foreground/40">
162 + {tool.verb}
163 + </span>
164 + </span>
165 + </li>
166 + ))}
167 + </ul>
168 + </div>
169 + </Column>
170 + </div>
171 +
172 + {/* footer caption */}
173 + <div className="border-t border-fd-border px-3 py-2 text-center font-mono text-[10px] text-fd-foreground/45">
174 + agent <Arrow /> session (user + auth + connections) <Arrow /> discover,
175 + authenticate, execute
176 + </div>
177 + </div>
178 + );
179 +}
180 +
181 +function Column({ children }: { children: ReactNode }) {
182 + return (
183 + <div className="relative flex flex-col gap-2 bg-fd-background p-3">
184 + {children}
185 + </div>
186 + );
187 +}
188 +
189 +function Lane({ label, accent = false }: { label: string; accent?: boolean }) {
190 + return (
191 + <div className="flex items-center gap-1.5">
192 + <span
193 + className={
194 + 'size-1.5 rounded-full ' +
195 + (accent ? 'bg-[var(--composio-brand)]' : 'bg-fd-foreground/30')
196 + }
197 + aria-hidden="true"
198 + />
199 + <span
200 + className={
201 + 'font-mono text-[10px] font-medium uppercase tracking-[0.07em] ' +
202 + (accent ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/55')
203 + }
204 + >
205 + {label}
206 + </span>
207 + </div>
208 + );
209 +}
210 +
211 +/**
212 + * Directional connector shown between columns. Horizontal arrow on desktop,
213 + * vertical on stacked mobile so the flow still reads top-to-bottom.
214 + */
215 +function Connector({ accent = false }: { accent?: boolean }) {
216 + const color = accent ? 'bg-[var(--composio-brand)]/40' : 'bg-fd-border';
217 + const tip = accent
218 + ? 'border-l-[var(--composio-brand)]/50'
219 + : 'border-l-fd-border';
220 + return (
221 + <div
222 + aria-hidden="true"
223 + className="pointer-events-none absolute z-10 hidden md:block"
224 + style={{ right: '-7px', top: '50%' }}
225 + >
226 + <div className="flex items-center">
227 + <span className={'h-px w-3 ' + color} />
228 + <span
229 + className={
230 + 'size-0 border-y-[3px] border-l-[5px] border-y-transparent ' + tip
231 + }
232 + />
233 + </div>
234 + </div>
235 + );
236 +}
237 +
238 +function Arrow() {
239 + return (
240 + <span aria-hidden="true" className="text-[var(--composio-brand)]">
241 + {'→'}
242 + </span>
243 + );
244 +}
docs/components/slack-bot-flow.tsx new
+222
@@ -0,0 +1,222 @@
1 +import { Check, Share2 } from 'lucide-react';
2 +import type { ReactNode } from 'react';
3 +
4 +const LOGO_CDN = 'https://logos.composio.dev/api';
5 +
6 +const CONNECTIONS: { slug: string; name: string; owner: string; shared?: boolean }[] = [
7 + { slug: 'slack', name: 'Slack', owner: 'workspace bot', shared: true },
8 + { slug: 'github', name: 'GitHub', owner: 'Alice' },
9 + { slug: 'gmail', name: 'Gmail', owner: 'Alice' },
10 +];
11 +
12 +/**
13 + * SlackBotFlow — branded replacement for the plain `slack → server → agent`
14 + * mermaid diagram on the Slack bot example page.
15 + *
16 + * Reads left-to-right as the request loop: a Slack message arrives as a trigger
17 + * webhook, your server hands it to the Pi agent, and the agent works through a
18 + * per-user session that pins one shared workspace Slack connection alongside the
19 + * user's own connected apps. The reply flows back to Slack as the bot.
20 + *
21 + * Server component, no client JS. Adapts to light/dark via fd-* tokens.
22 + */
23 +export function SlackBotFlow() {
24 + return (
25 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
26 + {/* header strip — mono, matches the other branded flow visuals */}
27 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
28 + <span>slackbot.runtime</span>
29 + <span className="inline-flex items-center gap-1.5 text-fd-foreground/55">
30 + <span className="relative inline-flex">
31 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" />
32 + <span className="absolute inset-0 animate-ping rounded-full bg-[var(--composio-brand)] opacity-60" />
33 + </span>
34 + listening in Slack
35 + </span>
36 + </div>
37 +
38 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-[minmax(0,0.9fr)_minmax(0,0.95fr)_minmax(0,1.3fr)]">
39 + {/* ── Slack ──────────────────────────────────────────────── */}
40 + <Column>
41 + <Lane label="Slack" />
42 + <div className="flex flex-1 items-center">
43 + <div className="w-full border border-fd-border bg-fd-card p-3">
44 + <div className="flex items-center gap-2">
45 + <img
46 + alt=""
47 + aria-hidden="true"
48 + className="size-7 rounded-sm object-contain p-0.5"
49 + draggable={false}
50 + src={`${LOGO_CDN}/slack`}
51 + />
52 + <div className="min-w-0">
53 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
54 + Message
55 + </div>
56 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
57 + @mention or DM
58 + </div>
59 + </div>
60 + </div>
61 + <p className="mt-2.5 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.05em] text-[var(--composio-brand)]">
62 + trigger <Arrow /> webhook
63 + </p>
64 + </div>
65 + </div>
66 + <Connector />
67 + </Column>
68 +
69 + {/* ── Your server / agent ────────────────────────────────── */}
70 + <Column>
71 + <Lane label="Your server" />
72 + <div className="flex flex-1 items-center">
73 + <div className="w-full border border-fd-border bg-fd-card p-3">
74 + <div className="flex items-center gap-2">
75 + <span className="flex size-7 items-center justify-center rounded-sm bg-fd-foreground/[0.06] font-mono text-[13px] text-fd-foreground/70">
76 + {'{ }'}
77 + </span>
78 + <div className="min-w-0">
79 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
80 + Pi agent
81 + </div>
82 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
83 + verifies + loops
84 + </div>
85 + </div>
86 + </div>
87 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/55">
88 + Verifies the webhook signature, then calls the session&apos;s tools.
89 + </p>
90 + </div>
91 + </div>
92 + <Connector accent />
93 + </Column>
94 +
95 + {/* ── Session (the hub) ──────────────────────────────────── */}
96 + <Column>
97 + <Lane label="Session" accent />
98 + <div className="flex flex-1 flex-col">
99 + <div className="relative flex-1 border border-[var(--composio-brand)]/30 bg-[var(--composio-brand)]/[0.04] p-3">
100 + <span
101 + aria-hidden="true"
102 + className="pointer-events-none absolute inset-y-0 left-0 w-[2px] bg-[var(--composio-brand)]"
103 + />
104 + <div className="flex items-center justify-between">
105 + <span className="font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--composio-brand)]">
106 + scoped to user
107 + </span>
108 + <span className="font-mono text-[10px] text-fd-foreground/45">
109 + slack:T09:alice
110 + </span>
111 + </div>
112 +
113 + {/* The shared workspace connection + the user's own apps */}
114 + <ul className="mt-2.5 overflow-hidden rounded-sm border border-fd-border bg-fd-card">
115 + {CONNECTIONS.map((conn, i) => (
116 + <li
117 + key={conn.slug}
118 + className={
119 + 'flex items-center gap-2 px-2.5 py-1.5' +
120 + (i < CONNECTIONS.length - 1 ? ' border-b border-fd-border' : '')
121 + }
122 + >
123 + <img
124 + alt=""
125 + aria-hidden="true"
126 + className="size-3.5 object-contain"
127 + draggable={false}
128 + src={`${LOGO_CDN}/${conn.slug}`}
129 + />
130 + <span className="text-[11px] text-fd-foreground/75">{conn.name}</span>
131 + <span className="font-mono text-[9px] text-fd-foreground/40">{conn.owner}</span>
132 + <span
133 + className={
134 + 'ml-auto inline-flex items-center gap-1 font-mono text-[9px] uppercase tracking-[0.05em] ' +
135 + (conn.shared ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/45')
136 + }
137 + >
138 + {conn.shared ? (
139 + <>
140 + <Share2 aria-hidden="true" className="size-2.5" />
141 + shared
142 + </>
143 + ) : (
144 + <>
145 + <Check aria-hidden="true" className="size-2.5" />
146 + linked
147 + </>
148 + )}
149 + </span>
150 + </li>
151 + ))}
152 + </ul>
153 +
154 + <p className="mt-2.5 text-[11px] leading-snug text-fd-foreground/60">
155 + Posts to Slack as the workspace bot; acts in every other app as the
156 + user.
157 + </p>
158 + </div>
159 + </div>
160 + </Column>
161 + </div>
162 +
163 + {/* footer caption */}
164 + <div className="border-t border-fd-border px-3 py-2 text-center font-mono text-[10px] text-fd-foreground/45">
165 + message <Arrow /> trigger <Arrow /> agent <Arrow /> session (shared slack +
166 + user apps) <Arrow /> reply
167 + </div>
168 + </div>
169 + );
170 +}
171 +
172 +function Column({ children }: { children: ReactNode }) {
173 + return <div className="relative flex flex-col gap-2 bg-fd-background p-3">{children}</div>;
174 +}
175 +
176 +function Lane({ label, accent = false }: { label: string; accent?: boolean }) {
177 + return (
178 + <div className="flex items-center gap-1.5">
179 + <span
180 + className={'size-1.5 rounded-full ' + (accent ? 'bg-[var(--composio-brand)]' : 'bg-fd-foreground/30')}
181 + aria-hidden="true"
182 + />
183 + <span
184 + className={
185 + 'font-mono text-[10px] font-medium uppercase tracking-[0.07em] ' +
186 + (accent ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/55')
187 + }
188 + >
189 + {label}
190 + </span>
191 + </div>
192 + );
193 +}
194 +
195 +/**
196 + * Directional connector shown between columns. Horizontal arrow on desktop,
197 + * vertical on stacked mobile so the flow still reads top-to-bottom.
198 + */
199 +function Connector({ accent = false }: { accent?: boolean }) {
200 + const color = accent ? 'bg-[var(--composio-brand)]/40' : 'bg-fd-border';
201 + const tip = accent ? 'border-l-[var(--composio-brand)]/50' : 'border-l-fd-border';
202 + return (
203 + <div
204 + aria-hidden="true"
205 + className="pointer-events-none absolute z-10 hidden md:block"
206 + style={{ right: '-7px', top: '50%' }}
207 + >
208 + <div className="flex items-center">
209 + <span className={'h-px w-3 ' + color} />
210 + <span className={'size-0 border-y-[3px] border-l-[5px] border-y-transparent ' + tip} />
211 + </div>
212 + </div>
213 + );
214 +}
215 +
216 +function Arrow() {
217 + return (
218 + <span aria-hidden="true" className="text-[var(--composio-brand)]">
219 + {'→'}
220 + </span>
221 + );
222 +}
docs/components/standup-example.tsx new
+20
@@ -0,0 +1,20 @@
1 +// Inline app logos used in the daily-standup-bot example page intro.
2 +
3 +const LOGO_CDN = 'https://logos.composio.dev/api';
4 +
5 +/** A small inline app logo (e.g. <AppLogo slug="github" />) from the Composio
6 + * logo CDN, sized to fit the text line. The CDN serves fixed-colour SVGs, so
7 + * pass `invert` for monochrome marks (GitHub) that would vanish on the dark
8 + * theme; leave full-colour logos (Slack) bare. */
9 +export function AppLogo({ slug, alt, invert }: { slug: string; alt?: string; invert?: boolean }) {
10 + return (
11 + <img
12 + src={`${LOGO_CDN}/${slug}`}
13 + alt={alt ?? slug}
14 + width={16}
15 + height={16}
16 + className={invert ? 'inline-block dark:invert' : 'inline-block'}
17 + style={{ height: '1em', width: '1em', verticalAlign: '-0.18em', margin: '0 0.12em' }}
18 + />
19 + );
20 +}
docs/components/terminal-kit/index.ts new
+4
@@ -0,0 +1,4 @@
1 +export * from "./shell"
2 +export * from "./session"
3 +export * from "./input"
4 +export * from "./ui"
docs/components/terminal-kit/input/index.ts new
+1
@@ -0,0 +1 @@
1 +export * from "./input"
docs/components/terminal-kit/input/input.tsx new
+306
@@ -0,0 +1,306 @@
1 +"use client"
2 +
3 +import { IconBolt as Zap } from "nucleo-pixel"
4 +import * as React from "react"
5 +
6 +import { useResolvedTerminalTheme } from "@/hooks/use-resolved-terminal-theme"
7 +import { cn } from "@/lib/utils"
8 +
9 +/** Default composer meta — lightning level indicator (e.g. max). */
10 +export function InputLevelMeta({ children = "max" }: { children?: React.ReactNode }) {
11 + return (
12 + <span className="inline-flex items-center gap-1">
13 + <Zap className="size-3 shrink-0" aria-hidden />
14 + {children}
15 + </span>
16 + )
17 +}
18 +
19 +export type InputProps = {
20 + value?: string
21 + defaultValue?: string
22 + onValueChange?: (value: string) => void
23 + onSubmit?: (value: string) => void
24 + prompt?: string
25 + status?: React.ReactNode
26 + /** Footer hint on the left — composer (default) and Claude stacked layouts. */
27 + metaLeft?: React.ReactNode
28 + /** Footer hint on the right — composer (default) and Claude stacked layouts. */
29 + metaRight?: React.ReactNode
30 + placeholder?: string
31 + disabled?: boolean
32 + /** Keep the blinking cursor visible even when unfocused. */
33 + showCursor?: boolean
34 + /**
35 + * `auto` — composer on default, inline box on grok, stacked lines on Claude.
36 + * `inline` — status on the right in a bordered box. `stacked` — always stacked.
37 + */
38 + layout?: "auto" | "inline" | "stacked"
39 + className?: string
40 +}
41 +
42 +function refocusTextarea(textarea: HTMLTextAreaElement | null) {
43 + if (!textarea) return
44 + textarea.focus()
45 + requestAnimationFrame(() => {
46 + textarea.focus()
47 + requestAnimationFrame(() => textarea.focus())
48 + })
49 +}
50 +
51 +export const Input = React.forwardRef<HTMLTextAreaElement, InputProps>(function Input(
52 + {
53 + value,
54 + defaultValue = "",
55 + onValueChange,
56 + onSubmit,
57 + prompt,
58 + status,
59 + metaLeft,
60 + metaRight,
61 + placeholder,
62 + disabled = false,
63 + showCursor = false,
64 + layout = "auto",
65 + className,
66 + },
67 + ref
68 +) {
69 + const [internalValue, setInternalValue] = React.useState(defaultValue)
70 + const [focused, setFocused] = React.useState(false)
71 + const [caretLeft, setCaretLeft] = React.useState(0)
72 + const textareaRef = React.useRef<HTMLTextAreaElement>(null)
73 + const mirrorRef = React.useRef<HTMLSpanElement>(null)
74 + const { ref: themeRef, isClaude, isBubble } = useResolvedTerminalTheme()
75 + const currentValue = value ?? internalValue
76 +
77 + const stacked = layout === "stacked" || (layout === "auto" && isClaude)
78 + const composer = layout === "auto" && isBubble
79 + const inline = !stacked && !composer
80 + const resolvedPrompt = prompt ?? "❯"
81 + const footerRight = metaRight ?? (stacked ? status : undefined)
82 + const showComposerMeta =
83 + composer && (metaLeft != null || metaRight != null || status != null)
84 + const showStackedFooter = stacked && (metaLeft != null || footerRight != null)
85 + const textColor = stacked ? "var(--terminal-fg)" : "var(--terminal-white)"
86 + const promptColor = "var(--terminal-teal)"
87 + const cursorColor = stacked ? "var(--terminal-fg)" : "var(--terminal-progress-fill)"
88 + const fieldLineHeight = stacked ? 18 : 16
89 + const cursorHeight = stacked ? 13 : 12
90 +
91 + React.useImperativeHandle(ref, () => textareaRef.current as HTMLTextAreaElement)
92 +
93 + const syncCaretPosition = React.useCallback(() => {
94 + const textarea = textareaRef.current
95 + const mirror = mirrorRef.current
96 + if (!textarea || !mirror) return
97 +
98 + const selectionStart = textarea.selectionStart ?? currentValue.length
99 + mirror.textContent = currentValue.slice(0, selectionStart) || "\u200b"
100 + setCaretLeft(mirror.offsetWidth)
101 + }, [currentValue])
102 +
103 + React.useLayoutEffect(() => {
104 + syncCaretPosition()
105 + }, [syncCaretPosition])
106 +
107 + const handleChange = (next: string) => {
108 + if (value === undefined) setInternalValue(next)
109 + onValueChange?.(next)
110 + }
111 +
112 + const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
113 + if (event.key === "Enter" && !event.shiftKey) {
114 + event.preventDefault()
115 + if (!currentValue.trim() || disabled) return
116 + onSubmit?.(currentValue)
117 + refocusTextarea(textareaRef.current)
118 + }
119 + }
120 +
121 + const field = (
122 + <div
123 + className={cn(
124 + "flex min-w-0 flex-1 items-center gap-2 overflow-hidden",
125 + stacked ? "gap-2.5" : undefined
126 + )}
127 + style={{ color: textColor }}
128 + >
129 + <span
130 + aria-hidden
131 + className="inline-flex shrink-0 items-center"
132 + style={{
133 + color: promptColor,
134 + fontSize: 9,
135 + lineHeight: `${fieldLineHeight}px`,
136 + }}
137 + >
138 + {resolvedPrompt}
139 + </span>
140 + <span
141 + className="relative flex min-w-0 flex-1 items-center overflow-hidden"
142 + style={{ lineHeight: `${fieldLineHeight}px`, minHeight: fieldLineHeight }}
143 + >
144 + <span
145 + ref={mirrorRef}
146 + aria-hidden
147 + className="pointer-events-none invisible absolute top-0 left-0 whitespace-pre text-[11px] leading-4"
148 + />
149 + <textarea
150 + ref={textareaRef}
151 + value={currentValue}
152 + onChange={(event) => handleChange(event.target.value)}
153 + onKeyDown={handleKeyDown}
154 + onKeyUp={syncCaretPosition}
155 + onSelect={syncCaretPosition}
156 + onClick={syncCaretPosition}
157 + onFocus={() => {
158 + setFocused(true)
159 + syncCaretPosition()
160 + }}
161 + onBlur={() => setFocused(false)}
162 + placeholder={placeholder}
163 + disabled={disabled}
164 + rows={1}
165 + spellCheck={false}
166 + className={cn(
167 + "terminal-input-control block w-full resize-none overflow-hidden border-0 bg-transparent p-0 font-inherit text-[11px] leading-4 caret-transparent outline-none"
168 + )}
169 + style={{
170 + color: textColor,
171 + minHeight: fieldLineHeight,
172 + maxHeight: fieldLineHeight,
173 + }}
174 + />
175 + {!disabled && (focused || showCursor) ? (
176 + <span
177 + aria-hidden
178 + className="terminal-cursor pointer-events-none absolute top-1/2 inline-block w-[0.55em] shrink-0 -translate-y-1/2"
179 + style={{
180 + left: caretLeft,
181 + height: cursorHeight,
182 + backgroundColor: cursorColor,
183 + }}
184 + />
185 + ) : null}
186 + </span>
187 + {inline && status ? (
188 + <div
189 + className="shrink-0 whitespace-nowrap text-[11px]"
190 + style={{ color: "var(--terminal-dim)" }}
191 + >
192 + {status}
193 + </div>
194 + ) : null}
195 + </div>
196 + )
197 +
198 + const fieldShell = (
199 + <div
200 + className={cn(
201 + "terminal-input-field flex items-center",
202 + stacked && "terminal-input-field--stacked px-0",
203 + composer && "terminal-input-field--composer terminal-panel gap-3 border px-3 py-2.5 sm:px-4",
204 + inline && "gap-3 rounded border px-3 py-2 sm:px-4"
205 + )}
206 + style={
207 + stacked
208 + ? undefined
209 + : {
210 + borderColor: "var(--terminal-border)",
211 + backgroundColor: "var(--terminal-input-bg)",
212 + }
213 + }
214 + >
215 + {field}
216 + </div>
217 + )
218 +
219 + return (
220 + <div
221 + ref={themeRef}
222 + className={cn("terminal-input w-full text-[11px]", className)}
223 + onClick={() => textareaRef.current?.focus()}
224 + >
225 + {composer ? (
226 + <div className="terminal-input-composer">
227 + {fieldShell}
228 + {showComposerMeta ? (
229 + <div className="terminal-input-meta-layer flex items-center justify-between gap-2">
230 + <span className="min-w-0 truncate">{metaLeft}</span>
231 + <span className="flex shrink-0 items-center gap-2 whitespace-nowrap">
232 + {metaRight}
233 + {status}
234 + </span>
235 + </div>
236 + ) : null}
237 + </div>
238 + ) : (
239 + <>
240 + {fieldShell}
241 + {showStackedFooter ? (
242 + <div
243 + className="terminal-input-meta mt-1.5 flex items-center justify-between gap-3 text-[11px] leading-4"
244 + style={{ color: "var(--terminal-dim)" }}
245 + >
246 + <span className="min-w-0 truncate">{metaLeft}</span>
247 + <span className="shrink-0 whitespace-nowrap">{footerRight}</span>
248 + </div>
249 + ) : null}
250 + </>
251 + )}
252 + </div>
253 + )
254 +})
255 +
256 +/** @deprecated Use Input */
257 +export type ShellInputProps = InputProps
258 +
259 +/** @deprecated Use Input */
260 +export const ShellInput = React.forwardRef<HTMLTextAreaElement, InputProps>(
261 + function ShellInput(props, ref) {
262 + return <Input {...props} ref={ref} />
263 + }
264 +)
265 +
266 +export type CommandSuggestProps = {
267 + commands: string[]
268 + activeIndex?: number
269 + onSelect?: (command: string) => void
270 + className?: string
271 +}
272 +
273 +export function CommandSuggest({
274 + commands,
275 + activeIndex = 0,
276 + onSelect,
277 + className,
278 +}: CommandSuggestProps) {
279 + return (
280 + <div
281 + className={cn("terminal-panel overflow-hidden border font-mono text-xs", className)}
282 + style={{
283 + borderColor: "var(--terminal-border)",
284 + backgroundColor: "var(--terminal-popover)",
285 + }}
286 + >
287 + {commands.map((command, index) => (
288 + <button
289 + key={command}
290 + type="button"
291 + onClick={() => onSelect?.(command)}
292 + className="flex w-full items-center px-3 py-1.5 text-left"
293 + style={{
294 + color:
295 + index === activeIndex ? "var(--terminal-white)" : "var(--terminal-dim)",
296 + backgroundColor:
297 + index === activeIndex ? "var(--terminal-panel-strong)" : "transparent",
298 + }}
299 + >
300 + <span style={{ color: "var(--terminal-green)" }}>/</span>
301 + {command.replace(/^\//, "")}
302 + </button>
303 + ))}
304 + </div>
305 + )
306 +}
docs/components/terminal-kit/session/index.ts new
+2
@@ -0,0 +1,2 @@
1 +export * from "./message"
2 +export * from "./session-content"
docs/components/terminal-kit/session/message.tsx new
+30
@@ -0,0 +1,30 @@
1 +import * as React from "react"
2 +
3 +import { cn } from "@/lib/utils"
4 +
5 +import { TerminalPrompt } from "../shell/terminal-line"
6 +
7 +export type MessageProps = React.HTMLAttributes<HTMLDivElement> & {
8 + prompt?: string
9 +}
10 +
11 +/** Submitted user message row, shown inside SessionContent. */
12 +export function Message({
13 + prompt = "❯",
14 + className,
15 + children,
16 + ...props
17 +}: MessageProps) {
18 + return (
19 + <div
20 + className={cn(
21 + "terminal-session-sent flex w-full items-start gap-2 bg-[var(--terminal-panel-strong)] py-1 text-[11px] text-[var(--terminal-fg)]",
22 + className
23 + )}
24 + {...props}
25 + >
26 + <TerminalPrompt symbol={prompt} tone="input" />
27 + <span className="min-w-0 flex-1 whitespace-pre-wrap break-words">{children}</span>
28 + </div>
29 + )
30 +}
docs/components/terminal-kit/session/session-content.tsx new
+319
@@ -0,0 +1,319 @@
1 +"use client"
2 +
3 +import { motion, useReducedMotion } from "motion/react"
4 +import * as React from "react"
5 +
6 +import { cn } from "@/lib/utils"
7 +
8 +import { Message } from "./message"
9 +import { BusyIndicator, ThinkingIndicator } from "../ui/thinking-indicator"
10 +import { StreamText, estimateStreamDurationMs, type TextStreamMode } from "../ui/stream-text"
11 +
12 +const SESSION_EASE = [0.23, 1, 0.32, 1] as const
13 +
14 +function isSentPrompt(child: React.ReactNode) {
15 + if (!React.isValidElement(child)) return false
16 + return child.type === Message
17 +}
18 +
19 +function isThinkingIndicator(child: React.ReactNode) {
20 + if (!React.isValidElement(child)) return false
21 + return child.type === ThinkingIndicator || child.type === BusyIndicator
22 +}
23 +
24 +function isStreamText(child: React.ReactNode) {
25 + if (!React.isValidElement(child)) return false
26 + return child.type === StreamText
27 +}
28 +
29 +/** Tail lines (e.g. live thinking) skip the streaming queue and stay last. */
30 +function isSessionTail(child: React.ReactNode) {
31 + if (!React.isValidElement(child)) return false
32 + return (child.props as { sessionTail?: boolean }).sessionTail === true
33 +}
34 +
35 +function sessionItemKey(resetKey: React.Key, index: number) {
36 + return `${String(resetKey)}-${index}`
37 +}
38 +
39 +function usesManualSessionInset(child: React.ReactNode) {
40 + if (!React.isValidElement(child)) return false
41 + const props = child.props as {
42 + "data-session-inset"?: string
43 + sessionInset?: "manual"
44 + }
45 + return (
46 + props["data-session-inset"] === "manual" || props.sessionInset === "manual"
47 + )
48 +}
49 +
50 +function shouldApplySessionInset(child: React.ReactNode) {
51 + if (isSentPrompt(child)) return false
52 + if (isThinkingIndicator(child)) return false
53 + if (usesManualSessionInset(child)) return false
54 + return true
55 +}
56 +
57 +function getScrollContainer(node: HTMLElement | null) {
58 + return node?.closest(".terminal-body-scroll") as HTMLElement | null
59 +}
60 +
61 +function getPauseAfter(child: React.ReactNode, fallbackMs: number) {
62 + if (!React.isValidElement(child)) return fallbackMs
63 +
64 + const props = child.props as {
65 + sessionPause?: number
66 + duration?: string
67 + streaming?: boolean
68 + steps?: unknown[]
69 + name?: string
70 + file?: string
71 + children?: string
72 + level?: string
73 + }
74 +
75 + if (typeof props.sessionPause === "number") return props.sessionPause
76 +
77 + if (isStreamText(child)) {
78 + const streamProps = child.props as {
79 + mode?: TextStreamMode
80 + speed?: number
81 + children?: string
82 + segmentDelay?: number
83 + fadeDuration?: number
84 + }
85 + if (typeof streamProps.children === "string") {
86 + return estimateStreamDurationMs(streamProps.children, {
87 + mode: streamProps.mode,
88 + speed: streamProps.speed,
89 + segmentDelay: streamProps.segmentDelay,
90 + fadeDuration: streamProps.fadeDuration,
91 + })
92 + }
93 + }
94 +
95 + if (typeof props.duration === "string") {
96 + const match = props.duration.match(/([\d.]+)\s*s/)
97 + if (match?.[1]) return Math.round(parseFloat(match[1]) * 1000)
98 + }
99 +
100 + if (props.streaming && Array.isArray(props.steps)) {
101 + return props.steps.length * 420 + 240
102 + }
103 +
104 + if (props.streaming && props.name) return 820
105 +
106 + if (typeof props.file === "string") return 520
107 +
108 + if (props.streaming && typeof props.children === "string") {
109 + const lines = props.children.split("\n").filter((line) => line.trim().length > 0)
110 + return lines.length * 300 + 240
111 + }
112 +
113 + if (props.level) return 320
114 +
115 + if (isSentPrompt(child)) return 280
116 +
117 + return fallbackMs
118 +}
119 +
120 +export type SessionLineProps = {
121 + children: React.ReactNode
122 + className?: string
123 + onReveal?: () => void
124 +}
125 +
126 +/** Animate a single session line on mount. */
127 +export function SessionLine({
128 + children,
129 + className,
130 + onReveal,
131 +}: SessionLineProps) {
132 + const reduceMotion = useReducedMotion()
133 +
134 + React.useEffect(() => {
135 + if (reduceMotion) onReveal?.()
136 + }, [onReveal, reduceMotion])
137 +
138 + if (reduceMotion) {
139 + return <div className={className}>{children}</div>
140 + }
141 +
142 + return (
143 + <motion.div
144 + className={className}
145 + initial={{ opacity: 0, y: 4 }}
146 + animate={{ opacity: 1, y: 0 }}
147 + transition={{
148 + duration: 0.2,
149 + ease: SESSION_EASE,
150 + }}
151 + onAnimationComplete={onReveal}
152 + >
153 + {children}
154 + </motion.div>
155 + )
156 +}
157 +
158 +export type SessionContentProps = {
159 + children: React.ReactNode
160 + className?: string
161 + /** Fallback pause between items when streaming (seconds). */
162 + stagger?: number
163 + /** Seconds before the first streamed item appears. */
164 + delay?: number
165 + /** Change to replay the enter sequence. */
166 + resetKey?: React.Key
167 + /** Keep the scroll container pinned to the bottom as lines appear. */
168 + autoScroll?: boolean
169 + /** Reveal children one at a time like a live agent session. */
170 + streaming?: boolean
171 +}
172 +
173 +/** Staggered enter animation for agent session content. */
174 +export function SessionContent({
175 + children,
176 + className,
177 + stagger = 0.45,
178 + delay = 0,
179 + resetKey = "session",
180 + autoScroll = false,
181 + streaming = false,
182 +}: SessionContentProps) {
183 + const reduceMotion = useReducedMotion()
184 + const sessionRef = React.useRef<HTMLDivElement>(null)
185 + const allItems = React.Children.toArray(children).filter(Boolean)
186 + const bodyItems = allItems.filter((child) => !isSessionTail(child))
187 + const tailItems = allItems.filter((child) => isSessionTail(child))
188 + const itemsRef = React.useRef(bodyItems)
189 + React.useEffect(() => {
190 + itemsRef.current = bodyItems
191 + })
192 +
193 + const [revealedCount, setRevealedCount] = React.useState(0)
194 +
195 + // Replay the staggered reveal when the reset key or body count changes.
196 + const revealKey = `${String(resetKey)}:${bodyItems.length}:${streaming}:${reduceMotion}`
197 + const [prevRevealKey, setPrevRevealKey] = React.useState(revealKey)
198 + if (revealKey !== prevRevealKey) {
199 + setPrevRevealKey(revealKey)
200 + setRevealedCount(0)
201 + }
202 +
203 + const scrollToBottom = React.useCallback(
204 + (behavior?: ScrollBehavior) => {
205 + const scrollEl = getScrollContainer(sessionRef.current)
206 + const resolved =
207 + behavior ?? (reduceMotion || streaming ? "auto" : "smooth")
208 + scrollEl?.scrollTo({ top: scrollEl.scrollHeight, behavior: resolved })
209 + },
210 + [reduceMotion, streaming]
211 + )
212 +
213 + React.useEffect(() => {
214 + if (!streaming || reduceMotion) return
215 +
216 + let cancelled = false
217 + const timers: number[] = []
218 +
219 + const showThrough = (count: number) => {
220 + if (cancelled) return
221 + setRevealedCount(count)
222 + if (autoScroll) scrollToBottom(count === 1 ? "auto" : "smooth")
223 + }
224 +
225 + const revealFrom = (index: number) => {
226 + if (cancelled || index >= itemsRef.current.length) return
227 + showThrough(index + 1)
228 +
229 + if (index + 1 >= itemsRef.current.length) return
230 +
231 + const pause = getPauseAfter(itemsRef.current[index], stagger * 1000)
232 + timers.push(window.setTimeout(() => revealFrom(index + 1), pause))
233 + }
234 +
235 + timers.push(
236 + window.setTimeout(() => revealFrom(0), Math.max(0, delay * 1000))
237 + )
238 +
239 + return () => {
240 + cancelled = true
241 + timers.forEach((timer) => window.clearTimeout(timer))
242 + }
243 + }, [
244 + streaming,
245 + resetKey,
246 + bodyItems.length,
247 + delay,
248 + stagger,
249 + reduceMotion,
250 + autoScroll,
251 + scrollToBottom,
252 + ])
253 +
254 + React.useEffect(() => {
255 + if (!autoScroll || streaming) return
256 + scrollToBottom("auto")
257 + }, [autoScroll, streaming, bodyItems.length, tailItems.length, resetKey, scrollToBottom])
258 +
259 + // Pin to bottom while transcript height grows (StreamText typing, etc.).
260 + React.useEffect(() => {
261 + if (!autoScroll) return
262 + const node = sessionRef.current
263 + if (!node) return
264 +
265 + const observer = new ResizeObserver(() => {
266 + scrollToBottom(streaming ? "auto" : "smooth")
267 + })
268 + observer.observe(node)
269 + return () => observer.disconnect()
270 + }, [autoScroll, scrollToBottom, streaming, resetKey])
271 +
272 + const handleLineReveal = React.useCallback(() => {
273 + if (autoScroll) scrollToBottom()
274 + }, [autoScroll, scrollToBottom])
275 +
276 + const visibleBodyItems =
277 + streaming && !reduceMotion ? bodyItems.slice(0, revealedCount) : bodyItems
278 +
279 + const renderTailItems = () =>
280 + tailItems.map((child, index) => (
281 + <div
282 + key={sessionItemKey(`${String(resetKey)}-tail`, index)}
283 + className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
284 + >
285 + {child}
286 + </div>
287 + ))
288 +
289 + if (reduceMotion) {
290 + return (
291 + <div ref={sessionRef} className={cn("terminal-session", className)}>
292 + {visibleBodyItems.map((child, index) => (
293 + <div
294 + key={sessionItemKey(resetKey, index)}
295 + className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
296 + >
297 + {child}
298 + </div>
299 + ))}
300 + {renderTailItems()}
301 + </div>
302 + )
303 + }
304 +
305 + return (
306 + <div ref={sessionRef} className={cn("terminal-session", className)}>
307 + {visibleBodyItems.map((child, index) => (
308 + <SessionLine
309 + key={sessionItemKey(resetKey, index)}
310 + className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
311 + onReveal={autoScroll && !streaming ? handleLineReveal : undefined}
312 + >
313 + {child}
314 + </SessionLine>
315 + ))}
316 + {renderTailItems()}
317 + </div>
318 + )
319 +}
docs/components/terminal-kit/shell/index.ts new
+2
@@ -0,0 +1,2 @@
1 +export * from "./terminal-window"
2 +export * from "./terminal-line"
docs/components/terminal-kit/shell/terminal-body-scroll.tsx new
+72
@@ -0,0 +1,72 @@
1 +"use client"
2 +
3 +import * as React from "react"
4 +
5 +import { cn } from "@/lib/utils"
6 +
7 +type TerminalBodyScrollProps = {
8 + fill?: boolean
9 + pinBottom?: boolean
10 + stickToBottom?: boolean
11 + children: React.ReactNode
12 +}
13 +
14 +function pinScrollElement(element: HTMLElement) {
15 + element.scrollTop = element.scrollHeight
16 +}
17 +
18 +function pinScrollElementSoon(element: HTMLElement) {
19 + pinScrollElement(element)
20 + requestAnimationFrame(() => {
21 + pinScrollElement(element)
22 + requestAnimationFrame(() => pinScrollElement(element))
23 + })
24 +}
25 +
26 +export function TerminalBodyScroll({
27 + fill,
28 + pinBottom = false,
29 + stickToBottom = false,
30 + children,
31 +}: TerminalBodyScrollProps) {
32 + const scrollRef = React.useRef<HTMLDivElement>(null)
33 +
34 + React.useEffect(() => {
35 + if (!stickToBottom) return
36 +
37 + const el = scrollRef.current
38 + if (!el) return
39 +
40 + const pin = () => pinScrollElementSoon(el)
41 +
42 + pin()
43 +
44 + const observer = new ResizeObserver(pin)
45 + observer.observe(el)
46 + if (el.firstElementChild) {
47 + observer.observe(el.firstElementChild)
48 + }
49 +
50 + return () => observer.disconnect()
51 + }, [stickToBottom, children])
52 +
53 + return (
54 + <div
55 + className={cn(
56 + "terminal-body-scroll-host",
57 + fill && "min-h-0 flex-1 overflow-hidden"
58 + )}
59 + >
60 + <div
61 + ref={scrollRef}
62 + className={cn(
63 + "terminal-body-scroll",
64 + fill && "min-h-0 flex-1",
65 + pinBottom && "terminal-body-scroll-pin-bottom"
66 + )}
67 + >
68 + {children}
69 + </div>
70 + </div>
71 + )
72 +}
docs/components/terminal-kit/shell/terminal-line.tsx new
+85
@@ -0,0 +1,85 @@
1 +import * as React from "react"
2 +
3 +import { cn } from "@/lib/utils"
4 +
5 +const lineVariantClasses = {
6 + default: "text-[var(--terminal-fg)]",
7 + dim: "text-[var(--terminal-dim)]",
8 + success: "text-[var(--terminal-green)]",
9 + error: "text-[var(--terminal-red)]",
10 + warning: "text-[var(--terminal-orange)]",
11 + thought: "text-[var(--terminal-purple)]",
12 + command: "text-[var(--terminal-blue)]",
13 +} as const
14 +
15 +export type TerminalLineVariant = keyof typeof lineVariantClasses
16 +
17 +export type TerminalLineProps = Omit<React.HTMLAttributes<HTMLDivElement>, "prefix"> & {
18 + variant?: TerminalLineVariant
19 + prefix?: React.ReactNode
20 + /** Preserve `\n` in content. Off by default so JSX formatting does not affect layout. */
21 + preserveWhitespace?: boolean
22 +}
23 +
24 +export function TerminalLine({
25 + variant = "default",
26 + prefix,
27 + preserveWhitespace = false,
28 + className,
29 + children,
30 + style,
31 + ...props
32 +}: TerminalLineProps) {
33 + return (
34 + <div
35 + className={cn(
36 + "flex min-w-0 items-start gap-2 py-0.5",
37 + lineVariantClasses[variant],
38 + className
39 + )}
40 + style={style}
41 + {...props}
42 + >
43 + {prefix ? <span className="shrink-0 select-none">{prefix}</span> : null}
44 + <div
45 + className={cn(
46 + "min-w-0 flex-1 break-words",
47 + preserveWhitespace ? "whitespace-pre-wrap" : "whitespace-normal"
48 + )}
49 + >
50 + {children}
51 + </div>
52 + </div>
53 + )
54 +}
55 +
56 +export type TerminalPromptProps = React.HTMLAttributes<HTMLSpanElement> & {
57 + symbol?: string
58 + tone?: "input" | "command"
59 +}
60 +
61 +export function TerminalPrompt({
62 + symbol = "❯",
63 + tone = "command",
64 + className,
65 + ...props
66 +}: TerminalPromptProps) {
67 + return (
68 + <span
69 + className={cn("terminal-prompt shrink-0 select-none", className)}
70 + style={{
71 + color:
72 + tone === "input" ? "var(--terminal-teal)" : "var(--terminal-green)",
73 + fontSize: tone === "input" ? 9 : undefined,
74 + lineHeight: tone === "input" ? "16px" : undefined,
75 + display: tone === "input" ? "inline-flex" : undefined,
76 + alignItems: tone === "input" ? "center" : undefined,
77 + height: tone === "input" ? 16 : undefined,
78 + }}
79 + {...props}
80 + >
81 + {symbol}
82 + </span>
83 + )
84 +}
85 +
docs/components/terminal-kit/shell/terminal-window.tsx new
+313
@@ -0,0 +1,313 @@
1 +import * as React from "react"
2 +
3 +import {
4 + terminalThemeClass,
5 + terminalThemeLightClass,
6 + type TerminalTheme,
7 +} from "@/lib/terminal-themes"
8 +import { cn } from "@/lib/utils"
9 +
10 +import { TerminalBodyScroll } from "./terminal-body-scroll"
11 +
12 +export type { TerminalTheme } from "@/lib/terminal-themes"
13 +
14 +export type TerminalProgressConfig = {
15 + value: number
16 + /** Label beside the bar — e.g. "context". */
17 + label?: React.ReactNode
18 + /** Show the numeric percentage after the bar. Defaults to false when label is set. */
19 + showValue?: boolean
20 +}
21 +
22 +export type TerminalProgress = number | TerminalProgressConfig | false
23 +
24 +function resolveProgress(progress: TerminalProgress | undefined) {
25 + if (progress === false || progress === undefined) return null
26 +
27 + if (typeof progress === "number") {
28 + return { value: progress, label: undefined, showValue: true }
29 + }
30 +
31 + return {
32 + value: progress.value,
33 + label: progress.label,
34 + showValue: progress.showValue ?? progress.label == null,
35 + }
36 +}
37 +
38 +export type TerminalBodyProps = React.HTMLAttributes<HTMLDivElement> & {
39 + footer?: React.ReactNode
40 + header?: React.ReactNode
41 + /** Stretch to fill a fixed-height window and scroll internally. Defaults to content-height flow. */
42 + fill?: boolean
43 + pinScrollBottom?: boolean
44 +}
45 +
46 +function TerminalBodyLayout({
47 + className,
48 + children,
49 + footer,
50 + header,
51 + fill = false,
52 + pinScrollBottom = false,
53 + ...props
54 +}: TerminalBodyProps) {
55 + return (
56 + <div
57 + className={cn(
58 + "flex w-full flex-col justify-start overflow-hidden",
59 + fill ? "min-h-0 flex-1" : "shrink-0",
60 + className
61 + )}
62 + {...props}
63 + >
64 + {header ? (
65 + <div className="terminal-body-header w-full shrink-0 px-[var(--terminal-session-pad-x)]">
66 + {header}
67 + </div>
68 + ) : null}
69 + <TerminalBodyScroll
70 + fill={fill}
71 + pinBottom={pinScrollBottom}
72 + stickToBottom={pinScrollBottom}
73 + >
74 + <div
75 + className={cn(
76 + "terminal-body-content w-full",
77 + pinScrollBottom ? "flex min-h-full flex-col justify-end" : "min-h-0"
78 + )}
79 + >
80 + {children}
81 + </div>
82 + </TerminalBodyScroll>
83 + {footer ? (
84 + <div className="terminal-body-footer w-full shrink-0 pb-[var(--terminal-session-pad-y)]">
85 + {footer}
86 + </div>
87 + ) : null}
88 + </div>
89 + )
90 +}
91 +
92 +export type TerminalWindowProps = React.HTMLAttributes<HTMLDivElement> & {
93 + path?: string
94 + /** Pass `false` to hide the header progress indicator. */
95 + progress?: TerminalProgress
96 + showTrafficLights?: boolean
97 + /** Built-in palette — default, grok, or claude. */
98 + theme?: TerminalTheme
99 + variant?: "dark" | "light"
100 + footer?: React.ReactNode
101 + header?: React.ReactNode
102 + /** Stretch to fill a fixed-height window and scroll internally. */
103 + fill?: boolean
104 + pinScrollBottom?: boolean
105 + /** Classes for the inner body layout wrapper. */
106 + bodyClassName?: string
107 + /** Optional control rendered at the end of the window chrome header. */
108 + headerAction?: React.ReactNode
109 +}
110 +
111 +export function TerminalWindow({
112 + path,
113 + progress,
114 + showTrafficLights = true,
115 + theme = "default",
116 + variant = "dark",
117 + className,
118 + children,
119 + style,
120 + footer,
121 + header,
122 + fill = false,
123 + pinScrollBottom = false,
124 + bodyClassName,
125 + headerAction,
126 + ...props
127 +}: TerminalWindowProps) {
128 + const resolvedProgress = resolveProgress(progress)
129 +
130 + return (
131 + <div
132 + className={cn(
133 + "terminal-theme flex w-full min-h-0 flex-col overflow-hidden border font-mono text-xs leading-relaxed",
134 + terminalThemeClass(theme),
135 + variant === "light" && terminalThemeLightClass(theme),
136 + className
137 + )}
138 + style={{
139 + backgroundColor: "var(--terminal-editor-bg)",
140 + borderColor: "var(--terminal-border)",
141 + borderRadius: "var(--terminal-radius-window)",
142 + color: "var(--terminal-fg)",
143 + ...style,
144 + }}
145 + {...props}
146 + >
147 + {(path || resolvedProgress || showTrafficLights || headerAction) && (
148 + <TerminalHeader
149 + path={path}
150 + progress={resolvedProgress ?? undefined}
151 + showTrafficLights={showTrafficLights}
152 + headerAction={headerAction}
153 + />
154 + )}
155 + <TerminalBodyLayout
156 + className={bodyClassName}
157 + fill={fill}
158 + footer={footer}
159 + header={header}
160 + pinScrollBottom={pinScrollBottom}
161 + >
162 + {children}
163 + </TerminalBodyLayout>
164 + </div>
165 + )
166 +}
167 +
168 +/** @deprecated Pass footer, header, fill, and pinScrollBottom to TerminalWindow instead. */
169 +export function TerminalBody(props: TerminalBodyProps) {
170 + return <TerminalBodyLayout {...props} />
171 +}
172 +
173 +export type TerminalHeaderProps = {
174 + path?: string
175 + progress?: {
176 + value: number
177 + label?: React.ReactNode
178 + showValue: boolean
179 + }
180 + showTrafficLights?: boolean
181 + className?: string
182 + headerAction?: React.ReactNode
183 + /** @default true */
184 + showBorderBottom?: boolean
185 +}
186 +
187 +function TerminalHeaderProgress({
188 + progress,
189 + label,
190 + showValue,
191 +}: {
192 + progress: number
193 + label?: React.ReactNode
194 + showValue: boolean
195 +}) {
196 + const ariaLabel =
197 + label != null && label !== "" ? String(label) : "Progress"
198 +
199 + return (
200 + <div className="flex shrink-0 items-center gap-2 text-[11px]">
201 + <span style={{ color: "var(--terminal-vdim)" }}>|</span>
202 + {label ? (
203 + <span className="shrink-0" style={{ color: "var(--terminal-dim)" }}>
204 + {label}
205 + </span>
206 + ) : null}
207 + <span
208 + className="relative inline-flex h-[1em] w-16 items-stretch overflow-hidden terminal-panel-sm"
209 + style={{ backgroundColor: "var(--terminal-progress-track)" }}
210 + role="progressbar"
211 + aria-valuenow={progress}
212 + aria-valuemin={0}
213 + aria-valuemax={100}
214 + aria-label={showValue ? `${ariaLabel} ${progress.toFixed(2)}%` : ariaLabel}
215 + >
216 + <span
217 + className="block h-full"
218 + style={{
219 + width: `${Math.min(100, Math.max(0, progress))}%`,
220 + backgroundColor: "var(--terminal-progress-fill)",
221 + }}
222 + />
223 + </span>
224 + {showValue ? (
225 + <span style={{ color: "var(--terminal-dim)" }}>{progress.toFixed(2)}%</span>
226 + ) : null}
227 + </div>
228 + )
229 +}
230 +
231 +export function TerminalHeader({
232 + path,
233 + progress,
234 + showTrafficLights = true,
235 + className,
236 + headerAction,
237 + showBorderBottom = true,
238 +}: TerminalHeaderProps) {
239 + return (
240 + <div
241 + className={cn("flex items-center gap-3 px-3 py-2", className)}
242 + style={
243 + showBorderBottom
244 + ? { borderBottom: "1px solid var(--terminal-border)" }
245 + : undefined
246 + }
247 + >
248 + {showTrafficLights && (
249 + <div className="terminal-traffic-lights flex shrink-0 gap-1.5">
250 + <div
251 + className="size-[9px] rounded-full"
252 + style={{ backgroundColor: "var(--terminal-traffic-red)" }}
253 + />
254 + <div
255 + className="size-[9px] rounded-full"
256 + style={{ backgroundColor: "var(--terminal-traffic-yellow)" }}
257 + />
258 + <div
259 + className="size-[9px] rounded-full"
260 + style={{ backgroundColor: "var(--terminal-traffic-green)" }}
261 + />
262 + </div>
263 + )}
264 + {path && (
265 + <div
266 + className="ml-1.5 min-w-0 flex-1 truncate text-[11px]"
267 + style={{ color: "var(--terminal-dim)" }}
268 + >
269 + {path}
270 + </div>
271 + )}
272 + {progress && (
273 + <TerminalHeaderProgress
274 + progress={progress.value}
275 + label={progress.label}
276 + showValue={progress.showValue}
277 + />
278 + )}
279 + {headerAction ? <div className="ml-auto shrink-0">{headerAction}</div> : null}
280 + </div>
281 + )
282 +}
283 +
284 +export type TerminalStatusBarProps = React.HTMLAttributes<HTMLDivElement> & {
285 + left?: React.ReactNode
286 + right?: React.ReactNode
287 +}
288 +
289 +export function TerminalStatusBar({
290 + left,
291 + right,
292 + className,
293 + children,
294 + ...props
295 +}: TerminalStatusBarProps) {
296 + return (
297 + <div
298 + className={cn(
299 + "flex items-center justify-between gap-3 px-3 py-2 text-[11px]",
300 + className
301 + )}
302 + style={{
303 + borderTop: "1px solid var(--terminal-border)",
304 + color: "var(--terminal-dim)",
305 + backgroundColor: "var(--terminal-surface)",
306 + }}
307 + {...props}
308 + >
309 + <div className="min-w-0 truncate">{left ?? children}</div>
310 + {right && <div className="shrink-0">{right}</div>}
311 + </div>
312 + )
313 +}
docs/components/terminal-kit/ui/index.ts new
+2
@@ -0,0 +1,2 @@
1 +export * from "./thinking-indicator"
2 +export * from "./stream-text"
docs/components/terminal-kit/ui/stream-text.tsx new
+243
@@ -0,0 +1,243 @@
1 +"use client"
2 +
3 +import { motion, useReducedMotion } from "motion/react"
4 +import * as React from "react"
5 +
6 +import { TerminalLine } from "../shell/terminal-line"
7 +
8 +export type TextStreamMode = "plain" | "fade"
9 +
10 +export type TextSegment = { text: string; index: number }
11 +
12 +export type StreamTimingOverrides = {
13 + /** Delay between word segments, ms (overrides speed). */
14 + segmentDelay?: number
15 + /** Fade-in duration per segment in fade mode, ms (overrides speed). */
16 + fadeDuration?: number
17 +}
18 +
19 +function clamp(value: number, min: number, max: number) {
20 + return Math.min(max, Math.max(min, value))
21 +}
22 +
23 +/** Map a 1-100 speed knob to concrete timings. */
24 +export function resolveStreamTiming(
25 + speed = 20,
26 + overrides: StreamTimingOverrides = {}
27 +) {
28 + const s = clamp(speed, 1, 100)
29 + return {
30 + segmentDelay: overrides.segmentDelay ?? Math.max(16, Math.round(170 - s * 1.4)),
31 + fadeDuration: overrides.fadeDuration ?? Math.max(120, Math.round(700 - s * 4)),
32 + }
33 +}
34 +
35 +/** Split into words while keeping trailing whitespace so spacing is preserved. */
36 +function splitSegments(text: string): TextSegment[] {
37 + const matches = text.match(/\S+\s*/g) ?? []
38 + return matches.map((segment, index) => ({ text: segment, index }))
39 +}
40 +
41 +/** Estimate how long a stream will take, e.g. to drive a SessionContent pause. */
42 +export function estimateStreamDurationMs(
43 + text: string,
44 + options: { mode?: TextStreamMode; speed?: number } & StreamTimingOverrides = {}
45 +) {
46 + const { mode = "plain", speed = 20, ...overrides } = options
47 + const timing = resolveStreamTiming(speed, overrides)
48 + const base =
49 + splitSegments(text).length * timing.segmentDelay + 120
50 + if (mode === "plain") return base
51 + return base + timing.fadeDuration
52 +}
53 +
54 +export type UseTextStreamOptions = {
55 + text: string
56 + mode?: TextStreamMode
57 + /** 1 (slowest) to 100 (fastest). Defaults to 20. */
58 + speed?: number
59 + /** When false, nothing is revealed. */
60 + enabled?: boolean
61 + /** Reveal the full text immediately (e.g. reduced motion). */
62 + instant?: boolean
63 + onComplete?: () => void
64 +} & StreamTimingOverrides
65 +
66 +/**
67 + * Client-side simulated text streaming. For controlled/fake progressive output
68 + * (demos, scripted sessions). For real LLM output, append tokens directly.
69 + */
70 +export function useTextStream({
71 + text,
72 + mode = "plain",
73 + speed = 20,
74 + enabled = true,
75 + instant = false,
76 + segmentDelay,
77 + fadeDuration,
78 + onComplete,
79 +}: UseTextStreamOptions) {
80 + const timing = resolveStreamTiming(speed, { segmentDelay, fadeDuration })
81 + const segments = React.useMemo(() => splitSegments(text), [text])
82 + const useFade = mode === "fade" && !instant
83 + const streamWords = enabled && !instant && segments.length > 0
84 +
85 + const initialSegments = enabled && !streamWords ? segments.length : 0
86 + const [segmentCount, setSegmentCount] = React.useState(initialSegments)
87 +
88 + const resetKey = `${text}::${mode}::${enabled}::${instant}`
89 + const [prevResetKey, setPrevResetKey] = React.useState(resetKey)
90 + if (resetKey !== prevResetKey) {
91 + setPrevResetKey(resetKey)
92 + setSegmentCount(initialSegments)
93 + }
94 +
95 + const onCompleteRef = React.useRef(onComplete)
96 + React.useEffect(() => {
97 + onCompleteRef.current = onComplete
98 + })
99 +
100 + React.useEffect(() => {
101 + if (!streamWords) return
102 + let cancelled = false
103 + let revealed = 0
104 + let timer = 0
105 +
106 + const tick = () => {
107 + if (cancelled) return
108 + revealed += 1
109 + setSegmentCount(revealed)
110 + if (revealed < segments.length) {
111 + timer = window.setTimeout(tick, timing.segmentDelay)
112 + }
113 + }
114 +
115 + timer = window.setTimeout(tick, timing.segmentDelay)
116 + return () => {
117 + cancelled = true
118 + window.clearTimeout(timer)
119 + }
120 + }, [streamWords, text, segments.length, timing.segmentDelay])
121 +
122 + const isComplete =
123 + !enabled ? false : instant || segmentCount >= segments.length
124 +
125 + const completedRef = React.useRef(false)
126 + React.useEffect(() => {
127 + if (isComplete && !completedRef.current) {
128 + completedRef.current = true
129 + onCompleteRef.current?.()
130 + } else if (!isComplete) {
131 + completedRef.current = false
132 + }
133 + }, [isComplete])
134 +
135 + return {
136 + segments,
137 + visibleSegmentCount: segmentCount,
138 + isComplete,
139 + timing,
140 + useFade,
141 + streamWords,
142 + }
143 +}
144 +
145 +export type StreamTextProps = {
146 + /** The text to stream. Must be a plain string. */
147 + children: string
148 + /** `plain` (default) reveals word-by-word; `fade` adds a fade-in per word. */
149 + mode?: TextStreamMode
150 + /** 1 (slowest) to 100 (fastest). Defaults to 26. */
151 + speed?: number
152 + /** Start streaming. Set false to hold until revealed. */
153 + enabled?: boolean
154 + className?: string
155 + onComplete?: () => void
156 + /**
157 + * SessionContent integration — ms to wait after this line before revealing the
158 + * next child when streaming. Not read by StreamText; SessionContent inspects
159 + * the prop on the child element. Defaults to estimateStreamDurationMs(text).
160 + */
161 + sessionPause?: number
162 +} & StreamTimingOverrides
163 +
164 +/**
165 + * Agent text inside a TerminalLine. Default reveals word-by-word with no
166 + * transition; use mode="fade" to fade each word in.
167 + */
168 +export function StreamText({
169 + children,
170 + mode = "plain",
171 + speed = 26,
172 + enabled = true,
173 + className,
174 + onComplete,
175 + sessionPause: _sessionPause,
176 + segmentDelay,
177 + fadeDuration,
178 +}: StreamTextProps) {
179 + const reduceMotion = useReducedMotion()
180 + const { segments, visibleSegmentCount, timing, useFade, streamWords } =
181 + useTextStream({
182 + text: children,
183 + mode,
184 + speed,
185 + enabled,
186 + instant: Boolean(reduceMotion),
187 + segmentDelay,
188 + fadeDuration,
189 + onComplete,
190 + })
191 +
192 + if (!enabled) {
193 + return <TerminalLine className={className} />
194 + }
195 +
196 + if (!streamWords) {
197 + return (
198 + <TerminalLine className={className}>
199 + {children}
200 + </TerminalLine>
201 + )
202 + }
203 +
204 + if (useFade) {
205 + return (
206 + <TerminalLine className={className}>
207 + {segments.map((segment) => {
208 + const visible = segment.index < visibleSegmentCount
209 + return (
210 + <motion.span
211 + key={segment.index}
212 + initial={false}
213 + animate={{ opacity: visible ? 1 : 0 }}
214 + transition={{
215 + duration: timing.fadeDuration / 1000,
216 + ease: "easeOut",
217 + }}
218 + >
219 + {segment.text}
220 + </motion.span>
221 + )
222 + })}
223 + </TerminalLine>
224 + )
225 + }
226 +
227 + return (
228 + <TerminalLine className={className}>
229 + {segments.map((segment) => {
230 + const visible = segment.index < visibleSegmentCount
231 + return (
232 + <span
233 + key={segment.index}
234 + aria-hidden={!visible}
235 + style={{ visibility: visible ? "visible" : "hidden" }}
236 + >
237 + {segment.text}
238 + </span>
239 + )
240 + })}
241 + </TerminalLine>
242 + )
243 +}
docs/components/terminal-kit/ui/thinking-indicator.tsx new
+265
@@ -0,0 +1,265 @@
1 +"use client"
2 +
3 +import * as React from "react"
4 +
5 +import { useResolvedTerminalTheme } from "@/hooks/use-resolved-terminal-theme"
6 +import { cn } from "@/lib/utils"
7 +
8 +/** Claude thinking spinner — cycles in this order (claude.ai / Claude Code). */
9 +export const CLAUDE_THINKING_FRAMES = [
10 + "\u00B7", // middle dot / bullet
11 + "\u273B", // teardrop-spoked asterisk ✻
12 + "\u273D", // heavy teardrop-spoked asterisk ✽
13 + "\u2736", // six pointed black star ✶
14 + "\u2733", // eight spoked asterisk ✳
15 + "\u2722", // four balloon-spoked asterisk ✢
16 +] as const
17 +
18 +export type TerminalAsciiSpinnerProps = {
19 + /** Single-character frames cycled in order. */
20 + frames?: ReadonlyArray<string>
21 + /** Milliseconds per frame. */
22 + speed?: number
23 + color?: string
24 + className?: string
25 +}
26 +
27 +export function TerminalAsciiSpinner({
28 + frames = CLAUDE_THINKING_FRAMES,
29 + speed = 150,
30 + color = "var(--terminal-teal)",
31 + className,
32 +}: TerminalAsciiSpinnerProps) {
33 + const [step, setStep] = React.useState(0)
34 + const [reduceMotion, setReduceMotion] = React.useState(false)
35 + const frameCount = Math.max(1, frames.length)
36 +
37 + React.useEffect(() => {
38 + const media = window.matchMedia("(prefers-reduced-motion: reduce)")
39 + const update = () => setReduceMotion(media.matches)
40 + update()
41 + media.addEventListener("change", update)
42 + return () => media.removeEventListener("change", update)
43 + }, [])
44 +
45 + React.useEffect(() => {
46 + if (reduceMotion) return
47 +
48 + const interval = window.setInterval(() => {
49 + setStep((current) => (current + 1) % frameCount)
50 + }, Math.max(16, speed))
51 +
52 + return () => window.clearInterval(interval)
53 + }, [reduceMotion, speed, frameCount])
54 +
55 + const frame = frames[reduceMotion ? 0 : step % frameCount] ?? frames[0] ?? "·"
56 +
57 + return (
58 + <span
59 + aria-hidden
60 + className={cn(
61 + "inline-flex w-[1em] shrink-0 items-center justify-center font-mono leading-none",
62 + className
63 + )}
64 + style={{ color }}
65 + >
66 + {frame}
67 + </span>
68 + )
69 +}
70 +
71 +// 3x3 grid (row-major indices). The 8 perimeter cells form a clockwise ring
72 +// swept by a comet head with a fading trail; the center (index 4) pulses as a
73 +// core in sync with each revolution.
74 +const DOT_GRID_SIZE = 9
75 +const DOT_RING = [0, 1, 2, 5, 8, 7, 6, 3]
76 +const DOT_CENTER = 4
77 +
78 +/** A custom animation frame: opacity (0–1) per grid cell, row-major (length 9). */
79 +export type TerminalDotFrame = ReadonlyArray<number>
80 +
81 +export type TerminalDotMatrixProps = {
82 + tone?: "default" | "active"
83 + /** Milliseconds per step (lower is faster). */
84 + speed?: number
85 + /** Number of cells that fade behind the comet head. (Built-in spin only.) */
86 + trail?: number
87 + /** Pulse the center dot as a core. (Built-in spin only.) */
88 + pulseCenter?: boolean
89 + /** Dot size in pixels. */
90 + dotSize?: number
91 + /** Override the dot color (any CSS color). Defaults to the tone color. */
92 + color?: string
93 + /**
94 + * Custom animation as a list of frames, each an array of opacity values
95 + * (0–1) for the 3x3 grid in row-major order. Overrides the built-in spin.
96 + */
97 + frames?: ReadonlyArray<TerminalDotFrame>
98 + className?: string
99 +}
100 +
101 +function clampOpacity(value: number | undefined) {
102 + if (value == null || Number.isNaN(value)) return 0
103 + return Math.min(1, Math.max(0, value))
104 +}
105 +
106 +export function TerminalDotMatrix({
107 + tone = "default",
108 + speed = 120,
109 + trail = 4,
110 + pulseCenter = true,
111 + dotSize = 2,
112 + color,
113 + frames,
114 + className,
115 +}: TerminalDotMatrixProps) {
116 + const [step, setStep] = React.useState(0)
117 + const [reduceMotion, setReduceMotion] = React.useState(false)
118 +
119 + const hasCustomFrames = Boolean(frames && frames.length > 0)
120 + const frameCount = hasCustomFrames ? frames!.length : DOT_RING.length
121 +
122 + React.useEffect(() => {
123 + const media = window.matchMedia("(prefers-reduced-motion: reduce)")
124 + const update = () => setReduceMotion(media.matches)
125 + update()
126 + media.addEventListener("change", update)
127 + return () => media.removeEventListener("change", update)
128 + }, [])
129 +
130 + React.useEffect(() => {
131 + if (reduceMotion) return
132 +
133 + const interval = window.setInterval(() => {
134 + setStep((current) => (current + 1) % frameCount)
135 + }, Math.max(16, speed))
136 +
137 + return () => window.clearInterval(interval)
138 + }, [reduceMotion, speed, frameCount])
139 +
140 + const dotColor =
141 + color ??
142 + (tone === "active" ? "var(--terminal-blue-bright)" : "var(--terminal-white)")
143 +
144 + const opacities = new Array<number>(DOT_GRID_SIZE).fill(0)
145 +
146 + if (hasCustomFrames) {
147 + const frame = frames![(reduceMotion ? 0 : step) % frames!.length] ?? []
148 + for (let index = 0; index < DOT_GRID_SIZE; index += 1) {
149 + opacities[index] = clampOpacity(frame[index])
150 + }
151 + } else {
152 + const head = reduceMotion ? 0 : step % DOT_RING.length
153 + const safeTrail = Math.max(1, trail)
154 + DOT_RING.forEach((cellIndex, ringPos) => {
155 + const distance = (head - ringPos + DOT_RING.length) % DOT_RING.length
156 + opacities[cellIndex] = distance < safeTrail ? 1 - distance / safeTrail : 0
157 + })
158 +
159 + if (pulseCenter) {
160 + const phase = head / DOT_RING.length
161 + opacities[DOT_CENTER] =
162 + 0.3 + 0.45 * (0.5 + 0.5 * Math.cos(2 * Math.PI * phase))
163 + }
164 + }
165 +
166 + return (
167 + <span
168 + aria-hidden
169 + className={cn("inline-grid shrink-0 align-middle leading-none", className)}
170 + style={{
171 + gridTemplateColumns: `repeat(3, ${dotSize}px)`,
172 + gridTemplateRows: `repeat(3, ${dotSize}px)`,
173 + gap: 1,
174 + }}
175 + >
176 + {opacities.map((opacity, index) => (
177 + <span
178 + key={index}
179 + className="rounded-full"
180 + style={{
181 + width: dotSize,
182 + height: dotSize,
183 + backgroundColor: dotColor,
184 + opacity,
185 + transition: `opacity ${Math.max(16, speed)}ms linear`,
186 + }}
187 + />
188 + ))}
189 + </span>
190 + )
191 +}
192 +
193 +export type ThinkingIndicatorProps = {
194 + label?: string
195 + children?: React.ReactNode
196 + /**
197 + * `auto` — Claude symbol loop inside `.terminal-theme-claude`, dot matrix elsewhere.
198 + * `ascii` — always use the symbol loop. `dots` / `cursor` — force that style.
199 + */
200 + variant?: "auto" | "dots" | "ascii" | "cursor"
201 + tone?: "default" | "active"
202 + /** Customize the dot-matrix animation (speed, trail, color, etc.). */
203 + dotProps?: Omit<TerminalDotMatrixProps, "tone" | "className">
204 + /** Customize the Claude-style ASCII symbol loop. */
205 + asciiProps?: Omit<TerminalAsciiSpinnerProps, "className">
206 + /**
207 + * SessionContent integration — skip the streaming queue and pin this line at the
208 + * transcript tail (e.g. live thinking). Not read by ThinkingIndicator; SessionContent
209 + * inspects the prop on the child element.
210 + */
211 + sessionTail?: boolean
212 + className?: string
213 +}
214 +
215 +export function ThinkingIndicator({
216 + label,
217 + children,
218 + variant = "auto",
219 + tone = "default",
220 + dotProps,
221 + asciiProps,
222 + sessionTail: _sessionTail,
223 + className,
224 +}: ThinkingIndicatorProps) {
225 + const content = children ?? label
226 + const { ref, isClaude, isCompact } = useResolvedTerminalTheme()
227 + const useAscii = variant === "ascii" || (variant === "auto" && isClaude)
228 + const useCursor = variant === "cursor" || (variant === "auto" && isCompact)
229 + const asciiColor = asciiProps?.color ?? "var(--terminal-teal)"
230 + const textColor = useAscii
231 + ? asciiColor
232 + : tone === "active"
233 + ? "var(--terminal-white)"
234 + : "var(--terminal-dim)"
235 +
236 + return (
237 + <div
238 + ref={ref}
239 + className={cn("flex items-center gap-2.5 text-[12px]", className)}
240 + role="status"
241 + aria-live="polite"
242 + >
243 + {useCursor ? (
244 + <span
245 + aria-hidden
246 + className="terminal-cursor inline-block h-3 w-[0.55em]"
247 + style={{ backgroundColor: "var(--terminal-progress-fill)" }}
248 + />
249 + ) : useAscii ? (
250 + <TerminalAsciiSpinner {...asciiProps} color={asciiColor} />
251 + ) : (
252 + <TerminalDotMatrix tone={tone} {...dotProps} />
253 + )}
254 + {content && <span style={{ color: textColor }}>{content}</span>}
255 + </div>
256 + )
257 +}
258 +
259 +/** @deprecated Use ThinkingIndicator */
260 +export type BusyIndicatorProps = ThinkingIndicatorProps
261 +
262 +/** @deprecated Use ThinkingIndicator */
263 +export function BusyIndicator(props: ThinkingIndicatorProps) {
264 + return <ThinkingIndicator {...props} />
265 +}
docs/components/terminal-theme-provider.tsx new
+80
@@ -0,0 +1,80 @@
1 +"use client"
2 +
3 +import {
4 + TERMINAL_THEMES,
5 + type TerminalTheme,
6 +} from "@/lib/terminal-themes"
7 +import * as React from "react"
8 +
9 +const STORAGE_KEY = "terminal-kit:theme"
10 +
11 +const listeners = new Set<() => void>()
12 +
13 +function readStoredTheme(): TerminalTheme {
14 + if (typeof window === "undefined") return "default"
15 +
16 + const stored = window.localStorage.getItem(STORAGE_KEY)
17 + if (stored && TERMINAL_THEMES.includes(stored as TerminalTheme)) {
18 + return stored as TerminalTheme
19 + }
20 +
21 + return "default"
22 +}
23 +
24 +function subscribe(listener: () => void) {
25 + listeners.add(listener)
26 + return () => listeners.delete(listener)
27 +}
28 +
29 +function getSnapshot() {
30 + return readStoredTheme()
31 +}
32 +
33 +function getServerSnapshot(): TerminalTheme {
34 + return "default"
35 +}
36 +
37 +function setStoredTheme(next: TerminalTheme) {
38 + window.localStorage.setItem(STORAGE_KEY, next)
39 + listeners.forEach((listener) => listener())
40 +}
41 +
42 +type TerminalThemeContextValue = {
43 + theme: TerminalTheme
44 + setTheme: (theme: TerminalTheme) => void
45 +}
46 +
47 +const TerminalThemeContext = React.createContext<TerminalThemeContextValue | null>(
48 + null
49 +)
50 +
51 +export function TerminalThemeProvider({ children }: { children: React.ReactNode }) {
52 + const theme = React.useSyncExternalStore(
53 + subscribe,
54 + getSnapshot,
55 + getServerSnapshot
56 + )
57 +
58 + const setTheme = React.useCallback((next: TerminalTheme) => {
59 + setStoredTheme(next)
60 + }, [])
61 +
62 + return (
63 + <TerminalThemeContext.Provider value={{ theme, setTheme }}>
64 + {children}
65 + </TerminalThemeContext.Provider>
66 + )
67 +}
68 +
69 +export function useTerminalTheme() {
70 + const context = React.useContext(TerminalThemeContext)
71 + if (!context) {
72 + throw new Error("useTerminalTheme must be used within TerminalThemeProvider")
73 + }
74 +
75 + return context
76 +}
77 +
78 +export function useTerminalThemeOptional() {
79 + return React.useContext(TerminalThemeContext)
80 +}
docs/components/toolkits/toolkits-landing.tsx
+2 -1
@@ -182,7 +182,8 @@ export function ToolkitsLanding() {
182 {/* Cards */}
183 <Cards>
184 <Card icon={<ShieldCheck />} title="Composio Managed Auth" href="/toolkits/managed-auth" description="Check which toolkits have managed auth" />
185 - <Card icon={<Sparkles />} title="Premium Tools" href="/toolkits/premium-tools" description="Learn about pricing and limits" />
185 + <Card icon={<Sparkles />} title="Pro Tools" href="/toolkits/pro-tools" description="Learn about pricing and limits" />
186 + <Card icon={<Wrench />} title="Meta Tools" href="/toolkits/meta-tools" description="The system tools every session gives your agent" />
187 </Cards>
188
189 {/* Search */}
docs/components/top-nav.tsx
+1 -1
@@ -6,8 +6,8 @@ import { usePathname } from 'next/navigation';
6
7 const navItems = [
8 { href: '/docs', label: 'Docs' },
9 + { href: '/examples', label: 'Examples' },
10 { href: '/docs/api', label: 'API' },
10 - { href: '/cookbooks', label: 'Cookbooks' },
11 ];
12
13 export function TopNav() {
docs/components/triggers-flow.tsx new
+416
@@ -0,0 +1,416 @@
1 +'use client';
2 +
3 +import { Radio, RefreshCw, Webhook, Check } from 'lucide-react';
4 +import { useCallback, useEffect, useRef, useState } from 'react';
5 +
6 +const LOGO_CDN = 'https://logos.composio.dev/api';
7 +
8 +const SOURCES: { slug: string; name: string; kind: 'realtime' | 'polling' }[] = [
9 + { slug: 'github', name: 'GitHub', kind: 'realtime' },
10 + { slug: 'slack', name: 'Slack', kind: 'realtime' },
11 + { slug: 'gmail', name: 'Gmail', kind: 'polling' },
12 +];
13 +
14 +const RT_POOL = 5; // concurrent packets per realtime source
15 +const POLL_POOL = 6; // packets that pile up in the polling box per batch
16 +const OUT_POOL = 6; // packets streaming out to your webhook URL
17 +
18 +// Polling cadence (seconds): packets fill in, wait, then release together.
19 +const FILL_GAP = 0.45;
20 +const T_RELEASE = 3.0;
21 +const MOVE_DUR = 0.6;
22 +const CYCLE = 3.9;
23 +
24 +type Pt = { x: number; y: number };
25 +type InGeom = { spawn: Pt; edge: Pt; end: Pt };
26 +type Geom = { ins: InGeom[]; out: { spawn: Pt; end: Pt } } | null;
27 +type Line = { x1: number; y1: number; x2: number; y2: number; dashed: boolean };
28 +
29 +type RtSlot = { active: boolean; p: number; dur: number; wait: number };
30 +type RtState = { slots: RtSlot[] };
31 +type PollState = { t: number; offsets: Pt[] };
32 +
33 +const rand = (a: number, b: number) => a + Math.random() * (b - a);
34 +const easeOut = (p: number) => 1 - (1 - p) * (1 - p);
35 +
36 +function makeRt(pool: number): RtState {
37 + return {
38 + slots: Array.from({ length: pool }, () => ({
39 + active: false,
40 + p: 0,
41 + dur: rand(0.55, 1.0),
42 + wait: rand(0, 1.3),
43 + })),
44 + };
45 +}
46 +
47 +function setCircle(el: SVGCircleElement | null, x: number, y: number, op: number, r: number) {
48 + if (!el) return;
49 + el.setAttribute('cx', String(x));
50 + el.setAttribute('cy', String(y));
51 + el.setAttribute('r', String(r));
52 + el.style.opacity = String(op);
53 +}
54 +
55 +function stepRealtime(state: RtState, pool: (SVGCircleElement | null)[], from: Pt, to: Pt, dt: number) {
56 + state.slots.forEach((s, k) => {
57 + if (!s.active) {
58 + s.wait -= dt;
59 + if (s.wait <= 0) {
60 + s.active = true;
61 + s.p = 0;
62 + s.dur = rand(0.5, 0.95);
63 + } else {
64 + setCircle(pool[k], 0, 0, 0, 0);
65 + return;
66 + }
67 + }
68 + s.p += dt / s.dur;
69 + if (s.p >= 1) {
70 + s.active = false;
71 + s.wait = rand(0.12, 0.85); // jitter between emissions
72 + setCircle(pool[k], 0, 0, 0, 0);
73 + return;
74 + }
75 + const e = easeOut(s.p);
76 + const op = Math.min(1, s.p * 7) * Math.min(1, (1 - s.p) * 7);
77 + setCircle(pool[k], from.x + (to.x - from.x) * e, from.y + (to.y - from.y) * e, op, 2);
78 + });
79 +}
80 +
81 +function stepPolling(state: PollState, pool: (SVGCircleElement | null)[], spawn: Pt, end: Pt, dt: number) {
82 + state.t += dt;
83 + if (state.t > CYCLE) state.t -= CYCLE;
84 + for (let k = 0; k < pool.length; k++) {
85 + const off = state.offsets[k] ?? { x: 0, y: 0 };
86 + const sx = spawn.x + off.x;
87 + const sy = spawn.y + off.y;
88 + const fillAt = k * FILL_GAP;
89 + if (state.t < fillAt) {
90 + setCircle(pool[k], 0, 0, 0, 0); // hasn't arrived in the box yet
91 + } else if (state.t < T_RELEASE) {
92 + setCircle(pool[k], sx, sy, 0.9, 2); // waiting inside the box
93 + } else {
94 + const mp = (state.t - T_RELEASE) / MOVE_DUR;
95 + if (mp >= 1) {
96 + setCircle(pool[k], 0, 0, 0, 0);
97 + } else {
98 + const e = easeOut(mp);
99 + setCircle(pool[k], sx + (end.x - sx) * e, sy + (end.y - sy) * e, 1, 2);
100 + }
101 + }
102 + }
103 +}
104 +
105 +/**
106 + * TriggersFlow — branded flow diagram for the Triggers concept page.
107 + *
108 + * Connected apps fan into the bare Composio logo (the hub), which fans out to
109 + * the single webhook URL you configure. The animation models the actual
110 + * behavior: realtime sources emit a packet that leaves almost as soon as it
111 + * appears (with jitter), while the polling source accumulates packets inside
112 + * its box and releases the whole batch on each poll tick. The point: however an
113 + * event reaches Composio, there is only one destination you configure.
114 + *
115 + * Client component: geometry is measured from live layout; packets are driven
116 + * by requestAnimationFrame. Honors prefers-reduced-motion (rails only).
117 + */
118 +export function TriggersFlow() {
119 + const rootRef = useRef<HTMLDivElement>(null);
120 + const appRefs = useRef<(HTMLLIElement | null)[]>([]);
121 + const hubRef = useRef<HTMLSpanElement>(null);
122 + const targetRef = useRef<HTMLDivElement>(null);
123 +
124 + const geomRef = useRef<Geom>(null);
125 + const inCircles = useRef<(SVGCircleElement | null)[][]>([[], [], []]);
126 + const outCircles = useRef<(SVGCircleElement | null)[]>([]);
127 + const simRef = useRef<{ ins: (RtState | PollState)[]; out: RtState } | null>(null);
128 +
129 + const [rails, setRails] = useState<{ ins: Line[]; out: Line | null }>({ ins: [], out: null });
130 + const [animate, setAnimate] = useState(true);
131 + const [pollFiring, setPollFiring] = useState(false);
132 + const firingRef = useRef(false);
133 +
134 + const poolSize = (kind: 'realtime' | 'polling') => (kind === 'polling' ? POLL_POOL : RT_POOL);
135 +
136 + const calc = useCallback(() => {
137 + const root = rootRef.current;
138 + const hub = hubRef.current;
139 + const target = targetRef.current;
140 + if (!root || !hub || !target) return;
141 + const cr = root.getBoundingClientRect();
142 + const hubR = hub.getBoundingClientRect();
143 + const tgtR = target.getBoundingClientRect();
144 + const hubLeft: Pt = { x: hubR.left - cr.left, y: hubR.top - cr.top + hubR.height / 2 };
145 + const hubRight: Pt = { x: hubR.right - cr.left, y: hubLeft.y };
146 + const tgtLeft: Pt = { x: tgtR.left - cr.left, y: tgtR.top - cr.top + tgtR.height / 2 };
147 +
148 + const ins: InGeom[] = [];
149 + const inLines: Line[] = [];
150 + appRefs.current.forEach((el, i) => {
151 + if (!el) return;
152 + const r = el.getBoundingClientRect();
153 + const y = r.top - cr.top + r.height / 2;
154 + const edge: Pt = { x: r.right - cr.left, y };
155 + // Spawn inside the card, in the clear right-hand lane (the extra pr on each
156 + // row), so packets read as coming from the app without covering its label.
157 + const spawn: Pt = { x: edge.x - 13, y };
158 + // Fan the convergence points slightly so the lines don't knot at the logo.
159 + const end: Pt = { x: hubLeft.x - 2, y: hubLeft.y + (i - 1) * 5 };
160 + ins[i] = { spawn, edge, end };
161 + inLines[i] = { x1: edge.x, y1: edge.y, x2: end.x, y2: end.y, dashed: SOURCES[i]?.kind === 'polling' };
162 + });
163 +
164 + geomRef.current = { ins, out: { spawn: hubRight, end: tgtLeft } };
165 + setRails({ ins: inLines, out: { x1: hubRight.x, y1: hubRight.y, x2: tgtLeft.x, y2: tgtLeft.y, dashed: false } });
166 + }, []);
167 +
168 + useEffect(() => {
169 + simRef.current = {
170 + ins: SOURCES.map((s) =>
171 + s.kind === 'realtime'
172 + ? makeRt(RT_POOL)
173 + : { t: 0, offsets: Array.from({ length: POLL_POOL }, () => ({ x: rand(-6, 3), y: rand(-7, 7) })) }
174 + ),
175 + out: makeRt(OUT_POOL),
176 + };
177 +
178 + calc();
179 + const t = setTimeout(calc, 120);
180 + window.addEventListener('resize', calc);
181 + const root = rootRef.current;
182 + const ro = root ? new ResizeObserver(() => calc()) : null;
183 + if (root && ro) ro.observe(root);
184 +
185 + const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
186 + setAnimate(!mq.matches);
187 + const onMq = () => setAnimate(!mq.matches);
188 + mq.addEventListener('change', onMq);
189 +
190 + let raf = 0;
191 + let last: number | null = null;
192 + const loop = (ts: number) => {
193 + if (last === null) last = ts;
194 + const dt = Math.min(0.05, (ts - last) / 1000);
195 + last = ts;
196 + const geom = geomRef.current;
197 + const sim = simRef.current;
198 + if (geom && sim && !mq.matches) {
199 + SOURCES.forEach((src, i) => {
200 + const g = geom.ins[i];
201 + const pool = inCircles.current[i];
202 + if (!g || !pool) return;
203 + if (src.kind === 'realtime') stepRealtime(sim.ins[i] as RtState, pool, g.spawn, g.end, dt);
204 + else stepPolling(sim.ins[i] as PollState, pool, g.spawn, g.end, dt);
205 + });
206 + stepRealtime(sim.out, outCircles.current, geom.out.spawn, geom.out.end, dt);
207 +
208 + // Light the polling tag while the batch is firing, with a buffer either side.
209 + const pollIdx = SOURCES.findIndex((s) => s.kind === 'polling');
210 + if (pollIdx >= 0) {
211 + const ps = sim.ins[pollIdx] as PollState;
212 + const BUF = 0.3;
213 + const firing = ps.t >= T_RELEASE - BUF && ps.t <= T_RELEASE + MOVE_DUR + BUF;
214 + if (firing !== firingRef.current) {
215 + firingRef.current = firing;
216 + setPollFiring(firing);
217 + }
218 + }
219 + }
220 + raf = requestAnimationFrame(loop);
221 + };
222 + raf = requestAnimationFrame(loop);
223 +
224 + return () => {
225 + clearTimeout(t);
226 + cancelAnimationFrame(raf);
227 + window.removeEventListener('resize', calc);
228 + ro?.disconnect();
229 + mq.removeEventListener('change', onMq);
230 + };
231 + }, [calc]);
232 +
233 + return (
234 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
235 + {/* header strip */}
236 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
237 + <span>triggers.delivery</span>
238 + <span className="inline-flex items-center gap-1.5 text-fd-foreground/55">
239 + <span className="relative inline-flex">
240 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" />
241 + <span className="absolute inset-0 animate-ping rounded-full bg-[var(--composio-brand)] opacity-60" />
242 + </span>
243 + one webhook URL
244 + </span>
245 + </div>
246 +
247 + <div ref={rootRef} className="relative flex flex-col gap-5 p-4 md:block md:h-[300px] md:p-6">
248 + {/* ── connector + packet overlay (md and up) ── */}
249 + <svg
250 + aria-hidden="true"
251 + className="pointer-events-none absolute inset-0 z-20 hidden size-full overflow-visible md:block"
252 + fill="none"
253 + style={{ color: 'var(--composio-brand)' }}
254 + >
255 + {rails.ins.map((l, i) => (
256 + <line
257 + key={SOURCES[i]?.slug ?? i}
258 + opacity={0.18}
259 + stroke="currentColor"
260 + strokeDasharray={l.dashed ? '3 4' : undefined}
261 + strokeWidth={1.25}
262 + x1={l.x1}
263 + x2={l.x2}
264 + y1={l.y1}
265 + y2={l.y2}
266 + />
267 + ))}
268 + {rails.out && (
269 + <line opacity={0.18} stroke="currentColor" strokeWidth={1.25} x1={rails.out.x1} x2={rails.out.x2} y1={rails.out.y1} y2={rails.out.y2} />
270 + )}
271 + {animate &&
272 + SOURCES.map((src, i) => (
273 + <g key={src.slug} fill="currentColor">
274 + {Array.from({ length: poolSize(src.kind) }).map((_, k) => (
275 + <circle
276 + key={k}
277 + cx={0}
278 + cy={0}
279 + r={2}
280 + ref={(el) => {
281 + inCircles.current[i][k] = el;
282 + }}
283 + style={{ opacity: 0 }}
284 + />
285 + ))}
286 + </g>
287 + ))}
288 + {animate && (
289 + <g fill="currentColor">
290 + {Array.from({ length: OUT_POOL }).map((_, k) => (
291 + <circle
292 + key={k}
293 + cx={0}
294 + cy={0}
295 + r={2}
296 + ref={(el) => {
297 + outCircles.current[k] = el;
298 + }}
299 + style={{ opacity: 0 }}
300 + />
301 + ))}
302 + </g>
303 + )}
304 + </svg>
305 +
306 + {/* ── Connected apps ── */}
307 + <div className="relative z-10 md:absolute md:top-1/2 md:left-0 md:w-[248px] md:-translate-y-1/2">
308 + <p className="mb-2 font-mono text-[10px] font-medium uppercase tracking-[0.07em] text-fd-foreground/55">
309 + Connected apps
310 + </p>
311 + <ul className="overflow-hidden rounded-sm border border-fd-border bg-fd-card">
312 + {SOURCES.map((app, i) => (
313 + <li
314 + key={app.slug}
315 + ref={(el) => {
316 + appRefs.current[i] = el;
317 + }}
318 + className={
319 + 'flex items-center gap-2 py-2.5 pl-2.5 pr-6' +
320 + (i < SOURCES.length - 1 ? ' border-b border-fd-border' : '')
321 + }
322 + >
323 + <img
324 + alt=""
325 + aria-hidden="true"
326 + className="size-4 object-contain"
327 + draggable={false}
328 + src={`${LOGO_CDN}/${app.slug}`}
329 + />
330 + <span className="text-[12px] text-fd-foreground/80">{app.name}</span>
331 + <KindTag kind={app.kind} active={app.kind === 'polling' && pollFiring} />
332 + </li>
333 + ))}
334 + </ul>
335 + </div>
336 +
337 + {/* ── Composio (bare logo hub, no card) ── */}
338 + <div className="relative z-10 flex justify-center md:absolute md:top-1/2 md:left-1/2 md:block md:-translate-x-1/2 md:-translate-y-1/2 md:text-center">
339 + <span ref={hubRef} className="inline-flex flex-col items-center">
340 + <img
341 + alt="Composio"
342 + className="h-7 w-auto object-contain dark:hidden"
343 + draggable={false}
344 + src="/Composio Logo.svg"
345 + />
346 + <img
347 + alt="Composio"
348 + className="hidden h-7 w-auto object-contain dark:block"
349 + draggable={false}
350 + src="/Composio Logo Dark.svg"
351 + />
352 + </span>
353 + </div>
354 +
355 + {/* ── Your application ── */}
356 + <div className="relative z-10 md:absolute md:top-1/2 md:right-0 md:w-[248px] md:-translate-y-1/2">
357 + <p className="mb-2 font-mono text-[10px] font-medium uppercase tracking-[0.07em] text-fd-foreground/55">
358 + Your application
359 + </p>
360 + <div ref={targetRef} className="border border-fd-border bg-fd-card p-3">
361 + <div className="flex items-center gap-2">
362 + <span className="flex size-7 items-center justify-center rounded-sm bg-[var(--composio-brand)]/10 text-[var(--composio-brand)]">
363 + <Webhook className="size-3.5" aria-hidden="true" />
364 + </span>
365 + <div className="min-w-0">
366 + <div className="truncate text-[12px] font-medium leading-tight text-fd-foreground">
367 + Your webhook URL
368 + </div>
369 + <div className="truncate font-mono text-[10px] text-fd-foreground/45">
370 + POST /webhooks/composio
371 + </div>
372 + </div>
373 + </div>
374 + <p className="mt-2.5 inline-flex items-center gap-1.5 text-[11px] leading-snug text-fd-foreground/55">
375 + <Check className="size-3 text-[var(--composio-brand)]" aria-hidden="true" />
376 + One URL receives every event.
377 + </p>
378 + </div>
379 + </div>
380 + </div>
381 +
382 + {/* footer caption */}
383 + <div className="border-t border-fd-border px-3 py-2 text-center font-mono text-[10px] text-fd-foreground/45">
384 + app event <Arrow /> Composio <Arrow /> your webhook URL
385 + </div>
386 + </div>
387 + );
388 +}
389 +
390 +function KindTag({ kind, active = false }: { kind: 'realtime' | 'polling'; active?: boolean }) {
391 + const realtime = kind === 'realtime';
392 + const lit = realtime || active;
393 + return (
394 + <span
395 + className={
396 + 'ml-auto inline-flex items-center gap-1 font-mono text-[9px] uppercase tracking-[0.05em] transition-colors duration-300 ' +
397 + (lit ? 'text-[var(--composio-brand)]' : 'text-fd-foreground/40')
398 + }
399 + >
400 + {realtime ? (
401 + <Radio className="size-2.5" aria-hidden="true" />
402 + ) : (
403 + <RefreshCw className={'size-2.5' + (active ? ' animate-spin' : '')} aria-hidden="true" />
404 + )}
405 + {kind}
406 + </span>
407 + );
408 +}
409 +
410 +function Arrow() {
411 + return (
412 + <span aria-hidden="true" className="text-[var(--composio-brand)]">
413 + {'→'}
414 + </span>
415 + );
416 +}
docs/components/version-selector.tsx
+1 -1
@@ -35,7 +35,7 @@ export function NavVersionSelector() {
35
36 if (newVersion === '3.0') {
37 // Shared pages — go to v3 overview
38 - if (path.includes('/sdk-reference') || path.includes('/meta-tools') || path === '/reference') {
38 + if (path.includes('/sdk-reference') || path === '/reference') {
39 window.location.href = '/reference/v3';
40 } else {
41 window.location.href = path.replace('/reference/', '/reference/v3/');
docs/components/white-label-flow.tsx new
+123
@@ -0,0 +1,123 @@
1 +import { CornerDownLeft } from 'lucide-react';
2 +
3 +const NODES: {
4 + label: string;
5 + sub: string;
6 + edge?: string;
7 + accent?: boolean;
8 +}[] = [
9 + { label: 'Your app', sub: 'user starts here' },
10 + {
11 + label: 'OAuth toolkit',
12 + sub: 'Google, GitHub, …',
13 + edge: 'user connects',
14 + },
15 + {
16 + label: 'yourdomain.com',
17 + sub: 'your proxy endpoint',
18 + edge: 'redirects user',
19 + accent: true,
20 + },
21 + {
22 + label: 'backend.composio.dev',
23 + sub: 'captures the token',
24 + edge: 'forwards redirect',
25 + },
26 +];
27 +
28 +/**
29 + * WhiteLabelFlow — branded replacement for the OAuth redirect-proxy mermaid
30 + * diagram on the white-labeling pages.
31 + *
32 + * Shows the browser redirect hop through your own domain: the user connects,
33 + * the toolkit redirects to your proxy, your proxy forwards to Composio, and
34 + * Composio sends the user back to your app. Your domain is brand-accented
35 + * because it's the white-label point. The proxy never touches the token, only
36 + * the browser redirect. Server component, light/dark via fd-* tokens.
37 + */
38 +export function WhiteLabelFlow() {
39 + return (
40 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
41 + {/* header strip */}
42 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
43 + <span>oauth.redirect</span>
44 + <span className="text-fd-foreground/55">browser hops only</span>
45 + </div>
46 +
47 + {/* the hops */}
48 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-4">
49 + {NODES.map((node, i) => {
50 + const last = i === NODES.length - 1;
51 + return (
52 + <div
53 + key={node.label}
54 + className="relative flex flex-col gap-2 bg-fd-background p-3"
55 + >
56 + {/* edge label sits above the node it points into */}
57 + <span className="font-mono text-[9px] uppercase tracking-[0.06em] text-fd-foreground/40">
58 + {node.edge ? `→ ${node.edge}` : ' '}
59 + </span>
60 + <div className="flex flex-1 items-center">
61 + <div
62 + className={
63 + 'relative w-full border p-3 ' +
64 + (node.accent
65 + ? 'border-[var(--composio-brand)]/30 bg-[var(--composio-brand)]/[0.04]'
66 + : 'border-fd-border bg-fd-card')
67 + }
68 + >
69 + {node.accent && (
70 + <span
71 + aria-hidden="true"
72 + className="pointer-events-none absolute inset-y-0 left-0 w-[2px] bg-[var(--composio-brand)]"
73 + />
74 + )}
75 + <code
76 + className={
77 + 'block truncate font-mono text-[12px] font-medium ' +
78 + (node.accent
79 + ? 'text-[var(--composio-brand)]'
80 + : 'text-fd-foreground')
81 + }
82 + >
83 + {node.label}
84 + </code>
85 + <span className="mt-1 block truncate font-mono text-[10px] text-fd-foreground/45">
86 + {node.sub}
87 + </span>
88 + </div>
89 + </div>
90 + {!last && <Connector />}
91 + </div>
92 + );
93 + })}
94 + </div>
95 +
96 + {/* the return hop */}
97 + <div className="flex items-center justify-center gap-1.5 border-t border-fd-border px-3 py-2 font-mono text-[10px] text-fd-foreground/50">
98 + <CornerDownLeft
99 + aria-hidden="true"
100 + className="size-3 text-[var(--composio-brand)]"
101 + />
102 + Composio redirects the user back to{' '}
103 + <code className="text-fd-foreground/70">your app</code>. Your proxy
104 + never sees the token
105 + </div>
106 + </div>
107 + );
108 +}
109 +
110 +function Connector() {
111 + return (
112 + <div
113 + aria-hidden="true"
114 + className="pointer-events-none absolute z-10 hidden md:block"
115 + style={{ right: '-7px', top: '50%' }}
116 + >
117 + <div className="flex items-center">
118 + <span className="h-px w-3 bg-fd-border" />
119 + <span className="size-0 border-y-[3px] border-l-[5px] border-y-transparent border-l-fd-border" />
120 + </div>
121 + </div>
122 + );
123 +}
docs/components/workbench-flow.tsx new
+136
@@ -0,0 +1,136 @@
1 +import { Search, Layers, Terminal, Check } from 'lucide-react';
2 +import type { ReactNode } from 'react';
3 +
4 +const STEPS: {
5 + n: string;
6 + icon: ReactNode;
7 + tool: string;
8 + note: string;
9 +}[] = [
10 + {
11 + n: '01',
12 + icon: <Search className="size-3.5" aria-hidden="true" />,
13 + tool: 'SEARCH_TOOLS',
14 + note: 'Discovers the Gmail and Sheets tools',
15 + },
16 + {
17 + n: '02',
18 + icon: <Layers className="size-3.5" aria-hidden="true" />,
19 + tool: 'MULTI_EXECUTE',
20 + note: 'Fetches the unread emails',
21 + },
22 + {
23 + n: '03',
24 + icon: <Terminal className="size-3.5" aria-hidden="true" />,
25 + tool: 'REMOTE_WORKBENCH',
26 + note: 'Classifies, labels, and logs to the sheet in parallel',
27 + },
28 +];
29 +
30 +/**
31 + * WorkbenchFlow — branded replacement for the meta-tool pipeline mermaid
32 + * diagram on the Workbench page.
33 + *
34 + * Reads as a story: one user request flows through the meta tools, escalating
35 + * from discovery to bulk execution to the workbench when the task gets too
36 + * complex for individual calls. The third step is brand-accented because it's
37 + * the page's subject. Server component, no client JS, light/dark via fd-* tokens.
38 + */
39 +export function WorkbenchFlow() {
40 + return (
41 + <div className="not-prose my-6 overflow-hidden rounded-sm border border-fd-border bg-fd-background">
42 + {/* header strip */}
43 + <div className="flex items-center justify-between border-b border-fd-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.06em] text-fd-foreground/45">
44 + <span>session.sandbox</span>
45 + <span className="inline-flex items-center gap-1.5 text-fd-foreground/55">
46 + <span className="relative inline-flex">
47 + <span className="size-1.5 rounded-full bg-[var(--composio-brand)]" />
48 + <span className="absolute inset-0 animate-ping rounded-full bg-[var(--composio-brand)] opacity-60" />
49 + </span>
50 + meta tools
51 + </span>
52 + </div>
53 +
54 + {/* the request */}
55 + <div className="flex items-start gap-2 border-b border-fd-border px-3 py-2.5">
56 + <span className="mt-px flex size-5 shrink-0 items-center justify-center rounded-full bg-[var(--composio-brand)]/12 font-mono text-[10px] font-medium text-[var(--composio-brand)]">
57 + U
58 + </span>
59 + <p className="text-[12px] italic leading-snug text-fd-foreground/70">
60 + &ldquo;Triage my emails, label the urgent ones, and log them to a
61 + Google Sheet.&rdquo;
62 + </p>
63 + </div>
64 +
65 + {/* the pipeline */}
66 + <div className="grid items-stretch gap-px bg-fd-border md:grid-cols-3">
67 + {STEPS.map((step, i) => {
68 + const last = i === STEPS.length - 1;
69 + return (
70 + <div
71 + key={step.tool}
72 + className="relative flex flex-col gap-2 bg-fd-background p-3"
73 + >
74 + <div className="flex items-center gap-2">
75 + <span
76 + className={
77 + 'flex size-6 shrink-0 items-center justify-center rounded-sm font-mono text-[10px] font-medium ' +
78 + (last
79 + ? 'bg-[var(--composio-brand)]/12 text-[var(--composio-brand)]'
80 + : 'bg-fd-foreground/[0.06] text-fd-foreground/55')
81 + }
82 + >
83 + {step.n}
84 + </span>
85 + <span
86 + className={
87 + 'flex size-6 shrink-0 items-center justify-center rounded-sm ' +
88 + (last
89 + ? 'bg-[var(--composio-brand)]/10 text-[var(--composio-brand)]'
90 + : 'bg-fd-foreground/[0.04] text-fd-foreground/45')
91 + }
92 + >
93 + {step.icon}
94 + </span>
95 + </div>
96 + <div className="min-w-0">
97 + <code className="block truncate font-mono text-[12px] font-medium text-fd-foreground">
98 + {step.tool}
99 + </code>
100 + <p className="mt-1 text-[11px] leading-snug text-fd-foreground/55">
101 + {step.note}
102 + </p>
103 + </div>
104 + {!last && <Connector />}
105 + </div>
106 + );
107 + })}
108 + </div>
109 +
110 + {/* footer caption */}
111 + <div className="flex items-center justify-center gap-1.5 border-t border-fd-border px-3 py-2 font-mono text-[10px] text-fd-foreground/45">
112 + <Check aria-hidden="true" className="size-3 text-[var(--composio-brand)]" />
113 + emails triaged, labeled, and logged
114 + </div>
115 + </div>
116 + );
117 +}
118 +
119 +/**
120 + * Directional connector between steps. Horizontal arrow on desktop, hidden on
121 + * stacked mobile (vertical order already reads top-to-bottom).
122 + */
123 +function Connector() {
124 + return (
125 + <div
126 + aria-hidden="true"
127 + className="pointer-events-none absolute z-10 hidden md:block"
128 + style={{ right: '-7px', top: '50%' }}
129 + >
130 + <div className="flex items-center">
131 + <span className="h-px w-3 bg-fd-border" />
132 + <span className="size-0 border-y-[3px] border-l-[5px] border-y-transparent border-l-fd-border" />
133 + </div>
134 + </div>
135 + );
136 +}
docs/content/changelog/04-17-26.mdx
+2 -2
@@ -15,7 +15,7 @@ Search, filter, and paginate individual tool execution events. Use this for debu
15
16 Authentication: project API key (`x-api-key`) or session cookie.
17
18 -See the [tool execution logs guide](/docs/observability/logs).
18 +See the [tool execution logs guide](/reference/api-reference/logs).
19
20 ## Usage metering
21
@@ -26,4 +26,4 @@ Aggregated counts of tool calls and sessions. Summary endpoints return totals; b
26
27 Entity types: `tool_calls`, `sessions`. Time ranges are epoch milliseconds; max range 366 days.
28
29 -See the [usage metering guide](/docs/observability/usage).
29 +See the [usage metering guide](/reference/api-reference/organization).
docs/content/changelog/04-24-26-trigger-disabled-event.mdx
+1 -1
@@ -59,4 +59,4 @@ The event is V3-only. Subscriptions on V1 or V2 payloads cannot enable it.
59 }
60 ```
61
62 -See [subscribing to triggers](/docs/setting-up-triggers/subscribing-to-events) for handler setup and [subscribing to connection expiry events](/docs/subscribing-to-connection-expiry-events) for re-auth flows on `connection_expired`.
62 +See [subscribing to triggers](/docs/setting-up-triggers/subscribing-to-events) for handler setup and [subscribing to connection expiry events](/docs/authentication#connection-lifecycle) for re-auth flows on `connection_expired`.
docs/content/changelog/04-28-26-sdk-sandbox-size.mdx
+1 -1
@@ -4,7 +4,7 @@ description: 'TypeScript and Python SDKs gain `workbench.sandboxSize` / `workben
4 date: '2026-04-28'
5 ---
6
7 -The Composio SDKs now let you pick the compute tier of the [workbench](/docs/workbench) sandbox when creating a Tool Router session. Heavier code execution and larger in-memory data benefit from a bigger sandbox.
7 +The Composio SDKs now let you pick the compute tier of the [sandbox](/docs/sandbox/remote) when creating a Tool Router session. Heavier code execution and larger in-memory data benefit from a bigger sandbox.
8
9 | Tier | vCPU | RAM |
10 | ---------- | ---- | ----- |
docs/content/changelog/05-07-26-toolrouter-preload-direct-tools.mdx
+1 -1
@@ -210,5 +210,5 @@ console.log(tools.map((tool) => tool.name));
210
211 See [Preloading tools](/docs/configuring-sessions#preloading-tools),
212 [Direct tools preset](/docs/configuring-sessions#direct-tools-preset), and
213 -[Preloading custom tools](/docs/toolkits/custom-tools-and-toolkits#preloading-custom-tools)
213 +[Preloading custom tools](/docs/extending-sessions/custom-tools-and-toolkits#preloading-custom-tools)
214 for Python examples and full guidance.
docs/content/changelog/05-08-26-session-use-update-connected-accounts.mdx
+1 -1
@@ -41,7 +41,7 @@ const tools = await session.tools();
41 </Tab>
42 </Tabs>
43
44 -Custom tools can also be attached when reusing a session. See [Reusing a session](/docs/how-composio-works#how-sessions-behave) and [Custom tools](/docs/toolkits/custom-tools-and-toolkits#reusing-a-session-with-custom-tools).
44 +Custom tools can also be attached when reusing a session. See [Reusing a session](/docs/how-composio-works#how-sessions-behave) and [Custom tools](/docs/extending-sessions/custom-tools-and-toolkits#reusing-a-session-with-custom-tools).
45
46 ### Update session config with `session.update()`
47
docs/content/changelog/06-04-26-security-reliability-hardening.mdx
+1 -1
@@ -19,7 +19,7 @@ A summary of recent security, API, and platform changes you may need to act on.
19 - Proxy Execute requests have a 250MB payload cap.
20
21 ### Connections
22 -- Connected-account tokens are redacted in API responses, for both Composio-managed and custom auth configs. Please use [Proxy Execute](https://docs.composio.dev/docs/proxy-execute) instead. If you need this for some special case please reach out to support.
22 +- Connected-account tokens are redacted in API responses, for both Composio-managed and custom auth configs. Please use [Proxy Execute](/reference/api-reference/tools) instead. If you need this for some special case please reach out to support.
23 - Reiterating: Composio-managed OAuth connections are moving from `initiate` to `link`. The cutover for remaining organizations is July 3, 2026.
24
25 ### Workbench
docs/content/changelog/06-17-26-posthog-region.mdx
+7 -7
@@ -4,18 +4,18 @@ description: "The PostHog region is now a per-connection setting. Existing conne
4 date: "2026-06-17"
5 ---
6
7 -The PostHog **region** (`us` or `eu`) is now set on the **connection** instead of the auth config. It used to be an auth-config setting, which fixed a single region for everyone connecting through that config, but region is really per-connection: different users can be in different regions.
7 +The PostHog **region** (`us` or `eu`) now lives on the **connection** instead of the auth config. Region is genuinely per-connection — different users can sit in different PostHog regions — so fixing it at the auth config forced everyone through one region. Each connection now carries its own.
8
9 -We have already taken care of existing connections, so nothing changes for you and there is no re-auth. If a connection was on the default (`us`), it stays on the default; if it used a different region such as `eu`, we carried that value over.
9 +You don't need to do anything. We migrated every existing connection with no re-auth: connections on the default (`us`) stay on `us`, and any that used another region such as `eu` keep that value.
10
11 ### Going forward
12
13 -- Set `us` (US Cloud) or `eu` (EU Cloud) on the connection. The host is built as `<region>.posthog.com`, so a full URL will not work, and PostHog self-hosted (on-prem) is not supported.
14 -- **[Link flow](https://docs.composio.dev/reference/api-reference/connected-accounts/postConnectedAccountsLink)**: the Region field appears when the user connects, prefilled with your default and editable.
15 -- **[Initiate flow](https://docs.composio.dev/reference/api-reference/connected-accounts/postConnectedAccounts)**: you set the region; the end user does not see it.
13 +- Set `us` (US Cloud) or `eu` (EU Cloud) on the connection. The host is built as `<region>.posthog.com`, so a full URL won't work and self-hosted PostHog isn't supported.
14 +- **[Link flow](/reference/api-reference/connected-accounts/postConnectedAccountsLink)**: the Region field appears when the user connects, prefilled with your default and editable.
15 +- **[Initiate flow](/reference/api-reference/connected-accounts/postConnectedAccounts)**: you set the region, and the end user never sees it.
16
17 ### Setting a default on your auth config
18
19 -The region default for an auth config lives in its `shared_credentials`. If you were on the default (`us`), nothing was written there. To pin a region explicitly, set `shared_credentials` when you [create an auth config](https://docs.composio.dev/reference/api-reference/auth-configs/postAuthConfigs), or update an existing one with [patch auth config](https://docs.composio.dev/reference/api-reference/auth-configs/patchAuthConfigsByNanoid).
19 +An auth config's region default lives in its `shared_credentials`. If you were on the default (`us`), nothing was written there. To pin a region explicitly, set `shared_credentials` when you [create an auth config](/reference/api-reference/auth-configs/postAuthConfigs), or [patch an existing one](/reference/api-reference/auth-configs/patchAuthConfigsByNanoid).
20
21 -See the [PostHog toolkit docs](https://docs.composio.dev/toolkits/posthog) for the current connection fields.
21 +See the [PostHog toolkit docs](/toolkits/posthog) for the current connection fields.
docs/content/cookbooks/app-connections-dashboard.mdx deleted
-107
@@ -1,107 +0,0 @@
1 ----
2 -title: Build an App Connections Dashboard
3 -description: Build a dashboard for managing user app connections and auth status
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/app-connections-dashboard)
7 -
8 -[Build a Chat App](/cookbooks/chat-app) handles authentication in-chat. That works for getting started, but production apps need a dedicated page where users manage their connections. This cookbook builds a dashboard where users can see all available apps, connect via OAuth, and disconnect at any time.
9 -
10 -## What you'll build
11 -
12 -- A connections dashboard showing all available apps and their auth status
13 -- Connect and disconnect buttons that handle OAuth flows
14 -
15 -## Prerequisites
16 -
17 -- [Bun](https://bun.sh) (or Node.js 18+)
18 -- [Composio API key](https://dashboard.composio.dev/settings)
19 -
20 -**Stack:** Next.js, `@composio/core`
21 -
22 -## Create the project
23 -
24 -```bash
25 -bunx create-next-app composio-dashboard --yes
26 -cd composio-dashboard
27 -bun add @composio/core
28 -```
29 -
30 -Add your API key to a `.env.local` file:
31 -
32 -```bash title=".env.local"
33 -COMPOSIO_API_KEY=your_composio_api_key
34 -```
35 -
36 -## Setting up the client
37 -
38 -Create `app/api/connections/route.ts`. Initialize the Composio client and set `dynamic = "force-dynamic"` so Next.js always fetches fresh connection data.
39 -
40 -<include meta='no-twoslash title="app/api/connections/route.ts"'>../../examples/app-connections-dashboard/connections-route.ts#setup</include>
41 -
42 -`"user_123"` is a placeholder. In production, replace it with the authenticated user's ID from your auth system. See [What is a session?](/docs/how-composio-works) for details.
43 -
44 -## List connections
45 -
46 -The `GET` handler creates a session and returns every toolkit's name, logo, and connection status. Toolkits where `isNoAuth` is `true` don't require authentication, so we filter them out.
47 -
48 -<include meta='no-twoslash title="app/api/connections/route.ts"'>../../examples/app-connections-dashboard/connections-route.ts#list</include>
49 -
50 -`session.toolkits()` returns each toolkit with a `connection` object. When `connection.isActive` is `true`, the user has already authorized that app. We also return the `connectedAccountId` so the frontend can disconnect later.
51 -
52 -<Callout>
53 -`session.toolkits()` paginates results. This example fetches up to 50. Use the `nextCursor` value from the response to fetch the next page.
54 -</Callout>
55 -
56 -## Connect an app
57 -
58 -The `POST` handler starts an OAuth flow for a given toolkit and returns the redirect URL.
59 -
60 -<include meta='no-twoslash title="app/api/connections/route.ts"'>../../examples/app-connections-dashboard/connections-route.ts#connect</include>
61 -
62 -`session.authorize(toolkit)` creates a connection request with a `callbackUrl`. After the user completes OAuth, they get redirected back to your app.
63 -
64 -## Disconnect an app
65 -
66 -Create `app/api/connections/disconnect/route.ts`. This endpoint takes a `connectedAccountId` and deletes it:
67 -
68 -<include meta='title="app/api/connections/disconnect/route.ts"'>../../examples/app-connections-dashboard/disconnect-route.ts</include>
69 -
70 -`composio.connectedAccounts.delete()` is a standalone SDK method. No session or provider needed.
71 -
72 -## Build the dashboard
73 -
74 -Replace `app/page.tsx` with a dashboard that shows connection cards:
75 -
76 -<include meta='title="app/page.tsx"'>../../examples/app-connections-dashboard/page.tsx</include>
77 -
78 -The page fetches toolkit connection status on load. Clicking **Connect** redirects the user to OAuth. After they authorize, the `callbackUrl` brings them back to the dashboard with the connection now active. Clicking **Disconnect** deletes the connection and refreshes the list.
79 -
80 -## Complete route
81 -
82 -The full `app/api/connections/route.ts` with both handlers:
83 -
84 -<include meta='title="app/api/connections/route.ts"'>../../examples/app-connections-dashboard/connections-route.ts</include>
85 -
86 -## Running the app
87 -
88 -```bash
89 -bun dev
90 -```
91 -
92 -Open [localhost:3000](http://localhost:3000). You'll see all available apps with their connection status.
93 -
94 -1. Click **Connect** on GitHub. You'll be redirected to GitHub's OAuth page.
95 -2. Authorize the app. You'll land back on the dashboard with GitHub showing "Connected."
96 -3. Click **Disconnect** on GitHub. The connection is removed immediately.
97 -
98 -## Take it further
99 -
100 -<Cards>
101 - <Card title="Managing multiple connected accounts" href="/docs/managing-multiple-connected-accounts">
102 - Let users connect multiple accounts for the same toolkit
103 - </Card>
104 - <Card title="Connected accounts" href="/docs/auth-configuration/connected-accounts">
105 - List, refresh, disable, and delete user connections
106 - </Card>
107 -</Cards>
docs/content/cookbooks/background-agent.mdx deleted
-129
@@ -1,129 +0,0 @@
1 ----
2 -title: Background Agent
3 -description: Build an autonomous agent that monitors GitHub, Gmail, and Slack and takes action while you sleep
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/background-agent)
7 -
8 -This cookbook builds a background agent that runs a "morning sweep" across your apps. It checks GitHub for PRs that need your review, finds unanswered emails in Gmail, and posts a summary to Slack. One script, three apps, zero human input.
9 -
10 -Run it manually, put it on a cron, or deploy it. The agent does the rest.
11 -
12 -## Prerequisites
13 -
14 -* Node.js 18+
15 -* [Composio API key](https://dashboard.composio.dev/settings)
16 -* [OpenAI API key](https://platform.openai.com/api-keys)
17 -
18 -## Project setup
19 -
20 -Create a new project and install dependencies:
21 -
22 -```bash
23 -mkdir composio-background-agent && cd composio-background-agent
24 -npm init -y
25 -npm install ai @ai-sdk/openai @composio/core @composio/vercel dotenv tsx
26 -```
27 -
28 -Add your API keys to a `.env` file:
29 -
30 -```bash title=".env"
31 -COMPOSIO_API_KEY=your_composio_api_key
32 -OPENAI_API_KEY=your_openai_api_key
33 -```
34 -
35 -## Initializing the clients
36 -
37 -`Composio` takes a `VercelProvider` so that tools come back as Vercel AI SDK tools with built-in execution. No manual tool-call loop needed.
38 -
39 -<include meta="no-twoslash">../../examples/background-agent/sweep.ts#setup</include>
40 -
41 -## The sweep
42 -
43 -The entire agent is one function. Create a session, get tools, and give the model a prompt describing what to do. `generateText` with `stopWhen: stepCountIs(15)` lets the model call as many tools as it needs, discovering available actions, authenticating with apps, and executing across GitHub, Gmail, and Slack, all in a single run.
44 -
45 -<include meta="no-twoslash">../../examples/background-agent/sweep.ts#sweep</include>
46 -
47 -That's it. The agent figures out which tools to call, handles pagination, formats the results, and posts to Slack. Composio's meta-tools handle tool discovery and auth inline. If an app isn't connected, the agent skips it gracefully.
48 -
49 -## Complete script
50 -
51 -<include meta='no-twoslash title="sweep.ts"'>../../examples/background-agent/sweep.ts</include>
52 -
53 -## Running the sweep
54 -
55 -```bash
56 -npx tsx sweep.ts
57 -```
58 -
59 -Example output:
60 -
61 -```
62 -### GitHub: PRs where your review is requested (3)
63 -- fix: robust platform detection (ComposioHQ/composio)
64 - https://github.com/ComposioHQ/composio/pull/2712
65 -- docs: add retry to health check workflow (ComposioHQ/composio)
66 - https://github.com/ComposioHQ/composio/pull/2711
67 -- chore(deps): bump next (ComposioHQ/composio)
68 - https://github.com/ComposioHQ/composio/pull/2473
69 -
70 -### Gmail: Emails from last 24h you haven't replied to (1)
71 -- Stephanie M. - CoreWeave - We'd love to chat!
72 -
73 -### Slack: Digest posted to #morning-sweep
74 -```
75 -
76 -<Callout>
77 -If an app isn't connected yet, the agent will return an authentication link in the output. Open it in your browser to complete OAuth, then run the sweep again.
78 -</Callout>
79 -
80 -## Running on a schedule
81 -
82 -The agent runs once and exits, which makes it perfect for cron jobs. Pick whichever scheduler you prefer.
83 -
84 -### crontab (every day at 8am)
85 -
86 -```bash
87 -crontab -e
88 -```
89 -
90 -```
91 -0 8 * * * cd /path/to/composio-background-agent && npx tsx sweep.ts >> sweep.log 2>&1
92 -```
93 -
94 -### GitHub Actions
95 -
96 -```yaml title=".github/workflows/sweep.yml"
97 -name: Morning Sweep
98 -on:
99 - schedule:
100 - - cron: '0 8 * * *' # 8am UTC daily
101 - workflow_dispatch: # manual trigger
102 -
103 -jobs:
104 - sweep:
105 - runs-on: ubuntu-latest
106 - steps:
107 - - uses: actions/checkout@v4
108 - - uses: actions/setup-node@v4
109 - with:
110 - node-version: 22
111 - - run: npm install
112 - - run: npx tsx sweep.ts
113 - env:
114 - COMPOSIO_API_KEY: ${{ secrets.COMPOSIO_API_KEY }}
115 - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
116 -```
117 -
118 -## Take it further
119 -
120 -The prompt is the agent's brain. Change it to change what it does. Some ideas:
121 -
122 -- **Triage support tickets**: scan Zendesk for unassigned tickets, categorize them, assign to the right team in Linear
123 -- **Daily standup prep**: pull yesterday's commits from GitHub, completed tasks from Linear, and draft a standup summary
124 -- **Invoice follow-up**: check QuickBooks for overdue invoices, draft follow-up emails in Gmail
125 -
126 -<Cards>
127 - <Card title="Hono Server" href="/cookbooks/hono" description="Wrap this agent in an HTTP server so multiple users can interact with it" />
128 - <Card title="Vercel AI SDK Provider" href="/docs/providers/vercel" description="Learn more about how Composio tools work with the Vercel AI SDK" />
129 -</Cards>
docs/content/cookbooks/box-integration.mdx deleted
-31
@@ -1,31 +0,0 @@
1 ----
2 -title: Connect Box to Composio
3 -description: Add Composio to your Box account to connect your files to AI agents and 1000+ apps
4 ----
5 -
6 -## What is Composio?
7 -
8 -Composio is an integration platform that connects Box to AI agents and 1000+ other apps — letting you automate workflows, build AI-powered document pipelines, and connect your Box files to tools like Slack, Gmail, Notion, GitHub, and more.
9 -
10 -## How to Add Composio to Box
11 -
12 -1. Go to [app.composio.dev](https://app.composio.dev)
13 -2. Sign up or log in to your Composio account
14 -3. Search for **Box** in the integrations list
15 -4. Click **Connect** and sign in with your Box account
16 -5. Authorize the requested permissions
17 -6. Done — your Box files are now accessible to any AI agent or workflow you build in Composio
18 -
19 -## What You Can Do
20 -
21 -Once connected, Composio can:
22 -- Read and download your Box files and folders
23 -- Upload and create new files in Box
24 -- Search across your Box content
25 -- Move, copy, rename, and delete files
26 -- Manage folder structures
27 -- Trigger workflows in 1000+ other apps based on Box activity
28 -
29 -## Get Started
30 -
31 -[app.composio.dev](https://app.composio.dev)
docs/content/cookbooks/chat-app.mdx deleted
-127
@@ -1,127 +0,0 @@
1 ----
2 -title: Build a Chat App
3 -description: Build an AI chat app with tool access to 1000+ apps in about 30 lines of code
4 ----
5 -
6 -Give your AI agent access to Gmail, GitHub, Slack, Notion, and 1000+ other apps. This tutorial builds a Next.js chat app that handles tool discovery, user authentication, and action execution in about **30 lines of code**.
7 -
8 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/chat-app)
9 -
10 -## What you'll build
11 -
12 -- A chat app where your agent can find and use tools across 1000+ apps
13 -- In-chat OAuth authentication so users can connect apps directly in the conversation
14 -- A tool call display that shows what the agent is doing in real time
15 -
16 -## Prerequisites
17 -
18 -- [Bun](https://bun.sh) (or Node.js 18+)
19 -- [Composio API key](https://dashboard.composio.dev/settings)
20 -- [OpenAI API key](https://platform.openai.com/api-keys)
21 -
22 -**Stack:** Next.js, Vercel AI SDK, OpenAI, Composio
23 -
24 -## Create the project
25 -
26 -Create a new Next.js app and install the dependencies:
27 -
28 -```bash
29 -bunx create-next-app composio-chat --yes
30 -cd composio-chat
31 -bun add @composio/core @composio/vercel @ai-sdk/openai ai @ai-sdk/react
32 -```
33 -
34 -<Callout type="info">
35 -Get your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings) and `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys).
36 -</Callout>
37 -
38 -Add your API keys to a `.env.local` file in the project root:
39 -
40 -```bash title=".env.local"
41 -COMPOSIO_API_KEY=your_composio_api_key
42 -OPENAI_API_KEY=your_openai_api_key
43 -```
44 -
45 -Start the dev server:
46 -
47 -```bash
48 -bun dev
49 -```
50 -
51 -## Build the backend
52 -
53 -A **session** scopes tools and credentials to a specific user. Create `app/api/chat/route.ts`:
54 -
55 -<include meta='title="app/api/chat/route.ts"'>../../examples/chat-app/route.ts</include>
56 -
57 -That's the entire backend. On the first request, `composio.create("user_123")` creates a session that lets the agent search for tools, authenticate users, and execute actions. Subsequent requests reuse the same session via `composio.use(sessionId)` so tool access and connected accounts carry over. In production, store the session ID per user in your database and use the user ID from your auth system.
58 -
59 -## Build the chat UI
60 -
61 -Replace `app/page.tsx`:
62 -
63 -<include meta='title="app/page.tsx"'>../../examples/chat-app/page.tsx</include>
64 -
65 -Go to [localhost:3000](http://localhost:3000). You should see the chat interface.
66 -
67 -## Try a tool call
68 -
69 -Send this message:
70 -
71 -```
72 -Star the composio repo on GitHub
73 -```
74 -
75 -Here's what happens:
76 -
77 -1. The agent searches for relevant tools, finds `GITHUB_STAR_REPO`, and checks your connection status.
78 -2. You haven't connected GitHub yet, so the agent generates an auth link and shows it to you.
79 -3. Click the link, authorize with GitHub, and tell the agent you're done.
80 -4. The agent executes `GITHUB_STAR_REPO` with your credentials.
81 -
82 -Discovery, authentication, and execution all happened automatically. You didn't write any tool-specific code.
83 -
84 -<Callout>
85 -This in-chat authentication flow works out of the box. For production apps, you can [authenticate users ahead of time](/docs/authenticating-users/manually-authenticating) during onboarding.
86 -</Callout>
87 -
88 -## Show tool calls in the UI
89 -
90 -Tool calls happen invisibly by default. Add a component that shows the tool name and status so you can see what the agent is doing.
91 -
92 -Create `components/ToolCallDisplay.tsx`:
93 -
94 -<include meta='title="components/ToolCallDisplay.tsx"'>../../examples/chat-app/ToolCallDisplay.tsx</include>
95 -
96 -Update `app/page.tsx` to render tool calls:
97 -
98 -<include meta='title="app/page.tsx"'>../../examples/chat-app/page-with-tools.tsx</include>
99 -
100 -Tool calls now show inline with a spinner while running and a checkmark when complete. Click to expand and see the raw output.
101 -
102 -## How it works
103 -
104 -The session handles tool discovery and execution at runtime. Instead of loading thousands of tool definitions into your agent's context, the agent searches for what it needs, authenticates the user if necessary, and executes the action. Token refresh and credential management are handled automatically.
105 -
106 -Try a few more requests:
107 -
108 -- "Summarize my emails from today"
109 -- "What's on my calendar this week?"
110 -- "Create a GitHub issue in my repo"
111 -
112 -## Take it further
113 -
114 -<Cards>
115 - <Card title="Build an App Connections Dashboard" href="/cookbooks/app-connections-dashboard">
116 - A dedicated page where users manage their app connections
117 - </Card>
118 - <Card title="Managing multiple connected accounts" href="/docs/managing-multiple-connected-accounts">
119 - Let users connect multiple accounts for the same toolkit
120 - </Card>
121 - <Card title="Configuring sessions" href="/docs/configuring-sessions">
122 - Lock down which toolkits your agent can access
123 - </Card>
124 - <Card title="What is a session?" href="/docs/how-composio-works">
125 - Understand sessions, tool discovery, and execution under the hood
126 - </Card>
127 -</Cards>
docs/content/cookbooks/fast-api.mdx deleted
-114
@@ -1,114 +0,0 @@
1 ----
2 -title: Basic FastAPI Server
3 -description: Build an AI agent with access to 1000+ tools using Composio and FastAPI
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/fast-api)
7 -
8 -This cookbook builds a FastAPI server where users can chat with an AI agent that has access to over 1000 tools like Gmail, GitHub, Slack, Notion, and more. Along the way we'll add endpoints to manage which apps a user has connected.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -* [OpenAI API key](https://platform.openai.com/api-keys)
16 -
17 -## Project setup
18 -
19 -Create a new project and install dependencies:
20 -
21 -```bash
22 -mkdir composio-fastapi && cd composio-fastapi
23 -uv init && uv add composio composio-openai-agents openai-agents fastapi uvicorn pydantic
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -OPENAI_API_KEY=your_openai_api_key
31 -```
32 -
33 -## Initializing the clients
34 -
35 -`Composio` takes an `OpenAIAgentsProvider` so that when we ask for tools later, they come back in the format the OpenAI Agents SDK expects.
36 -
37 -<include>../../examples/fast-api/main.py#setup</include>
38 -
39 -## Chat endpoint
40 -
41 -The core of the server is a `/chat` endpoint. A user sends a message, and the agent responds, using whatever tools it needs.
42 -
43 -`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to an `Agent` and let `Runner.run_sync` handle the agentic loop.
44 -
45 -<include>../../examples/fast-api/main.py#chat</include>
46 -
47 -<Callout>
48 -If the user hasn't connected the app they're trying to use, the agent will automatically
49 -return an authentication link in its response. The user can complete OAuth and then retry.
50 -</Callout>
51 -
52 -That's a working agent. But in most apps you'll also want to manage connections outside of chat, for example to show users what's connected or let them connect new apps from a settings page.
53 -
54 -## Checking connections
55 -
56 -`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
57 -
58 -<include>../../examples/fast-api/main.py#list-connections</include>
59 -
60 -If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
61 -
62 -<include>../../examples/fast-api/main.py#check-connection</include>
63 -
64 -## Connecting an app
65 -
66 -When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
67 -
68 -<include>../../examples/fast-api/main.py#connect</include>
69 -
70 -## Complete app
71 -
72 -Here's everything together:
73 -
74 -<include>../../examples/fast-api/main.py</include>
75 -
76 -## Running the server
77 -
78 -```bash
79 -uv run --env-file .env uvicorn main:app --reload
80 -```
81 -
82 -The server runs at `http://localhost:8000`. Visit `/docs` for the interactive Swagger UI.
83 -
84 -## Testing with cURL
85 -
86 -### Chat with the agent
87 -
88 -```bash
89 -curl -X POST http://localhost:8000/chat \
90 - -H "Content-Type: application/json" \
91 - -d '{"user_id": "user_123", "message": "Star the composiohq/composio repo on GitHub"}'
92 -```
93 -
94 -### List all connections
95 -
96 -```bash
97 -curl http://localhost:8000/connections/user_123
98 -```
99 -
100 -### Check a specific connection
101 -
102 -```bash
103 -curl http://localhost:8000/connections/user_123/gmail
104 -```
105 -
106 -### Connect an app
107 -
108 -```bash
109 -curl -X POST http://localhost:8000/connect/gmail \
110 - -H "Content-Type: application/json" \
111 - -d '{"user_id": "user_123"}'
112 -```
113 -
114 -Open the `redirect_url` from the response in your browser to complete OAuth.
docs/content/cookbooks/gmail-labeler.mdx deleted
-96
@@ -1,96 +0,0 @@
1 ----
2 -title: Gmail Labeler
3 -description: Build a Python script that listens for new Gmail messages and labels them using Composio and the Claude Agent SDK
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/gmail-labeler)
7 -
8 -This cookbook builds a Python script that connects to Gmail, listens for new messages using Composio triggers, and uses Claude to label each email automatically. The agent is scoped to Gmail tools only using a **scoped session**.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -* [Anthropic API key](https://console.anthropic.com/settings/keys)
16 -
17 -## Project setup
18 -
19 -Create a new project and install dependencies:
20 -
21 -```bash
22 -mkdir composio-gmail-labeler && cd composio-gmail-labeler
23 -uv init && uv add composio composio-claude-agent-sdk claude-agent-sdk
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -ANTHROPIC_API_KEY=your_anthropic_api_key
31 -```
32 -
33 -## Setting up the client
34 -
35 -`Composio` takes a `ClaudeAgentSDKProvider` so that tools come back in the format the Claude Agent SDK expects.
36 -
37 -<include>../../examples/gmail-labeler/main.py#setup</include>
38 -
39 -## Connecting to Gmail
40 -
41 -Before labeling emails, the user needs to connect their Gmail account. The `connect` function creates a scoped session with `toolkits=["gmail"]` and checks the connection status with `session.toolkits()`. If Gmail is not connected, `session.authorize("gmail")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
42 -
43 -<include>../../examples/gmail-labeler/main.py#connect</include>
44 -
45 -## Labeling with Claude
46 -
47 -For each incoming email, `label_email` fetches Gmail tools from `session.tools()`, wraps them in an MCP server using `create_sdk_mcp_server()`, and passes them to a Claude agent. The agent lists existing labels, picks the best fit or creates a new one, and applies it to the email.
48 -
49 -<include>../../examples/gmail-labeler/main.py#label</include>
50 -
51 -## Listening for emails
52 -
53 -The `listen` function creates a trigger for new Gmail messages and subscribes to events over WebSocket. When a new email arrives, the handler calls `label_email` to classify and label it.
54 -
55 -<include>../../examples/gmail-labeler/main.py#listen</include>
56 -
57 -<Callout>
58 -SDK subscriptions are ideal for local development and testing. For production, use [webhooks](/docs/setting-up-triggers/subscribing-to-events) to receive trigger events at a URL endpoint.
59 -</Callout>
60 -
61 -## Complete script
62 -
63 -Here is everything together:
64 -
65 -<include>../../examples/gmail-labeler/main.py</include>
66 -
67 -## Running the script
68 -
69 -First, connect your Gmail account:
70 -
71 -```bash
72 -uv run --env-file .env python main.py connect default
73 -```
74 -
75 -If Gmail is not connected yet, you will get an OAuth URL. Open it in your browser and authorize the app. If already connected, the script prints "Gmail is already connected."
76 -
77 -Then start the listener:
78 -
79 -```bash
80 -uv run --env-file .env python main.py listen default
81 -```
82 -
83 -Send yourself an email and watch the terminal. The agent will receive the event, inspect the email, and apply a label.
84 -
85 -## Take it further
86 -
87 -The trigger + agent pattern works for any event-driven workflow. Swap the prompt and toolkit to build:
88 -
89 -- **Auto-responder**: draft and send replies to common questions instead of just labeling
90 -- **Slack notifier**: add the Slack toolkit so the agent posts a summary of important emails to a channel
91 -- **Lead router**: connect Salesforce and have the agent tag inbound emails by deal stage and assign to reps
92 -
93 -<Cards>
94 - <Card title="Slack Summarizer" href="/cookbooks/slack-summariser" description="Summarize Slack channels with a single command" />
95 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Run agents autonomously on a schedule" />
96 -</Cards>
docs/content/cookbooks/hono.mdx deleted
-114
@@ -1,114 +0,0 @@
1 ----
2 -title: Basic Hono Server
3 -description: Build an AI agent with access to 1000+ tools using Composio and Hono.js
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/hono)
7 -
8 -This cookbook builds a Hono.js server where users can chat with an AI agent that has access to over 1000 tools like Gmail, GitHub, Slack, Notion, and more. Along the way we'll add endpoints to manage which apps a user has connected.
9 -
10 -## Prerequisites
11 -
12 -* Node.js 18+
13 -* [Composio API key](https://dashboard.composio.dev/settings)
14 -* [OpenAI API key](https://platform.openai.com/api-keys)
15 -
16 -## Project setup
17 -
18 -Create a new project and install dependencies:
19 -
20 -```bash
21 -mkdir composio-hono && cd composio-hono
22 -npm init -y
23 -npm install hono @hono/node-server openai @composio/core @composio/openai tsx dotenv
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -OPENAI_API_KEY=your_openai_api_key
31 -```
32 -
33 -## Initializing the clients
34 -
35 -`Composio` takes an `OpenAIProvider` so that when we ask for tools later, they come back in the format OpenAI expects.
36 -
37 -<include meta="no-twoslash">../../examples/hono/server.ts#setup</include>
38 -
39 -## Chat endpoint
40 -
41 -The core of the server is a `/chat` endpoint. A user sends a message, and the agent responds, using whatever tools it needs.
42 -
43 -`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to OpenAI and loop until the model stops calling tools.
44 -
45 -<include meta="no-twoslash">../../examples/hono/server.ts#chat</include>
46 -
47 -<Callout>
48 -If the user hasn't connected the app they're trying to use, the agent will automatically
49 -return an authentication link in its response. The user can complete OAuth and then retry.
50 -</Callout>
51 -
52 -That's a working agent. But in most apps you'll also want to manage connections outside of chat, for example to show users what's connected or let them connect new apps from a settings page.
53 -
54 -## Checking connections
55 -
56 -`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
57 -
58 -<include meta="no-twoslash">../../examples/hono/server.ts#list-connections</include>
59 -
60 -If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
61 -
62 -<include meta="no-twoslash">../../examples/hono/server.ts#check-connection</include>
63 -
64 -## Connecting an app
65 -
66 -When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
67 -
68 -<include meta="no-twoslash">../../examples/hono/server.ts#connect</include>
69 -
70 -## Complete app
71 -
72 -Here's everything together:
73 -
74 -<include meta='title="server.ts"'>../../examples/hono/server.ts</include>
75 -
76 -## Running the server
77 -
78 -```bash
79 -npx tsx server.ts
80 -```
81 -
82 -The server runs at `http://localhost:8000`.
83 -
84 -## Testing with cURL
85 -
86 -### Chat with the agent
87 -
88 -```bash
89 -curl -X POST http://localhost:8000/chat \
90 - -H "Content-Type: application/json" \
91 - -d '{"userId": "user_123", "message": "Star the composiohq/composio repo on GitHub"}'
92 -```
93 -
94 -### List all connections
95 -
96 -```bash
97 -curl http://localhost:8000/connections/user_123
98 -```
99 -
100 -### Check a specific connection
101 -
102 -```bash
103 -curl http://localhost:8000/connections/user_123/gmail
104 -```
105 -
106 -### Connect an app
107 -
108 -```bash
109 -curl -X POST http://localhost:8000/connect/gmail \
110 - -H "Content-Type: application/json" \
111 - -d '{"userId": "user_123"}'
112 -```
113 -
114 -Open the `redirectUrl` from the response in your browser to complete OAuth.
docs/content/cookbooks/index.mdx deleted
-42
@@ -1,42 +0,0 @@
1 ----
2 -title: Cookbooks
3 -description: Real-world examples and use cases for Composio
4 ----
5 -
6 -Browse open-source templates or follow step-by-step guides below.
7 -
8 -<Cards>
9 - <Card title="Templates" href="/cookbooks/templates" description="Open-source starter projects with full source code. Clone and deploy." />
10 -</Cards>
11 -
12 -## Getting Started
13 -
14 -<Cards>
15 - <Card title="Build a Chat App" href="/cookbooks/chat-app" description="Next.js chat app with tool discovery across 1000+ apps" />
16 - <Card title="App Connections Dashboard" href="/cookbooks/app-connections-dashboard" description="Dashboard for managing user app connections" />
17 - <Card title="Basic FastAPI Server" href="/cookbooks/fast-api" description="Build a Gmail agent with FastAPI" />
18 - <Card title="Basic Hono Server" href="/cookbooks/hono" description="Build a Gmail agent with Hono.js" />
19 -</Cards>
20 -
21 -## Productivity & Automation
22 -
23 -<Cards>
24 - <Card title="Workplace Search Agent" href="/cookbooks/workplace-search" description="Search across GitHub, Slack, Gmail, and Notion from a single agent" />
25 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Autonomous agent that monitors GitHub, Gmail, and Slack on a schedule" />
26 - <Card title="Support Knowledge Agent" href="/cookbooks/support-agent" description="Agentic RAG system that searches Notion, checks Datadog, and manages GitHub issues" />
27 - <Card title="Gmail Labeler" href="/cookbooks/gmail-labeler" description="Automatically label incoming emails using triggers" />
28 - <Card title="Slack Summarizer" href="/cookbooks/slack-summariser" description="Summarize Slack channel messages" />
29 - <Card title="Supabase SQL Agent" href="/cookbooks/supabase-sql-agent" description="Execute SQL queries using natural language" />
30 -</Cards>
31 -
32 -## Developer Tools
33 -
34 -<Cards>
35 - <Card title="PR Review Agent" href="/cookbooks/pr-review-agent" description="AI reviewer that reads your CLAUDE.md and posts structured feedback on every PR" />
36 -</Cards>
37 -
38 -## Behind the Curtain
39 -
40 -<Cards>
41 - <Card title="Tool Type Generator" href="/cookbooks/tool-generator" description="Build platforms using raw tool definitions" />
42 -</Cards>
docs/content/cookbooks/meta.json deleted
-23
@@ -1,23 +0,0 @@
1 -{
2 - "title": "Cookbooks",
3 - "root": true,
4 - "pages": [
5 - "---Getting Started---",
6 - "templates",
7 - "chat-app",
8 - "app-connections-dashboard",
9 - "fast-api",
10 - "hono",
11 - "---Productivity & Automation---",
12 - "workplace-search",
13 - "background-agent",
14 - "support-agent",
15 - "gmail-labeler",
16 - "slack-summariser",
17 - "supabase-sql-agent",
18 - "---Developer Tools---",
19 - "pr-review-agent",
20 - "---Behind the Curtain---",
21 - "tool-generator"
22 - ]
23 -}
docs/content/cookbooks/pr-review-agent.mdx deleted
-132
@@ -1,132 +0,0 @@
1 ----
2 -title: PR review agent
3 -description: Build an AI PR review agent that reads your CLAUDE.md, reviews diffs, and posts feedback on every pull request
4 ----
5 -
6 -Build a PR review agent that runs on every pull request, reads your repo's `CLAUDE.md` or `AGENTS.md`, reviews the diff against those rules, and posts structured feedback as a comment. About 40 lines of Python and a 20-line GitHub Action.
7 -
8 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/pr-review-agent)
9 -
10 -## What you'll build
11 -
12 -- An AI reviewer that runs automatically on every PR via GitHub Actions
13 -- Reads `CLAUDE.md` or `AGENTS.md` from your repo to enforce project-specific rules
14 -- Posts structured reviews with categorized issues, security analysis, and test coverage checks
15 -
16 -## Prerequisites
17 -
18 -- Python 3.10+
19 -- [Composio API key](https://dashboard.composio.dev/settings)
20 -- [OpenAI API key](https://platform.openai.com/api-keys)
21 -- A GitHub repository where you have admin access (for adding secrets and workflows)
22 -
23 -**Stack:** Python, OpenAI Agents SDK, Composio, GitHub Actions
24 -
25 -## Set up the project
26 -
27 -Create a new directory and install dependencies:
28 -
29 -```bash
30 -mkdir pr-review-agent && cd pr-review-agent
31 -pip install composio composio-openai-agents openai-agents
32 -```
33 -
34 -<Callout type="info">
35 -Get your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings) and `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys).
36 -</Callout>
37 -
38 -Set your API keys:
39 -
40 -```bash title=".env"
41 -COMPOSIO_API_KEY=your_composio_api_key
42 -OPENAI_API_KEY=your_openai_api_key
43 -```
44 -
45 -## Build the agent
46 -
47 -Create `agent.py`:
48 -
49 -<include meta='title="agent.py"'>../../examples/pr-review-agent/agent.py</include>
50 -
51 -Here's what's happening:
52 -
53 -1. **Session creation**: `composio.create(user_id="user_123", toolkits=["github"])` creates a session with GitHub tools like `GITHUB_GET_A_PULL_REQUEST`, `GITHUB_LIST_PULL_REQUESTS_FILES`, and `GITHUB_CREATE_A_REVIEW_FOR_A_PULL_REQUEST`.
54 -
55 -2. **CLAUDE.md / AGENTS.md as review rules**: The agent checks for either file in the repo root and uses it as its review checklist. Your existing project standards become the review guide with zero extra setup.
56 -
57 -3. **Focused review**: The agent only flags new code that could break something or mislead someone. It skips style preferences, pre-existing issues, and anything CI already catches.
58 -
59 -## Run it locally
60 -
61 -```bash
62 -python agent.py
63 -```
64 -
65 -If you haven't connected GitHub yet, the agent will prompt you with an auth link. Authorize and rerun.
66 -
67 -To review a specific PR:
68 -
69 -```bash
70 -GITHUB_REPO=owner/repo PR_NUMBER=42 python agent.py
71 -```
72 -
73 -## Run it on every PR with GitHub Actions
74 -
75 -Add `agent.py` to the root of your repo, then create `.github/workflows/review.yml`:
76 -
77 -<include meta='title=".github/workflows/review.yml"'>../../examples/pr-review-agent/review.yml</include>
78 -
79 -Your repo should look like this:
80 -
81 -```
82 -your-repo/
83 -├── agent.py
84 -├── .github/workflows/review.yml
85 -└── CLAUDE.md (optional)
86 -```
87 -
88 -Then set up your repo:
89 -
90 -1. Go to **Settings > Secrets and variables > Actions**
91 -2. Add `COMPOSIO_API_KEY` and `OPENAI_API_KEY` as repository secrets
92 -3. **Connect GitHub to Composio** (one-time setup). The agent runs as `user_123` in CI, so that user needs a GitHub connection before the workflow can post reviews:
93 -
94 -```bash
95 -python -c "
96 -from composio import Composio
97 -composio = Composio()
98 -session = composio.create(user_id='user_123', toolkits=['github'])
99 -connection = session.authorize('github')
100 -print('Visit this URL to connect GitHub:', connection.redirect_url)
101 -connection.wait_for_connection()
102 -print('Connected!')
103 -"
104 -```
105 -
106 -After you authorize once, the connection persists. The GitHub Action will work for all future PRs.
107 -
108 -## How it works
109 -
110 -When a PR is opened:
111 -
112 -1. GitHub Actions triggers the workflow and runs `agent.py`
113 -2. The agent creates a Composio session with GitHub tools
114 -3. It fetches the PR details and diffs using `GITHUB_GET_A_PULL_REQUEST` and `GITHUB_LIST_PULL_REQUESTS_FILES`
115 -4. It checks for `CLAUDE.md` or `AGENTS.md` in the repo root
116 -5. It reviews the diff and posts a structured comment using `GITHUB_CREATE_A_REVIEW_FOR_A_PULL_REQUEST`
117 -
118 -Composio handles OAuth, tool discovery, and API execution. You don't write any GitHub API code.
119 -
120 -## Take it further
121 -
122 -<Cards>
123 - <Card title="Build a Chat App" href="/cookbooks/chat-app">
124 - Build a full chat interface with tool calling
125 - </Card>
126 - <Card title="Configuring sessions" href="/docs/configuring-sessions">
127 - Lock down which toolkits and tools your agent can access
128 - </Card>
129 - <Card title="Authenticating users" href="/docs/authenticating-users/manually-authenticating">
130 - Authenticate users ahead of time during onboarding
131 - </Card>
132 -</Cards>
docs/content/cookbooks/slack-summariser.mdx deleted
-86
@@ -1,86 +0,0 @@
1 ----
2 -title: Slack Summarizer
3 -description: Build an agent that summarizes Slack channel messages using Composio
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/slack-summariser)
7 -
8 -This cookbook builds a standalone Python script that connects to a Slack workspace, fetches recent messages from a channel, and summarizes the key topics, decisions, and action items. We'll use **scoped sessions** to limit the agent to Slack tools only.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -* [OpenAI API key](https://platform.openai.com/api-keys)
16 -
17 -## Project setup
18 -
19 -Create a new project and install dependencies:
20 -
21 -```bash
22 -mkdir composio-slack-summarizer && cd composio-slack-summarizer
23 -uv init && uv add composio composio-openai-agents openai-agents
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -OPENAI_API_KEY=your_openai_api_key
31 -```
32 -
33 -## Setting up the client
34 -
35 -`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
36 -
37 -<include>../../examples/slack-summariser/main.py#setup</include>
38 -
39 -## Connecting to Slack
40 -
41 -Before summarizing, we need to make sure the user has connected their Slack workspace. The `connect` function creates a scoped session with `toolkits=["slack"]` and checks the connection status via `session.toolkits()`. If Slack is not connected, `session.authorize("slack")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
42 -
43 -<include>../../examples/slack-summariser/main.py#connect</include>
44 -
45 -## Summarizing a channel
46 -
47 -With Slack connected, the `summarize` function creates a session and grabs the tools. We hand them to an agent with focused summarization instructions. `Runner.run_sync` handles the agentic loop: the agent calls the Slack tool to fetch messages and produces a summary.
48 -
49 -<include>../../examples/slack-summariser/main.py#summarize</include>
50 -
51 -## Complete script
52 -
53 -Here is everything together:
54 -
55 -<include>../../examples/slack-summariser/main.py</include>
56 -
57 -## Running the script
58 -
59 -First, connect your Slack workspace:
60 -
61 -```bash
62 -uv run --env-file .env python main.py connect default
63 -```
64 -
65 -If Slack is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app. If you've already connected, the script will print "Slack is already connected."
66 -
67 -Then run the summarizer:
68 -
69 -```bash
70 -uv run --env-file .env python main.py summarize default general
71 -```
72 -
73 -Replace `general` with any channel name you want to summarize.
74 -
75 -## Take it further
76 -
77 -The summarizer reads from one channel, but the same pattern scales to broader workflows:
78 -
79 -- **Cross-channel digest**: summarize multiple channels in one run and post a combined digest to a `#daily-summary` channel
80 -- **Trigger-based**: use a [Slack trigger](/docs/setting-up-triggers/creating-triggers) to auto-summarize whenever a channel hits 50+ unread messages
81 -- **Action items to Linear**: add the Linear toolkit and have the agent extract action items from the summary and create tickets
82 -
83 -<Cards>
84 - <Card title="Gmail Labeler" href="/cookbooks/gmail-labeler" description="Event-driven agent that labels emails as they arrive" />
85 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Run agents autonomously on a schedule" />
86 -</Cards>
docs/content/cookbooks/supabase-sql-agent.mdx deleted
-95
@@ -1,95 +0,0 @@
1 ----
2 -title: Supabase SQL Agent
3 -description: Build an agent that executes SQL queries on Supabase using natural language
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/supabase-sql-agent)
7 -
8 -This cookbook builds a CLI agent that connects to your Supabase account and lets you query your databases using natural language. The agent translates plain English into SQL, runs it against your project, and explains the results. We'll use **scoped sessions** to limit the agent to Supabase tools only.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -* [OpenAI API key](https://platform.openai.com/api-keys)
16 -
17 -## Project setup
18 -
19 -Create a new project and install dependencies:
20 -
21 -```bash
22 -mkdir composio-supabase-agent && cd composio-supabase-agent
23 -uv init && uv add composio composio-openai-agents openai-agents
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -OPENAI_API_KEY=your_openai_api_key
31 -```
32 -
33 -## Setting up the client
34 -
35 -`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
36 -
37 -<include>../../examples/supabase-sql-agent/main.py#setup</include>
38 -
39 -## Connecting to Supabase
40 -
41 -Before running queries, the user needs to connect their Supabase account. The `connect` function creates a scoped session with `toolkits=["supabase"]` and checks the connection status via `session.toolkits()`. If Supabase is not connected, `session.authorize("supabase")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
42 -
43 -<include>../../examples/supabase-sql-agent/main.py#connect</include>
44 -
45 -## Querying with natural language
46 -
47 -With Supabase connected, the `query` function creates a session scoped to `toolkits=["supabase"]` and grabs the tools. We hand them to an agent and run an interactive loop where the user types questions and the agent translates them into SQL.
48 -
49 -<include>../../examples/supabase-sql-agent/main.py#query</include>
50 -
51 -## Complete script
52 -
53 -Here is everything together:
54 -
55 -<include>../../examples/supabase-sql-agent/main.py</include>
56 -
57 -## Running the script
58 -
59 -First, connect your Supabase account:
60 -
61 -```bash
62 -uv run --env-file .env python main.py connect default
63 -```
64 -
65 -If Supabase is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app.
66 -
67 -Then start the interactive query agent:
68 -
69 -```bash
70 -uv run --env-file .env python main.py query default
71 -```
72 -
73 -Try asking things like:
74 -
75 -```
76 -you > List all my Supabase projects
77 -you > Show me all tables in my default project
78 -you > How many users signed up this week?
79 -you > What are the top 10 most recent orders?
80 -```
81 -
82 -Type `exit` to quit.
83 -
84 -## Take it further
85 -
86 -The agent has full access to your Supabase projects via SQL. Some ideas:
87 -
88 -- **Scheduled reports**: wrap this in a cron job to generate daily metrics and post them to Slack using the Slack toolkit
89 -- **Admin dashboard backend**: pair with FastAPI to expose natural-language queries as an API for internal tools
90 -- **Data migration helper**: ask the agent to compare schemas across projects and generate migration SQL
91 -
92 -<Cards>
93 - <Card title="FastAPI Server" href="/cookbooks/fast-api" description="Wrap an agent in an HTTP server with auth and connection management" />
94 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Run agents autonomously on a schedule" />
95 -</Cards>
docs/content/cookbooks/support-agent.mdx deleted
-89
@@ -1,89 +0,0 @@
1 ----
2 -title: Support Knowledge Agent
3 -description: Build an agentic RAG system that searches Notion, checks Datadog, and manages GitHub issues for support triage
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/support-agent)
7 -
8 -This cookbook builds an **agentic RAG** system: an interactive CLI agent that triages support issues by pulling context from Notion docs, Datadog monitors, and GitHub issues. It uses scoped sessions, multi-turn chat with streaming, and a structured system prompt.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -* [OpenAI API key](https://platform.openai.com/api-keys)
16 -
17 -## Project setup
18 -
19 -Create a new project and install dependencies:
20 -
21 -```bash
22 -mkdir composio-support-agent && cd composio-support-agent
23 -uv init && uv add composio composio-openai-agents openai-agents
24 -```
25 -
26 -Add your API keys to a `.env` file:
27 -
28 -```bash title=".env"
29 -COMPOSIO_API_KEY=your_composio_api_key
30 -OPENAI_API_KEY=your_openai_api_key
31 -```
32 -
33 -## Setting up the client
34 -
35 -`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects. We also import the streaming event types we'll need for real-time output.
36 -
37 -<include>../../examples/support-agent/main.py#setup</include>
38 -
39 -## Defining the agent
40 -
41 -The system prompt tells the agent what tools it has and how to behave. It knows about Datadog, Notion, and GitHub, and decides on its own which to use based on the question.
42 -
43 -<include>../../examples/support-agent/main.py#agent</include>
44 -
45 -## Chat loop with streaming
46 -
47 -The chat loop creates a session scoped to three toolkits: `datadog`, `notion`, and `github`. The agent only sees tools from these services. `Runner.run_streamed` streams tokens as they arrive so you see the response in real time. Message history is tracked in a list for multi-turn context.
48 -
49 -<include>../../examples/support-agent/main.py#chat</include>
50 -
51 -<Callout>
52 -If a toolkit isn't connected yet, the agent will automatically return an authentication link in its response. The user can complete OAuth and then retry.
53 -</Callout>
54 -
55 -## Complete script
56 -
57 -Here's everything together:
58 -
59 -<include>../../examples/support-agent/main.py</include>
60 -
61 -## Running the agent
62 -
63 -```bash
64 -uv run --env-file .env python main.py
65 -```
66 -
67 -The agent starts an interactive chat. Type a message and watch the response stream in. Type `quit` to exit.
68 -
69 -```
70 -Support Knowledge Agent (type 'quit' to exit)
71 ---------------------------------------------------
72 -
73 -You: The payments service is returning 500 errors. Can you check what's going on?
74 -
75 -Agent: I checked Datadog and found an active alert on the payments-api monitor...
76 -```
77 -
78 -## Take it further
79 -
80 -The agent's scope is defined by its toolkits and system prompt. Swap them to build different support workflows:
81 -
82 -- **Escalation bot**: add PagerDuty and Slack toolkits so the agent can page on-call engineers and post incident threads automatically
83 -- **Customer-facing KB**: replace Datadog with Zendesk, let the agent search help articles and draft replies to open tickets
84 -- **Incident timeline**: add Jira and Confluence toolkits so the agent can cross-reference tickets with runbook docs and build a timeline
85 -
86 -<Cards>
87 - <Card title="Workplace Search" href="/cookbooks/workplace-search" description="Search across GitHub, Slack, Gmail, and Notion from a single agent" />
88 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Run a multi-app agent autonomously on a cron schedule" />
89 -</Cards>
docs/content/cookbooks/templates.mdx deleted
-63
@@ -1,63 +0,0 @@
1 ----
2 -title: Templates
3 -description: Open-source templates and starter projects built with Composio
4 ----
5 -
6 -Clone, customize, and deploy. Each template is a fully working project you can use as a starting point.
7 -
8 -<TemplateGrid columns={1}>
9 - <TemplateCard
10 - title="TrustClaw"
11 - description="Secure AI assistant that automates tasks across 1000+ apps with OAuth authentication and sandboxed execution."
12 - href="https://www.trustclaw.app/"
13 - image="/images/templates/trustclaw.mp4"
14 - />
15 - <TemplateCard
16 - title="Data Analyst Agent"
17 - description="Multi-framework AI agent that connects to HubSpot, Google Sheets, and Attio to analyze data, generate insights, and create visualizations."
18 - href="https://github.com/ComposioHQ/data-analyst-agent"
19 - image="/images/templates/data-analyst-agent.gif"
20 - />
21 - <TemplateCard
22 - title="Open ChatGPT Atlas"
23 - description="Research and analyze topics with AI-powered deep research capabilities."
24 - href="https://github.com/ComposioHQ/open-chatgpt-atlas"
25 - image="/images/templates/open-chatgpt-atlas.gif"
26 - />
27 - <TemplateCard
28 - title="Open Gamma"
29 - description="AI agent that generates presentation slides in Google Slides from natural language prompts."
30 - href="https://github.com/ComposioHQ/open-gamma"
31 - image="/images/templates/open-gamma.mp4"
32 - />
33 -</TemplateGrid>
34 -
35 -## Direct Tool Execution
36 -
37 -<TemplateGrid>
38 - <TemplateCard
39 - title="Gmail Agent with FastAPI"
40 - description="Build and serve a Gmail AI agent using Composio's managed authentication, OpenAI, and FastAPI."
41 - href="https://github.com/ComposioHQ/composio-fastapi"
42 - />
43 - <TemplateCard
44 - title="Perplexity Email Assistant"
45 - description="Email assistant that listens for incoming emails via triggers and automatically executes instructions using Tool Router, LangGraph, and MCP."
46 - href="https://github.com/ComposioHQ/open-perplexity-email-assistant"
47 - />
48 - <TemplateCard
49 - title="Personalised Onboarding Agent"
50 - description="Intelligent agent that researches users by analyzing their Gmail data and web presence, then engages in personalized conversations."
51 - href="https://github.com/ComposioHQ/open-poke"
52 - />
53 - <TemplateCard
54 - title="Open Gumloop"
55 - description="Visual drag-and-drop agent workflow builder for creating and executing AI-powered pipelines using a node-based interface."
56 - href="https://github.com/ComposioHQ/open-gumloop"
57 - />
58 - <TemplateCard
59 - title="Open Email Agent"
60 - description="Chat-based email assistant that lets you search, read, reply to, and manage Gmail using natural language."
61 - href="https://github.com/ComposioHQ/open-email-assistant"
62 - />
63 -</TemplateGrid>
docs/content/cookbooks/tool-generator.mdx deleted
-94
@@ -1,94 +0,0 @@
1 ----
2 -title: Tool Type Generator
3 -description: Build a platform on top of Composio using raw tool definitions and toolkit metadata
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/tool-generator)
7 -
8 -This cookbook shows how to access the raw tool definitions and toolkit metadata that Composio exposes. If you are building a platform on top of Composio, say a workflow builder or an IDE plugin, you will need to display tool schemas, auth requirements, and input/output parameters to your users. This is how you get that data.
9 -
10 -## Prerequisites
11 -
12 -* Python 3.10+
13 -* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14 -* [Composio API key](https://dashboard.composio.dev/settings)
15 -
16 -## Project setup
17 -
18 -Create a new project and install dependencies:
19 -
20 -```bash
21 -mkdir composio-tool-generator && cd composio-tool-generator
22 -uv init && uv add composio
23 -```
24 -
25 -Add your API key to a `.env` file:
26 -
27 -```bash title=".env"
28 -COMPOSIO_API_KEY=your_composio_api_key
29 -```
30 -
31 -## Setting up the client
32 -
33 -No provider is needed here. We are reading tool metadata directly from the Composio API, not passing tools to an AI framework.
34 -
35 -<include>../../examples/tool-generator/main.py#setup</include>
36 -
37 -## Raw tool definitions
38 -
39 -Composio has two internal representations for tools: **raw definitions** and **provider definitions**. Raw definitions are framework-agnostic JSON schemas with `input_parameters`, `output_parameters`, scopes, and tags. Provider definitions translate these into the format a specific framework expects (OpenAI, Anthropic, etc.).
40 -
41 -For building platform UIs, the raw definitions are what you want. `composio.tools.get_raw_composio_tools()` returns them for an entire toolkit. Each tool has a standard JSON Schema for its inputs and outputs, so you can render forms, validate user input, or generate types from it.
42 -
43 -<include>../../examples/tool-generator/main.py#list-tools</include>
44 -
45 -## Toolkit metadata
46 -
47 -A toolkit groups related tools under one integration. `composio.toolkits.get()` returns metadata about the toolkit itself, including its supported auth schemes. Each auth scheme lists the fields required for two stages: creating an auth config (platform setup) and initiating a connected account (end-user connection). This is useful if you need to build your own auth configuration UI.
48 -
49 -<include>../../examples/tool-generator/main.py#toolkit-info</include>
50 -
51 -## Exporting to JSON
52 -
53 -For code generation or static analysis, you can export the full raw schemas to a JSON file. Each entry includes the `input_parameters` and `output_parameters` as standard JSON Schema objects, which you can feed into tools like `json-schema-to-typescript` or `datamodel-code-generator` to produce typed interfaces.
54 -
55 -<include>../../examples/tool-generator/main.py#export</include>
56 -
57 -## Complete script
58 -
59 -Here is everything together:
60 -
61 -<include>../../examples/tool-generator/main.py</include>
62 -
63 -## Running the script
64 -
65 -List all tools in a toolkit:
66 -
67 -```bash
68 -uv run --env-file .env python main.py list-tools gmail
69 -```
70 -
71 -Inspect a toolkit's auth schemes:
72 -
73 -```bash
74 -uv run --env-file .env python main.py toolkit-info gmail
75 -```
76 -
77 -Export raw tool schemas to a JSON file:
78 -
79 -```bash
80 -uv run --env-file .env python main.py export gmail tools.json
81 -```
82 -
83 -## Take it further
84 -
85 -Raw tool schemas are building blocks for platform features:
86 -
87 -- **Dynamic form builder**: use `input_parameters` JSON Schema to render forms for any tool — no hardcoded UI per integration
88 -- **Type generation pipeline**: feed exported JSON into `json-schema-to-typescript` or `datamodel-code-generator` in CI to keep types in sync
89 -- **Tool catalog UI**: combine `list-tools` and `toolkit-info` to build a searchable directory of available integrations and their auth requirements
90 -
91 -<Cards>
92 - <Card title="App Connections Dashboard" href="/cookbooks/app-connections-dashboard" description="Build a UI for managing user connections" />
93 - <Card title="Tool Type Generator source" href="https://github.com/ComposioHQ/composio/tree/next/docs/examples/tool-generator" description="View the full source on GitHub" />
94 -</Cards>
docs/content/cookbooks/workplace-search.mdx deleted
-129
@@ -1,129 +0,0 @@
1 ----
2 -title: Workplace search agent
3 -description: Search across GitHub, Slack, Gmail, and Notion from a single agent
4 ----
5 -
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/workplace-search)
7 -
8 -Build a search agent that queries across your workplace tools and returns answers with citations. One session, four toolkits.
9 -
10 -## What you'll learn
11 -
12 -- **Manual authentication**: connect multiple apps with `session.authorize()` and `wait_for_connection()`
13 -- **Multi-toolkit sessions**: one session spanning GitHub, Slack, Gmail, and Notion
14 -- **Cross-app search**: agent decides which apps to query based on the question
15 -
16 -## Prerequisites
17 -
18 -- Python 3.10+
19 -- [UV](https://docs.astral.sh/uv/getting-started/installation/)
20 -- [Composio API key](https://dashboard.composio.dev/settings)
21 -- [OpenAI API key](https://platform.openai.com/api-keys)
22 -
23 -## Project setup
24 -
25 -```bash
26 -mkdir composio-workplace-search && cd composio-workplace-search
27 -uv init && uv add composio composio-openai-agents openai-agents
28 -```
29 -
30 -```bash title=".env"
31 -COMPOSIO_API_KEY=your_composio_api_key
32 -OPENAI_API_KEY=your_openai_api_key
33 -USER_ID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
34 -```
35 -
36 -## File structure
37 -
38 -```
39 -composio-workplace-search/
40 - authorize.py # One-time: connect GitHub, Slack, Gmail, Notion
41 - agent.py # The search agent
42 - .env
43 -```
44 -
45 -## Step 1: Connect your apps
46 -
47 -Before the agent can search, each toolkit needs an active connection. `authorize.py` walks through them one by one, skipping any that are already connected.
48 -
49 -<include>../../examples/workplace-search/authorize.py</include>
50 -
51 -Run it once:
52 -
53 -```bash
54 -uv run --env-file .env python authorize.py
55 -```
56 -
57 -Each toolkit prints a URL. Open it in a browser, complete OAuth, and the script moves to the next one. You only need to do this once per user.
58 -
59 -<Callout>
60 -If you're using sessions with meta tools (`COMPOSIO_MANAGE_CONNECTIONS`), authentication happens in-chat automatically. This manual flow is useful when you want to pre-connect apps once locally before deploying `agent.py` to a CI pipeline or scheduled job.
61 -</Callout>
62 -
63 -## Step 2: Build the agent
64 -
65 -### Setting up the client
66 -
67 -<include>../../examples/workplace-search/agent.py#setup</include>
68 -
69 -### The system prompt
70 -
71 -The prompt tells the agent to search across apps, synthesize findings, and cite every source. If a toolkit isn't connected, it skips it instead of failing.
72 -
73 -<include>../../examples/workplace-search/agent.py#agent</include>
74 -
75 -### Running the search
76 -
77 -`session.tools()` returns provider-wrapped tools ready for the OpenAI Agents SDK. The `USER_ID` from your `.env` file scopes all connections to that user.
78 -
79 -<include>../../examples/workplace-search/agent.py#search</include>
80 -
81 -## Running the agent
82 -
83 -```bash
84 -uv run --env-file .env python agent.py "What decisions were made about the v2 migration?"
85 -```
86 -
87 -Or start it interactively:
88 -
89 -```bash
90 -uv run --env-file .env python agent.py
91 -```
92 -
93 -Example output:
94 -
95 -```
96 -Based on my search across your connected apps:
97 -
98 -**GitHub**: PR #412 "v2 migration plan" (merged Feb 15) outlines the database
99 -schema changes. Issue #389 tracks the remaining blockers.
100 -(Source: github.com/acme/backend/pull/412)
101 -
102 -**Slack**: In #engineering on Feb 14, @alice proposed splitting the migration
103 -into two phases. The team agreed in the thread.
104 -(Source: #engineering, Feb 14)
105 -
106 -**Gmail**: No relevant emails found for "v2 migration".
107 -
108 -**Notion**: Skipped (not connected)
109 -```
110 -
111 -## How it works
112 -
113 -1. `authorize.py` connects each toolkit via OAuth using `session.authorize()` and `wait_for_connection()`. It checks `session.toolkits()` first to skip already-connected apps.
114 -2. The session is created with four toolkits. Composio scopes all tool calls to the user's connected accounts.
115 -3. The agent searches across apps, synthesizes results, and cites sources with links, channel names, or sender info.
116 -4. The `USER_ID` in `.env` scopes all connections — swap it to switch users without changing code.
117 -
118 -## Take it further
119 -
120 -The prompt and toolkits are the only moving parts. Change them to change what the agent searches:
121 -
122 -- **Engineering on-call**: add PagerDuty and Datadog toolkits, ask "what incidents fired overnight and which PRs might be related?"
123 -- **Sales prep**: connect Salesforce and Gmail, ask "summarize all recent activity with Acme Corp before my call"
124 -- **Compliance audit**: add Jira and Confluence, ask "which security tickets are still open and do any docs reference the old auth flow?"
125 -
126 -<Cards>
127 - <Card title="Background Agent" href="/cookbooks/background-agent" description="Run a similar multi-app agent on a cron schedule" />
128 - <Card title="Enable and disable toolkits" href="/docs/toolkits/enable-and-disable-toolkits" description="Restrict tools to read-only with tags" />
129 -</Cards>
docs/content/docs/auth-configuration/connected-accounts.mdx
+3 -6
@@ -3,6 +3,7 @@ title: Connected Accounts
3 description: Manage and monitor user connections to toolkits
4 keywords: [list accounts, refresh token, disable, delete account]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
@@ -374,10 +375,6 @@ console.log('Tool executed:', result);
375 </Tab>
376 </Tabs>
377
377 -## What to read next
378 +## Next
379
379 -<Cards>
380 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
381 - <Card icon={<Palette />} title="Custom auth configs" href="/docs/auth-configuration/custom-auth-configs" description="Use your own OAuth apps for white-labeled authentication" />
382 - <Card icon={<Wrench />} title="Programmatic auth configs" href="/docs/auth-configuration/programmatic-auth-configs" description="Create auth configs programmatically via the SDK" />
383 -</Cards>
380 +<Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
docs/content/docs/auth-configuration/custom-auth-configs.mdx
+3 -6
@@ -3,6 +3,7 @@ title: Custom Auth Configs
3 description: Customize auth configs for any toolkit
4 keywords: [white label, custom oauth, own developer app]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
@@ -132,10 +133,6 @@ console.log(connection);
133 </Tab>
134 </Tabs>
135
135 -## What to read next
136 +## Next
137
137 -<Cards>
138 - <Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
139 - <Card icon={<Wrench />} title="Programmatic auth configs" href="/docs/auth-configuration/programmatic-auth-configs" description="Create auth configs programmatically via the SDK" />
140 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
141 -</Cards>
138 +<Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
docs/content/docs/auth-configuration/custom-auth-params.mdx
+4 -7
@@ -3,10 +3,11 @@ title: Custom Auth Parameters
3 description: Inject custom credentials in headers or parameters
4 keywords: [inject headers, custom credentials, BYOT, bring your own token, OAuth token, access token]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
9 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. Sessions handle authentication automatically via [in-chat authentication](/docs/authenticating-users/in-chat-authentication) or [manual authentication](/docs/authenticating-users/manually-authenticating).
10 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. Sessions handle authentication automatically via [in-chat authentication](/docs/authentication#in-chat-authentication) or [manual authentication](/docs/manually-authenticating).
11 </Callout>
12
13 If you already manage OAuth tokens or API keys yourself and want Composio to execute tools using your credentials, you can pass them directly at execution time — no connected account or redirect flow required.
@@ -170,10 +171,6 @@ console.log(JSON.stringify(result, null, 2));
171 </Tab>
172 </Tabs>
173
173 -## What to read next
174 +## Next
175
175 -<Cards>
176 - <Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
177 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
178 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
179 -</Cards>
176 +<Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
docs/content/docs/auth-configuration/meta.json
-1
@@ -4,7 +4,6 @@
4 "pages": [
5 "custom-auth-configs",
6 "white-labeling",
7 - "programmatic-auth-configs",
7 "custom-auth-params",
8 "connected-accounts",
9 "migrating-initiate-to-link"
docs/content/docs/auth-configuration/migrating-initiate-to-link.mdx
+1
@@ -1,6 +1,7 @@
1 ---
2 title: Migrating from initiate() to link()
3 description: Move Composio-managed OAuth flows off the legacy POST /api/v3/connected_accounts endpoint and onto link() before the 2026-05-08 / 2026-07-03 cutover.
4 +legacy: true
5 ---
6
7 `composio.connected_accounts.initiate()` (Python) and `composio.connectedAccounts.initiate()` (TypeScript) wrap `POST /api/v3/connected_accounts`. That endpoint is being retired for **Composio-managed auth configs on redirectable OAuth schemes** (OAuth1, OAuth2, DCR_OAUTH):
docs/content/docs/auth-configuration/programmatic-auth-configs.mdx deleted
-262
@@ -1,262 +0,0 @@
1 ----
2 -title: Programmatic Auth Configs
3 -description: Create auth configs programmatically
4 -keywords: [create auth config, sdk]
5 -llmGuardrails: "direct-execution"
6 ----
7 -
8 -<Callout type="info">
9 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions#custom-auth-configs) instead. Sessions let you pass custom auth configs directly when creating a session.
10 -</Callout>
11 -
12 -Auth configs are created once and reused many times. However, when managing multiple toolkits, you may want to create auth configs programmatically.
13 -
14 -- When creating and destroying auth configs multiple times in your app's lifecycle.
15 -- When creating auth configs for your users' users.
16 -
17 -## OAuth2 based apps
18 -
19 -### Using Composio Default Auth
20 -
21 -Since OAuth2 is the most common authentication type for applications, Composio provides managed auth for most OAuth2 based applications. This is to speed up development and prototyping. This means you don't have to provide your own OAuth credentials.
22 -
23 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
24 - <Tab value="Python">
25 -```python
26 -from composio import Composio
27 -
28 -composio = Composio()
29 -
30 -# Use composio managed auth
31 -auth_config = composio.auth_configs.create(
32 - toolkit="github",
33 - options={
34 - "type": "use_composio_managed_auth",
35 - },
36 -)
37 -print(auth_config)
38 -```
39 - </Tab>
40 - <Tab value="TypeScript">
41 -```typescript
42 -import { Composio } from "@composio/core";
43 -
44 -const composio = new Composio();
45 -
46 -const authConfig = await composio.authConfigs.create("GITHUB", {
47 - name: "GitHub",
48 - type: "use_composio_managed_auth",
49 -});
50 -
51 -console.log(authConfig);
52 -```
53 - </Tab>
54 -</Tabs>
55 -
56 -The returned `auth_config_id` should be stored securely in your database for future use to be created and destroyed multiple times.
57 -
58 -You can also provide your own authentication details. The required `credentials` and `authScheme` depend on the auth type.
59 -
60 -### Using your own OAuth2 credentials
61 -
62 -Setting up and using your own OAuth2 credentials is the recommended way when going to production or expecting high usage.
63 -
64 -In this example, we're using our own OAuth2 client ID and secret to create the auth config for Notion.
65 -
66 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
67 - <Tab value="Python">
68 -```python
69 -# Use custom auth
70 -auth_config = composio.auth_configs.create(
71 - toolkit="notion",
72 - options={
73 - "name": "Notion Auth",
74 - "type": "use_custom_auth",
75 - "auth_scheme": "OAUTH2",
76 - "credentials": {
77 - "client_id": "1234567890",
78 - "client_secret": "1234567890",
79 - "oauth_redirect_uri": "https://backend.composio.dev/api/v3.1/toolkits/auth/callback",
80 - },
81 - },
82 -)
83 -print(auth_config)
84 -```
85 - </Tab>
86 - <Tab value="TypeScript">
87 -```typescript
88 -import { Composio } from '@composio/core';
89 -const composio = new Composio({ apiKey: 'your_api_key' });
90 -// ---cut---
91 -const authConfig = await composio.authConfigs.create("NOTION", {
92 - name: "Notion",
93 - type: "use_custom_auth",
94 - credentials: {
95 - client_id: "1234567890",
96 - client_secret: "1234567890",
97 - oauth_redirect_uri: "https://backend.composio.dev/api/v3.1/toolkits/auth/callback",
98 - },
99 - authScheme: "OAUTH2",
100 -});
101 -
102 -console.log(authConfig);
103 -```
104 - </Tab>
105 -</Tabs>
106 -
107 -<Callout type="info">
108 -You can specify a custom redirect URI by including the `oauth_redirect_uri` parameter in the credentials object. If not provided, Composio uses the default redirect URI.
109 -</Callout>
110 -
111 -**Specifying the authorized redirect URI**
112 -
113 -The process of setting up your own OAuth2 credentials usually involves generating a client ID and secret and specifying the **authorized redirect URI** in the OAuth configuration.
114 -
115 -<Callout type="info">
116 -The **authorized redirect URI** is the URI that captures the OAuth code that is returned to the app.
117 -</Callout>
118 -
119 -While doing so, you must ensure to set the **authorized redirect URI** in the OAuth configuration to:
120 -
121 -```
122 -https://backend.composio.dev/api/v3.1/toolkits/auth/callback
123 -```
124 -
125 -<Tabs items={['GitHub', 'Google']}>
126 - <Tab value="GitHub">
127 -<Figure src="/images/github-callback.png" alt="Developer settings for GitHub OAuth2 app" caption="Redirect URI for GitHub" size="sm" />
128 - </Tab>
129 - <Tab value="Google">
130 -<Figure src="/images/google-callback.png" alt="Developer settings for Google OAuth2 app" caption="Redirect URI for Google" size="sm" />
131 - </Tab>
132 -</Tabs>
133 -
134 -### Specifying scopes
135 -
136 -Composio requests a set of appropriate default OAuth2 scopes for each toolkit wherever possible. However, you can override or modify these scopes by passing a `scopes` field to the `credentials` object.
137 -
138 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
139 - <Tab value="Python">
140 -```python
141 -from composio import Composio
142 -
143 -composio = Composio()
144 -
145 -response = composio.auth_configs.create(
146 - toolkit="HUBSPOT",
147 - options={
148 - "name": "HubspotConfig",
149 - "authScheme": "OAUTH2",
150 - "type": "use_composio_managed_auth",
151 - "credentials": {
152 - "scopes": "sales-email-read,tickets"
153 - }
154 - }
155 -)
156 -
157 -print(response.id)
158 -```
159 - </Tab>
160 - <Tab value="TypeScript">
161 -```typescript
162 -import { Composio } from "@composio/core";
163 -
164 -const composio = new Composio();
165 -
166 -const authConfig = await composio.authConfigs.create("HUBSPOT", {
167 - name: "HubspotConfig",
168 - type: "use_composio_managed_auth",
169 - credentials: {
170 - scopes: "sales-email-read,tickets",
171 - },
172 -});
173 -
174 -console.log(authConfig);
175 -```
176 - </Tab>
177 -</Tabs>
178 -
179 -## Other auth types
180 -
181 -Composio supports many applications that use different authentication types like API keys, Bearer tokens, JWT and even no authentication at all.
182 -
183 -Generating the auth config for other auth types only has minor differences:
184 -- `use_custom_auth` is used instead of `use_composio_managed_auth`
185 -- The `credentials` field is used to pass the authentication details
186 -- The `authScheme` field is used to specify the auth type
187 -
188 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
189 - <Tab value="Python">
190 -```python
191 -# Use custom auth
192 -auth_config = composio.auth_configs.create(
193 - toolkit="perplexityai",
194 - options={
195 - "type": "use_custom_auth",
196 - "auth_scheme": "API_KEY",
197 - "credentials": {}
198 - },
199 -)
200 -print(auth_config)
201 -```
202 - </Tab>
203 - <Tab value="TypeScript">
204 -```typescript
205 -import { Composio } from '@composio/core';
206 -const composio = new Composio({ apiKey: 'your_api_key' });
207 -// ---cut---
208 -const authConfig = await composio.authConfigs.create('PERPLEXITYAI', {
209 - name: 'Perplexity AI',
210 - type: 'use_custom_auth',
211 - credentials: {},
212 - authScheme: 'API_KEY',
213 -});
214 -
215 -console.log(authConfig);
216 -```
217 - </Tab>
218 -</Tabs>
219 -
220 -## Programmatically inspecting fields
221 -
222 -In cases where you need to dynamically discover the exact field names and handle different auth schemes programmatically, you can inspect the auth config details first.
223 -
224 -This works for all auth types.
225 -
226 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
227 - <Tab value="Python">
228 -```python
229 -required_fields = composio.toolkits.get_auth_config_creation_fields(
230 - toolkit="NOTION",
231 - auth_scheme="OAUTH2",
232 - required_only=True,
233 -)
234 -print(required_fields)
235 -```
236 - </Tab>
237 - <Tab value="TypeScript">
238 -```typescript
239 -import { Composio } from '@composio/core';
240 -const composio = new Composio({ apiKey: 'your_api_key' });
241 -// ---cut---
242 -const toolkits = await composio.toolkits.get("NOTION");
243 -
244 -// Extract field names from authConfigDetails
245 -const authFields = await composio.toolkits.getAuthConfigCreationFields('NOTION', 'OAUTH2', {
246 - requiredOnly: true,
247 -});
248 -
249 -console.log("Required auth config fields:", authFields);
250 -```
251 - </Tab>
252 -</Tabs>
253 -
254 -Then inspect the required fields and specify them in the `credentials` object.
255 -
256 -## What to read next
257 -
258 -<Cards>
259 - <Card icon={<Palette />} title="Custom auth configs" href="/docs/auth-configuration/custom-auth-configs" description="Use your own OAuth apps for white-labeled authentication" />
260 - <Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
261 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
262 -</Cards>
docs/content/docs/auth-configuration/white-labeling.mdx
+5 -14
@@ -3,6 +3,7 @@ title: White-labeling (direct execution)
3 description: Remove Composio branding from your auth flows
4 keywords: [branding, own oauth, custom redirect, white label]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
@@ -170,7 +171,7 @@ const githubConn = await composio.connectedAccounts.initiate(
171 {
172 config: {
173 authScheme: "OAUTH2",
173 - // val fields use snake_case — they're sent to the API as-is
174 + // val fields use snake_case; they're sent to the API as-is
175 val: { status: "INITIALIZING", long_redirect_url: true },
176 },
177 },
@@ -248,22 +249,12 @@ In the Composio dashboard, update your auth config to use your custom redirect U
249
250 Here's how the redirect flow works. Your proxy just forwards the browser redirect to Composio. It never touches the authorization code or token.
251
251 -```mermaid
252 -flowchart TD
253 - A[Your App] -->|User connects| B["OAuth toolkit (e.g. Google, GitHub)"]
254 - B -->|Redirects user| C[yourdomain.com]
255 - C -->|Forwards redirect| D[backend.composio.dev]
256 - D -.->|Redirects back| A
257 -```
252 +<WhiteLabelFlow />
253
254 <Callout type="info">
255 For FAQs and setup guides for individual toolkits, browse the [toolkits page](/toolkits).
256 </Callout>
257
263 -## What to read next
258 +## Next
259
265 -<Cards>
266 - <Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
267 - <Card icon={<Wrench />} title="Custom auth configs" href="/docs/auth-configuration/custom-auth-configs" description="Customize auth configs with your own OAuth apps" />
268 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
269 -</Cards>
260 +<Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
docs/content/docs/authenticating-users/in-chat-authentication.mdx deleted
-195
@@ -1,195 +0,0 @@
1 ----
2 -title: In-chat authentication
3 -description: Let your agent prompt users to connect accounts during conversation
4 -keywords: [automatic auth, dynamic auth, agent prompts]
5 ----
6 -
7 -In-chat authentication lets your agent prompt users to connect accounts during chat. When a tool requires authentication, the agent returns a Connect Link URL. The user authenticates, confirms in chat, and the agent retries. For an overview of all auth approaches, see [Authentication](/docs/authentication).
8 -
9 -## How it works
10 -
11 -1. Agent searches for tools via the `COMPOSIO_SEARCH_TOOLS` meta-tool
12 -2. The `COMPOSIO_MANAGE_CONNECTIONS` meta-tool checks connection status, returns Connect Link URL if needed
13 -3. User authenticates, confirms in chat, agent continues
14 -
15 -## Configuration
16 -
17 -By just creating a session with default configs, you are enabling in-chat auth. The `manage_connections` parameter defaults to `True`, which includes the `COMPOSIO_MANAGE_CONNECTIONS` meta-tool automatically:
18 -
19 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
20 -<Tab value="Python">
21 -```python
22 -session = composio.create(user_id="user_123")
23 -```
24 -</Tab>
25 -<Tab value="TypeScript">
26 -```typescript
27 -import { Composio } from '@composio/core';
28 -const composio = new Composio({ apiKey: 'your_api_key' });
29 -// ---cut---
30 -const session = await composio.create("user_123");
31 -```
32 -</Tab>
33 -</Tabs>
34 -
35 -### Custom callback URL
36 -
37 -Redirect users back to your chat page after they complete authentication:
38 -
39 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
40 -<Tab value="Python">
41 -```python
42 -session = composio.create(
43 - user_id="user_123",
44 - manage_connections={
45 - "callback_url": "https://yourapp.com/chat"
46 - },
47 -)
48 -```
49 -</Tab>
50 -<Tab value="TypeScript">
51 -```typescript
52 -import { Composio } from '@composio/core';
53 -const composio = new Composio({ apiKey: 'your_api_key' });
54 -// ---cut---
55 -const session = await composio.create("user_123", {
56 - manageConnections: {
57 - callbackUrl: "https://yourapp.com/chat",
58 - },
59 -});
60 -```
61 -</Tab>
62 -</Tabs>
63 -
64 -## Examples
65 -
66 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
67 -<Tab value="Python">
68 -```python
69 -from dotenv import load_dotenv
70 -from composio import Composio
71 -from agents import Agent, Runner, SQLiteSession
72 -from composio_openai_agents import OpenAIAgentsProvider
73 -
74 -load_dotenv()
75 -
76 -# Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
77 -composio = Composio(provider=OpenAIAgentsProvider())
78 -
79 -# Unique identifier of the user
80 -user_id = "user_123"
81 -
82 -# Create a session and get native tools for the user
83 -session = composio.create(user_id=user_id)
84 -tools = session.tools()
85 -
86 -# Configure OpenAI agent with Composio tools
87 -agent = Agent(
88 - name="Personal Assistant",
89 - instructions="You are a helpful personal assistant. Use Composio tools to take action.",
90 - model="gpt-5.2",
91 - tools=tools,
92 -)
93 -
94 -# Memory for multi-turn conversation
95 -memory = SQLiteSession("conversation")
96 -
97 -print("""
98 -What task would you like me to help you with?
99 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
100 -(Type 'exit' to exit)
101 -Example tasks:
102 - • 'Summarize my emails from today'
103 - • 'List all open issues on the composio github repository'
104 -""")
105 -
106 -while True:
107 - user_input = input("You: ").strip()
108 - if user_input.lower() == "exit":
109 - break
110 -
111 - print("Assistant: ", end="", flush=True)
112 - try:
113 - result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
114 - print(f"{result.final_output}\n")
115 - except Exception as e:
116 - print(f"\n[Error]: {e}")
117 -```
118 -</Tab>
119 -<Tab value="TypeScript">
120 -```typescript
121 -import "dotenv/config";
122 -import { Composio } from "@composio/core";
123 -import { Agent, run, MemorySession } from "@openai/agents";
124 -import { OpenAIAgentsProvider } from "@composio/openai-agents";
125 -import { createInterface } from "readline/promises";
126 -
127 -// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
128 -const composio = new Composio({ provider: new OpenAIAgentsProvider() });
129 -
130 -// Unique identifier of the user
131 -const userId = "user_123";
132 -// Create a session for the user
133 -const session = await composio.create(userId);
134 -const tools = await session.tools();
135 -
136 -const agent = new Agent({
137 - name: "Personal Assistant",
138 - instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
139 - model: "gpt-5.2",
140 - tools,
141 -});
142 -
143 -// Set up interactive terminal input/output for the conversation
144 -const readline = createInterface({ input: process.stdin, output: process.stdout });
145 -// Create a memory session for persistent multi-turn conversation
146 -const memory = new MemorySession();
147 -
148 -console.log(`
149 -What task would you like me to help you with?
150 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
151 -(Type 'exit' to exit)
152 -Example tasks:
153 - • 'Summarize my emails from today'
154 - • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
155 -`);
156 -
157 -// Multi-turn conversation with agentic tool calling
158 -while (true) {
159 - const query = await readline.question("You: ");
160 - const input = query.trim();
161 -
162 - if (input.toLowerCase() === "exit") break;
163 - process.stdout.write("Assistant: ");
164 -
165 - try {
166 - const result = await run(agent, input, { session: memory });
167 - process.stdout.write(`${result.finalOutput}`);
168 - } catch (error) {
169 - console.error("\n[Error]:", error instanceof Error ? error.message : error);
170 - }
171 -}
172 -readline.close();
173 -```
174 -</Tab>
175 -</Tabs>
176 -
177 -What this looks like when you run the code:
178 -
179 -```
180 -Assistant: What would you like me to do today? Type 'exit' to end the conversation.
181 -
182 -> Star the composio repo on GitHub
183 -Assistant: I need you to connect your GitHub account first.
184 -Please click here to authorize: https://connect.composio.dev/link/ln_abc123
185 -
186 -> Done
187 -```
188 -
189 -## What to read next
190 -
191 -<Cards>
192 - <Card icon={<ShieldCheck />} title="Manual authentication" href="/docs/authenticating-users/manually-authenticating" description="Pre-authenticate users before chat using Connect Links and session.authorize()" />
193 - <Card icon={<Palette />} title="White-labeling authentication" href="/docs/white-labeling-authentication" description="Use your own OAuth apps so users see your branding on consent screens" />
194 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Restrict toolkits, set custom auth configs, and select connected accounts" />
195 -</Cards>
\ No newline at end of file
docs/content/docs/authenticating-users/meta.json deleted
-8
@@ -1,8 +0,0 @@
1 -{
2 - "title": "Authenticating users",
3 - "pages": [
4 - "in-chat-authentication",
5 - "manually-authenticating",
6 - "shared-connections"
7 - ]
8 -}
docs/content/docs/authentication.mdx
+103 -72
@@ -1,107 +1,138 @@
1 ---
2 title: Authentication
3 description: Understand how Composio handles user authentication to toolkits
4 -keywords: [connect link, oauth, auth config]
4 +keywords: [connect link, oauth, auth config, in-chat auth, dynamic auth]
5 ---
6
7 -Composio simplifies authentication with Connect Links: hosted pages where users securely connect their accounts. There are two approaches. Choose based on where in your app users should authenticate.
7 +Composio organizes everything around your **users**. A user is whoever your agent acts on behalf of: a person in your app, identified by a [`userID`](/docs/how-composio-works) you choose. Authentication is always per user. Each user connects their own accounts, their Gmail, their GitHub, their Slack, and Composio stores and refreshes those credentials against that `userID`.
8
9 -<Video src="/images/connect-link-auth-flow-recording.mp4" autoPlay />
9 +This is the core idea: your agent runs the same tools for many people, and every tool call runs as a specific user against that user's connected accounts. User A's agent never touches user B's data. You pass the `userID` when you create a session, and Composio handles the auth from there.
10
11 -## Which approach should I use?
11 +Because connections are stored under the `userID`, use a stable identifier, like your database ID, never one that can change.
12
13 -- **Users chat with your agent?** Use [in-chat authentication](#in-chat-authentication). The agent handles connection prompts automatically, no setup needed.
14 -- **Want users connected before they chat?** Use [manual authentication](#manual-authentication). Your app calls `session.authorize()` during onboarding or from a settings page.
13 +<Accordions>
14 +<Accordion title="userID best practices">
15 +- **Recommended:** database UUID or primary key (`user.id`)
16 +- **Acceptable:** unique username (`user.username`)
17 +- **Avoid:** email addresses (they can change)
18 +- **Never:** `default` in production (it exposes other users' data)
19 +</Accordion>
20 +</Accordions>
21 +
22 +Your users connect their accounts through a secure [Connect Link](/reference/api-reference/connected-accounts/postConnectedAccountsLink), and Composio manages their tokens for you.
23 +
24 +<ManageConnectionsVisual />
25 +
26 +## How Composio handles authentication
27 +
28 +Every session includes the [`COMPOSIO_MANAGE_CONNECTIONS`](/toolkits/meta-tools/manage_connections) meta tool. When a tool needs an account, it reads the toolkit's **auth config** (how that toolkit authenticates: method, scopes, credentials), creates a connection, and returns a secure [Connect Link](/reference/api-reference/connected-accounts/postConnectedAccountsLink). This works for all Composio managed connections, so you don't have to set up any OAuth credentials yourself.
29
16 -Not sure? Start with in-chat. You can add manual auth later.
30 +The user signs in on the hosted link and Composio stores the resulting connected account. Credentials never pass through your app or the model, so it's safe to surface the link right in the chat.
31 +
32 +You only need a [custom auth config](/docs/custom-app-vs-managed-app) to bring your own OAuth app, request specific scopes, or use a toolkit without managed auth.
33
34 ## In-chat authentication
35
20 -By default, when a tool requires authentication, the agent prompts the user with a Connect Link. The user authenticates and confirms in chat. No setup needed. Just create a session and the agent handles OAuth flows, token refresh, and credential management automatically.
36 +<MediaSplit>
37 +<div>
38
22 -<ClaudeMockUI>
23 - <p><strong>You:</strong> Summarize my emails from today</p>
24 - <p><strong>Agent:</strong> I need you to connect your Gmail account first. Please click here to authorize: <a href="https://connect.composio.dev/link/ln_abc123">https://connect.composio.dev/link/ln_abc123</a></p>
25 - <p><strong>You:</strong> Done</p>
26 - <p><strong>Agent:</strong> Here's a summary of your emails from today...</p>
27 -</ClaudeMockUI>
39 +The agent posts the Connect Link straight into the conversation. The user clicks it, signs in, and the agent retries the tool and continues. No auth UI for you to build.
40
29 -<Card icon={<MessageCircle />} title="In-chat authentication guide" href="/docs/authenticating-users/in-chat-authentication">
30 - Configuration, callback URLs, and full examples
31 -</Card>
41 +</div>
42
33 -## Manual authentication
43 +<InChatAuthTerminal
44 + task="Summarize my emails from today"
45 + toolkit="Gmail"
46 + toolkitSlug="gmail"
47 + tool="GMAIL_FETCH_EMAILS"
48 + toolArgs="newer_than: 1d"
49 + toolResult="12 emails"
50 + connectUrl="https://connect.composio.dev/link/ln_abc123"
51 + result="Here's a summary of your emails from today..."
52 +/>
53 +</MediaSplit>
54
35 -Use `session.authorize()` to generate Connect Links programmatically when you want to control when and where users authenticate. Common use cases:
55 +You can also call `COMPOSIO_MANAGE_CONNECTIONS` yourself, intercept the Connect Link, and surface it wherever you need: DM it to the user, render it in your own UI, or email it. See [redirect auth links](/examples/general-agent-with-pi#redirect-auth-links) for a worked example.
56
37 -- **Onboarding**: connect accounts during signup before the user ever chats with the agent
38 -- **Settings page**: let users manage their connections from a dedicated UI
39 -- **Pre-flight checks**: verify all required connections are active before starting a task
57 +### Custom callback URL
58
41 -<Card icon={<ShieldCheck />} title="Manual authentication guide" href="/docs/authenticating-users/manually-authenticating">
42 - `session.authorize()` API, callback URLs, and connection status checks
43 -</Card>
59 +To send users back to your app after they connect, pass a `callback_url`:
60
45 -## How Composio manages authentication
61 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
62 +<Tab value="Python">
63 +```python
64 +session = composio.create(
65 + user_id="user_123",
66 + manage_connections={"callback_url": "https://yourapp.com/chat"},
67 +)
68 +```
69 +</Tab>
70 +<Tab value="TypeScript">
71 +```typescript
72 +import { Composio } from '@composio/core';
73 +const composio = new Composio({ apiKey: 'your_api_key' });
74 +// ---cut---
75 +const session = await composio.create("user_123", {
76 + manageConnections: { callbackUrl: "https://yourapp.com/chat" },
77 +});
78 +```
79 +</Tab>
80 +</Tabs>
81
47 -Behind the scenes, Composio uses **auth configs** to manage authentication.
82 +## Manually triggering authentication
83
49 -An **auth config** is a blueprint that defines how authentication works for a toolkit across all your users. It specifies:
84 +Don't want to wait for the agent? Call `session.authorize()` to generate a Connect Link on demand, for onboarding, a settings page, or a pre-flight check before a task.
85
51 -- **Authentication method**: OAuth2, Bearer token, API key, or Basic Auth
52 -- **Scopes**: what actions your tools can perform
53 -- **Credentials**: your own app credentials or Composio's managed auth
86 +<Card icon={<ShieldCheck />} title="Manual auth management" href="/docs/manually-authenticating">
87 + `session.authorize()`, callback URLs, connection status, and disabling in-chat prompts
88 +</Card>
89
55 -Composio creates one auth config per toolkit, and it applies to every user who connects that toolkit. When a user authenticates, Composio creates a **connected account** that stores their credentials (OAuth tokens or API keys) and links them to your user ID. When you need to use your own OAuth credentials or customize scopes, you can create [custom auth configs](/docs/custom-app-vs-managed-app).
90 +## Behind the scenes
91
57 -```mermaid
58 -graph LR
59 - AC["Auth Config<br/><b>ac_gmail_oauth2</b>"]
92 +Composio manages authentication with **auth configs**. An [auth config](/reference/api-reference/auth-configs) is a blueprint for how a toolkit authenticates across all your users. It defines three things:
93
61 - subgraph user_1
62 - CA1["Work Gmail · <b>ca_1a2b3c</b>"]
63 - CA2["Personal Gmail · <b>ca_4d5e6f</b>"]
64 - end
94 +- **Authentication method**: OAuth2, Bearer token, API key, or Basic Auth
95 +- **Scopes**: what actions your tools can perform
96 +- **Credentials**: your own app credentials, or Composio's managed auth
97
66 - subgraph user_2
67 - CA3["Gmail · <b>ca_7g8h9i</b>"]
68 - end
98 +Composio creates one auth config per toolkit and applies it to every user who connects that toolkit. Most toolkits use Composio managed auth, so you don't create or configure anything. You only need a [custom auth config](/docs/custom-app-vs-managed-app) to use your own OAuth app or customize scopes.
99
70 - AC --> CA1
71 - AC --> CA2
72 - AC --> CA3
73 -```
100 +<AuthConfigFlow />
101
75 -Composio handles this automatically:
102 +When a user authenticates, Composio creates a [connected account](/reference/api-reference/connected-accounts): their credentials (OAuth tokens or API keys) linked to your userID. Each user can have multiple, even for the same toolkit (e.g. work and personal Gmail).
103
77 -1. When a toolkit needs authentication, we create an auth config using Composio managed credentials
78 -2. The auth config is reused for all users authenticating with that toolkit
79 -3. Connected accounts are created and linked to your users
104 +### Connection lifecycle
105
81 -<Accordions>
82 -<Accordion title="What are connected accounts?">
83 -A connected account is created when a user authenticates with a toolkit. It stores the user's credentials (OAuth tokens or API keys) and links them to your user ID. Each user can have multiple connected accounts, even for the same toolkit (e.g., work and personal Gmail).
84 -</Accordion>
85 -<Accordion title="What happens when tokens expire?">
86 -Composio automatically refreshes OAuth tokens before they expire. You don't need to handle re-authentication or token expiration. Connected accounts stay valid as long as the user doesn't revoke access.
87 -</Accordion>
88 -</Accordions>
106 +For OAuth, Composio refreshes access tokens automatically before they expire, so connections stay `ACTIVE` with no work from you. If a refresh token is revoked or expires, the connection moves to `EXPIRED` and the user has to reconnect.
107
90 -Most toolkits work out of the box with **Composio managed OAuth**. For API key-based toolkits, users enter their keys directly via Connect Link.
108 +<ConnectionRefreshVisual />
109
92 -You only need to create a custom auth config when:
93 -- You want to use your **own OAuth app credentials** for white-labeling
94 -- You need **specific OAuth scopes** beyond the defaults
95 -- The toolkit doesn't have Composio managed auth
96 -- You have **existing auth configs** with connected accounts you want to use
110 +Catch this before a tool call fails by subscribing to the `composio.connected_account.expired` event on a [webhook subscription](/reference/api-reference/webhook-subscriptions). When it fires, send the user a fresh Connect Link to re-authenticate:
111
98 -To bring your own OAuth apps or customize scopes, see [custom auth configs](/docs/custom-app-vs-managed-app).
112 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
113 +<Tab value="Python">
114 +```python
115 +session = composio.create(user_id="user_123")
116 +connection_request = session.authorize("gmail")
117 +
118 +# Send this URL to the user (email, in-app notification, etc.)
119 +print(connection_request.redirect_url)
120 +```
121 +</Tab>
122 +<Tab value="TypeScript">
123 +```typescript
124 +import { Composio } from '@composio/core';
125 +const composio = new Composio({ apiKey: 'your_api_key' });
126 +// ---cut---
127 +const session = await composio.create("user_123");
128 +const connectionRequest = await session.authorize("gmail");
129 +
130 +// Send this URL to the user (email, in-app notification, etc.)
131 +console.log(connectionRequest.redirectUrl);
132 +```
133 +</Tab>
134 +</Tabs>
135
100 -## What to read next
136 +## Next
137
102 -<Cards>
103 - <Card icon={<MessageCircle />} title="In-chat authentication" href="/docs/authenticating-users/in-chat-authentication" description="Let the agent prompt users to authenticate during conversation" />
104 - <Card icon={<ShieldCheck />} title="Manual authentication" href="/docs/authenticating-users/manually-authenticating" description="Generate Connect Links programmatically in your app" />
105 - <Card icon={<Key />} title="Managed vs custom auth" href="/docs/custom-app-vs-managed-app" description="Decide when to use Composio managed auth or your own credentials" />
106 - <Card icon={<Palette />} title="White-labeling" href="/docs/white-labeling-authentication" description="Customize OAuth screens with your branding" />
107 -</Cards>
138 +<Card icon={<ShieldCheck />} title="Manual auth management" href="/docs/manually-authenticating" description="Generate Connect Links yourself, check connection status, and disable in-chat prompts" />
docs/content/docs/cli.mdx
+22 -23
@@ -4,9 +4,9 @@ description: Use the Composio CLI inside Claude Code for knowledge work, debuggi
4 keywords: [cli, claude code, command line, terminal, composio for you, knowledge work, dev commands]
5 ---
6
7 -The Composio CLI is primarily the command-line surface for [Composio for You](https://composio.dev/for-you). It is meant to be installed in your terminal and used from inside **Claude Code**, so Claude can connect apps, execute tools, inspect schemas, call authenticated APIs, and debug Composio projects while it works with you.
7 +The Composio CLI gives Claude Code a local tool surface. From your terminal, Claude can connect apps, execute tools, inspect schemas, call authenticated APIs, and debug Composio projects while it works with you. It's the command-line side of [Composio for You](https://composio.dev/for-you).
8
9 -Use the CLI directly when you want to give Claude Code a reliable local tool surface instead of copying API keys, schemas, and one-off scripts into chat.
9 +Reach for it when you want Claude to act in your connected apps directly, instead of pasting API keys, schemas, and one-off scripts into the chat.
10
11 ## Install
12
@@ -15,7 +15,7 @@ curl -fsSL https://composio.dev/install | bash
15 composio login
16 ```
17
18 -Then open Claude Code in the project where you want to work. `composio login` installs the `composio-cli` skill for Claude Code by default. To install the skill manually:
18 +Open Claude Code in the project you want to work in. `composio login` installs the `composio-cli` skill for Claude Code by default. To install it manually:
19
20 ```bash
21 composio --install-skill composio-cli claude
@@ -29,11 +29,11 @@ composio --version
29 composio upgrade
30 ```
31
32 -## 1. Using Composio CLI for knowledge work
32 +## Knowledge work in Claude Code
33
34 -This is the recommended way to use Composio from inside Claude Code. The CLI can execute tools for you, connect accounts, script workflows, call authenticated APIs, and inspect trigger events without you wiring a custom integration first.
34 +This is the recommended way to use Composio from inside Claude Code. The CLI executes tools, connects accounts, scripts workflows, calls authenticated APIs, and inspects trigger events, all without you wiring up a custom integration first.
35
36 -### 1.1 Search, connect, and execute tools
36 +### Search, connect, and execute tools
37
38 Use this flow when Claude needs to act in one of your connected apps:
39
@@ -52,7 +52,7 @@ composio execute GMAIL_FETCH_EMAILS \
52 -d '{ query: "is:unread newer_than:1d", max_results: 10 }'
53 ```
54
55 -Useful commands:
55 +The commands you'll reach for most:
56
57 | Command | Use it for |
58 |---------|------------|
@@ -61,15 +61,15 @@ Useful commands:
61 | `composio link` | Connect an app account |
62 | `composio proxy` | Call provider APIs with Composio-managed auth |
63
64 -Use `composio proxy` when Claude already knows the provider API endpoint and wants Composio to inject auth from your connected account:
64 +Use `composio proxy` when Claude already knows the provider's API endpoint and just needs Composio to inject auth from your connected account:
65
66 ```bash
67 composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail
68 ```
69
70 -### 1.2 Run scripts and sub-agents
70 +### Run scripts and sub-agents
71
72 -Use `composio run` when Claude needs a multi-step workflow, loops, parallel fan-out, data transformation, or LLM-assisted summarization. It runs inline TS/JS or a file with `execute()`, `search()`, `proxy()`, `experimental_subAgent()`, `result.prompt()`, and `z` injected.
72 +Reach for `composio run` when Claude needs a multi-step workflow: loops, parallel fan-out, data transformation, or LLM-assisted summarization. It runs inline TS/JS or a file, with `execute()`, `search()`, `proxy()`, `experimental_subAgent()`, `result.prompt()`, and `z` injected.
73
74 Run a single scripted workflow:
75
@@ -126,9 +126,9 @@ Run a checked-in script:
126 composio run --file ./workflow.ts -- --repo composiohq/composio
127 ```
128
129 -### 1.3 Listen to trigger events
129 +### Listen to trigger events
130
131 -Use trigger listening when Claude needs to wait for new events, inspect incoming payloads, or forward events while debugging. In the current CLI, trigger event streaming is exposed through the developer namespace:
131 +Use trigger listening when Claude needs to wait for new events, inspect incoming payloads, or forward events while debugging. Event streaming lives in the developer namespace:
132
133 ```bash
134 # Compact table view for matching events
@@ -144,11 +144,11 @@ composio dev listen --toolkits github --forward https://example.com/webhook
144 composio dev listen --toolkits slack --out ./events.jsonl
145 ```
146
147 -Filter by toolkit, trigger slug, trigger ID, connected account ID, or user ID when you want Claude to focus on one event source.
147 +Filter by toolkit, trigger slug, trigger ID, connected account ID, or userID to focus Claude on a single event source.
148
149 -## 2. Using Composio CLI to build on Composio
149 +## Build on the Composio platform
150
151 -Use the CLI while building on the Composio developer platform. These commands help initialize local project context, create auth configs, manage connected accounts, test tool execution, inspect logs, and debug trigger flows.
151 +Use these commands while building on the Composio developer platform. They initialize local project context, create auth configs, manage connected accounts, test tool execution, inspect logs, and debug trigger flows.
152
153 ### Initialize project context
154
@@ -192,7 +192,7 @@ composio dev auth-configs create "GitHub OAuth" \
192
193 ### Manage connected accounts
194
195 -Top-level `composio link` is the fastest path for personal knowledge work. Use developer connected-account commands when you are building against project users, auth configs, and playground flows.
195 +Top-level `composio link` is the fastest path for personal knowledge work. Use the developer connected-account commands when you're building against project users, auth configs, and playground flows.
196
197 ```bash
198 composio dev connected-accounts list
@@ -237,17 +237,16 @@ composio generate ts --toolkits github,gmail
237 composio generate py --toolkits github,gmail
238 ```
239
240 -Use this section when you are debugging auth configs, connected accounts, trigger delivery, or tool execution in a Composio project. For general user-facing app development, prefer the SDK/session docs first and use the CLI as a local debugging companion.
240 +Reach for this section when you're debugging auth configs, connected accounts, trigger delivery, or tool execution in a Composio project. For user-facing app development, start with the SDK and session docs and keep the CLI as a local debugging companion.
241
242 -## 3. Building directly on top of the CLI
242 +## Building on top of the CLI
243
244 -Building products directly on top of the CLI is **not recommended**. The CLI is in constant development and Composio does not provide CLI-level SLAs as an application runtime contract.
244 +<Callout type="warning">
245 +Don't build a production integration on top of the CLI. It's in constant development, and Composio doesn't offer CLI-level SLAs as an application runtime contract. For a stable integration, build on the Composio SDKs and APIs instead.
246 +</Callout>
247
246 -If you need a stable production integration, build on top of the Composio SDKs and APIs instead.
248 +That said, the CLI works well as a bootstrap or helper layer for agent-native products:
249
248 -That said, the CLI can be useful as a bootstrap or helper layer for agent-native products:
249 -
250 -- Use [Signing up as an agent](/docs/signing-up-as-an-agent) when an agent needs to programmatically create or reuse a Composio identity.
250 - Use `composio connections list` to inspect which connected accounts are available locally.
251 - Use `composio run` or `composio proxy` for internal automations where CLI churn is acceptable.
252
docs/content/docs/common-faq.mdx deleted
-315
@@ -1,315 +0,0 @@
1 ----
2 -title: General FAQs
3 -description: Frequently asked questions about Composio
4 -keywords: [faq, questions, help, common questions]
5 ----
6 -
7 -## General
8 -
9 -<Accordions>
10 -
11 -<Accordion title="Do I need an AI agent to use Composio?">
12 -No. If you're building an AI agent, Composio can give it [meta tools](/docs/tools-and-toolkits) that handle tool discovery and execution automatically.
13 -
14 -If you don't have an agent, use the legacy direct execution guides under **Direct Tool Execution Guides (Legacy)**.
15 -</Accordion>
16 -
17 -<Accordion title="What is the difference between a tool and a toolkit?">
18 -A **toolkit** is a collection of related tools grouped by app, for example the GitHub toolkit or the Gmail toolkit. A **tool** is a single action within a toolkit, like `GITHUB_CREATE_ISSUE` or `GMAIL_SEND_EMAIL`.
19 -
20 -You connect to toolkits (via OAuth or API keys), and then execute individual tools within them. See [Tools and toolkits](/docs/tools-and-toolkits).
21 -</Accordion>
22 -
23 -<Accordion title="What is User ID and how should I use it?">
24 -The User ID is how Composio identifies your end users. It maps each user to their connected accounts and sessions. Use any unique identifier from your system, like an email, database ID, or UUID.
25 -
26 -When you create a session with `composio.create(user_id="user_123")`, all connected accounts and tool executions are scoped to that user. See [What is a session?](/docs/how-composio-works).
27 -</Accordion>
28 -
29 -<Accordion title="What is the difference between an auth config and an MCP config in the dashboard?">
30 -An **auth config** defines how users authenticate with a toolkit (OAuth credentials, scopes, API keys). You need one whenever you want users to connect to an app.
31 -
32 -An **MCP config** creates a hosted MCP server that exposes specific tools over the Model Context Protocol. It's only needed if you're connecting to Composio from an MCP client like Claude Desktop, Cursor, or OpenAI's Responses API via MCP.
33 -
34 -**If you're using the Composio SDK** (sessions or direct execution), you only need auth configs. The SDK handles tool delivery natively. You don't need to create an MCP config.
35 -
36 -**If you're using an MCP client**, you need both: an auth config (so users can authenticate) and an MCP config (so the client can discover and call tools over the MCP protocol).
37 -
38 -See [Native Tools vs MCP](/docs/native-tools-vs-mcp) for a full comparison.
39 -</Accordion>
40 -
41 -<Accordion title="When should I create a new session?">
42 -Create a new session when you want a fresh task context, a different user, or a fundamentally different setup. Every `create()` call returns a new session ID, even if you pass the same config.
43 -
44 -For multi-turn conversations, store the session ID and call `composio.use(session_id)` / `composio.use(sessionId)` on later requests. If the same conversation needs different toolkits, auth configs, or connected accounts, update the existing session with `session.update()` instead of creating a new one. See [What is a session?](/docs/how-composio-works).
45 -</Accordion>
46 -
47 -</Accordions>
48 -
49 -## Tools & Toolkits
50 -
51 -<Accordions>
52 -
53 -<Accordion title="Where can I see all available toolkits?">
54 -You can browse all toolkits on the [Toolkits page](/toolkits) in the docs or in the [Composio dashboard](https://dashboard.composio.dev/~/project/toolkits). Both list every supported app along with available auth schemes and tools.
55 -</Accordion>
56 -
57 -<Accordion title="What toolkits are available by default in a session?">
58 -All toolkits in the Composio catalog are available by default. When you create a session without specifying a `toolkits` parameter, your agent can discover and use any toolkit through `COMPOSIO_SEARCH_TOOLS`.
59 -
60 -To restrict which toolkits are available, pass `toolkits` when creating the session:
61 -
62 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
63 -<Tab value="Python">
64 -```python
65 -# Only GitHub and Gmail
66 -session = composio.create(user_id="user_123", toolkits=["github", "gmail"])
67 -
68 -# Everything except Linear and Jira
69 -session = composio.create(user_id="user_123", toolkits={"disable": ["linear", "jira"]})
70 -```
71 -</Tab>
72 -<Tab value="TypeScript">
73 -```typescript
74 -import { Composio } from '@composio/core';
75 -const composio = new Composio({ apiKey: 'your_api_key' });
76 -// ---cut---
77 -// Only GitHub and Gmail
78 -const session = await composio.create("user_123", { toolkits: ["github", "gmail"] });
79 -
80 -// Everything except Linear and Jira
81 -const session2 = await composio.create("user_123", { toolkits: { disable: ["linear", "jira"] } });
82 -```
83 -</Tab>
84 -</Tabs>
85 -
86 -You can also list the toolkits available in a session with `session.toolkits()`. See [Enable and disable toolkits](/docs/toolkits/enable-and-disable-toolkits).
87 -</Accordion>
88 -
89 -<Accordion title="The tool I need doesn't exist. How do I request one?">
90 -You can request new tools or toolkits on the [tool request board](https://request.composio.dev/boards/tool-requests). The team reviews requests regularly.
91 -</Accordion>
92 -
93 -<Accordion title="How do I work with toolkit versions?">
94 -Composio toolkits are versioned using date-based identifiers (e.g., `20251027_00`). You can pin versions at SDK initialization or per tool execution to keep behavior consistent across deployments.
95 -
96 -**When to use `latest` vs a pinned version:** Use `latest` when tool outputs and trigger payloads are consumed by an LLM or AI agent — agents adapt to response changes dynamically and benefit from always having the newest tools. Pin to a specific version when your code parses outputs programmatically (e.g., destructuring fields, mapping to a schema, or feeding into a typed pipeline).
97 -
98 -This applies to direct tool execution only. Sessions with meta tools always use the latest version. See [Toolkit versioning](/docs/tools-direct/toolkit-versioning).
99 -</Accordion>
100 -
101 -<Accordion title="Why does the API return fewer tools than the platform UI?">
102 -When calling the Get Tools API (`GET /api/v3.1/tools`) without specifying a `toolkit_versions` parameter, the API defaults to the base version (`00000000_00`), which only includes tools from the initial release. The platform UI shows tools from the latest version.
103 -
104 -To get all available tools, pass `toolkit_versions=latest`:
105 -
106 -```bash
107 -curl 'https://backend.composio.dev/api/v3.1/tools?toolkit_slug=googledrive&toolkit_versions=latest' \
108 - -H 'x-api-key: YOUR_API_KEY'
109 -```
110 -
111 -See [Toolkit versioning](/docs/tools-direct/toolkit-versioning) for more details.
112 -</Accordion>
113 -
114 -<Accordion title="Does Composio support triggers?">
115 -Yes. Triggers let you listen for events from connected apps, like a new email in Gmail, a new issue in GitHub, or a new message in Slack. When the event fires, Composio sends a webhook to your endpoint with the event payload.
116 -
117 -See [Triggers](/docs/triggers) for setup and [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events) for receiving events.
118 -</Accordion>
119 -
120 -</Accordions>
121 -
122 -## Authentication & Connections
123 -
124 -<Accordions>
125 -
126 -<Accordion title="What is an auth config?">
127 -An auth config is a blueprint that defines how authentication works for a toolkit. It specifies the auth method (OAuth2, API Key, etc.), the scopes to request, and the credentials to use.
128 -
129 -If you're using sessions with meta tools (`composio.create()`), you don't need to create auth configs yourself. When a user connects to a toolkit, Composio automatically uses a default auth config with managed credentials. The agent handles the entire flow through `COMPOSIO_MANAGE_CONNECTIONS`.
130 -
131 -You only need to create auth configs manually when you're [executing tools directly](/docs/tools-direct/authenticating-tools), want to [use your own OAuth app](/docs/white-labeling-authentication), need [custom scopes](/docs/auth-configuration/custom-auth-configs), or are working with a toolkit that doesn't have Composio-managed auth. See [Authentication](/docs/authentication) for the full overview and [Managed vs custom auth](/docs/custom-app-vs-managed-app) for help deciding.
132 -</Accordion>
133 -
134 -<Accordion title="What authentication types does Composio support?">
135 -Composio supports **OAuth2**, **OAuth1**, **API Key**, **Bearer Token**, and **Basic Auth**. Most toolkits use OAuth2. Each toolkit defines which auth types it supports. You can see the available schemes when creating an auth config in the dashboard.
136 -
137 -For toolkits with Composio-managed auth, you don't need to configure anything. For toolkits without it, you'll need to create a [custom auth config](/docs/custom-app-vs-managed-app). See [Authentication](/docs/authentication) for the full overview.
138 -</Accordion>
139 -
140 -<Accordion title="Can a user connect multiple accounts for the same app?">
141 -Yes. For example, a user can connect both a personal and work Gmail account. Call `session.authorize()` multiple times for the same toolkit. Each session uses the most recently connected account by default, but you can pin a specific account when creating the session.
142 -
143 -For direct tool execution, use `initiate()` with `allow_multiple: true` and pass the `connected_account_id` when executing. See [Managing multiple connected accounts](/docs/managing-multiple-connected-accounts).
144 -</Accordion>
145 -
146 -<Accordion title="How does token refresh work?">
147 -Composio automatically refreshes OAuth tokens before they expire. You don't need to handle this yourself.
148 -
149 -If a refresh fails permanently (e.g., the user revoked access or the OAuth app was deleted), the connection status changes to `EXPIRED`. You can [subscribe to expiry events](/docs/subscribing-to-connection-expiry-events) to detect this and prompt users to re-authenticate. See [Connection statuses](/docs/tools-direct/authenticating-tools#connection-statuses) for more details.
150 -</Accordion>
151 -
152 -<Accordion title="How do I redirect users back to my app after they connect?">
153 -Pass a `callbackUrl` when calling `link()`, `initiate()`, or `session.authorize()`. After authentication, Composio redirects the user to that URL with `status=success` or `status=failed` and the `connected_account_id` appended as query parameters.
154 -
155 -You can include your own query parameters in the callback URL (e.g., `?user_id=user_123&source=onboarding`) to carry context through the flow. Composio preserves them. See [sessions](/docs/authenticating-users/manually-authenticating#redirecting-users-after-authentication) or [direct tool setup](/docs/tools-direct/authenticating-tools#redirecting-users-after-authentication).
156 -</Accordion>
157 -
158 -<Accordion title="How do I use my own API key for a toolkit instead of asking each user for theirs?">
159 -For toolkits that require API keys (like Tavily, Perplexity, or ImgBB), you can create connections on behalf of your users by passing your own API key through `connectedAccounts.initiate()`. This way, your users get access to the service without needing to provide their own credentials.
160 -
161 -Create an auth config for the toolkit, then call `initiate()` with your API key and each user's ID:
162 -
163 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
164 - <Tab value="Python">
165 -```python
166 -connection = composio.connected_accounts.initiate(
167 - user_id="user_123",
168 - auth_config_id="your_auth_config_id",
169 - config={
170 - "auth_scheme": "API_KEY", "val": {"api_key": "your_own_api_key"}
171 - }
172 -)
173 -```
174 - </Tab>
175 - <Tab value="TypeScript">
176 -```typescript
177 -import { Composio, AuthScheme } from '@composio/core';
178 -
179 -declare const composio: Composio;
180 -// ---cut---
181 -const connection = await composio.connectedAccounts.initiate('user_123', 'your_auth_config_id', {
182 - config: AuthScheme.APIKey({
183 - api_key: 'your_own_api_key',
184 - }),
185 -});
186 -```
187 - </Tab>
188 -</Tabs>
189 -
190 -Each user gets their own connected account scoped to their `user_id`, but they all share your API key under the hood. See [API key connections](/docs/tools-direct/authenticating-tools#api-key-connections) for the full setup.
191 -</Accordion>
192 -
193 -<Accordion title="How do I configure sessions with custom auth configs?">
194 -Some toolkits require your own OAuth credentials or API keys. Create an auth config in the dashboard by selecting the toolkit, choosing the auth scheme, and entering your credentials. Then pass the auth config ID when creating a session using the `auth_configs` (or `auth_config_id`) parameter so the session uses your developer credentials instead of Composio-managed auth. See [Managed vs custom auth](/docs/custom-app-vs-managed-app).
195 -</Accordion>
196 -
197 -<Accordion title="When should I use my own developer credentials instead of Composio managed auth?">
198 -Use your own credentials when you're going to production and users will see OAuth consent screens, when you need custom scopes, when you're hitting shared rate limits, or when connecting to a self-hosted instance. For development and prototyping, Composio managed auth works out of the box with no setup. See [Managed vs custom auth](/docs/custom-app-vs-managed-app).
199 -</Accordion>
200 -
201 -<Accordion title="How do I check if a toolkit has Composio managed auth?">
202 -Call the toolkits API and check the `composio_managed_auth_schemes` field:
203 -
204 -```bash
205 -curl 'https://backend.composio.dev/api/v3.1/toolkits/github' \
206 - -H 'x-api-key: YOUR_API_KEY'
207 -```
208 -
209 -If the array is empty, you'll need to provide your own credentials.
210 -
211 -To fetch all toolkits and filter by managed auth availability, use the list endpoint:
212 -
213 -```bash
214 -curl 'https://backend.composio.dev/api/v3.1/toolkits' \
215 - -H 'x-api-key: YOUR_API_KEY'
216 -```
217 -
218 -Each toolkit in the response includes `composio_managed_auth_schemes`. You can also browse the full list on the [managed auth page](/toolkits/managed-auth) or check individual toolkit pages on the [toolkits page](/toolkits).
219 -</Accordion>
220 -
221 -<Accordion title="What happens to existing connections when I switch to my own OAuth app?">
222 -Nothing — existing connected accounts are permanently tied to the auth config they were created with. Switching to a custom auth config only affects new connections.
223 -
224 -- **Existing connections keep working.** Tokens continue refreshing using the original auth config's credentials.
225 -- **New connections use your custom auth config.** Users who connect after the switch see your app name on the consent screen.
226 -- **To fully migrate a user**, delete their old connected account and have them re-authenticate through your OAuth app. There is no way to move an existing connection between auth configs without re-authentication.
227 -
228 -This applies whether you're using sessions or direct tool execution:
229 -- **Sessions:** Pass `authConfigs` when calling `composio.create()`. See [Switching auth configs (sessions)](/docs/white-labeling-authentication#switching-from-composio-managed-to-your-own-oauth-app).
230 -- **Direct tool execution:** Pass the new `authConfigId` when calling `initiate()`. See [Switching auth configs (direct)](/docs/auth-configuration/white-labeling#switching-from-composio-managed-to-your-own-oauth-app).
231 -</Accordion>
232 -
233 -</Accordions>
234 -
235 -## White Labeling & Branding
236 -
237 -<Accordions>
238 -
239 -<Accordion title="Can I white label Composio's auth screens?">
240 -Yes. By default, OAuth consent screens show "Composio" as the app name. If you create an auth config with your own OAuth client ID and secret, users will see your app's name and logo instead.
241 -
242 -You can also proxy the OAuth redirect through your own domain so users never see `backend.composio.dev` in the URL bar. See [White-labeling authentication](/docs/white-labeling-authentication).
243 -</Accordion>
244 -
245 -<Accordion title="Is white labeling available on the free plan?">
246 -Yes. White labeling works on all plans, including free. You can create custom auth configs with your own OAuth credentials on any account. See [White-labeling authentication](/docs/white-labeling-authentication).
247 -</Accordion>
248 -
249 -<Accordion title="How do I hide the Composio logo during authentication?">
250 -Go to your [auth screen settings](https://dashboard.composio.dev/~/project/settings/auth-screen) and upload your own logo and app title. This replaces Composio branding on the Connect Link page. To also remove "Composio" from OAuth consent screens (Google, GitHub, Slack, etc.), create a custom auth config with your own OAuth credentials. See [White-labeling authentication](/docs/white-labeling-authentication) for the full guide.
251 -</Accordion>
252 -
253 -<Accordion title="I changed my branding but still see 'Secured by Composio'">
254 -The Connect Link logo and app title customization does not remove the "Secured by Composio" badge. To remove it, you need to set up your own OAuth app by creating a [custom auth config](/docs/white-labeling-authentication#using-your-own-oauth-apps) with your own client ID and secret.
255 -</Accordion>
256 -
257 -</Accordions>
258 -
259 -## Debugging & Troubleshooting
260 -
261 -<Accordions>
262 -
263 -<Accordion title="Why are my connected account secrets showing `abcd...` or `REDACTED`?">
264 -Connected account secrets are masked by default for security. The API returns the first 4 characters followed by `...` (e.g., `gho_...`). Values shorter than 4 characters show as `REDACTED`.
265 -
266 -To disable masking, go to **Settings → Project Settings → Project Configuration** and turn off "Mask Connected Account Secrets", or use the Patch Project Config API.
267 -
268 -See [Connected accounts](/docs/auth-configuration/connected-accounts#get-account-credentials) for full details.
269 -</Accordion>
270 -
271 -<Accordion title="Where can I find execution logs?">
272 -Every tool execution is logged in the [Composio dashboard](https://dashboard.composio.dev/~/project/logs) under **Logs > Tools**. Each execution response includes a `log_id` you can use to look up detailed request and response data. Trigger delivery attempts are logged separately under **Logs > Triggers**.
273 -
274 -See [Troubleshooting tools](/docs/troubleshooting/tools) for how to use logs to debug failed executions.
275 -</Accordion>
276 -
277 -<Accordion title="How do I check complete logs / API calls from the SDK?">
278 -Enable debug logging to view all API calls and network requests made by the SDK.
279 -
280 -Python:
281 -```bash
282 -COMPOSIO_LOGGING_LEVEL=debug
283 -```
284 -
285 -TypeScript:
286 -```bash
287 -COMPOSIO_LOG_LEVEL=debug
288 -```
289 -
290 -See [Troubleshooting SDKs](/docs/troubleshooting/sdks).
291 -</Accordion>
292 -
293 -</Accordions>
294 -
295 -## Platform & Pricing
296 -
297 -<Accordions>
298 -
299 -<Accordion title="Is Composio secure? Where can I find compliance details?">
300 -Yes. Composio is SOC 2 Type II compliant and follows industry-standard security practices for data handling, encryption, and access control. Visit the [Composio Trust Center](https://trust.composio.dev/) for detailed compliance reports, security policies, and certifications.
301 -</Accordion>
302 -
303 -<Accordion title="What is the IP range for Composio's MCP servers?">
304 -Composio does not have fixed IP ranges. Traffic is routed through Cloudflare and Vercel, which use dynamic IPs.
305 -</Accordion>
306 -
307 -<Accordion title="How do I increase my quota?">
308 -Upgrade your plan. See [pricing](https://composio.dev/pricing) for available plans and limits.
309 -</Accordion>
310 -
311 -<Accordion title="Can Composio be self-hosted?">
312 -Yes, Composio supports self-hosting on the Enterprise plan. See [pricing](https://composio.dev/pricing) for details or [talk to us](https://calendly.com/composiohq/enterprise).
313 -</Accordion>
314 -
315 -</Accordions>
docs/content/docs/configuring-sessions.mdx
+383 -188
@@ -22,15 +22,13 @@ const session = await composio.create("user_123");
22 </Tab>
23 </Tabs>
24
25 -By default, a session has access to **all toolkits** in the Composio catalog. Your agent can discover and use any of them through `COMPOSIO_SEARCH_TOOLS`. Use the options below to restrict or customize what's available.
25 +By default, a session has access to every toolkit in the Composio catalog. Your agent can discover and use any of them through `COMPOSIO_SEARCH_TOOLS`. Use the options below to restrict or customize what's available.
26
27 -You can also attach local experimental custom tools and custom toolkits that run in-process alongside Composio tools. See [Custom tools and toolkits](/docs/toolkits/custom-tools-and-toolkits).
28 -
29 -Every `create()` call returns a new session ID. For multi-turn conversations, store the session ID and reuse it with `composio.use()` instead of calling `create()` for each turn.
27 +You can also attach local custom tools and custom toolkits that run in-process alongside Composio tools. See [Custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits).
28
29 ## Enabling toolkits
30
33 -Restrict the session to specific toolkits:
31 +To limit a session to specific toolkits, pass an array of toolkit slugs. The agent can only discover and use tools from these toolkits.
32
33 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
34 <Tab value="Python">
@@ -68,7 +66,7 @@ const session2 = await composio.create("user_123", {
66
67 ## Disabling toolkits
68
71 -Keep all toolkits enabled except specific ones:
69 +To keep every toolkit discoverable except a few, use the `disable` syntax. This is useful when you want broad access but need to exclude specific toolkits.
70
71 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
72 <Tab value="Python">
@@ -91,32 +89,16 @@ const session = await composio.create("user_123", {
89 </Tab>
90 </Tabs>
91
94 -## Preloading tools
92 +## Direct tools preset
93
96 -By default, sessions expose [meta tools](/reference/meta-tools) that let the agent
97 -discover app tools at runtime. Use `preload.tools` when you already know the
98 -small set of tools that should be returned directly from `session.tools()` and
99 -the session MCP tool list.
94 +The direct tools preset preloads every tool allowed by session filters into the session's tool list and disables session meta tools by default. Use it for specialized agents with a narrow tool set that don't need dynamic tool discovery, in-chat auth, or workbench helpers.
95
101 -Preloading is useful for frequently used tools because the agent can call them
102 -without going through search each time. Keep the preloaded set small, generally
103 -fewer than 20 tools, to avoid context bloat.
104 -
105 -<Callout type="info">
106 -Requires `@composio/core` ≥ `0.9.0` (TypeScript) or `composio` ≥ `0.13.0`
107 -(Python). Older SDKs do not support `preload.tools`,
108 -`sessionPreset` / `session_preset`, or custom-tool `preload`.
109 -</Callout>
110 -
111 -<Callout type="info">
112 -`preload.tools` is not supported when `multiAccount.enable` is true. See
113 -[Managing multiple connected accounts](/docs/managing-multiple-connected-accounts).
114 -</Callout>
96 +This is not the default mode for broad agents. The default session behavior keeps meta tools available so the agent can search for relevant tools and avoid context bloat.
97
98 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
99 <Tab value="Python">
100 ```python
119 -from composio import Composio
101 +from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
102 from composio_openai_agents import OpenAIAgentsProvider
103
104 composio = Composio(
@@ -127,25 +109,26 @@ composio = Composio(
109 session = composio.create(
110 user_id="user_123",
111 toolkits=["gmail"],
130 - preload={
131 - "tools": [
132 - "GMAIL_FETCH_EMAILS",
133 - "GMAIL_CREATE_EMAIL_DRAFT",
134 - ],
112 + tools={
113 + "gmail": {
114 + "enable": [
115 + "GMAIL_FETCH_EMAILS",
116 + "GMAIL_CREATE_EMAIL_DRAFT",
117 + ],
118 + },
119 },
120 + session_preset=SESSION_PRESET_DIRECT_TOOLS,
121 )
122
123 tools = session.tools()
124 print([tool.name for tool in tools])
125 # GMAIL_FETCH_EMAILS
126 # GMAIL_CREATE_EMAIL_DRAFT
142 -# COMPOSIO_SEARCH_TOOLS
143 -# ... other default meta tools
127 ```
128 </Tab>
129 <Tab value="TypeScript">
130 ```typescript
148 -import { Composio } from '@composio/core';
131 +import { Composio, SessionPreset } from '@composio/core';
132 import { OpenAIAgentsProvider } from '@composio/openai-agents';
133
134 const composio = new Composio({
@@ -155,39 +138,25 @@ const composio = new Composio({
138 // ---cut---
139 const session = await composio.create("user_123", {
140 toolkits: ["gmail"],
158 - preload: {
159 - tools: ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"],
141 + tools: {
142 + gmail: {
143 + enable: ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"],
144 + },
145 },
146 + sessionPreset: SessionPreset.DIRECT_TOOLS,
147 });
148
149 const tools = await session.tools();
150 console.log(tools.map((tool) => tool.name));
151 // GMAIL_FETCH_EMAILS
152 // GMAIL_CREATE_EMAIL_DRAFT
167 -// COMPOSIO_SEARCH_TOOLS
168 -// ... other default meta tools
153 ```
154 </Tab>
155 </Tabs>
156
173 -For SDK custom tools, set `preload: true` on the custom tool or custom toolkit. See
174 -[Preloading custom tools](/docs/toolkits/custom-tools-and-toolkits#preloading-custom-tools).
175 -
176 -Use the `preload.tools = "all"` shortcut (`preload={"tools": "all"}` in Python,
177 -`preload: { tools: "all" }` in TypeScript) to preload every tool allowed by the
178 -session filters. The `all` shorthand works for both Composio tools and SDK
179 -custom tools.
180 -
181 -## Direct tools preset
182 -
183 -The direct tools preset preloads every tool allowed by session filters into the
184 -session's tool list and disables session meta tools by default. This can be
185 -useful for specialized agents with a narrow tool set that do not need dynamic
186 -tool discovery, in-chat auth, or workbench helpers.
157 +### Enable selected meta tools
158
188 -This is not the default mode for broad agents. The default session behavior keeps
189 -meta tools available so the agent can search for relevant tools and avoid
190 -context bloat.
159 +With the direct tools preset, you can re-enable supported meta tool groups that your agent still needs. This session loads Gmail tools upfront while keeping connection management and workbench support available:
160
161 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
162 <Tab value="Python">
@@ -212,16 +181,26 @@ session = composio.create(
181 },
182 },
183 session_preset=SESSION_PRESET_DIRECT_TOOLS,
184 + manage_connections={
185 + "enable": True,
186 + },
187 + sandbox={
188 + "enable": True,
189 + },
190 )
191
192 tools = session.tools()
193 print([tool.name for tool in tools])
194 # GMAIL_FETCH_EMAILS
195 # GMAIL_CREATE_EMAIL_DRAFT
196 +# COMPOSIO_MANAGE_CONNECTIONS
197 +# COMPOSIO_REMOTE_WORKBENCH
198 +# COMPOSIO_REMOTE_BASH_TOOL
199 ```
200 </Tab>
201 <Tab value="TypeScript">
202 ```typescript
203 +// @noErrors
204 import { Composio, SessionPreset } from '@composio/core';
205 import { OpenAIAgentsProvider } from '@composio/openai-agents';
206
@@ -238,27 +217,237 @@ const session = await composio.create("user_123", {
217 },
218 },
219 sessionPreset: SessionPreset.DIRECT_TOOLS,
220 + manageConnections: {
221 + enable: true,
222 + },
223 + sandbox: {
224 + enable: true,
225 + },
226 });
227
228 const tools = await session.tools();
229 console.log(tools.map((tool) => tool.name));
230 // GMAIL_FETCH_EMAILS
231 // GMAIL_CREATE_EMAIL_DRAFT
232 +// COMPOSIO_MANAGE_CONNECTIONS
233 +// COMPOSIO_REMOTE_WORKBENCH
234 +// COMPOSIO_REMOTE_BASH_TOOL
235 ```
236 </Tab>
237 </Tabs>
238
251 -**Enable selected meta tools**
239 +## Enabling or disabling specific tools
240
253 -When using the direct tools preset, you can selectively re-enable supported meta
254 -tool groups that your agent still needs. For example, this session loads Gmail
255 -reply-drafting tools upfront while keeping connection management and workbench
256 -support available:
241 +To control which individual tools are available within a toolkit, use the `tools` configuration. The key is the toolkit slug and the value specifies which tools to enable or disable.
242 +
243 +To enable only specific tools, pass an `enable` list per toolkit:
244
245 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
246 <Tab value="Python">
247 ```python
261 -from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
248 +session = composio.create(
249 + user_id="user_123",
250 + tools={
251 + # Only these Gmail tools will be available
252 + "gmail": {"enable": ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]},
253 + # Only issue-related GitHub tools
254 + "github": {"enable": ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]}
255 + }
256 +)
257 +```
258 +</Tab>
259 +<Tab value="TypeScript">
260 +```typescript
261 +import { Composio } from '@composio/core';
262 +const composio = new Composio({ apiKey: 'your_api_key' });
263 +// ---cut---
264 +const session = await composio.create("user_123", {
265 + tools: {
266 + // Only these Gmail tools will be available
267 + gmail: { enable: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"] },
268 + // Only issue-related GitHub tools
269 + github: { enable: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"] }
270 + }
271 +});
272 +```
273 +</Tab>
274 +</Tabs>
275 +
276 +The shorthand array syntax is equivalent to `enable`:
277 +
278 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
279 +<Tab value="Python">
280 +```python
281 +session = composio.create(
282 + user_id="user_123",
283 + tools={
284 + "gmail": ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"],
285 + "github": ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]
286 + }
287 +)
288 +```
289 +</Tab>
290 +<Tab value="TypeScript">
291 +```typescript
292 +import { Composio } from '@composio/core';
293 +const composio = new Composio({ apiKey: 'your_api_key' });
294 +// ---cut---
295 +const session = await composio.create("user_123", {
296 + tools: {
297 + gmail: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"],
298 + github: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]
299 + }
300 +});
301 +```
302 +</Tab>
303 +</Tabs>
304 +
305 +To keep every tool in a toolkit except a few, use `disable`:
306 +
307 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
308 +<Tab value="Python">
309 +```python
310 +session = composio.create(
311 + user_id="user_123",
312 + tools={
313 + # All Slack tools except delete
314 + "slack": {"disable": ["SLACK_DELETE_MESSAGE"]},
315 + # All GitHub tools except destructive ones
316 + "github": {"disable": ["GITHUB_DELETE_REPO", "GITHUB_DELETE_BRANCH"]}
317 + }
318 +)
319 +```
320 +</Tab>
321 +<Tab value="TypeScript">
322 +```typescript
323 +import { Composio } from '@composio/core';
324 +const composio = new Composio({ apiKey: 'your_api_key' });
325 +// ---cut---
326 +const session = await composio.create("user_123", {
327 + tools: {
328 + // All Slack tools except delete
329 + slack: { disable: ["SLACK_DELETE_MESSAGE"] },
330 + // All GitHub tools except destructive ones
331 + github: { disable: ["GITHUB_DELETE_REPO", "GITHUB_DELETE_BRANCH"] }
332 + }
333 +});
334 +```
335 +</Tab>
336 +</Tabs>
337 +
338 +## Filtering tools by tags
339 +
340 +Tools carry behavior tags that you can filter on. The available tags are:
341 +
342 +| Tag | Description |
343 +|-----|-------------|
344 +| `readOnlyHint` | Tools that only read data |
345 +| `destructiveHint` | Tools that modify or delete data |
346 +| `idempotentHint` | Tools that can be safely retried |
347 +| `openWorldHint` | Tools that operate in an open world context |
348 +
349 +To apply tag filters across all toolkits, pass `tags` at the session level:
350 +
351 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
352 +<Tab value="Python">
353 +```python
354 +# Only include read-only and idempotent tools
355 +session = composio.create(
356 + user_id="user_123",
357 + tags=["readOnlyHint", "idempotentHint"]
358 +)
359 +
360 +# Enable some tags, disable others
361 +session = composio.create(
362 + user_id="user_123",
363 + tags={
364 + "enable": ["readOnlyHint"],
365 + "disable": ["destructiveHint"]
366 + }
367 +)
368 +```
369 +</Tab>
370 +<Tab value="TypeScript">
371 +```typescript
372 +import { Composio } from '@composio/core';
373 +const composio = new Composio({ apiKey: 'your_api_key' });
374 +// ---cut---
375 +// Only include read-only and idempotent tools
376 +const session = await composio.create("user_123", {
377 + tags: ["readOnlyHint", "idempotentHint"]
378 +});
379 +
380 +// Enable some tags, disable others
381 +const sessionWithTagConfig = await composio.create("user_123", {
382 + tags: {
383 + enable: ["readOnlyHint"],
384 + disable: ["destructiveHint"]
385 + }
386 +});
387 +```
388 +</Tab>
389 +</Tabs>
390 +
391 +To override the global tags for a specific toolkit, set `tags` inside that toolkit's `tools` config:
392 +
393 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
394 +<Tab value="Python">
395 +```python
396 +session = composio.create(
397 + user_id="user_123",
398 + # Global: only read-only tools
399 + tags=["readOnlyHint"],
400 + tools={
401 + # Override for GitHub: allow all tools except destructive
402 + "github": {"tags": {"disable": ["destructiveHint"]}},
403 + # Override for Gmail: only read-only tools (explicit)
404 + "gmail": {"tags": ["readOnlyHint"]}
405 + }
406 +)
407 +```
408 +</Tab>
409 +<Tab value="TypeScript">
410 +```typescript
411 +import { Composio } from '@composio/core';
412 +const composio = new Composio({ apiKey: 'your_api_key' });
413 +// ---cut---
414 +const session = await composio.create("user_123", {
415 + // Global: only read-only tools
416 + tags: ["readOnlyHint"],
417 + tools: {
418 + // Override for GitHub: allow all tools except destructive
419 + github: { tags: { disable: ["destructiveHint"] } },
420 + // Override for Gmail: only read-only tools (explicit)
421 + gmail: { tags: ["readOnlyHint"] }
422 + }
423 +});
424 +```
425 +</Tab>
426 +</Tabs>
427 +
428 +## Preloading tools
429 +
430 +Return a known set of tools directly from `session.tools()` and the session MCP tool list, without the agent searching for them first.
431 +
432 +By default, sessions expose [meta tools](/toolkits/meta-tools) that let the agent discover app tools at runtime. Use `preload.tools` when you already know which tools the agent needs, so it can call them without going through search each time.
433 +
434 +Keep the preloaded set small, generally fewer than 20 tools, to avoid context bloat.
435 +
436 +<Callout type="info">
437 +Requires `@composio/core` ≥ `0.9.0` (TypeScript) or `composio` ≥ `0.13.0`
438 +(Python). Older SDKs do not support `preload.tools`,
439 +`sessionPreset` / `session_preset`, or custom-tool `preload`.
440 +</Callout>
441 +
442 +<Callout type="info">
443 +`preload.tools` is not supported when `multiAccount.enable` is true. See
444 +[Managing multiple connected accounts](/docs/managing-multiple-connected-accounts).
445 +</Callout>
446 +
447 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
448 +<Tab value="Python">
449 +```python
450 +from composio import Composio
451 from composio_openai_agents import OpenAIAgentsProvider
452
453 composio = Composio(
@@ -269,20 +458,11 @@ composio = Composio(
458 session = composio.create(
459 user_id="user_123",
460 toolkits=["gmail"],
272 - tools={
273 - "gmail": {
274 - "enable": [
275 - "GMAIL_FETCH_EMAILS",
276 - "GMAIL_CREATE_EMAIL_DRAFT",
277 - ],
278 - },
279 - },
280 - session_preset=SESSION_PRESET_DIRECT_TOOLS,
281 - manage_connections={
282 - "enable": True,
283 - },
284 - workbench={
285 - "enable": True,
461 + preload={
462 + "tools": [
463 + "GMAIL_FETCH_EMAILS",
464 + "GMAIL_CREATE_EMAIL_DRAFT",
465 + ],
466 },
467 )
468
@@ -290,14 +470,13 @@ tools = session.tools()
470 print([tool.name for tool in tools])
471 # GMAIL_FETCH_EMAILS
472 # GMAIL_CREATE_EMAIL_DRAFT
293 -# COMPOSIO_MANAGE_CONNECTIONS
294 -# COMPOSIO_REMOTE_WORKBENCH
295 -# COMPOSIO_REMOTE_BASH_TOOL
473 +# COMPOSIO_SEARCH_TOOLS
474 +# ... other default meta tools
475 ```
476 </Tab>
477 <Tab value="TypeScript">
478 ```typescript
300 -import { Composio, SessionPreset } from '@composio/core';
479 +import { Composio } from '@composio/core';
480 import { OpenAIAgentsProvider } from '@composio/openai-agents';
481
482 const composio = new Composio({
@@ -307,17 +486,8 @@ const composio = new Composio({
486 // ---cut---
487 const session = await composio.create("user_123", {
488 toolkits: ["gmail"],
310 - tools: {
311 - gmail: {
312 - enable: ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"],
313 - },
314 - },
315 - sessionPreset: SessionPreset.DIRECT_TOOLS,
316 - manageConnections: {
317 - enable: true,
318 - },
319 - workbench: {
320 - enable: true,
489 + preload: {
490 + tools: ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"],
491 },
492 });
493
@@ -325,16 +495,19 @@ const tools = await session.tools();
495 console.log(tools.map((tool) => tool.name));
496 // GMAIL_FETCH_EMAILS
497 // GMAIL_CREATE_EMAIL_DRAFT
328 -// COMPOSIO_MANAGE_CONNECTIONS
329 -// COMPOSIO_REMOTE_WORKBENCH
330 -// COMPOSIO_REMOTE_BASH_TOOL
498 +// COMPOSIO_SEARCH_TOOLS
499 +// ... other default meta tools
500 ```
501 </Tab>
502 </Tabs>
503
504 +For SDK custom tools, set `preload: true` on the custom tool or custom toolkit. See [Preloading custom tools](/docs/extending-sessions/custom-tools-and-toolkits#preloading-custom-tools).
505 +
506 +To preload every tool allowed by the session filters, use the `preload.tools = "all"` shortcut (`preload={"tools": "all"}` in Python, `preload: { tools: "all" }` in TypeScript). The `all` shorthand works for both Composio tools and SDK custom tools.
507 +
508 ## Custom auth configs
509
337 -Use your own OAuth credentials instead of Composio's defaults:
510 +Use your own OAuth credentials instead of Composio's defaults. Pass an auth config ID per toolkit:
511
512 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
513 <Tab value="Python">
@@ -367,7 +540,7 @@ See [White-labeling authentication](/docs/white-labeling-authentication) for bra
540
541 ## Account selection
542
370 -If a user has multiple connected accounts for the same toolkit, you can specify which one to use:
543 +When a user has multiple connected accounts for the same toolkit, specify which one the session uses:
544
545 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
546 <Tab value="Python">
@@ -402,26 +575,26 @@ Arrays are the preferred format for `connectedAccounts`. A single string (e.g. `
575
576 ### Precedence
577
405 -When executing a tool, the connected account is selected in this order:
578 +When executing a tool, the session selects the connected account in this order:
579
407 -1. `connectedAccounts` override if provided in session config
408 -2. `authConfigs` override - finds or creates connection on that config
409 -3. Auth config previously created for this toolkit
410 -4. Creates new auth config using Composio managed auth
411 -5. Error if no Composio managed auth scheme exists for the toolkit
580 +1. The `connectedAccounts` override, if provided in the session config.
581 +2. The `authConfigs` override, which finds or creates a connection on that config.
582 +3. An auth config previously created for this toolkit.
583 +4. A new auth config created using Composio managed auth.
584 +5. Otherwise, an error if no Composio managed auth scheme exists for the toolkit.
585
413 -If a user has multiple connected accounts for a toolkit, the most recently connected one is used.
586 +When a user has multiple connected accounts for a toolkit, the session uses the most recently connected one.
587
415 -## Disabling workbench
588 +## Disabling the sandbox
589
417 -By default, sessions include the [workbench](/docs/workbench) — a persistent sandbox that provides `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL`. If your use case doesn't need code execution, you can disable it:
590 +By default, sessions include the [sandbox](/docs/sandbox/remote), a persistent environment that provides `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL`. If your use case doesn't need code execution, disable it:
591
592 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
593 <Tab value="Python">
594 ```python
595 session = composio.create(
596 user_id="user_123",
424 - workbench={
597 + sandbox={
598 "enable": False
599 }
600 )
@@ -429,11 +602,12 @@ session = composio.create(
602 </Tab>
603 <Tab value="TypeScript">
604 ```typescript
605 +// @noErrors
606 import { Composio } from '@composio/core';
607 const composio = new Composio({ apiKey: 'your_api_key' });
608 // ---cut---
609 const session = await composio.create("user_123", {
436 - workbench: {
610 + sandbox: {
611 enable: false,
612 },
613 });
@@ -443,12 +617,16 @@ const session = await composio.create("user_123", {
617
618 When disabled:
619 - `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL` are excluded from the session
446 -- Workbench-related system prompt lines are stripped
447 -- Direct workbench calls are rejected with a 400 error
620 +- Sandbox-related system prompt lines are stripped
621 +- Direct sandbox calls are rejected with a 400 error
622 +
623 +<Callout>
624 +`sandbox` is the preferred config key. `workbench` still works as a fully supported alias and isn't deprecated, so existing code keeps running unchanged.
625 +</Callout>
626
627 ## Sandbox compute tier
628
451 -The workbench runs in a per-session sandbox. You can pick a compute tier to match the workload — heavier code execution or larger in-memory data benefits from a bigger sandbox. The tier is passed via `workbench.sandbox_size` (snake_case on the wire; `sandboxSize` in the TypeScript SDK).
629 +The sandbox runs per session. Pick a compute tier to match the workload: heavier code execution or larger in-memory data benefits from a bigger sandbox. Pass the tier via `sandbox.sandbox_size` (snake_case on the wire, `sandboxSize` in the TypeScript SDK).
630
631 <Callout type="info">
632 Requires `@composio/core` ≥ `0.8.1` (TypeScript) or `composio` ≥ `0.12.1` (Python). Older SDKs reject `sandboxSize` (TypeScript) or silently drop `sandbox_size` (Python). See the [release notes](/docs/changelog/2026/04/28).
@@ -469,7 +647,7 @@ Defaults to `standard` when omitted.
647 ```python
648 session = composio.create(
649 user_id="user_123",
472 - workbench={
650 + sandbox={
651 "sandbox_size": "large",
652 },
653 )
@@ -477,11 +655,12 @@ session = composio.create(
655 </Tab>
656 <Tab value="TypeScript">
657 ```typescript
658 +// @noErrors
659 import { Composio } from '@composio/core';
660 const composio = new Composio({ apiKey: 'your_api_key' });
661 // ---cut---
662 const session = await composio.create("user_123", {
484 - workbench: {
663 + sandbox: {
664 enable: true,
665 sandboxSize: "large",
666 },
@@ -491,26 +670,22 @@ const session = await composio.create("user_123", {
670 </Tabs>
671
672 <Callout type="info">
494 -**Pricing:** Sandboxes are not billed today. Composio plans to begin billing for sandbox usage soon (metered by tier and runtime). Pick a tier that matches your workload — but expect future pricing to track actual usage.
673 +**Pricing:** Sandboxes are not billed today. Composio plans to begin billing for sandbox usage soon (metered by tier and runtime). Pick a tier that matches your workload, but expect future pricing to track actual usage.
674 </Callout>
675
497 -Changing `sandbox_size` on an existing session recreates the sandbox on next access. The sandbox's in-memory filesystem state is lost, but the persistent `/mnt/files/` mount survives the restart.
676 +Changing `sandbox_size` on an existing session recreates the sandbox on the next access. The sandbox's in-memory filesystem state is lost, but the persistent [`/mnt/files/` mount](/docs/sandbox/remote#files-and-mounts) survives the restart.
677 +
678 +## Session methods
679
499 -## Session lifecycle and methods
680 +For framework examples, see provider-specific documentation like [OpenAI](/docs/providers/openai) or [Vercel AI SDK](/docs/providers/vercel). To connect over MCP instead, see [Using sessions via MCP](/docs/sessions-via-mcp).
681
501 -### use()
682 +### tools()
683
503 -Reuse an existing session by ID. This keeps tool, auth, MCP, and workbench context available across multi-turn requests.
684 +Get the tools the session exposes for your AI framework. By default these are the session's [meta tools](/toolkits/meta-tools), formatted for your configured provider.
685
686 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
687 <Tab value="Python">
688 ```python
508 -# First request
509 -session = composio.create(user_id="user_123")
510 -session_id = session.session_id
511 -
512 -# Later request
513 -session = composio.use(session_id)
689 tools = session.tools()
690 ```
691 </Tab>
@@ -518,57 +693,58 @@ tools = session.tools()
693 ```typescript
694 import { Composio } from '@composio/core';
695 const composio = new Composio({ apiKey: 'your_api_key' });
521 -// ---cut---
522 -// First request
696 const session = await composio.create("user_123");
524 -const sessionId = session.sessionId;
525 -
526 -// Later request
527 -const reusedSession = await composio.use(sessionId);
528 -const tools = await reusedSession.tools();
697 +// ---cut---
698 +const tools = await session.tools();
699 ```
700 </Tab>
701 </Tabs>
702
533 -### update()
703 +### authorize()
704
535 -Patch an existing session without creating a new session ID. Only the fields you pass are changed.
705 +Manually authenticate a user to a toolkit outside of the chat flow.
706
707 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
708 <Tab value="Python">
709 ```python
540 -session.update(
541 - toolkits=["gmail", "slack"],
542 - auth_configs={"gmail": "ac_new_config"},
543 - connected_accounts={"slack": ["ca_work_slack"]},
544 -)
710 +connection_request = session.authorize("github")
711 +
712 +print(connection_request.redirect_url)
713 +
714 +connected_account = connection_request.wait_for_connection()
715 ```
716 </Tab>
717 <Tab value="TypeScript">
718 ```typescript
719 import { Composio } from '@composio/core';
720 const composio = new Composio({ apiKey: 'your_api_key' });
551 -const session = await composio.use("session_id");
721 +const session = await composio.create("user_123");
722 // ---cut---
553 -await session.update({
554 - toolkits: ["gmail", "slack"],
555 - authConfigs: { gmail: "ac_new_config" },
556 - connectedAccounts: { slack: ["ca_work_slack"] },
723 +const connectionRequest = await session.authorize("github", {
724 + callbackUrl: "https://myapp.com/callback",
725 });
726 +
727 +console.log(connectionRequest.redirectUrl);
728 +
729 +const connectedAccount = await connectionRequest.waitForConnection();
730 ```
731 </Tab>
732 </Tabs>
733
562 -### mcp
734 +For more details, see [Manually authenticating users](/docs/manually-authenticating).
735
564 -Get the MCP server URL to use with any MCP-compatible client.
736 +### toolkits()
737
566 -Use the SDK-generated `session.mcp.url` as-is. MCP URLs include the session's user context; if you construct a single-toolkit MCP URL manually, include either `user_id` or `connected_account_id`.
738 +List the toolkits enabled for the session and their connection status, sorted by popularity. Use it to build a UI showing which apps are connected. Each toolkit includes its `slug`, `name`, `logo`, and connection status, and the call returns the first 20 by default.
739
740 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
741 <Tab value="Python">
742 ```python
571 -mcp_url = session.mcp.url
743 +toolkits = session.toolkits()
744 +
745 +for toolkit in toolkits.items:
746 + status = toolkit.connection.connected_account.id if toolkit.connection.is_active else "Not connected"
747 + print(f"{toolkit.name}: {status}")
748 ```
749 </Tab>
750 <Tab value="TypeScript">
@@ -577,22 +753,21 @@ import { Composio } from '@composio/core';
753 const composio = new Composio({ apiKey: 'your_api_key' });
754 const session = await composio.create("user_123");
755 // ---cut---
580 -const { mcp } = session;
581 -console.log(mcp.url);
756 +const toolkits = await session.toolkits();
757 +
758 +toolkits.items.forEach((toolkit) => {
759 + console.log(`${toolkit.name}: ${toolkit.connection?.connectedAccount?.id ?? "Not connected"}`);
760 +});
761 ```
762 </Tab>
763 </Tabs>
764
586 -For framework examples, see provider-specific documentation like [OpenAI](/docs/providers/openai) or [Vercel AI SDK](/docs/providers/vercel).
587 -
588 -### tools()
589 -
590 -Get native tools from the session for use with AI frameworks.
765 +Filter to only connected toolkits:
766
767 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
768 <Tab value="Python">
769 ```python
595 -tools = session.tools()
770 +connected = session.toolkits(is_connected=True)
771 ```
772 </Tab>
773 <Tab value="TypeScript">
@@ -601,23 +776,25 @@ import { Composio } from '@composio/core';
776 const composio = new Composio({ apiKey: 'your_api_key' });
777 const session = await composio.create("user_123");
778 // ---cut---
604 -const tools = await session.tools();
779 +const connected = await session.toolkits({ isConnected: true });
780 ```
781 </Tab>
782 </Tabs>
783
609 -### authorize()
610 -
611 -Manually authenticate a user to a toolkit outside of the chat flow.
784 +Paginate through every toolkit with `limit` and the returned cursor:
785
786 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
787 <Tab value="Python">
788 ```python
616 -connection_request = session.authorize("github")
617 -
618 -print(connection_request.redirect_url)
789 +all_toolkits = []
790 +cursor = None
791
620 -connected_account = connection_request.wait_for_connection()
792 +while True:
793 + result = session.toolkits(limit=20, next_cursor=cursor)
794 + all_toolkits.extend(result.items)
795 + cursor = result.next_cursor
796 + if not cursor:
797 + break
798 ```
799 </Tab>
800 <Tab value="TypeScript">
@@ -626,55 +803,73 @@ import { Composio } from '@composio/core';
803 const composio = new Composio({ apiKey: 'your_api_key' });
804 const session = await composio.create("user_123");
805 // ---cut---
629 -const connectionRequest = await session.authorize("github", {
630 - callbackUrl: "https://myapp.com/callback",
631 -});
806 +const allToolkits: any[] = [];
807 +let cursor: string | undefined;
808
633 -console.log(connectionRequest.redirectUrl);
634 -
635 -const connectedAccount = await connectionRequest.waitForConnection();
809 +do {
810 + const { items, cursor: nextCursor } = await session.toolkits({ limit: 20, cursor });
811 + allToolkits.push(...items);
812 + cursor = nextCursor;
813 +} while (cursor);
814 ```
815 </Tab>
816 </Tabs>
817
640 -For more details, see [Manually authenticating users](/docs/authenticating-users/manually-authenticating).
818 +## Browsing the catalog
819
642 -### toolkits()
643 -
644 -List available toolkits and their connection status. You can use this to build a UI showing which apps are connected.
820 +Before configuring a session, explore the toolkits and tools available. Browse them visually at [dashboard.composio.dev](https://dashboard.composio.dev) or in the [docs catalog](/toolkits), or fetch them programmatically:
821
822 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
823 <Tab value="Python">
824 ```python
649 -toolkits = session.toolkits()
825 +# List toolkits
826 +toolkits = composio.toolkits.get()
827
651 -for toolkit in toolkits.items:
652 - status = toolkit.connection.connected_account.id if toolkit.connection.is_active else "Not connected"
653 - print(f"{toolkit.name}: {status}")
828 +# List tools within a toolkit (top 20 by default)
829 +tools = composio.tools.get("user_123", toolkits=["GITHUB"])
830 ```
831 </Tab>
832 <Tab value="TypeScript">
833 ```typescript
834 import { Composio } from '@composio/core';
835 const composio = new Composio({ apiKey: 'your_api_key' });
660 -const session = await composio.create("user_123");
836 +const userId = 'user_123';
837 // ---cut---
662 -const toolkits = await session.toolkits();
838 +// List toolkits
839 +const toolkits = await composio.toolkits.get();
840
664 -toolkits.items.forEach((toolkit) => {
665 - console.log(`${toolkit.name}: ${toolkit.connection?.connectedAccount?.id ?? "Not connected"}`);
666 -});
841 +// List tools within a toolkit (top 20 by default)
842 +const tools = await composio.tools.get(userId, { toolkits: ["GITHUB"] });
843 ```
844 </Tab>
845 </Tabs>
846
671 -Returns the first 20 toolkits by default.
847 +Inspect a tool's input and output schema without a user context with `getRawComposioToolBySlug`:
848 +
849 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
850 +<Tab value="Python">
851 +```python
852 +tool = composio.tools.get_raw_composio_tool_by_slug("GMAIL_SEND_EMAIL")
853 +print(tool.name)
854 +print(tool.description)
855 +print(tool.input_parameters)
856 +print(tool.output_parameters)
857 +```
858 +</Tab>
859 +<Tab value="TypeScript">
860 +```typescript
861 +import { Composio } from '@composio/core';
862 +const composio = new Composio({ apiKey: 'your_api_key' });
863 +// ---cut---
864 +const tool = await composio.tools.getRawComposioToolBySlug("GMAIL_SEND_EMAIL");
865 +console.log(tool.name);
866 +console.log(tool.description);
867 +console.log(tool.inputParameters);
868 +console.log(tool.outputParameters);
869 +```
870 +</Tab>
871 +</Tabs>
872
673 -## What to read next
873 +## Next
874
675 -<Cards>
676 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="Understand the meta tools and toolkit catalog behind session tools" />
677 - <Card icon={<Wrench />} title="Enable & disable toolkits" href="/docs/toolkits/enable-and-disable-toolkits" description="Control which toolkits and individual tools are available in sessions" />
678 - <Card icon={<Monitor />} title="Workbench" href="/docs/workbench" description="Configure the sandbox for bulk operations and data processing" />
679 - <Card icon={<MessageCircle />} title="In-chat authentication" href="/docs/authenticating-users/in-chat-authentication" description="Let the agent prompt users to connect accounts during conversation" />
680 -</Cards>
875 +<Card icon={<Database />} title="Sandbox" href="/docs/sandbox/remote" description="Give sessions a persistent compute environment with COMPOSIO_REMOTE_WORKBENCH and COMPOSIO_REMOTE_BASH_TOOL" />
docs/content/docs/controlling-scopes.mdx new
+153
@@ -0,0 +1,153 @@
1 +---
2 +title: Controlling scopes
3 +description: Override the default OAuth scopes Composio requests for a toolkit
4 +keywords: [oauth scopes, scopes, permissions, custom scopes, user scopes, least privilege]
5 +---
6 +
7 +Scopes are the permissions an OAuth toolkit grants your app: read email, write to a repo, manage calendar events. Composio requests a sensible set of default scopes for each toolkit, so most apps never set scopes at all. Override them when the defaults grant too much or too little: to follow least privilege, or to reach an API the defaults don't cover.
8 +
9 +You control scopes on an [auth config](/docs/authentication#behind-the-scenes), then [pass that auth config to a session](#use-the-auth-config-in-a-session) so the session requests your scopes when users connect.
10 +
11 +<Callout type="info">
12 +Scopes apply to OAuth toolkits. Toolkits that authenticate with API keys or bearer tokens don't have scopes to set.
13 +</Callout>
14 +
15 +## Set scopes with Composio managed auth
16 +
17 +Pass a `scopes` field in `credentials` to override the defaults while still using Composio's managed OAuth app. Give scopes as a comma-separated string.
18 +
19 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
20 +<Tab value="Python">
21 +```python
22 +from composio import Composio
23 +
24 +composio = Composio()
25 +
26 +auth_config = composio.auth_configs.create(
27 + toolkit="hubspot",
28 + options={
29 + "type": "use_composio_managed_auth",
30 + "name": "HubSpot",
31 + "credentials": {"scopes": "sales-email-read,tickets"},
32 + },
33 +)
34 +```
35 +</Tab>
36 +<Tab value="TypeScript">
37 +```typescript
38 +import { Composio } from '@composio/core';
39 +
40 +const composio = new Composio();
41 +// ---cut---
42 +const authConfig = await composio.authConfigs.create('hubspot', {
43 + type: 'use_composio_managed_auth',
44 + name: 'HubSpot',
45 + credentials: { scopes: 'sales-email-read,tickets' },
46 +});
47 +```
48 +</Tab>
49 +</Tabs>
50 +
51 +## Set scopes with your own OAuth app
52 +
53 +When you bring your own OAuth credentials, put `scopes` alongside the client ID and secret. Make sure your OAuth app has those scopes approved in the provider's portal.
54 +
55 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
56 +<Tab value="Python">
57 +```python
58 +import os
59 +
60 +auth_config = composio.auth_configs.create(
61 + toolkit="github",
62 + options={
63 + "type": "use_custom_auth",
64 + "auth_scheme": "OAUTH2",
65 + "name": "GitHub",
66 + "credentials": {
67 + "client_id": os.environ["GITHUB_CLIENT_ID"],
68 + "client_secret": os.environ["GITHUB_CLIENT_SECRET"],
69 + "scopes": "repo,read:org",
70 + },
71 + },
72 +)
73 +```
74 +</Tab>
75 +<Tab value="TypeScript">
76 +```typescript
77 +import { Composio } from '@composio/core';
78 +
79 +const composio = new Composio();
80 +// ---cut---
81 +const authConfig = await composio.authConfigs.create('github', {
82 + type: 'use_custom_auth',
83 + authScheme: 'OAUTH2',
84 + name: 'GitHub',
85 + credentials: {
86 + client_id: process.env.GITHUB_CLIENT_ID!,
87 + client_secret: process.env.GITHUB_CLIENT_SECRET!,
88 + scopes: 'repo,read:org',
89 + },
90 +});
91 +```
92 +</Tab>
93 +</Tabs>
94 +
95 +## Update scopes on an existing config
96 +
97 +Change the scopes on an auth config you already created without recreating it.
98 +
99 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
100 +<Tab value="Python">
101 +```python
102 +composio.auth_configs.update(
103 + "ac_1234",
104 + {"type": "default", "scopes": "repo,read:org,read:user"},
105 +)
106 +```
107 +</Tab>
108 +<Tab value="TypeScript">
109 +```typescript
110 +import { Composio } from '@composio/core';
111 +const composio = new Composio({ apiKey: 'your_api_key' });
112 +// ---cut---
113 +await composio.authConfigs.update('ac_1234', {
114 + type: 'default',
115 + scopes: 'repo,read:org,read:user',
116 +});
117 +```
118 +</Tab>
119 +</Tabs>
120 +
121 +<Callout type="warn">
122 +Changing scopes affects new connections only. Users with an existing [connected account](/docs/authentication#behind-the-scenes) keep the scopes they already granted until they reconnect. To apply new scopes to a current user, have them re-authenticate.
123 +</Callout>
124 +
125 +## Use the auth config in a session
126 +
127 +Setting scopes on an auth config does nothing until a session uses it. Pass the auth config ID to `authConfigs` (keyed by toolkit) when you create the session, and the session requests your scopes when the user connects that toolkit.
128 +
129 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
130 +<Tab value="Python">
131 +```python
132 +session = composio.create(
133 + user_id="user_123",
134 + auth_configs={"github": auth_config.id},
135 +)
136 +```
137 +</Tab>
138 +<Tab value="TypeScript">
139 +```typescript
140 +import { Composio } from '@composio/core';
141 +const composio = new Composio({ apiKey: 'your_api_key' });
142 +const authConfig = { id: 'ac_your_github_config' };
143 +// ---cut---
144 +const session = await composio.create('user_123', {
145 + authConfigs: { github: authConfig.id },
146 +});
147 +```
148 +</Tab>
149 +</Tabs>
150 +
151 +## Next
152 +
153 +<Card icon={<Palette />} title="White-labeling authentication" href="/docs/white-labeling-authentication" description="Remove Composio branding from your auth flows" />
docs/content/docs/custom-app-vs-managed-app.mdx
+7 -7
@@ -9,7 +9,7 @@ Composio supports two ways to authenticate users with toolkits.
9 - **[Composio managed apps](/toolkits/managed-auth)**: Composio registers and maintains OAuth apps for popular toolkits (GitHub, Gmail, Slack, etc.). Zero setup, works out of the box.
10 - **Custom auth configs**: You provide your own OAuth app, API key, bearer token, or other credentials and tell Composio to use them for a toolkit.
11
12 -Use this page as the canonical guide for deciding between managed auth and custom auth configs, then wiring the chosen auth config into a session.
12 +This page covers when to use each, how to create a custom auth config, and how to wire it into a session.
13
14 ## When to use Composio managed apps
15
@@ -34,6 +34,8 @@ Bring your own credentials when any of these apply:
34
35 To check whether a toolkit already has a Composio managed app, see the [managed auth toolkit list](/toolkits/managed-auth). You can still create a custom auth config for branding, scopes, rate limits, polling intervals, or custom instances.
36
37 +The steps below use the dashboard. To create auth configs in code instead, for example one per customer, see [Programmatic auth configs](/docs/programmatic-auth-configs).
38 +
39 <Steps>
40 <Step>
41 <StepTitle>Create the auth config in the Composio dashboard</StepTitle>
@@ -67,6 +69,8 @@ After you enter the required credentials, click **Create** and copy the auth con
69 <Step>
70 <StepTitle>Pass the auth config ID in your session</StepTitle>
71
72 +Creating the auth config isn't enough on its own. A session uses your config only when you pass its ID to `authConfigs`, keyed by toolkit. Toolkits you leave out keep using Composio managed auth.
73 +
74 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
75 <Tab value="Python">
76 ```python
@@ -136,10 +140,6 @@ const session = await composio.create("user_123", {
140
141 Some toolkits don't have Composio managed auth. For these, the setup is the same as above, except the provider may ask for API keys or instance details instead of OAuth credentials. Browse the full list on the [managed auth page](/toolkits/managed-auth) or check individual toolkit pages on the [toolkits page](/toolkits).
142
139 -## What to read next
143 +## Next
144
141 -<Cards>
142 - <Card icon={<Palette />} title="White-labeling authentication" href="/docs/white-labeling-authentication" description="Remove all Composio branding from your auth flows" />
143 - <Card icon={<Key />} title="Importing existing connections" href="/docs/importing-existing-connections" description="Bring existing OAuth tokens or API keys into Composio" />
144 - <Card icon={<Database />} title="Managing multiple accounts" href="/docs/managing-multiple-connected-accounts" description="Handle users with multiple accounts for the same toolkit" />
145 -</Cards>
145 +<Card icon={<Code />} title="Programmatic auth configs" href="/docs/programmatic-auth-configs" description="Create auth configs in code and pass them to a session" />
docs/content/docs/debugging-info.mdx deleted
-46
@@ -1,46 +0,0 @@
1 ----
2 -title: Debugging Info
3 -description: Share your debugging info with Composio team for faster issue resolution
4 -keywords: [debug, support, troubleshoot]
5 ----
6 -
7 -Your debugging info is tied to your [project](/docs/projects) and it helps us trace what happened and debug the issue faster. Before reaching out, check the [troubleshooting guide](/docs/troubleshooting) and [common FAQ](/docs/common-faq) for solutions to frequent issues.
8 -
9 -## Finding Your Debugging Info
10 -
11 -Navigate to your project settings to find your debugging information:
12 -
13 -<Figure src="/images/project-settings.jpeg" alt="Project Settings Debugging Info" />
14 -
15 -<Figure src="/images/debugging-info.png" alt="Debugging Info Location" />
16 -
17 -## What to Share
18 -
19 -When reaching out for support, share these identifiers:
20 -
21 -```
22 -@project_id: pr_xxxxxxxxxxxxx
23 -@org_id: ok_xxxxxxxxxxxxx
24 -@org_member_email: your-email@example.com
25 -```
26 -
27 -The identifiers with `pr_` (project) and `ok_` (organization) prefixes let us quickly check your logs inside our internal tracing tools, helping us resolve issues faster.
28 -
29 -## Getting Help
30 -
31 -import { MessageCircle, Bug, Mail, Grip } from 'lucide-react';
32 -
33 -<Cards>
34 - <Card title="Join Discord" href="https://discord.gg/composio" icon={<MessageCircle />}>
35 - Get basic support from the community and Composio team
36 - </Card>
37 - <Card title="Request Tools" href="https://request.composio.dev" icon={<Grip />}>
38 - Request new tools and toolkits
39 - </Card>
40 - <Card title="File an Issue" href="https://github.com/ComposioHQ/composio/issues" icon={<Bug />}>
41 - Report SDK issues and bugs
42 - </Card>
43 - <Card title="Contact Support" href="mailto:support@composio.dev" icon={<Mail />}>
44 - Reach out for dedicated support channels on Growth and Enterprise plans
45 - </Card>
46 -</Cards>
docs/content/docs/extending-sessions/custom-tools-and-toolkits.mdx renamed
+14 -19
@@ -1,22 +1,15 @@
1 ---
2 -title: "Custom Tools and Toolkits (Experimental)"
2 +title: Custom Tools and Toolkits
3 description: Define local tools that run in-process alongside remote Composio tools
4 keywords: [custom tools, custom toolkits, experimental, local tools, proxy execute]
5 +experimental: true
6 ---
7
7 -<Callout type="warn">
8 -Custom tool APIs are experimental and may change in future releases.
9 -</Callout>
10 -
11 -<Callout type="info">
12 -Custom tools work with **native tools** (`session.tools()`). MCP support is coming soon. Custom tools are not available via the MCP server URL yet.
13 -</Callout>
14 -
15 -Custom tools let you define tools that run in-process alongside remote Composio tools within a session. There are three patterns:
8 +Custom tools let you define tools that run in-process alongside remote Composio tools within a session. You have three patterns:
9
17 -- **Standalone tools** - for internal app logic that doesn't need Composio auth (DB lookups, in-memory data, business rules)
18 -- **Extension tools** - wrap a Composio toolkit's API with custom business logic via `extendsToolkit` / `extends_toolkit`, using `ctx.proxyExecute()` / `ctx.proxy_execute()` for authenticated requests
19 -- **Custom toolkits** - group related standalone tools under a namespace
10 +- **Standalone tools**: internal app logic that doesn't need Composio auth (DB lookups, in-memory data, business rules).
11 +- **Extension tools**: wrap a Composio toolkit's API with custom business logic via `extendsToolkit` / `extends_toolkit`, using `ctx.proxyExecute()` / `ctx.proxy_execute()` for authenticated requests.
12 +- **Custom toolkits**: group related standalone tools under a namespace.
13
14 <IntegrationTabs tabs={[
15 { value: "standalone", label: "Standalone Tool" },
@@ -218,7 +211,7 @@ composio = Composio(api_key="your_api_key")
211
212 An extension tool wraps a Composio toolkit's API with custom business logic. It inherits auth via `extendsToolkit` / `extends_toolkit`, so `ctx.proxyExecute()` / `ctx.proxy_execute()` handles credentials automatically.
213
221 -Prefer relative `endpoint` values in proxy calls. They resolve against the toolkit base URL. Absolute URLs are only accepted when they stay on the same scheme and registrable domain as that base URL.
214 +Prefer relative `endpoint` values in proxy calls. They resolve against the toolkit base URL. Composio only accepts absolute URLs when they stay on the same scheme and registrable domain as that base URL.
215
216 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
217 <Tab value="TypeScript">
@@ -583,7 +576,7 @@ Custom tools work automatically with Composio's meta tools:
576 | `COMPOSIO_MANAGE_CONNECTIONS` | Handles auth for extension tools. If a tool extends `gmail`, the agent can prompt the user to connect Gmail |
577
578 <Callout type="info">
586 -Custom tools are not supported in Workbench.
579 +Custom tools are not supported in the sandbox.
580 </Callout>
581
582 ## Context object (`ctx`)
@@ -595,7 +588,7 @@ Every custom tool's `execute` function receives `(input, ctx)`. Use `ctx` to acc
588
589 | Property / Method | Description |
590 |-------------------|-------------|
598 -| `ctx.userId` | The user ID for the current session |
591 +| `ctx.userId` | The userID for the current session |
592 | `ctx.proxyExecute({ toolkit, endpoint, method, body?, parameters? })` | Make an authenticated HTTP request via Composio's auth layer |
593 | `ctx.execute(toolSlug, args)` | Execute any Composio native tool from within your custom tool |
594
@@ -604,7 +597,7 @@ Every custom tool's `execute` function receives `(input, ctx)`. Use `ctx` to acc
597
598 | Property / Method | Description |
599 |-------------------|-------------|
607 -| `ctx.user_id` | The user ID for the current session |
600 +| `ctx.user_id` | The userID for the current session |
601 | `ctx.proxy_execute(toolkit, endpoint, method, body=None, parameters=[])` | Make an authenticated HTTP request via Composio's auth layer |
602 | `ctx.execute(tool_slug, arguments)` | Execute any Composio native tool from within your custom tool |
603
@@ -700,7 +693,7 @@ In TypeScript, use uppercase slugs like `SEND_PROMO_EMAIL`. In Python, slugs are
693
694 ### Accessing authenticated APIs
695
703 -If your tool needs to call an API that requires user credentials (Gmail, GitHub, etc.), set `extendsToolkit` / `extends_toolkit` to the toolkit name. Composio will handle authentication automatically, and the agent can prompt users to connect their account if needed.
696 +If your tool calls an API that requires user credentials (Gmail, GitHub, and so on), set `extendsToolkit` / `extends_toolkit` to the toolkit name. Composio handles authentication automatically, and the agent can prompt users to connect their account when needed.
697
698 ### Defining inputs in Python
699
@@ -715,4 +708,6 @@ Slugs exposed to the agent are automatically prefixed with `LOCAL_` and the tool
708
709 Your slugs cannot start with `LOCAL_`. This prefix is reserved.
710
718 -For more best practices, see [How to Build Tools for AI Agents: A Field Guide](https://composio.dev/blog/how-to-build-tools-for-ai-agents-a-field-guide).
711 +## Next
712 +
713 +<Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Filter toolkits and tools, set auth configs, and read tools with session.tools()" />
docs/content/docs/extending-sessions/meta.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "title": "Extending sessions capabilities",
3 + "defaultOpen": true,
4 + "pages": [
5 + "proxy-execute",
6 + "custom-tools-and-toolkits"
7 + ]
8 +}
docs/content/docs/extending-sessions/proxy-execute.mdx new
+110
@@ -0,0 +1,110 @@
1 +---
2 +title: Proxy execute
3 +description: Call any API endpoint on a toolkit from a session and let Composio inject the authenticated credentials for you
4 +keywords: [proxy, proxy execute, session proxy, custom api call, raw api, raw request, direct http, bearer token injection, oauth token]
5 +---
6 +
7 +`session.proxyExecute()` calls any HTTP endpoint on a toolkit your session can already reach, and Composio injects the authentication (OAuth token, API key, basic auth, and so on) on the server side. Your code never handles raw credentials.
8 +
9 +The session is already scoped to a [userID](/docs/how-composio-works), so you pass a `toolkit` slug rather than an account ID. Composio resolves the user's connected account for that toolkit and signs the request with it.
10 +
11 +Proxy execute is a building block, not just a fallback. Use it to build experiences on top of Composio that reach past predefined tools, like the [Pi + Slack bot example](/examples/general-agent-with-pi#reach-the-gaps-with-the-proxy), which drops down to the proxy for the Slack Web API calls the toolkit doesn't wrap as tools. We'll link more examples here as we add them.
12 +
13 +<Callout title="Use a scoped API key">
14 +Proxy execute is gated behind its own permission. Authenticate with a [scoped project API key](/reference/authenticating-to-composio/project-api-key-permissions) that has the **Proxy execute** permission granted. Default full-access keys already include it.
15 +</Callout>
16 +
17 +## When to use it
18 +
19 +- **Endpoints with no predefined tool.** You need a specific endpoint (an unusual GitHub, LinkedIn, or Notion route) that isn't exposed as a Composio tool. Send it through the proxy instead of extracting the raw token and calling the API yourself.
20 +- **Request shapes a tool can't express.** Custom query parameters, partial field masks, or advanced filters on Gmail, Drive, Sheets, and similar. The proxy gives you the full HTTP surface of the upstream API while Composio keeps managing auth.
21 +
22 +## Quick start
23 +
24 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
25 +<Tab value="Python">
26 +```python
27 +from composio import Composio
28 +
29 +composio = Composio(api_key="your_api_key")
30 +session = composio.create("user_123", toolkits=["github"])
31 +
32 +response = session.proxy_execute(
33 + toolkit="github",
34 + endpoint="/repos/composiohq/composio/issues/1",
35 + method="GET",
36 + parameters=[
37 + {"name": "Accept", "value": "application/vnd.github.v3+json", "in": "header"},
38 + ],
39 +)
40 +
41 +print(response.status)
42 +print(response.data)
43 +```
44 +</Tab>
45 +<Tab value="TypeScript">
46 +```typescript
47 +import { Composio } from '@composio/core';
48 +const composio = new Composio({ apiKey: 'your_api_key' });
49 +const session = await composio.create('user_123', { toolkits: ['github'] });
50 +// ---cut---
51 +const { status, data } = await session.proxyExecute({
52 + toolkit: 'github',
53 + endpoint: '/repos/composiohq/composio/issues/1',
54 + method: 'GET',
55 + parameters: [
56 + { name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' },
57 + ],
58 +});
59 +
60 +console.log(status);
61 +console.log(data);
62 +```
63 +</Tab>
64 +</Tabs>
65 +
66 +The `endpoint` is a path relative to the toolkit's base URL (`/repos/...` resolves against `api.github.com`). Pass an absolute URL only when you need a host that isn't the toolkit's standard API, such as a regional Salesforce or Zendesk domain.
67 +
68 +<Callout type="warn">
69 +Proxy execute rejects cross-domain requests. The `endpoint` must resolve to the same domain as the toolkit's connected account (a GitHub connection can only call `api.github.com` paths). This is an intentional security boundary, not a quota, so you can't work around it by reshaping the request.
70 +</Callout>
71 +
72 +## Parameters
73 +
74 +| Parameter | Required | Type | Description |
75 +|---|---|---|---|
76 +| `toolkit` | Yes | `string` | Toolkit slug (`github`, `gmail`, and so on). Composio uses the session user's connected account for this toolkit. |
77 +| `endpoint` | Yes | `string` | Path relative to the toolkit's base URL, or an absolute URL. |
78 +| `method` | Yes | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE"` | HTTP verb. |
79 +| `body` | No | `object` | JSON request body. Used with `POST`, `PUT`, and `PATCH`. |
80 +| `parameters` | No | `Array<{ name, value, in }>` | Extra headers or query parameters. `in` is `"header"` or `"query"`. |
81 +
82 +## Response shape
83 +
84 +The call returns the upstream response verbatim:
85 +
86 +| Field | Type | Description |
87 +|---|---|---|
88 +| `status` | `number` | HTTP status code from the upstream API. |
89 +| `data` | `unknown` | Parsed JSON body the API returned. |
90 +| `headers` | `Record<string, string>` | Response headers. |
91 +| `binaryData` | `object` | Present only when the upstream returns a file (`url`, `contentType`, `size`, `expiresAt`). |
92 +
93 +<Callout type="warn">
94 +Don't set the `Authorization` header yourself through `parameters`. Composio injects the correct one from the connected account's auth scheme, and setting it manually overrides that credential and usually produces a `401`.
95 +</Callout>
96 +
97 +## Error handling
98 +
99 +`status` and `data` reflect exactly what the toolkit API returned, so check `status` and branch on the common failures.
100 +
101 +| Status | Typical cause | How to resolve |
102 +|---|---|---|
103 +| `400 Bad Request` | Malformed endpoint path, invalid body, or unsupported `method`. | Check the upstream API docs for the expected shape. The proxy doesn't validate upstream schemas. |
104 +| `401 Unauthorized` | The connected account's token expired or was revoked. | Re-authenticate the user, or [import fresh credentials](/docs/importing-existing-connections). |
105 +| `403 Forbidden` | The user's OAuth scopes or API key don't cover this endpoint. | Update the [auth config scopes](/docs/auth-configuration/custom-auth-configs) and have the user re-consent. |
106 +| `429 Too Many Requests` | Upstream rate limit (GitHub, Google, and so on). | Honor the `Retry-After` header and back off. Composio doesn't retry automatically. |
107 +
108 +## Next
109 +
110 +<Card icon={<Blocks />} title="Custom tools and toolkits" href="/docs/extending-sessions/custom-tools-and-toolkits" description="Define in-process tools and toolkits that run alongside Composio tools" />
docs/content/docs/glossary.mdx deleted
-146
@@ -1,146 +0,0 @@
1 ----
2 -title: Glossary
3 -description: Definitions of key Composio terms and concepts.
4 -llmGuardrails: "none"
5 -keywords: [glossary, definitions, terminology]
6 ----
7 -
8 -<Glossary>
9 -
10 -<GlossaryTerm name="Auth Config">
11 -A blueprint defining how authentication works for a toolkit: auth method (OAuth2, API key, Bearer token, Basic Auth), scopes, and credentials. Created automatically by a [session](/docs/how-composio-works) when needed. You can [create a custom one](/docs/auth-configuration/custom-auth-configs) to use your own OAuth credentials or non-default scopes.
12 -</GlossaryTerm>
13 -
14 -<GlossaryTerm name="Auth Scheme">
15 -The authentication method used by an auth config, such as `OAUTH2`, `API_KEY`, `BEARER_TOKEN`, or `BASIC`.
16 -</GlossaryTerm>
17 -
18 -<GlossaryTerm name="Callback URL">
19 -The URL a user is redirected to after completing an OAuth flow through a Connect Link. Passed as `callbackUrl` when initiating authentication.
20 -</GlossaryTerm>
21 -
22 -<GlossaryTerm name="Composio API Key">
23 -A project-scoped secret used to authenticate SDK and API requests. All resources created with it are scoped to that project.
24 -</GlossaryTerm>
25 -
26 -<GlossaryTerm name="Composio Managed Auth">
27 -The default mode where Composio provides its own OAuth app credentials for each toolkit. No setup required.
28 -</GlossaryTerm>
29 -
30 -<GlossaryTerm name="Connect Link">
31 -A hosted page where a user authorizes access to a toolkit. Returned as a `redirect_url` from `session.authorize()` or `connectedAccounts.initiate()`. Composio manages the full OAuth flow. See [Authentication](/docs/authentication).
32 -</GlossaryTerm>
33 -
34 -<GlossaryTerm name="Connected Account">
35 -Created when a user authenticates with a toolkit. Stores credentials (OAuth tokens or API keys) linked to a user ID. Composio automatically refreshes OAuth tokens. A user can have [multiple connected accounts](/docs/managing-multiple-connected-accounts) for the same toolkit. IDs are prefixed `ca_`.
36 -</GlossaryTerm>
37 -
38 -<GlossaryTerm name="Connection Request">
39 -The object returned when you initiate authentication. Contains the Connect Link URL and a `waitForConnection()` method that resolves once the user completes the flow.
40 -</GlossaryTerm>
41 -
42 -<GlossaryTerm name="Custom Tool">
43 -A user-defined tool used alongside Composio's built-in tools. Use local experimental custom tools and custom toolkits via [Custom tools and toolkits](/docs/toolkits/custom-tools-and-toolkits).
44 -</GlossaryTerm>
45 -
46 -<GlossaryTerm name="In-Chat Authentication">
47 -A flow where the AI agent handles authentication by calling `COMPOSIO_MANAGE_CONNECTIONS` to generate a Connect Link and send it to the user in the conversation. See [In-chat authentication](/docs/authenticating-users/in-chat-authentication).
48 -</GlossaryTerm>
49 -
50 -<GlossaryTerm name="MCP (Model Context Protocol)">
51 -An open protocol for connecting AI models to external tools. Every session exposes `session.mcp.url` and `session.mcp.headers`, an MCP-compatible endpoint any MCP client can connect to.
52 -</GlossaryTerm>
53 -
54 -<GlossaryTerm name="Manual Authentication">
55 -Authenticating users from your own code using `session.authorize()` or `connectedAccounts.initiate()`, as opposed to letting the AI agent handle it via in-chat authentication. See [Manual authentication](/docs/authenticating-users/manually-authenticating).
56 -</GlossaryTerm>
57 -
58 -<GlossaryTerm name="Meta Tools">
59 -A set of tools included in every session, including `COMPOSIO_SEARCH_TOOLS`, `COMPOSIO_GET_TOOL_SCHEMAS`, `COMPOSIO_MANAGE_CONNECTIONS`, `COMPOSIO_MULTI_EXECUTE_TOOL`, `COMPOSIO_REMOTE_WORKBENCH`, and `COMPOSIO_REMOTE_BASH_TOOL`. They let the agent discover tools, manage auth, execute in parallel, and run code without loading hundreds of tool definitions upfront. See [Meta Tools Reference](/reference/meta-tools).
60 -</GlossaryTerm>
61 -
62 -<GlossaryTerm name="Modifiers">
63 -Middleware that transforms tool behavior: [schema modifiers](/docs/tools-direct/modify-tool-behavior/schema-modifiers) change a tool's schema before the agent sees it, [before-execution modifiers](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers) modify arguments before a tool runs, [after-execution modifiers](/docs/tools-direct/modify-tool-behavior/after-execution-modifiers) transform the result. In Python, [`@before_file_upload`](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) intercepts local paths for `file_uploadable` parameters before read/upload.
64 -</GlossaryTerm>
65 -
66 -<GlossaryTerm name="Native Tools">
67 -Tools accessed through provider packages via `session.tools()`, as opposed to connecting via MCP (`session.mcp.url`). Both methods give the agent the same capabilities, but native tools integrate directly with your AI framework.
68 -</GlossaryTerm>
69 -
70 -<GlossaryTerm name="Organization">
71 -The top-level Composio account entity. Contains team members and projects.
72 -</GlossaryTerm>
73 -
74 -<GlossaryTerm name="Organization API Key">
75 -A key (`x-org-api-key`) for organization-level operations like creating and managing projects. Distinct from the project-scoped Composio API Key.
76 -</GlossaryTerm>
77 -
78 -<GlossaryTerm name="Project">
79 -An isolated environment within an organization that scopes API keys, connected accounts, auth configs, and webhooks. Resources in one project are inaccessible from another. IDs are prefixed `proj_`. See [Projects](/docs/projects).
80 -</GlossaryTerm>
81 -
82 -<GlossaryTerm name="Proxy Execute">
83 -Making authenticated HTTP requests through a toolkit's connected account without a predefined tool. Useful for API endpoints Composio doesn't have a built-in tool for.
84 -</GlossaryTerm>
85 -
86 -<GlossaryTerm name="Provider">
87 -An adapter package that transforms Composio tools into the format expected by an AI framework (OpenAI, Anthropic, LangChain, Vercel AI SDK, etc.). See [Providers](/docs/providers).
88 -</GlossaryTerm>
89 -
90 -<GlossaryTerm name="Session">
91 -A runtime context from `composio.create(userId)`. Ties together a user ID, available toolkits, auth configs, connected accounts, MCP state, and workbench state. Store its session ID and reuse it with `composio.use()` for multi-turn conversations, or patch its config with `session.update()`. Exposes `tools()`, `mcp.url`, `authorize()`, and `toolkits()`. See [What is a session?](/docs/how-composio-works).
92 -</GlossaryTerm>
93 -
94 -<GlossaryTerm name="Session ID">
95 -Unique identifier for a session. Store it for multi-turn conversations and pass it to `composio.use()` to rehydrate the same session context across requests.
96 -</GlossaryTerm>
97 -
98 -<GlossaryTerm name="Tool">
99 -An individual action an agent can execute. Has an input schema and output schema. Named `{TOOLKIT}_{ACTION}` (e.g., `GITHUB_CREATE_ISSUE`).
100 -</GlossaryTerm>
101 -
102 -<GlossaryTerm name="Tool Slug">
103 -A tool's unique identifier, following the `{TOOLKIT}_{ACTION}` pattern, e.g. `GITHUB_CREATE_ISSUE`.
104 -</GlossaryTerm>
105 -
106 -<GlossaryTerm name="Toolkit">
107 -A collection of related tools for a single external service. Users connect to a toolkit via authentication, and all its tools execute with the user's credentials.
108 -</GlossaryTerm>
109 -
110 -<GlossaryTerm name="Toolkit Slug">
111 -The lowercase identifier for a toolkit, e.g. `github`, `gmail`, `slack`. Used when configuring sessions, fetching tools, or creating triggers.
112 -</GlossaryTerm>
113 -
114 -<GlossaryTerm name="Toolkit Versioning">
115 -Pinning a toolkit to a specific version so your integration uses a consistent set of tools even as Composio updates definitions. See [Toolkit versioning](/docs/tools-direct/toolkit-versioning).
116 -</GlossaryTerm>
117 -
118 -<GlossaryTerm name="Trigger">
119 -Sends structured payloads to your application when something happens in a connected app. Two delivery types: **webhook** (the provider pushes events in real time, e.g. Slack, GitHub, Asana) and **polling** (Composio polls the provider on a schedule, e.g. Gmail). See [Triggers](/docs/triggers).
120 -</GlossaryTerm>
121 -
122 -<GlossaryTerm name="Trigger Instance">
123 -A specific, active trigger scoped to a user's connected account.
124 -</GlossaryTerm>
125 -
126 -<GlossaryTerm name="Webhook Endpoint">
127 -The ingress URL Composio issues per OAuth app for webhook triggers, plus the signing secret used to verify each inbound request. Composio configures it for you in most cases. When a trigger type's `requires_webhook_endpoint_setup` flag is true, you configure it yourself once per OAuth app via the [Webhook Endpoints API](/reference/api-reference/webhook-endpoints). See [Configuring the webhook endpoint](/docs/setting-up-triggers/creating-triggers#configuring-the-webhook-endpoint).
128 -</GlossaryTerm>
129 -
130 -<GlossaryTerm name="Webhook Subscription">
131 -The URL Composio delivers signed events to in your application. One per project, configured via the dashboard or the [Webhook Subscriptions API](/reference/api-reference/webhook-subscriptions). See [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events).
132 -</GlossaryTerm>
133 -
134 -<GlossaryTerm name="User ID">
135 -An identifier from your application that Composio uses to scope connected accounts, tool executions, and authorizations. Connections are fully isolated between user IDs. See [What is a session?](/docs/how-composio-works).
136 -</GlossaryTerm>
137 -
138 -<GlossaryTerm name="White-Labeling">
139 -Customizing the auth experience so users see your brand during the OAuth flow. You provide your own OAuth credentials, redirect URIs, and branding. See [White-labeling authentication](/docs/white-labeling-authentication).
140 -</GlossaryTerm>
141 -
142 -<GlossaryTerm name="Workbench">
143 -A persistent Python sandbox via the `COMPOSIO_REMOTE_WORKBENCH` meta tool. State persists across calls within a session. Used for bulk operations, data transformations, and processing large tool responses. See [Workbench](/docs/workbench).
144 -</GlossaryTerm>
145 -
146 -</Glossary>
docs/content/docs/how-composio-works.mdx
+43 -56
@@ -1,19 +1,14 @@
1 ---
2 title: What is a session?
3 -description: What Composio sessions do and how they scope users, tools, auth, MCP, and workbench state
4 -keywords: [session, user id, concepts, meta tools, mcp, workbench]
3 +description: What Composio sessions do, and how they scope users, tools, toolkits, auth, MCP, and workbench state
4 +keywords: [session, userID, tools, toolkits, meta tools, mcp, workbench]
5 ---
6
7 -A **session** is the runtime context your agent uses to work for one of your users. It tells Composio whose connected accounts to use, which tools are available, how authentication should happen, and where state should persist while the agent works.
7 +A **session** is the runtime context for an agentic run: the scoped environment an AI agent works in while it acts for one of your users. You create it with `composio.create(userId)`, and it ties together the user, the toolkits available, authentication, and connected accounts. By default it gives the agent meta tools to discover, authenticate, and execute app tools at runtime, instead of loading hundreds of tool definitions into context.
8
9 ## The basics
10
11 -When you create a session, Composio gives your agent two ways to access tools:
12 -
13 -- **Native tools** from `session.tools()` for frameworks with tool-calling support.
14 -- **A remote MCP URL** from `session.mcp.url` for MCP-compatible clients.
15 -
16 -Both point at the same session context.
11 +Create a session for a user, then read its tools formatted for your framework. To connect over MCP instead, see [Using sessions via MCP](/docs/sessions-via-mcp).
12
13 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
14 <Tab value="Python">
@@ -21,7 +16,6 @@ Both point at the same session context.
16 session = composio.create(user_id="user_123")
17
18 tools = session.tools()
24 -mcp_url = session.mcp.url
19 ```
20 </Tab>
21 <Tab value="TypeScript">
@@ -32,71 +26,69 @@ const composio = new Composio({ apiKey: 'your_api_key' });
26 const session = await composio.create("user_123");
27
28 const tools = await session.tools();
35 -const mcpUrl = session.mcp.url;
29 ```
30 </Tab>
31 </Tabs>
32
40 -A session ties together:
33 +A session scopes four things:
34
42 -- **User ID**: which user's connected accounts and tool executions are in scope.
43 -- **Tool access**: all toolkits by default, or a filtered set of toolkits/tools/tags.
44 -- **Authentication**: managed auth, custom auth configs, and connected account selection.
35 +- **userID**: whose connected accounts and tool executions are in scope.
36 +- **Tool access**: all toolkits by default, or a filtered set of toolkits, tools, or tags.
37 +- **Authentication**: managed auth, custom auth configs, and connected-account selection.
38 - **Execution state**: logs, tool memory, MCP state, and workbench files for the task.
39
47 -## Users
40 +## Tools and toolkits
41
49 -A user is an identifier from your app. Connections are stored under that ID, so tools run with the right account and stay isolated from other users.
42 +A **toolkit** is a collection of related tools for a service. The `github` toolkit, for example, contains tools for creating issues, managing pull requests, and starring repositories.
43
51 -**User ID best practices:**
44 +A **tool** is an individual action your agent can execute. Each tool has an input schema (its parameters) and an output schema (what it returns), and follows a `{TOOLKIT}_{ACTION}` naming pattern, like `GITHUB_CREATE_ISSUE`.
45
53 -- **Recommended:** Database UUID or primary key (`user.id`)
54 -- **Acceptable:** Unique username (`user.username`)
55 -- **Avoid:** Email addresses (they can change)
56 -- **Never:** `default` in production (exposes other users' data)
46 +Every toolkit in the catalog is discoverable by default. Create a session without a `toolkits` parameter and the agent can find any of them at runtime. To restrict the set, pass `toolkits` when you create the session. See [Enable and disable toolkits](/docs/configuring-sessions). You can also bind local, in-process tools to a session with the experimental [custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits) API.
47
58 -A user can connect multiple accounts for the same toolkit, such as work and personal Gmail. Use the same user ID, then select the connected account when a session needs a specific account. See [Managing multiple connected accounts](/docs/managing-multiple-connected-accounts).
48 +## Users
49
60 -## What sessions do
50 +A user is an identifier from your app. Composio stores connections under that ID, so tools run with the right account and stay isolated from other users. Use a stable identifier like your database ID, never one that can change.
51
62 -### Discover and execute tools
52 +<Accordions>
53 +<Accordion title="userID best practices">
54 +- **Recommended:** database UUID or primary key (`user.id`)
55 +- **Acceptable:** unique username (`user.username`)
56 +- **Avoid:** email addresses (they can change)
57 +- **Never:** `default` in production (it exposes other users' data)
58 +</Accordion>
59 +</Accordions>
60
64 -Instead of loading hundreds of tool definitions into context, a session gives your agent meta tools that discover, authenticate, and execute tools at runtime:
61 +A user can connect multiple accounts for the same toolkit, like work and personal Gmail. Use the same userID, then select the connected account when a session needs a specific one. See [Managing multiple connected accounts](/docs/managing-multiple-connected-accounts).
62
66 -```mermaid
67 -graph LR
68 - A["Your agent"] --> B["Session"]
69 - B --> C["Meta tools"]
70 - C --> D["COMPOSIO_SEARCH_TOOLS"]
71 - C --> E["COMPOSIO_GET_TOOL_SCHEMAS"]
72 - C --> F["COMPOSIO_MANAGE_CONNECTIONS"]
73 - C --> G["COMPOSIO_MULTI_EXECUTE_TOOL"]
74 - C --> H["COMPOSIO_REMOTE_WORKBENCH"]
75 -```
63 +## Meta tools
64 +
65 +A session gives your agent meta tools, a small fixed set that discover, authenticate, and execute tools at runtime, so you never load hundreds of tool definitions into context:
66 +
67 +<SessionFlow />
68
77 -The agent searches for relevant tools, authenticates if needed, and executes them through the same session. Meta tool calls share context through the session, so the agent can search in one call and execute in the next without losing state.
69 +The agent searches for relevant tools, authenticates if needed, and executes them through the same session. Meta-tool calls share context, so the agent searches in one call and executes in the next without losing state. See the [Meta Tools reference](/toolkits/meta-tools) for each tool's input and output schema.
70
79 -### Handle authentication
71 +Know the exact tools upfront? The [direct tools preset](/docs/configuring-sessions#direct-tools-preset) returns them directly from `session.tools()` with no search step, while keeping session auth, connected accounts, and the workbench.
72
81 -When a tool needs a connection, the session can generate a Connect Link with `session.authorize()` or let the agent handle the flow through `COMPOSIO_MANAGE_CONNECTIONS`.
73 +## Authentication
74
83 -In chat, this means the agent can pause, ask the user to connect an app, then retry the tool once auth is complete. Composio manages the OAuth redirects, token exchange, and refresh. Once a user connects a toolkit, the connected account persists for that user and can be reused by future sessions without re-authentication.
75 +When a tool needs a connection, the session generates a Connect Link with `session.authorize()`, or the agent handles the flow through `COMPOSIO_MANAGE_CONNECTIONS`.
76
85 -<Card icon={<Key />} title="Authentication" href="/docs/authentication" description="Connect Links, in-chat auth, manual auth, and custom auth configs" />
77 +In chat, the agent can pause, ask the user to connect an app, then retry the tool once auth completes. Composio manages the OAuth redirects, token exchange, and refresh. Once a user connects a toolkit, the connected account persists and future sessions reuse it without re-authentication.
78
87 -### Preserve workbench state
79 +For OAuth toolkits, Composio uses [managed apps](/docs/custom-app-vs-managed-app) by default. Bring your own app when you need your own branding, scopes, or consent screen.
80
89 -Large responses and bulk operations can be handled in the remote workbench. Instead of stuffing long tool responses into the model context, the agent can use the workbench to read files, search outputs, write Python, transform data, and call Composio tools in bulk.
81 +## Sandbox
82
91 -The workbench is scoped to the session, so files, variables, helper functions, and intermediate results stay available while the agent works through a task.
83 +Handle large responses and bulk operations in the remote sandbox. Instead of stuffing long tool responses into the model context, the agent reads files, searches outputs, writes Python, transforms data, and calls Composio tools in bulk.
84
93 -<Card icon={<Monitor />} title="Workbench" href="/docs/workbench" description="Persistent Python sandbox for large responses, bulk operations, and data processing" />
85 +The sandbox is scoped to the session, so files, variables, helper functions, and intermediate results stay available while the agent works through a task.
86
87 ## How sessions behave
88
97 -Every `create()` call returns a new session ID. Use this when you want a fresh task context.
89 +Every `create()` call returns a new session ID. Use it for a fresh task context.
90
99 -Sessions persist on the server and do not expire. For multi-turn conversations, store the session ID and reuse it with `composio.use()` rather than calling `create()` again.
91 +Sessions persist on the server and don't expire. For multi-turn conversations, store the session ID and reuse it with `composio.use()` instead of calling `create()` again.
92
93 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
94 <Tab value="Python">
@@ -116,7 +108,7 @@ const tools = await session.tools();
108 </Tab>
109 </Tabs>
110
119 -You can also update a session without creating a new one:
111 +You can also update a session in place instead of creating a new one:
112
113 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
114 <Tab value="Python">
@@ -143,13 +135,8 @@ await session.update({
135 </Tab>
136 </Tabs>
137
146 -Create a new session for a different user or fundamentally different task setup. Reuse or update the session when the same conversation should keep its tool, auth, and workbench context.
138 +Create a new session for a different user or a fundamentally different task setup. Reuse or update a session when the same conversation should keep its tool, auth, and workbench context.
139
148 -## What to read next
140 +## Next
141
150 -<Cards>
151 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Enable toolkits, set auth configs, and select connected accounts" />
152 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="How meta tools discover, authenticate, and execute tools" />
153 - <Card icon={<Key />} title="Authentication" href="/docs/authentication" description="Connect Links, OAuth, API keys, and auth configs" />
154 - <Card icon={<Monitor />} title="Workbench" href="/docs/workbench" description="Write and run code in a persistent sandbox" />
155 -</Cards>
142 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Enable toolkits, set auth configs, and select connected accounts" />
docs/content/docs/importing-existing-connections.mdx
+8 -17
@@ -13,18 +13,13 @@ This is useful when:
13
14 ## How it works
15
16 -```mermaid
17 -graph LR
18 - A[Create auth config] --> B[Create connection with credentials]
19 - B --> C[Use in Tool Router / Execute tools]
20 - C --> D[Update credentials when needed]
21 -```
16 +<ImportConnectionFlow />
17
18 ## Prerequisites
19
25 -1. **An [auth config](/docs/auth-configuration/programmatic-auth-configs)** for the toolkit you're importing into
20 +1. **An [auth config](/docs/programmatic-auth-configs)** for the toolkit you're importing into
21 2. **The existing credentials** for each user (API keys, bearer tokens, username/password, etc.)
27 -3. **A user ID** for each user — any string that uniquely identifies them in your system
22 +3. **A userID** for each user. Any string that uniquely identifies them in your system.
23
24 ## API keys
25
@@ -75,11 +70,11 @@ console.log('Connected:', connection.id);
70
71 ## Bearer tokens
72
78 -If you manage your own OAuth flow and already have an access token for a service, you can import it into Composio as a bearer token. This lets you bring existing OAuth connections into Composio without re-authenticating your users. It works with **all toolkits that support OAuth2 or S2S auth** — Gmail, GitHub, Slack, Google Docs, and more. Any additional parameters the toolkit supports (e.g., `subdomain`, `base_url`) work the same way.
73 +If you manage your own OAuth flow and already have an access token for a service, you can import it into Composio as a bearer token. This lets you bring existing OAuth connections into Composio without re-authenticating your users. It works with **all toolkits that support OAuth2 or S2S auth** (Gmail, GitHub, Slack, Google Docs, and more). Any additional parameters the toolkit supports (e.g., `subdomain`, `base_url`) work the same way.
74
80 -Since you're providing your own token, Composio won't handle OAuth refresh — you're responsible for refreshing the token on your end and pushing the updated value to Composio via the [PATCH method](#updating-credentials) whenever it changes.
75 +Since you're providing your own token, Composio won't handle OAuth refresh. You're responsible for refreshing the token on your end and pushing the updated value to Composio via the [PATCH method](#updating-credentials) whenever it changes.
76
82 -After [creating an auth config](/docs/auth-configuration/programmatic-auth-configs) with `authScheme: "BEARER_TOKEN"`, use the snippet below to create a connected account:
77 +After [creating an auth config](/docs/programmatic-auth-configs) with `authScheme: "BEARER_TOKEN"`, use the snippet below to create a connected account:
78
79 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
80 <Tab value="Python">
@@ -329,10 +324,6 @@ const session = await composio.create('user_123', {
324 </Tab>
325 </Tabs>
326
332 -## What to read next
327 +## Next
328
334 -<Cards>
335 - <Card icon={<Database />} title="Managing multiple accounts" href="/docs/managing-multiple-connected-accounts" description="Pin and select connected accounts for a user" />
336 - <Card icon={<Palette />} title="White-labeling" href="/docs/white-labeling-authentication" description="Use your own branding on OAuth consent screens" />
337 - <Card icon={<Key />} title="Connection expiry events" href="/docs/subscribing-to-connection-expiry-events" description="Detect expired OAuth connections and prompt re-authentication" />
338 -</Cards>
329 +<Card icon={<Database />} title="Managing multiple accounts" href="/docs/managing-multiple-connected-accounts" description="Pin and select connected accounts for a user" />
docs/content/docs/index.mdx
+1 -1
@@ -1,6 +1,6 @@
1 ---
2 title: Welcome
3 -description: Composio is the home for AI agents — 1000+ toolkits, per-user sessions, authentication, triggers, and a workbench to help you build agents that turn intent into action.
3 +description: Give your AI agent 1000+ pre-authenticated toolkits, per-user sessions, authentication, triggers, and a sandbox, so you can ship agents that turn intent into action.
4 keywords: [getting started, introduction]
5 ---
6
docs/content/docs/managing-multiple-connected-accounts.mdx
+5 -41
@@ -103,29 +103,14 @@ Aliases are human-readable labels for connected accounts (e.g., `"work-gmail"`,
103
104 ### Setting an alias during connection
105
106 -Pass `alias` to `session.authorize()`, `connectedAccounts.initiate()`, or `connectedAccounts.link()`:
106 +Pass `alias` to `session.authorize()`:
107
108 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
109 <Tab value="Python">
110 ```python
111 session = composio.create(user_id="user_123")
112
113 -# Via session.authorize()
113 connection_request = session.authorize("gmail", alias="work-gmail")
115 -
116 -# Via connectedAccounts.initiate()
117 -connection_request = composio.connected_accounts.initiate(
118 - "user_123",
119 - "ac_auth_config_id",
120 - alias="work-gmail",
121 -)
122 -
123 -# Via connectedAccounts.link()
124 -connection_request = composio.connected_accounts.link(
125 - "user_123",
126 - "ac_auth_config_id",
127 - alias="work-gmail",
128 -)
114 ```
115 </Tab>
116 <Tab value="TypeScript">
@@ -135,26 +120,13 @@ import { Composio } from '@composio/core';
120 const composio = new Composio({ apiKey: 'your_api_key' });
121 const session = await composio.create("user_123");
122 // ---cut---
138 -// Via session.authorize()
123 const connectionRequest = await session.authorize("gmail", { alias: "work-gmail" });
140 -
141 -// Via connectedAccounts.initiate()
142 -const connectionRequest2 = await composio.connectedAccounts.initiate(
143 - "user_123",
144 - "ac_auth_config_id",
145 - { alias: "work-gmail" },
146 -);
147 -
148 -// Via connectedAccounts.link()
149 -const connectionRequest3 = await composio.connectedAccounts.link(
150 - "user_123",
151 - "ac_auth_config_id",
152 - { alias: "work-gmail" },
153 -);
124 ```
125 </Tab>
126 </Tabs>
127
128 +The direct-execution methods `connectedAccounts.initiate()` and `connectedAccounts.link()` accept the same `alias` parameter.
129 +
130 ### Updating or clearing an alias
131
132 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
@@ -214,10 +186,6 @@ const session = await composio.create("user_123", {
186 </Tab>
187 </Tabs>
188
217 -<Callout type="info">
218 -Arrays are the preferred format for `connected_accounts` / `connectedAccounts`. A single connected account ID string is still accepted for backwards compatibility and is treated as a one-item array.
219 -</Callout>
220 -
189 ## Viewing session's active accounts
190
191 Use `session.toolkits()` to see which accounts are currently active:
@@ -250,10 +218,6 @@ for (const toolkit of toolkits.items) {
218 </Tab>
219 </Tabs>
220
253 -## What to read next
221 +## Next
222
255 -<Cards>
256 - <Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Pass connectedAccounts, auth configs, and toolkit restrictions to sessions" />
257 - <Card icon={<ShieldCheck />} title="Manual authentication" href="/docs/authenticating-users/manually-authenticating" description="Pre-authenticate users with session.authorize() and Connect Links" />
258 - <Card icon={<Key />} title="Authentication overview" href="/docs/authentication" description="Connect Links, OAuth, API keys, and how Composio manages auth" />
259 -</Cards>
223 +<Card icon={<Database />} title="Shared connections" href="/docs/shared-connections" description="Make one connected account usable by multiple users with a per-user access control list" />
docs/content/docs/manually-authenticating.mdx renamed
+13 -19
@@ -1,16 +1,16 @@
1 ---
2 -title: Manually authenticating users
3 -description: Authenticate users to toolkits outside of chat
2 +title: Manual auth management
3 +description: Authenticate and manage user connections to toolkits outside of chat
4 keywords: [pre-auth, onboarding, custom ui, authorize]
5 ---
6
7 -Manual authentication lets you connect users to toolkits outside of the chat flow. Use this when you want to:
8 -- Pre-authenticate users before they start chatting
9 -- Build a custom connections UI in your app
7 +Manual authentication lets you connect users to toolkits outside the chat flow. Reach for it when you want to:
8 +- Pre-authenticate users before they start chatting.
9 +- Build a custom connections UI in your app.
10
11 ## Authorize a toolkit
12
13 -Use `session.authorize()` to generate a [Connect Link](/docs/tools-direct/authenticating-tools#hosted-authentication-connect-link) URL, redirect the user, and wait for them to complete:
13 +Call `session.authorize()` to generate a [Connect Link](/docs/tools-direct/authenticating-tools#hosted-authentication-connect-link) URL, redirect the user, and wait for them to finish:
14
15 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
16 <Tab value="Python">
@@ -44,7 +44,7 @@ console.log(`Connected: ${connectedAccount.id}`);
44 </Tab>
45 </Tabs>
46
47 -Redirect the user to the redirect URL. After they authenticate, they'll return to your callback URL. The connection request polls until the user completes authentication (default timeout: 60 seconds).
47 +Redirect the user to the `redirectUrl`. After they authenticate, they'll return to your callback URL. The connection request polls until the user completes authentication (default timeout: 60 seconds).
48
49 <Callout type="info">
50 If the user closes the Connect Link without completing auth, the connection remains in `INITIATED` status until it expires.
@@ -52,7 +52,7 @@ If the user closes the Connect Link without completing auth, the connection rema
52
53 ## Redirecting users after authentication
54
55 -Pass a `callbackUrl` to control where users land after authenticating. You can include query parameters to carry context through the flow, for example to identify which user or session triggered the connection.
55 +Pass a `callbackUrl` to control where users land after authenticating. You can include query parameters to carry context through the flow, for example to identify which `userID` or session triggered the connection.
56
57 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
58 <Tab value="Python">
@@ -122,7 +122,7 @@ toolkits.items.forEach((toolkit) => {
122
123 ## Disabling in-chat auth
124
125 -By default, sessions include the `COMPOSIO_MANAGE_CONNECTIONS` meta-tool that prompts users to authenticate during chat. To disable this and handle auth entirely in your UI:
125 +By default, sessions include the `COMPOSIO_MANAGE_CONNECTIONS` meta-tool that prompts users to authenticate during chat. To turn it off and handle auth entirely in your own UI, set `manage_connections` to `False`:
126
127 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
128 <Tab value="Python">
@@ -147,7 +147,6 @@ const session = await composio.create("user_123", {
147
148 ## Putting it together
149
150 -
150 A common pattern is to verify all required connections before starting the agent:
151
152 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
@@ -177,7 +176,7 @@ for slug in pending:
176 print(f"Connect {slug}: {connection_request.redirect_url}")
177 connection_request.wait_for_connection()
178
180 -print(f"All toolkits connected! MCP URL: {session.mcp.url}")
179 +print("All toolkits connected!")
180 ```
181 </Tab>
182 <Tab value="TypeScript">
@@ -209,16 +208,11 @@ for (const slug of pending) {
208 await connectionRequest.waitForConnection();
209 }
210
212 -console.log(`All toolkits connected! MCP URL: ${session.mcp.url}`);
211 +console.log("All toolkits connected!");
212 ```
213 </Tab>
214 </Tabs>
215
217 -## What to read next
216 +## Next
217
219 -<Cards>
220 - <Card icon={<Database />} title="Shared connections" href="/docs/authenticating-users/shared-connections" description="Share connected accounts across users while preserving access controls" />
221 - <Card icon={<Palette />} title="White-labeling authentication" href="/docs/white-labeling-authentication" description="Use your own OAuth apps so users see your branding on consent screens" />
222 - <Card icon={<Database />} title="Managing multiple accounts" href="/docs/managing-multiple-connected-accounts" description="Handle users with multiple accounts for the same toolkit (e.g., work and personal Gmail)" />
223 - <Card icon={<LayoutDashboard />} title="Build an App Connections Dashboard" href="/cookbooks/app-connections-dashboard" description="Full working example of a connections page with OAuth and disconnect" />
224 -</Cards>
218 +<Card icon={<Database />} title="Managing multiple connected accounts" href="/docs/managing-multiple-connected-accounts" description="Let a user connect work and personal accounts for the same toolkit, then pick which one runs" />
docs/content/docs/meta.json
+16 -20
@@ -7,36 +7,32 @@
7 "---Customizing sessions---",
8 "how-composio-works",
9 "configuring-sessions",
10 - "tools-and-toolkits",
11 - "toolkits",
12 - "workbench",
10 + "sessions-via-mcp",
11 + "sandbox",
12 + "extending-sessions",
13 "---Authenticate users---",
14 "authentication",
15 - "authenticating-users",
15 + "manually-authenticating",
16 + "managing-multiple-connected-accounts",
17 + "shared-connections",
18 + "importing-existing-connections",
19 + "---Customizing auth---",
20 "custom-app-vs-managed-app",
21 + "programmatic-auth-configs",
22 + "controlling-scopes",
23 "white-labeling-authentication",
18 - "importing-existing-connections",
19 - "managing-multiple-connected-accounts",
20 - "subscribing-to-connection-expiry-events",
21 - "---Triggers and webhooks---",
24 + "---Triggers---",
25 "triggers",
23 - "setting-up-triggers",
24 - "webhook-verification",
26 + "setting-up-triggers/creating-triggers",
27 + "setting-up-triggers/subscribing-to-events",
28 + "setting-up-triggers/managing-triggers",
29 + "setting-up-triggers/custom-oauth-webhooks",
30 "---Direct Tool Execution Guides (Legacy)---",
31 "sessions-vs-direct-execution",
32 "tools-direct",
33 "auth-configuration",
34 "---Other topics---",
35 "cli",
31 - "native-tools-vs-mcp",
32 - "proxy-execute",
33 - "projects",
34 - "observability",
35 - "signing-up-as-an-agent",
36 - "common-faq",
37 - "glossary",
38 - "debugging-info",
39 - "migration-guide",
40 - "troubleshooting"
36 + "migration-guide"
37 ]
38 }
docs/content/docs/migration-guide/direct-to-sessions.mdx
+2 -5
@@ -277,9 +277,6 @@ If you've set up white-labeled OAuth screens with custom auth configs, those car
277
278 See [White-labeling authentication](/docs/white-labeling-authentication) for more.
279
280 -## Get started
280 +## Next
281
282 -<Cards>
283 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, account selection, and session methods" />
284 - <Card icon={<Database />} title="What is a session?" href="/docs/how-composio-works" description="Understand how sessions scope tools and connected accounts" />
285 -</Cards>
282 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, account selection, and session methods" />
docs/content/docs/migration-guide/mcp-servers-to-sessions.mdx
+6 -6
@@ -79,12 +79,14 @@ session = composio.create(
79 toolkits=["gmail"],
80 auth_configs={"gmail": "ac_xyz123"},
81 tools={"gmail": {"enable": ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]}},
82 + mcp=True,
83 )
84 mcp_url = session.mcp.url
85 ```
86 </Tab>
87 <Tab value="TypeScript">
88 ```typescript
89 +// @noErrors
90 import { Composio } from '@composio/core';
91
92 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
@@ -102,6 +104,7 @@ const session = await composio.create("user-123", {
104 toolkits: ["gmail"],
105 authConfigs: { gmail: "ac_xyz123" },
106 tools: { gmail: { enable: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"] } },
107 + mcp: true,
108 });
109 const { mcp } = session;
110 const mcpUrl = mcp.url;
@@ -234,7 +237,7 @@ const result = await session.execute("GITHUB_CREATE_ISSUE", {
237 session once and keep using it across calls; see [Configuring Sessions](/docs/configuring-sessions).
238 - **Sharing one account across users** — sessions support **shared connections**
239 (`account_type:"SHARED"` + an allow/deny ACL), pinned per session. See
237 - [Shared connections](/docs/authenticating-users/shared-connections).
240 + [Shared connections](/docs/shared-connections).
241 - **Tenant-specific params** (SharePoint sub-site, Jira subdomain) — prefill them via shared
242 credentials on the auth config.
243 - **White-labeling carries over** — pass the same white-labeled auth config IDs; users keep seeing
@@ -244,9 +247,6 @@ const result = await session.execute("GITHUB_CREATE_ISSUE", {
247 - **Dashboard** — sessions are created via the SDK. For no-code, personal app connections, use
248 **Composio For You** — reachable from the product switcher in the top-left of the dashboard.
249
247 -## Get started
250 +## Next
251
249 -<Cards>
250 - <Card title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, account selection, presets, and session methods" />
251 - <Card title="What is a session?" href="/docs/how-composio-works" description="How sessions scope tools and connected accounts" />
252 -</Cards>
252 +<Card title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, account selection, presets, and session methods" />
docs/content/docs/migration-guide/new-sdk.mdx
+6 -6
@@ -41,7 +41,7 @@ We have updated several key terms in the SDK and API to improve clarity and cons
41 | Apps | Toolkits | A collection of tools grouped under a single application |
42 | Integration | Auth Config | Configuration containing developer credentials and application-level settings such as scopes and API endpoints. Scoped to a toolkit. |
43 | Connection | Connected accounts | User-linked accounts associated with a toolkit |
44 -| Entity ID | User ID | The identifier of the user performing the action (UUID or email) |
44 +| Entity ID | userID | The identifier of the user performing the action (UUID or email) |
45 | Trigger | Trigger | An event that can be subscribed to |
46 | Toolsets | Providers | LLM or agent framework that can be used with Composio to create agents |
47
@@ -82,11 +82,11 @@ npm install @composio/core
82
83 Both SDKs now implement proper namespacing for each concept.
84
85 -### User ID scoping
85 +### UserID scoping
86
87 The concept of `entity_id` has been expanded and renamed to `user_id`.
88
89 -All operations are now scoped to a user ID, including:
89 +All operations are now scoped to a userID, including:
90 - Fetching tools
91 - Initiating connections
92 - Executing tools
@@ -621,7 +621,7 @@ const session = await composio.create("default", {
621 </Tab>
622 </Tabs>
623
624 -For more information, see [Custom Tools and Toolkits](/docs/toolkits/custom-tools-and-toolkits).
624 +For more information, see [Custom Tools and Toolkits](/docs/extending-sessions/custom-tools-and-toolkits).
625
626 ### Auth configs (formerly integrations)
627
@@ -736,7 +736,7 @@ console.log(authConfig);
736 </Tab>
737 </Tabs>
738
739 -For using custom authentication credentials, refer to the [Programmatic Auth Configs](/docs/auth-configuration/programmatic-auth-configs) documentation.
739 +For using custom authentication credentials, refer to the [Programmatic Auth Configs](/docs/programmatic-auth-configs) documentation.
740
741 <Callout type="info">
742 The callback URL for creating custom OAuth configs is now `https://backend.composio.dev/api/v3/toolkits/auth/callback`. The previous URL was `https://backend.composio.dev/api/v1/auth-apps/add`.
@@ -1002,7 +1002,7 @@ await composio.triggers.enable("ti_abcd123");
1002
1003 We recommend listening to triggers through webhooks. The following are example routes for Next.js and FastAPI.
1004
1005 -For development, you can also [listen to triggers through the SDK](/docs/setting-up-triggers/subscribing-to-events#sdk-subscriptions).
1005 +For development, you can also [listen to triggers through the SDK](/docs/setting-up-triggers/subscribing-to-events#receive-events-locally).
1006
1007 <Tabs items={['FastAPI', 'Next.js']}>
1008 <Tab value="FastAPI">
docs/content/docs/migration-guide/tool-router-beta.mdx
+2 -5
@@ -101,9 +101,6 @@ const session = await composio.create('user_123',
101 </Step>
102 </Steps>
103
104 -## Get started
104 +## Next
105
106 -<Cards>
107 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Restrict toolkits, set auth configs, and select connected accounts" />
108 - <Card icon={<Database />} title="What is a session?" href="/docs/how-composio-works" description="Understand the stable sessions model" />
109 -</Cards>
106 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Restrict toolkits, set auth configs, and select connected accounts" />
docs/content/docs/migration-guide/toolkit-versioning.mdx
+2 -6
@@ -156,10 +156,6 @@ const result = await composio.tools.execute({
156 The `dangerouslySkipVersionCheck` flag is only for migration or debugging. Never use in production.
157 </Callout>
158
159 -## What to read next
159 +## Next
160
161 -<Cards>
162 - <Card icon={<Rocket />} title="Migrate to sessions" href="/docs/migration-guide/direct-to-sessions" description="Move from older tool execution patterns to sessions" />
163 - <Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Control toolkits, auth configs, connected accounts, and tool availability" />
164 - <Card icon={<Blocks />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="Understand tool discovery and toolkit access in sessions" />
165 -</Cards>
161 +<Card icon={<Rocket />} title="Migrate to sessions" href="/docs/migration-guide/direct-to-sessions" description="Move from older tool execution patterns to sessions" />
docs/content/docs/native-tools-vs-mcp.mdx deleted
-141
@@ -1,141 +0,0 @@
1 ----
2 -title: Native Tools vs MCP
3 -description: When to use Composio's native SDK vs MCP servers
4 -keywords: [mcp, native tools, function calling, model context protocol, architecture, decision]
5 ----
6 -
7 -**Native tools** give your LLM tool schemas as function definitions. Composio formats them for your specific framework (OpenAI, Anthropic, Vercel AI, etc.) through [provider packages](/docs/providers).
8 -
9 -**MCP** exposes tools through the [Model Context Protocol](https://modelcontextprotocol.io). Any MCP-compatible client can connect to a Composio MCP server URL. No provider packages needed.
10 -
11 -| | Native tools | MCP |
12 -|---|---|---|
13 -| **Setup** | [Provider package](/docs/providers) for your framework | SDK or just a URL |
14 -| **Intercepting tool calls** | Yes, you can log, retry, or require approval before each call | Limited, depends on what the MCP client supports |
15 -| **Context window** | You control what's loaded | Client loads all tools the server exposes |
16 -| **Latency** | SDK calls Composio API directly | MCP protocol adds overhead for tool list discovery and each execution |
17 -
18 -With native tools, you choose exactly which schemas enter your LLM's context. With MCP, the client pulls the full tool list from the server. A [5-server setup can consume ~55K tokens](https://www.anthropic.com/engineering/advanced-tool-use) before the conversation starts. If you're working with many tools, native tools give you more control over that cost.
19 -
20 -## Native tools
21 -
22 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
23 -<Tab value="Python">
24 -```python
25 -from composio import Composio
26 -from composio_openai import OpenAIProvider
27 -
28 -composio = Composio(provider=OpenAIProvider())
29 -session = composio.create(user_id="user_123")
30 -tools = session.tools()
31 -# Returns meta tools (COMPOSIO_SEARCH_TOOLS, COMPOSIO_MANAGE_CONNECTIONS, etc.)
32 -# Agent discovers and executes tools at runtime
33 -```
34 -</Tab>
35 -<Tab value="TypeScript">
36 -```typescript
37 -import { Composio } from '@composio/core';
38 -import { OpenAIProvider } from '@composio/openai';
39 -
40 -const composio = new Composio({
41 - apiKey: process.env.COMPOSIO_API_KEY,
42 - provider: new OpenAIProvider(),
43 -});
44 -const session = await composio.create("user_123");
45 -const tools = await session.tools();
46 -// Returns meta tools (COMPOSIO_SEARCH_TOOLS, COMPOSIO_MANAGE_CONNECTIONS, etc.)
47 -```
48 -</Tab>
49 -</Tabs>
50 -
51 -## MCP
52 -
53 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
54 -<Tab value="Python">
55 -```python
56 -from composio import Composio
57 -
58 -composio = Composio()
59 -session = composio.create(user_id="user_123")
60 -
61 -mcp_url = session.mcp.url
62 -mcp_headers = session.mcp.headers
63 -```
64 -</Tab>
65 -<Tab value="TypeScript">
66 -```typescript
67 -import { Composio } from '@composio/core';
68 -
69 -const composio = new Composio();
70 -const session = await composio.create("user_123");
71 -
72 -const mcpUrl = session.mcp.url;
73 -const mcpHeaders = session.mcp.headers;
74 -```
75 -</Tab>
76 -</Tabs>
77 -
78 -Then pass `session.mcp.url` and `session.mcp.headers` to your framework:
79 -
80 -<Tabs items={['OpenAI Agents (Python)', 'Claude Agent SDK (Python)', 'Vercel AI SDK (TypeScript)']}>
81 -<Tab value="OpenAI Agents (Python)">
82 -```python
83 -from agents import Agent, HostedMCPTool
84 -
85 -agent = Agent(
86 - name="Assistant",
87 - tools=[
88 - HostedMCPTool(
89 - tool_config={
90 - "type": "mcp",
91 - "server_label": "composio",
92 - "server_url": session.mcp.url,
93 - "headers": session.mcp.headers,
94 - "require_approval": "never",
95 - }
96 - )
97 - ],
98 -)
99 -```
100 -</Tab>
101 -<Tab value="Claude Agent SDK (Python)">
102 -```python
103 -from claude_agent_sdk import ClaudeAgentOptions
104 -
105 -options = ClaudeAgentOptions(
106 - mcp_servers={
107 - "composio": {
108 - "type": "http",
109 - "url": session.mcp.url,
110 - "headers": session.mcp.headers,
111 - }
112 - },
113 -)
114 -```
115 -</Tab>
116 -<Tab value="Vercel AI SDK (TypeScript)">
117 -```typescript
118 -import { Composio } from "@composio/core";
119 -import { createMCPClient } from "@ai-sdk/mcp";
120 -
121 -const composio = new Composio();
122 -const { mcp } = await composio.create("user_123");
123 -
124 -const client = await createMCPClient({
125 - transport: {
126 - type: "http",
127 - url: mcp.url,
128 - headers: mcp.headers,
129 - },
130 -});
131 -const tools = await client.tools();
132 -```
133 -</Tab>
134 -</Tabs>
135 -
136 -## Next steps
137 -
138 -<Cards>
139 - <Card icon={<Key />} title="Providers" href="/docs/providers" description="OpenAI, Anthropic, Vercel AI, LangChain" />
140 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Configure native tools or MCP endpoints for a session" />
141 -</Cards>
docs/content/docs/observability/index.mdx deleted
-34
@@ -1,34 +0,0 @@
1 ----
2 -title: Observability
3 -description: Inspect tool execution activity and usage for your org or project.
4 -keywords: ['observability', 'logs', 'usage', 'metering', 'metrics']
5 ----
6 -
7 -Composio exposes two v3.1 REST APIs for inspecting activity in your org or project: a **Logs API** for individual tool execution events and a **Usage API** for aggregated counts. Use this page to figure out which one to call.
8 -
9 -## Which API should I use?
10 -
11 -| I want to... | Use |
12 -|---|---|
13 -| Debug a specific tool execution (payloads, errors, timing) | [Tool execution logs](/docs/observability/logs) |
14 -| See how many tool calls or sessions happened in a window | [Usage summary](/docs/observability/usage#summary) |
15 -| Break usage down by tool, toolkit, user, or session | [Usage breakdown](/docs/observability/usage#breakdown) |
16 -
17 -Logs record **individual events** and are primarily for debugging. Usage queries return **aggregated counts** and are primarily for dashboards, billing integrations, and customer-facing analytics.
18 -
19 -## Authentication at a glance
20 -
21 -Each endpoint family takes a specific credential. Use the right one for the scope you need.
22 -
23 -| Endpoints | Header | Scope |
24 -|---|---|---|
25 -| `POST /api/v3.1/org/usage/summary`<br/>`POST /api/v3.1/org/usage/{entity_type}` | `x-org-api-key` *(or org JWT)* | All projects in your org |
26 -| `POST /api/v3.1/project/usage/summary`<br/>`POST /api/v3.1/project/usage/{entity_type}` | `x-api-key` *(or session cookie)* | Single project |
27 -| `POST /api/v3.1/logs/tool_execution`<br/>`GET /api/v3.1/logs/tool_execution/{id}` | `x-api-key` *(or session cookie)* | Single project |
28 -
29 -The org-level usage endpoints accept a `project_id` filter so you can slice by project without rotating keys.
30 -
31 -## Reference
32 -
33 -- [Organization API reference](/reference/api-reference/organization) — org-level usage endpoints
34 -- [Projects API reference](/reference/api-reference/projects) — project-level usage endpoints and project-scoped APIs
docs/content/docs/observability/meta.json deleted
-4
@@ -1,4 +0,0 @@
1 -{
2 - "title": "Observability",
3 - "pages": ["...", "logs", "usage"]
4 -}
docs/content/docs/programmatic-auth-configs.mdx new
+195
@@ -0,0 +1,195 @@
1 +---
2 +title: Programmatic auth configs
3 +description: Create auth configs in code and pass them to a session
4 +keywords: [create auth config, auth config sdk, programmatic auth, provision auth config, auth config id]
5 +---
6 +
7 +An [auth config](/docs/authentication#behind-the-scenes) is a blueprint for how a toolkit authenticates: the method, scopes, and credentials. Most of the time you create one in the [dashboard](https://dashboard.composio.dev/~/project/auth-configs) and reuse it. Create them in code when you provision auth dynamically: a config per customer, per environment, or spun up and torn down as part of your app's lifecycle.
8 +
9 +`composio.authConfigs.create()` returns an auth config ID like `ac_xxxxxxxx`. Store that ID, then [pass it to a session](#use-the-auth-config-in-a-session) so the session authenticates with it.
10 +
11 +## Composio managed auth
12 +
13 +For OAuth2 toolkits, Composio maintains a managed app so you can create an auth config without bringing your own credentials. This is the fastest way to start.
14 +
15 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
16 +<Tab value="Python">
17 +```python
18 +from composio import Composio
19 +
20 +composio = Composio()
21 +
22 +auth_config = composio.auth_configs.create(
23 + toolkit="github",
24 + options={"type": "use_composio_managed_auth", "name": "GitHub"},
25 +)
26 +
27 +print(auth_config.id) # ac_xxxxxxxx
28 +```
29 +</Tab>
30 +<Tab value="TypeScript">
31 +```typescript
32 +import { Composio } from '@composio/core';
33 +
34 +const composio = new Composio();
35 +// ---cut---
36 +const authConfig = await composio.authConfigs.create('github', {
37 + type: 'use_composio_managed_auth',
38 + name: 'GitHub',
39 +});
40 +
41 +console.log(authConfig.id); // ac_xxxxxxxx
42 +```
43 +</Tab>
44 +</Tabs>
45 +
46 +## Your own OAuth2 credentials
47 +
48 +Bring your own OAuth app to show your branding on consent screens, request custom scopes, or get a dedicated rate-limit quota. Register the app in the provider's developer portal, set its authorized redirect URI to Composio's callback, then pass the client ID and secret.
49 +
50 +```
51 +https://backend.composio.dev/api/v3.1/toolkits/auth/callback
52 +```
53 +
54 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
55 +<Tab value="Python">
56 +```python
57 +import os
58 +from composio import Composio
59 +
60 +composio = Composio()
61 +
62 +auth_config = composio.auth_configs.create(
63 + toolkit="notion",
64 + options={
65 + "type": "use_custom_auth",
66 + "auth_scheme": "OAUTH2",
67 + "name": "Notion",
68 + "credentials": {
69 + "client_id": os.environ["NOTION_CLIENT_ID"],
70 + "client_secret": os.environ["NOTION_CLIENT_SECRET"],
71 + "oauth_redirect_uri": "https://backend.composio.dev/api/v3.1/toolkits/auth/callback",
72 + },
73 + },
74 +)
75 +```
76 +</Tab>
77 +<Tab value="TypeScript">
78 +```typescript
79 +import { Composio } from '@composio/core';
80 +
81 +const composio = new Composio();
82 +// ---cut---
83 +const authConfig = await composio.authConfigs.create('notion', {
84 + type: 'use_custom_auth',
85 + authScheme: 'OAUTH2',
86 + name: 'Notion',
87 + credentials: {
88 + client_id: process.env.NOTION_CLIENT_ID!,
89 + client_secret: process.env.NOTION_CLIENT_SECRET!,
90 + oauth_redirect_uri: 'https://backend.composio.dev/api/v3.1/toolkits/auth/callback',
91 + },
92 +});
93 +```
94 +</Tab>
95 +</Tabs>
96 +
97 +<Callout type="info">
98 +Omit `oauth_redirect_uri` to use Composio's default callback. Set it only when you [route the callback through your own domain](/docs/white-labeling-authentication#routing-the-callback-through-your-domain).
99 +</Callout>
100 +
101 +## Other auth types
102 +
103 +Toolkits that use API keys, bearer tokens, basic auth, or no auth follow the same call. Set `auth_scheme` to the toolkit's scheme and put the required fields in `credentials`. For a toolkit whose key the user supplies at connect time, pass empty `credentials`.
104 +
105 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
106 +<Tab value="Python">
107 +```python
108 +auth_config = composio.auth_configs.create(
109 + toolkit="perplexityai",
110 + options={
111 + "type": "use_custom_auth",
112 + "auth_scheme": "API_KEY",
113 + "name": "Perplexity AI",
114 + "credentials": {},
115 + },
116 +)
117 +```
118 +</Tab>
119 +<Tab value="TypeScript">
120 +```typescript
121 +import { Composio } from '@composio/core';
122 +
123 +const composio = new Composio();
124 +// ---cut---
125 +const authConfig = await composio.authConfigs.create('perplexityai', {
126 + type: 'use_custom_auth',
127 + authScheme: 'API_KEY',
128 + name: 'Perplexity AI',
129 + credentials: {},
130 +});
131 +```
132 +</Tab>
133 +</Tabs>
134 +
135 +## Use the auth config in a session
136 +
137 +Creating an auth config does not change which credentials a session uses. Pass the auth config ID to `authConfigs` (keyed by toolkit) when you create the session, and the session authenticates that toolkit with your config. Toolkits you leave out keep using Composio managed auth.
138 +
139 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
140 +<Tab value="Python">
141 +```python
142 +session = composio.create(
143 + user_id="user_123",
144 + auth_configs={"notion": auth_config.id},
145 +)
146 +```
147 +</Tab>
148 +<Tab value="TypeScript">
149 +```typescript
150 +import { Composio } from '@composio/core';
151 +const composio = new Composio({ apiKey: 'your_api_key' });
152 +const authConfig = { id: 'ac_your_notion_config' };
153 +// ---cut---
154 +const session = await composio.create('user_123', {
155 + authConfigs: { notion: authConfig.id },
156 +});
157 +```
158 +</Tab>
159 +</Tabs>
160 +
161 +See [Configuring sessions](/docs/configuring-sessions#custom-auth-configs) for how `authConfigs` interacts with account selection and precedence.
162 +
163 +## Discover the required fields
164 +
165 +Different schemes need different credential fields. To build the `credentials` object dynamically, ask the toolkit which fields it requires for a given scheme before you create the config.
166 +
167 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
168 +<Tab value="Python">
169 +```python
170 +fields = composio.toolkits.get_auth_config_creation_fields(
171 + toolkit="notion",
172 + auth_scheme="OAUTH2",
173 + required_only=True,
174 +)
175 +print(fields)
176 +```
177 +</Tab>
178 +<Tab value="TypeScript">
179 +```typescript
180 +import { Composio } from '@composio/core';
181 +
182 +const composio = new Composio();
183 +// ---cut---
184 +const fields = await composio.toolkits.getAuthConfigCreationFields('notion', 'OAUTH2', {
185 + requiredOnly: true,
186 +});
187 +
188 +console.log(fields);
189 +```
190 +</Tab>
191 +</Tabs>
192 +
193 +## Next
194 +
195 +<Card icon={<Key />} title="Controlling scopes" href="/docs/controlling-scopes" description="Override the default OAuth scopes Composio requests for a toolkit" />
docs/content/docs/projects.mdx deleted
-102
@@ -1,102 +0,0 @@
1 ----
2 -title: Projects
3 -description: Isolate resources across environments or clients using projects for multi-tenancy
4 -keywords: [projects, organizations, teams, api keys, environments, multi-tenancy, multitenancy, tenant isolation]
5 ----
6 -
7 -Projects are Composio's multi-tenancy primitive. Every Composio account belongs to an **organization**. Inside an organization, **projects** are isolated environments that scope your API keys, connected accounts, auth configs, and webhook configurations. Resources in one project are not accessible from another.
8 -
9 -```mermaid
10 -graph LR
11 - ORG["Organization (org_xxx)"] --- P1["Project: Production (proj_xxx)"]
12 - ORG --- P2["Project: Staging (proj_xxx)"]
13 - ORG --- TM["Team Members"]
14 - P1 --- A1["API Keys"]
15 - P1 --- A2["Connected Accounts"]
16 - P1 --- A3["Auth Configs"]
17 - P1 --- A4["Webhook Config"]
18 - P2 --- B1["..."]
19 -```
20 -
21 -Common reasons to use multiple projects:
22 -- **Separate environments**: keep production and staging isolated
23 -- **Separate products**: keep resources for different apps independent
24 -- **Client isolation**: give each client their own project with separate credentials and data
25 -
26 -## Managing projects
27 -
28 -You can manage projects from the [dashboard](https://dashboard.composio.dev/~/org/) or via the API using an **organization API key** (`x-org-api-key`).
29 -
30 -<Callout type="info">
31 -Project management endpoints use the `x-org-api-key` header, not the regular `x-api-key`. You can find your org API key in the dashboard under **Settings > Organization**.
32 -</Callout>
33 -
34 -### Create a project
35 -
36 -There is no limit on the number of projects per organization. Project names must be unique within the organization.
37 -
38 -```bash
39 -curl -X POST https://backend.composio.dev/api/v3.1/org/owner/project/new \
40 - -H "x-org-api-key: YOUR_ORG_API_KEY" \
41 - -H "Content-Type: application/json" \
42 - -d '{
43 - "name": "my-staging-project",
44 - "should_create_api_key": true
45 - }'
46 -```
47 -
48 -The response includes the project ID and, if requested, an API key:
49 -
50 -```json
51 -{
52 - "id": "proj_abc123xyz456",
53 - "name": "my-staging-project",
54 - "api_key": "ak_abc123xyz456"
55 -}
56 -```
57 -
58 -### List projects
59 -
60 -```bash
61 -curl https://backend.composio.dev/api/v3.1/org/owner/project/list \
62 - -H "x-org-api-key: YOUR_ORG_API_KEY"
63 -```
64 -
65 -Supports pagination with `limit` and `cursor` query parameters.
66 -
67 -### Get project details
68 -
69 -```bash
70 -curl https://backend.composio.dev/api/v3.1/org/owner/project/proj_abc123xyz456 \
71 - -H "x-org-api-key: YOUR_ORG_API_KEY"
72 -```
73 -
74 -Returns the full project object including its API keys.
75 -
76 -## Project settings
77 -
78 -Each project has settings that control security, logging, and display behavior. These endpoints use your **project API key** (`x-api-key`), not the org key.
79 -
80 -```bash
81 -curl -X PATCH https://backend.composio.dev/api/v3.1/org/project/config \
82 - -H "x-api-key: YOUR_API_KEY" \
83 - -H "Content-Type: application/json" \
84 - -d '{
85 - "mask_secret_keys_in_connected_account": false,
86 - "log_visibility_setting": "show_all"
87 - }'
88 -```
89 -
90 -Notable security setting:
91 -- `require_mcp_api_key`: when `true`, MCP server requests must include a valid `x-api-key` header. This defaults to `true` for organizations created on or after March 5, 2026.
92 -
93 -You can also view and update these from **Settings > Project Settings** in the [dashboard](https://dashboard.composio.dev/~/project/settings/general). See the [Projects API reference](/reference/api-reference/projects) for all available settings.
94 -
95 -## What to read next
96 -
97 -<Cards>
98 - <Card icon={<Key />} title="Authentication" href="/docs/authentication" description="Auth configs are scoped to projects — learn how Composio manages auth" />
99 - <Card icon={<Key />} title="Scoped project API keys" href="/reference/authentication/project-api-key-permissions" description="Choose scoped access levels for project API keys" />
100 - <Card icon={<Database />} title="What is a session?" href="/docs/how-composio-works" description="Connected accounts and sessions live within a project" />
101 - <Card icon={<Zap />} title="Triggers" href="/docs/triggers" description="Webhook configurations are project-scoped" />
102 -</Cards>
docs/content/docs/providers/anthropic.mdx
+22 -39
@@ -4,7 +4,12 @@ description: Build an agent with Claude and enable it to use 1000+ tools with Co
4 keywords: [claude, messages api, claude agent sdk, agents sdk]
5 ---
6
7 -Composio integrates with Anthropic through the [Claude Messages API](https://docs.anthropic.com/en/api/messages) and the [Claude Agent SDK](https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk). Pick the tab that matches your integration.
7 +The Anthropic provider formats Composio tools for Claude and executes the tool calls Claude returns. It works two ways:
8 +
9 +- The [Claude Messages API](https://docs.anthropic.com/en/api/messages), where you run the tool-call loop yourself.
10 +- The [Claude Agent SDK](https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk), where the SDK runs the loop and Composio tools are exposed as an in-process MCP server.
11 +
12 +Pick the tab that matches your integration.
13
14 <IntegrationTabs tabs={[
15 { value: "messages", label: "Messages API" },
@@ -13,7 +18,7 @@ Composio integrates with Anthropic through the [Claude Messages API](https://doc
18
19 <IntegrationContent value="messages">
20
16 -The Anthropic Provider transforms Composio tools into a format compatible with the Claude Messages API.
21 +The `AnthropicProvider` transforms Composio tools into the format the Claude Messages API expects, then executes the tool calls Claude requests and shapes the results back into Messages API content blocks.
22
23 <Steps>
24 <Step>
@@ -75,7 +80,7 @@ response = client.messages.create(
80 messages=messages,
81 )
82
78 -# Agentic loop — keep executing tool calls until the model responds with text
83 +# Agentic loop: keep executing tool calls until the model responds with text
84 while response.stop_reason == "tool_use":
85 tool_use_blocks = [block for block in response.content if block.type == "tool_use"]
86 results = composio.provider.handle_tool_calls(user_id="user_123", response=response)
@@ -129,7 +134,7 @@ let response = await client.messages.create({
134 messages: messages,
135 });
136
132 -// Agentic loop — keep executing tool calls until the model responds with text
137 +// Agentic loop: keep executing tool calls until the model responds with text
138 while (response.stop_reason === "tool_use") {
139 const toolResults = await composio.provider.handleToolCalls("user_123", response);
140 messages.push({ role: "assistant", content: response.content });
@@ -154,11 +159,15 @@ for (const block of response.content) {
159 </Step>
160 </Steps>
161
162 +<Callout type="info">
163 +`handleToolCalls` does the loop body for you. It extracts every `tool_use` block from the response, executes the matching Composio tools, and returns a ready-to-append array of Messages API content (a `user` message holding `tool_result` blocks). That is why the TypeScript example spreads the result straight into `messages` with `messages.push(...toolResults)`. In Python it returns the raw result list, which the example wraps into `tool_result` blocks by hand.
164 +</Callout>
165 +
166 </IntegrationContent>
167
168 <IntegrationContent value="agent-sdk">
169
161 -The Claude Agent SDK provider transforms Composio tools into tools compatible with the Claude Agent SDK.
170 +The `ClaudeAgentSDKProvider` exposes your Composio tools to the Claude Agent SDK as an in-process MCP server. You build the server with `create_sdk_mcp_server` (Python) or `createSdkMcpServer` (TypeScript), register it on the agent, and the SDK runs the tool-call loop for you.
171
172 <Steps>
173 <Step>
@@ -264,41 +273,15 @@ for await (const content of query({
273
274 </IntegrationTabs>
275
267 -## Multi-turn chat
268 -
269 -For multi-turn apps, create the session once and reuse it across requests with `composio.use()`:
276 +## Provider specifics
277
271 -<Tabs groupId="language" items={["Python", "TypeScript"]} persist>
272 -<Tab value="Python">
273 -```python
274 -from composio import Composio
278 +A few things are specific to the Anthropic provider:
279
276 -composio = Composio()
280 +- **Tool caching.** Pass `cacheTools: true` to the constructor (`new AnthropicProvider({ cacheTools: true })`) to attach Anthropic's ephemeral `cache_control` to every tool definition and tool-result block. This lets Claude reuse cached tool schemas across requests and can cut prompt cost when you send the same large tool set on every turn.
281 +- **`handleToolCalls` returns Messages API content, not raw strings.** On the TypeScript side it returns `Anthropic.Messages.MessageParam[]` (a `user` message of `tool_result` blocks) that you append directly to your message list. This is why the loop above does not build `tool_result` blocks by hand.
282 +- **String-encoded tool inputs are handled for you.** Claude occasionally emits a tool's `input` as a JSON string instead of an object. The provider normalizes this before execution, so you do not have to parse it yourself.
283 +- **`cacheTools` only.** The constructor takes no other options. There is no agentic execution in this provider; you run the loop (Messages API) or hand the loop to the Claude Agent SDK (Agent SDK tab).
284
278 -# First request — create and store the session ID
279 -session = composio.create(user_id="user_123")
280 -session_id = session.session_id
281 -# store session_id in your database or chat state
285 +## Next
286
283 -# Subsequent requests — reuse the session
284 -session = composio.use(session_id)
285 -tools = session.tools()
286 -```
287 -</Tab>
288 -<Tab value="TypeScript">
289 -```typescript
290 -// @noErrors
291 -import { Composio } from '@composio/core';
292 -const composio = new Composio({ apiKey: 'your_api_key' });
293 -// ---cut---
294 -// First request — create and store the session ID
295 -const session = await composio.create("user_123");
296 -const sessionId = session.sessionId;
297 -// store sessionId in your database or chat state
298 -
299 -// Subsequent requests — reuse the session
300 -const session = await composio.use(sessionId);
301 -const tools = await session.tools();
302 -```
303 -</Tab>
304 -</Tabs>
287 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/autogen.mdx
+15 -1
@@ -4,7 +4,7 @@ description: Build an agent with AutoGen and enable it to use 1000+ tools with C
4 keywords: [autogen, microsoft autogen]
5 ---
6
7 -The AutoGen provider transforms Composio tools into AutoGen's [FunctionTool](https://microsoft.github.io/autogen/) format for use with AutoGen agents.
7 +The AutoGen provider turns Composio tools into AutoGen [`FunctionTool`](https://microsoft.github.io/autogen/) objects and registers them with your agents. You connect an account, fetch the tools, register them with a caller and executor agent, and AutoGen handles the conversation and tool calls.
8
9 <Steps>
10 <Step>
@@ -67,3 +67,17 @@ print(response.chat_history)
67 ```
68 </Step>
69 </Steps>
70 +
71 +## Provider specifics
72 +
73 +AutoGen needs tools registered with two agents, not passed once. Call `composio.provider.register_tools(caller=..., executor=..., tools=tools)`: the `caller` decides which tool to invoke, and the `executor` runs it.
74 +
75 +Each tool comes back as an AutoGen `FunctionTool` with a generated `name`. AutoGen caps function names at 64 characters, so the provider hashes and truncates long tool slugs to stay under the limit. The registered name will not always match the original Composio slug.
76 +
77 +<Callout type="info">
78 +`register_tools` is unique to the AutoGen provider. Other providers pass tools straight into the agent constructor, so don't expect this method elsewhere.
79 +</Callout>
80 +
81 +## Next
82 +
83 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/crewai.mdx
+17 -1
@@ -4,7 +4,7 @@ description: Build an agent with CrewAI and enable it to use 1000+ tools with Co
4 keywords: [crewai]
5 ---
6
7 -The CrewAI provider transforms Composio tools into CrewAI's [BaseTool](https://docs.crewai.com/concepts/tools) format with built-in execution.
7 +The CrewAI provider turns Composio tools into CrewAI [`BaseTool`](https://docs.crewai.com/concepts/tools) objects that execute themselves. You connect an account, fetch the tools, pass them to an `Agent`, and CrewAI runs the task end to end.
8
9 <Steps>
10 <Step>
@@ -62,3 +62,19 @@ print(result)
62 ```
63 </Step>
64 </Steps>
65 +
66 +## Provider specifics
67 +
68 +Each Composio tool becomes a CrewAI `BaseTool` whose `args_schema` is built from the tool's input schema, so CrewAI validates arguments before running anything.
69 +
70 +When validation fails, the tool does not raise. It returns a structured result instead:
71 +
72 +```python
73 +{"successful": False, "error": "<validation message>", "data": None}
74 +```
75 +
76 +Check `successful` in your task output rather than wrapping calls in `try`/`except`.
77 +
78 +## Next
79 +
80 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/custom-providers/python.mdx
+37 -43
@@ -3,23 +3,23 @@ title: Python Custom Provider
3 description: Build an agent with any Python framework and enable it to use 1000+ tools with Composio.
4 ---
5
6 -This guide shows how to create custom providers for the Composio Python SDK. Custom providers enable compatibility with different AI frameworks and platforms.
6 +A **custom provider** adapts Composio tools to the format your AI framework expects, so you can use 1000+ tools with a platform Composio doesn't ship support for. This guide shows you how to build one in Python.
7
8 ## Provider architecture
9
10 -The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:
10 +A provider does two things:
11
12 -1. **Tool format transformation**: Converting Composio tools into formats compatible with specific AI platforms
13 -2. **Platform-specific compatibility**: Providing helper methods for seamless compatibility
12 +1. **Tool format transformation**: converts Composio tools into the format your AI platform understands.
13 +2. **Platform-specific compatibility**: adds helper methods for executing tool calls and handling responses.
14
15 -## Types of providers
15 +There are two kinds of providers:
16
17 -There are two types of providers:
17 +| Type | Use it for | Examples |
18 +| --- | --- | --- |
19 +| **Non-agentic** | Platforms that don't have their own agency. You drive the tool-call loop. | OpenAI, Anthropic |
20 +| **Agentic** | Platforms that run their own agent loop and call tools themselves. | LangChain, CrewAI |
21
19 -1. **Non-agentic providers**: Transform tools for platforms that don't have their own agency (e.g., OpenAI, Anthropic)
20 -2. **Agentic providers**: Transform tools for platforms that have their own agency (e.g., LangChain, CrewAI)
21 -
22 -## Provider class hierarchy
22 +Each type extends a different abstract base class:
23
24 ```
25 BaseProvider (Abstract)
@@ -34,7 +34,7 @@ BaseProvider (Abstract)
34
35 ## Quick start
36
37 -The fastest way to create a new provider is using the provider scaffolding script:
37 +Scaffold a working provider with the `make create-provider` script:
38
39 ```bash
40 # Create a non-agentic provider
@@ -43,27 +43,16 @@ make create-provider name=myprovider
43 # Create an agentic provider
44 make create-provider name=myagent agentic=true
45
46 -# Create provider with custom output directory
46 +# Write to a custom output directory
47 make create-provider name=myprovider output=/path/to/custom/dir
48
49 # Combine options
50 make create-provider name=myagent agentic=true output=/my/custom/path
51 ```
52
53 -This will create a new provider in the specified directory (default: `python/providers/<provider-name>/`) with:
54 -- Complete package structure with `pyproject.toml`
55 -- Provider implementation template
56 -- Demo script
57 -- README with usage examples
58 -- Type annotations and proper inheritance
59 -
60 -<Callout>
61 -The scaffolding script creates a fully functional provider template. You just need to implement the tool transformation logic specific to your platform. You can maintain your provider implementation in your own repository.
62 -</Callout>
63 -
64 -### Generated structure
53 +This generates a provider in `python/providers/<provider-name>/` (or your `output` directory) with a `pyproject.toml`, a provider template, a demo script, a `README`, and type annotations. The template runs as-is. You implement the tool transformation for your platform, and you can keep your provider in your own repository.
54
66 -The create-provider script generates the following structure:
55 +The generated structure:
56
57 ```
58 python/providers/<provider-name>/
@@ -77,15 +66,16 @@ python/providers/<provider-name>/
66 └── py.typed # PEP 561 type marker
67 ```
68
80 -After generation, you can:
81 -1. Navigate to the provider directory: `cd python/providers/<provider-name>`
82 -2. Install in development mode: `uv pip install -e .`
83 -3. Implement your provider logic in `composio_<provider-name>/provider.py`
84 -4. Test with the demo script: `python <provider-name>_demo.py`
69 +From there:
70 +
71 +1. Navigate to the provider directory: `cd python/providers/<provider-name>`.
72 +2. Install in development mode: `uv pip install -e .`.
73 +3. Implement your provider logic in `composio_<provider-name>/provider.py`.
74 +4. Test with the demo script: `python <provider-name>_demo.py`.
75
76 ## Creating a non-agentic provider
77
88 -Non-agentic providers inherit from the `NonAgenticProvider` abstract class:
78 +A non-agentic provider extends `NonAgenticProvider` and implements two methods: `wrap_tool` (transform one tool) and `wrap_tools` (transform a collection). Add helper methods to execute tool calls in your platform's format.
79
80 ```python
81 from typing import List, Optional, Sequence, TypeAlias
@@ -148,7 +138,7 @@ class MyAIProvider(NonAgenticProvider[MyAITool, MyAIToolCollection], name="my-ai
138
139 ## Creating an agentic provider
140
151 -Agentic providers inherit from the `AgenticProvider` abstract class:
141 +An agentic provider extends `AgenticProvider`. Because the platform calls tools itself, `wrap_tool` receives an `execute_tool` function that you wrap into a callable the framework can invoke directly.
142
143 ```python
144 from typing import Callable, Dict, List, Sequence
@@ -198,9 +188,11 @@ class MyAgentProvider(AgenticProvider[AgentTool, List[AgentTool]], name="my-agen
188
189 ## Using your custom provider
190
201 -After creating your provider, use it with the Composio SDK:
191 +Pass an instance of your provider to `Composio`, and every tool you fetch comes back in your format.
192 +
193 +### Non-agentic provider
194
203 -### Non-agentic provider example
195 +You drive the loop: fetch tools, send them to the platform, then hand the response back to the provider to execute the calls.
196
197 ```python
198 from composio import Composio
@@ -233,7 +225,9 @@ result = composio.provider.handle_tool_calls(response=response, user_id="default
225 print(result)
226 ```
227
236 -### Agentic provider example
228 +### Agentic provider
229 +
230 +The framework runs the loop. Fetch tools, attach them to an agent, and the agent calls them itself.
231
232 ```python
233 import asyncio
@@ -273,11 +267,11 @@ asyncio.run(main())
267
268 ## Best practices
269
276 -1. **Keep providers focused**: Each provider should integrate with one specific platform
277 -2. **Handle errors gracefully**: Catch and transform errors from tool execution
278 -3. **Follow platform conventions**: Adopt naming and structural conventions of the target platform
279 -4. **Use type annotations**: Leverage Python's typing system for better IDE support and documentation
280 -5. **Cache transformed tools**: Store transformed tools when appropriate to improve performance
281 -6. **Add helper methods**: Provide convenient methods for common platform-specific operations
282 -7. **Document your provider**: Include docstrings and usage examples
283 -8. **Set meaningful provider names**: Use the name parameter for telemetry and debugging
270 +- **Keep providers focused**: each provider integrates with one platform.
271 +- **Handle errors gracefully**: catch and transform errors from tool execution.
272 +- **Follow platform conventions**: adopt the naming and structure of the target platform.
273 +- **Use type annotations**: lean on Python's typing for IDE support and documentation.
274 +- **Cache transformed tools**: store transformed tools when it helps performance.
275 +- **Add helper methods**: provide convenient methods for common platform operations.
276 +- **Document your provider**: include docstrings and usage examples.
277 +- **Set a meaningful provider name**: the `name` parameter is used for telemetry and debugging.
docs/content/docs/providers/custom-providers/typescript.mdx
+30 -30
@@ -3,24 +3,24 @@ title: TypeScript Custom Provider
3 description: Build an agent with any TypeScript framework and enable it to use 1000+ tools with Composio.
4 ---
5
6 -This guide provides a comprehensive walkthrough of creating custom providers for the Composio TypeScript SDK, enabling compatibility with different AI frameworks and platforms.
6 +A **provider** adapts Composio tools to the format your AI framework expects. Write one, and any framework can call Composio's 1000+ tools. This guide shows you how to build your own in TypeScript.
7
8 -## Provider Architecture
8 +## Provider architecture
9
10 -The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:
10 +A provider does three things:
11
12 -1. **Tool Format Transformation**: Converting Composio tools into formats compatible with specific AI platforms
13 -2. **Tool Execution**: Managing the flow of tool execution and results
14 -3. **Platform-Specific Compatibility**: Providing helper methods for seamless compatibility
12 +- **Transforms tool format**: converts Composio tools into the shape your AI platform expects.
13 +- **Executes tools**: runs tool calls and returns results.
14 +- **Adds platform helpers**: exposes convenience methods specific to your platform.
15
16 -## Types of Providers
16 +There are two kinds, depending on whether the target platform runs its own agent loop:
17
18 -There are two types of providers:
18 +| Type | When to use | Examples |
19 +| --- | --- | --- |
20 +| **Non-agentic** | The platform has no agency of its own. You drive the loop. | OpenAI |
21 +| **Agentic** | The platform runs its own agent loop and calls tools itself. | LangChain, AutoGPT |
22
20 -1. **Non-Agentic Providers**: Transform tools for platforms that don't have their own agency (e.g., OpenAI)
21 -2. **Agentic Providers**: Transform tools for platforms that have their own agency (e.g., LangChain, AutoGPT)
22 -
23 -## Provider Class Hierarchy
23 +Both extend `BaseProvider`:
24
25 ```
26 BaseProvider (Abstract)
@@ -31,9 +31,9 @@ BaseProvider (Abstract)
31 └── [Your Custom Agentic Provider] (Concrete)
32 ```
33
34 -## Creating a Non-Agentic Provider
34 +## Non-agentic provider
35
36 -Non-agentic providers implement the `BaseNonAgenticProvider` abstract class:
36 +A non-agentic provider extends `BaseNonAgenticProvider`. You supply a `name`, `wrapTool`, and `wrapTools`, and call the built-in `executeTool` when you're ready to run a tool.
37
38 ```typescript
39 import { BaseNonAgenticProvider, Tool } from '@composio/core';
@@ -94,9 +94,9 @@ export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyA
94 }
95 ```
96
97 -## Creating an Agentic Provider
97 +## Agentic provider
98
99 -Agentic providers implement the `BaseAgenticProvider` abstract class:
99 +An **agentic provider** extends `BaseAgenticProvider`. The difference from the non-agentic case: `wrapTool` and `wrapTools` receive an `executeToolFn`, which you embed in each tool so the framework's agent can run the tool itself.
100
101 ```typescript
102 // @noErrors
@@ -164,9 +164,9 @@ export class MyAgentProvider extends BaseAgenticProvider<AgentToolkit, AgentTool
164 }
165 ```
166
167 -## Using Your Custom Provider
167 +## Use your provider
168
169 -After creating your provider, use it with the Composio SDK:
169 +Pass an instance to `Composio` via the `provider` option. Every tool you fetch comes back in your custom format.
170
171 ```typescript
172 // @noErrors
@@ -191,9 +191,9 @@ const tools = await composio.tools.get('default', {
191 console.log(tools); // These will be in your custom format
192 ```
193
194 -## Provider State and Context
194 +## Provider state and context
195
196 -Your provider can maintain state and context:
196 +A provider is a class, so it can hold state. Use the constructor for config, and instance fields for caches or counters.
197
198 ```typescript
199 // @noErrors
@@ -242,9 +242,9 @@ export class StatefulProvider extends BaseNonAgenticProvider<ToolCollection, Too
242 }
243 ```
244
245 -## Advanced: Provider Composition
245 +## Advanced: compose providers
246
247 -You can compose functionality by extending existing providers:
247 +You don't have to start from a base class. Extend an existing provider to add behavior like analytics or retries, and call `super` to reuse its logic.
248
249 ```typescript
250 // @noErrors
@@ -296,12 +296,12 @@ export class EnhancedOpenAIProvider extends OpenAIProvider {
296 }
297 ```
298
299 -## Best Practices
299 +## Best practices
300
301 -1. **Keep providers focused**: Each provider should integrate with one specific platform
302 -2. **Handle errors gracefully**: Catch and transform errors from tool execution
303 -3. **Follow platform conventions**: Adopt naming and structural conventions of the target platform
304 -4. **Optimize for performance**: Cache transformed tools when possible
305 -5. **Add helper methods**: Provide convenient methods for common platform-specific operations
306 -6. **Provide clear documentation**: Document your provider's unique features and usage
307 -7. **Use telemetry**: Set a meaningful provider name for telemetry insights
301 +- **Keep providers focused**: each provider should target one platform.
302 +- **Handle errors gracefully**: catch and transform errors from tool execution.
303 +- **Follow platform conventions**: adopt the naming and structure of the target platform.
304 +- **Cache transformed tools**: reuse wrapped tools instead of rebuilding them.
305 +- **Add helper methods**: expose convenience methods for common platform operations.
306 +- **Document your provider**: describe its features and usage.
307 +- **Set a meaningful `name`**: it's used for telemetry insights.
docs/content/docs/providers/google.mdx
+9 -5
@@ -4,7 +4,7 @@ description: Build an agent with Gemini or Google ADK and enable it to use 1000+
4 keywords: [gemini, google generative ai, google genai, google adk, agent development kit]
5 ---
6
7 -Composio integrates with Google through [Gemini function calling](https://ai.google.dev/) and the [Agent Development Kit (ADK)](https://google.github.io/adk-docs/). Pick the tab that matches your integration.
7 +The Google provider formats Composio tools for [Gemini](https://ai.google.dev/) and the [Google Agent Development Kit (ADK)](https://google.github.io/adk-docs/). Pick the tab that matches your setup.
8
9 <IntegrationTabs tabs={[
10 { value: "gemini", label: "Gemini" },
@@ -13,7 +13,7 @@ Composio integrates with Google through [Gemini function calling](https://ai.goo
13
14 <IntegrationContent value="gemini">
15
16 -The Google Generative AI provider transforms Composio tools into a format compatible with Gemini function calling.
16 +The Google Generative AI provider transforms Composio tools into Gemini function declarations. Gemini is non-agentic, so the model returns function calls and you run the loop: execute each call with `composio.provider.executeToolCall`, feed the result back, and repeat until the model replies with text.
17
18 <Steps>
19 <Step>
@@ -68,7 +68,7 @@ config = types.GenerateContentConfig(tools=tools)
68 chat = client.chats.create(model="gemini-3-pro-preview", config=config)
69 response = chat.send_message("Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'")
70
71 -# Agentic loop — keep executing tool calls until the model responds with text
71 +# Agentic loop: keep executing tool calls until the model responds with text
72 while response.function_calls:
73 parts = []
74 for fc in response.function_calls:
@@ -105,7 +105,7 @@ let response = await chat.sendMessage({
105 message: "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
106 });
107
108 -// Agentic loop — keep executing tool calls until the model responds with text
108 +// Agentic loop: keep executing tool calls until the model responds with text
109 while (response.functionCalls && response.functionCalls.length > 0) {
110 const parts: Part[] = [];
111 for (const fc of response.functionCalls) {
@@ -135,7 +135,7 @@ console.log(response.text);
135
136 <IntegrationContent value="adk">
137
138 -The Google ADK provider transforms Composio tools into Google ADK's FunctionTool format for use with Google ADK agents. ADK integration is Python-only.
138 +The Google ADK provider transforms Composio tools into ADK's `FunctionTool` format. Unlike Gemini function calling, ADK runs the tool loop for you: hand the tools to an `Agent`, and the `Runner` executes calls and continues until the agent produces a final response. ADK integration is Python-only.
139
140 <Steps>
141 <Step>
@@ -211,3 +211,7 @@ for event in events:
211 </IntegrationContent>
212
213 </IntegrationTabs>
214 +
215 +## Next
216 +
217 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/index.mdx
+75 -12
@@ -3,29 +3,92 @@ title: Providers
3 description: Composio works with any AI framework. Pick your preferred SDK to get started.
4 ---
5
6 -Composio works with any AI framework. Each provider transforms Composio tools into the native format your framework expects — no glue code needed.
6 +Composio works with any AI framework. A provider is the adapter that turns Composio tools into the native tool format your framework expects, so you don't write glue code.
7 +
8 +Pick the provider that matches the SDK or agent framework you already use. Each one fetches tools, handles execution, and hands your agent objects it understands. If your framework isn't listed, you can [build your own provider](/docs/providers/custom-providers).
9
10 ## AI SDKs
11
12 +Use these when you call a model SDK directly.
13 +
14 <ProviderGrid>
11 - <ProviderCard name="Anthropic" href="/docs/providers/anthropic" logo="/images/providers/anthropic-logo.svg" logoDark="/images/providers/anthropic-logo-dark.svg" languages={["Python", "TypeScript"]} />
12 - <ProviderCard name="OpenAI" href="/docs/providers/openai" logo="/images/providers/openai-logo.svg" logoDark="/images/providers/openai-logo-dark.svg" languages={["Python", "TypeScript"]} />
13 - <ProviderCard name="Vercel AI SDK" href="/docs/providers/vercel" logo="/images/providers/vercel-logo.svg" logoDark="/images/providers/vercel-logo-dark.svg" languages={["TypeScript"]} />
14 - <ProviderCard name="Google" href="/docs/providers/google" logo="/images/providers/google-logo.svg" languages={["Python", "TypeScript"]} />
15 + <ProviderCard
16 + name="Anthropic"
17 + href="/docs/providers/anthropic"
18 + logo="/images/providers/anthropic-logo.svg"
19 + logoDark="/images/providers/anthropic-logo-dark.svg"
20 + languages={['Python', 'TypeScript']}
21 + />
22 + <ProviderCard
23 + name="OpenAI"
24 + href="/docs/providers/openai"
25 + logo="/images/providers/openai-logo.svg"
26 + logoDark="/images/providers/openai-logo-dark.svg"
27 + languages={['Python', 'TypeScript']}
28 + />
29 + <ProviderCard
30 + name="Vercel AI SDK"
31 + href="/docs/providers/vercel"
32 + logo="/images/providers/vercel-logo.svg"
33 + logoDark="/images/providers/vercel-logo-dark.svg"
34 + languages={['TypeScript']}
35 + />
36 + <ProviderCard
37 + name="Google"
38 + href="/docs/providers/google"
39 + logo="/images/providers/google-logo.svg"
40 + languages={['Python', 'TypeScript']}
41 + />
42 </ProviderGrid>
43
17 -## Agent Frameworks
44 +## Agent frameworks
45 +
46 +Use these when an agent framework orchestrates the tool calls for you.
47
48 <ProviderGrid>
20 - <ProviderCard name="LangChain" href="/docs/providers/langchain" logo="/images/providers/langchain-logo.svg" logoDark="/images/providers/langchain-logo-dark.svg" languages={["Python", "TypeScript"]} />
21 - <ProviderCard name="CrewAI" href="/docs/providers/crewai" logo="/images/providers/crewai-logo.svg" languages={["Python"]} />
22 - <ProviderCard name="LlamaIndex" href="/docs/providers/llamaindex" logo="/images/providers/llamaIndex-logo.svg" languages={["Python", "TypeScript"]} />
23 - <ProviderCard name="Mastra" href="/docs/providers/mastra" logo="/images/providers/mastra-logo.svg" logoDark="/images/providers/mastra-logo-dark.svg" languages={["TypeScript"]} />
24 - <ProviderCard name="AutoGen" href="/docs/providers/autogen" languages={["Python"]} />
49 + <ProviderCard
50 + name="LangChain"
51 + href="/docs/providers/langchain"
52 + logo="/images/providers/langchain-logo.svg"
53 + logoDark="/images/providers/langchain-logo-dark.svg"
54 + languages={['Python', 'TypeScript']}
55 + />
56 + <ProviderCard
57 + name="CrewAI"
58 + href="/docs/providers/crewai"
59 + logo="/images/providers/crewai-logo.svg"
60 + languages={['Python']}
61 + />
62 + <ProviderCard
63 + name="LlamaIndex"
64 + href="/docs/providers/llamaindex"
65 + logo="/images/providers/llamaIndex-logo.svg"
66 + languages={['Python', 'TypeScript']}
67 + />
68 + <ProviderCard
69 + name="Mastra"
70 + href="/docs/providers/mastra"
71 + logo="/images/providers/mastra-logo.svg"
72 + logoDark="/images/providers/mastra-logo-dark.svg"
73 + languages={['TypeScript']}
74 + />
75 + <ProviderCard
76 + name="Pi"
77 + href="/docs/providers/pi"
78 + logo="/images/providers/pi-logo.svg"
79 + logoDark="/images/providers/pi-logo-dark.svg"
80 + languages={['TypeScript']}
81 + />
82 + <ProviderCard name="AutoGen" href="/docs/providers/autogen" languages={['Python']} />
83 </ProviderGrid>
84
85 ## Custom
86
87 <ProviderGrid>
30 - <ProviderCard name="Build your own" href="/docs/providers/custom-providers" icon={<Blocks size={32} />} languages={["Python", "TypeScript"]} />
88 + <ProviderCard
89 + name="Build your own"
90 + href="/docs/providers/custom-providers"
91 + icon={<Blocks size={32} />}
92 + languages={['Python', 'TypeScript']}
93 + />
94 </ProviderGrid>
docs/content/docs/providers/langchain.mdx
+7 -3
@@ -4,7 +4,7 @@ description: Build an agent with LangChain or LangGraph and enable it to use 100
4 keywords: [langchain, langgraph]
5 ---
6
7 -Composio integrates with [LangChain](https://python.langchain.com/) and [LangGraph](https://langchain-ai.github.io/langgraph/). Pick the tab that matches your integration.
7 +The LangChain provider formats Composio tools for [LangChain](https://python.langchain.com/) and [LangGraph](https://langchain-ai.github.io/langgraph/) agents. Pick the tab that matches your setup.
8
9 <IntegrationTabs tabs={[
10 { value: "langchain", label: "LangChain" },
@@ -13,7 +13,7 @@ Composio integrates with [LangChain](https://python.langchain.com/) and [LangGra
13
14 <IntegrationContent value="langchain">
15
16 -The LangChain provider transforms Composio tools into LangChain's StructuredTool format with built-in execution.
16 +The LangChain provider transforms each Composio tool into a LangChain [`DynamicStructuredTool`](https://js.langchain.com/docs/concepts/tools/) with built-in execution. You can hand the tools to `create_agent` in Python or wire them into a graph node in TypeScript, and the framework runs the tool loop for you.
17
18 <Steps>
19 <Step>
@@ -130,7 +130,7 @@ console.log(finalState.messages[finalState.messages.length - 1].content);
130
131 <IntegrationContent value="langgraph">
132
133 -The LangGraph provider transforms Composio tools into LangChain StructuredTool format for use with LangGraph agents. LangGraph integration is Python-only.
133 +The LangGraph provider transforms Composio tools into the same LangChain `DynamicStructuredTool` format, ready to use with LangGraph agents. LangGraph integration is Python-only.
134
135 <Steps>
136 <Step>
@@ -181,3 +181,7 @@ print(result["messages"][-1].content)
181 </IntegrationContent>
182
183 </IntegrationTabs>
184 +
185 +## Next
186 +
187 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/llamaindex.mdx
+5 -1
@@ -4,7 +4,7 @@ description: Build an agent with LlamaIndex and enable it to use 1000+ tools wit
4 keywords: [llamaindex]
5 ---
6
7 -The LlamaIndex provider transforms Composio tools into LlamaIndex's [FunctionTool](https://docs.llamaindex.ai/en/stable/module_guides/deploying/agents/) format with built-in execution.
7 +The LlamaIndex provider turns Composio tools into LlamaIndex [`FunctionTool`](https://docs.llamaindex.ai/en/stable/module_guides/deploying/agents/) objects that execute themselves. You connect an account, fetch the tools, hand them to a `FunctionAgent`, and LlamaIndex drives the calls. The provider ships for both Python and TypeScript.
8
9 <Steps>
10 <Step>
@@ -97,3 +97,7 @@ console.log(result.data.result);
97 </Tabs>
98 </Step>
99 </Steps>
100 +
101 +## Next
102 +
103 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/mastra.mdx
+21 -1
@@ -4,7 +4,7 @@ description: Build an agent with Mastra and enable it to use 1000+ tools with Co
4 keywords: [mastra]
5 ---
6
7 -The Mastra provider transforms Composio tools into [Mastra's tool format](https://mastra.ai/en/docs/tools-mcp/overview#creating-tools) with built-in execution.
7 +The Mastra provider transforms Composio tools into [Mastra's tool format](https://mastra.ai/en/docs/tools-mcp/overview#creating-tools) with built-in execution. Pass the wrapped tools to a Mastra `Agent`, and the agent calls them automatically. Each tool gets both an input and an output schema, so Mastra can validate tool results as well as arguments.
8
9 <Steps>
10 <Step>
@@ -61,3 +61,23 @@ console.log(text);
61 ```
62 </Step>
63 </Steps>
64 +
65 +## Provider specifics
66 +
67 +**Strict mode.** Pass `strict: true` to drop every non-required property from each tool's input schema before Mastra compiles it:
68 +
69 +```typescript
70 +// @noErrors
71 +import { Composio } from "@composio/core";
72 +import { MastraProvider } from "@composio/mastra";
73 +
74 +const composio = new Composio({ provider: new MastraProvider({ strict: true }) });
75 +```
76 +
77 +<Callout type="info">
78 +The provider runs each tool's JSON Schema through Mastra's schema-compat layer and inlines internal `$ref` pointers first. A few Composio tools reference `$defs` entries that the upstream API does not emit. Rather than crash `tools.get`, the provider falls back to a permissive object schema for that property and logs one warning per tool, so the affected field validates loosely.
79 +</Callout>
80 +
81 +## Next
82 +
83 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/meta.json
+1
@@ -5,6 +5,7 @@
5 "anthropic",
6 "openai",
7 "vercel",
8 + "pi",
9 "google",
10 "langchain",
11 "autogen",
docs/content/docs/providers/openai.mdx
+24 -44
@@ -4,7 +4,13 @@ description: Build an agent with OpenAI and enable it to use 1000+ tools with Co
4 keywords: [gpt, responses api, chat completions, openai agents sdk, agents sdk]
5 ---
6
7 -Composio integrates with OpenAI through the [Responses API](https://platform.openai.com/docs/api-reference/responses), [Chat Completions API](https://platform.openai.com/docs/api-reference/chat), and [Agents SDK](https://openai.github.io/openai-agents-python/). Pick the tab that matches your integration.
7 +The OpenAI provider formats Composio tools for OpenAI's function-calling and executes the tool calls the model returns. It works three ways:
8 +
9 +- The [Responses API](https://platform.openai.com/docs/api-reference/responses), the recommended way to build agentic flows, where you run the tool-call loop yourself.
10 +- The [Chat Completions API](https://platform.openai.com/docs/api-reference/chat), the classic message-based interface, where you also run the loop.
11 +- The [Agents SDK](https://openai.github.io/openai-agents-python/), where the SDK runs the loop and executes Composio tools for you.
12 +
13 +The OpenAI provider is the default provider for the Composio SDK, so you get it without configuring anything. Pick the tab that matches your integration.
14
15 <IntegrationTabs tabs={[
16 { value: "responses", label: "Responses API" },
@@ -14,7 +20,7 @@ Composio integrates with OpenAI through the [Responses API](https://platform.ope
20
21 <IntegrationContent value="responses">
22
17 -The OpenAI Provider is the default provider for the Composio SDK. It transforms Composio tools into a format compatible with OpenAI function calling through the Responses API.
23 +The `OpenAIResponsesProvider` transforms Composio tools into OpenAI's function-calling format for the Responses API, then executes the tool calls the model returns and shapes the results into `function_call_output` items you feed back in.
24
25 <Steps>
26 <Step>
@@ -50,7 +56,7 @@ OPENAI_API_KEY=xxxxxxxxx
56 <Step>
57 **Create session and run**
58
53 -The [Responses API](https://platform.openai.com/docs/api-reference/responses) is the recommended way to build agentic flows with OpenAI.
59 +The [Responses API](https://platform.openai.com/docs/api-reference/responses) is the recommended way to build agentic flows with OpenAI. You pass `previous_response_id` on each turn so the model keeps the prior context, and you send back only the new `function_call_output` items.
60
61 <Tabs groupId="language" items={["Python", "TypeScript"]} persist>
62 <Tab value="Python">
@@ -78,7 +84,7 @@ response = client.responses.create(
84 ]
85 )
86
81 -# Agentic loop — keep executing tool calls until the model responds with text
87 +# Agentic loop: keep executing tool calls until the model responds with text
88 while True:
89 tool_calls = [o for o in response.output if o.type == "function_call"]
90 if not tool_calls:
@@ -126,7 +132,7 @@ let response = await client.responses.create({
132 ],
133 });
134
129 -// Agentic loop — keep executing tool calls until the model responds with text
135 +// Agentic loop: keep executing tool calls until the model responds with text
136 while (true) {
137 const toolCalls = response.output.filter((o) => o.type === "function_call");
138 if (toolCalls.length === 0) break;
@@ -162,7 +168,7 @@ for (const item of response.output) {
168
169 <IntegrationContent value="chat">
170
165 -The `OpenAIProvider` (Chat Completions) is the default provider used by the Composio SDK when no other provider is specified.
171 +The `OpenAIProvider` targets the Chat Completions API and is the default provider used by the Composio SDK when you do not specify one.
172
173 <Steps>
174 <Step>
@@ -198,8 +204,7 @@ OPENAI_API_KEY=xxxxxxxxx
204 <Step>
205 **Create session and run**
206
201 -The [Chat Completions API](https://platform.openai.com/docs/api-reference/chat) generates a model response from a list of messages.
202 -The `OpenAIProvider` (Chat Completions) is the default provider used by Composio SDK.
207 +The [Chat Completions API](https://platform.openai.com/docs/api-reference/chat) generates a model response from a list of messages. You keep the full message list yourself and append each assistant message and its `tool` results before the next call.
208
209 <Tabs groupId="language" items={["Python", "TypeScript"]} persist>
210 <Tab value="Python">
@@ -226,7 +231,7 @@ response = client.chat.completions.create(
231 messages=messages,
232 )
233
229 -# Agentic loop — keep executing tool calls until the model responds with text
234 +# Agentic loop: keep executing tool calls until the model responds with text
235 while response.choices[0].message.tool_calls:
236 results = composio.provider.handle_tool_calls(response=response, user_id="user_123")
237 messages.append(response.choices[0].message)
@@ -273,7 +278,7 @@ let response = await client.chat.completions.create({
278 messages: messages,
279 });
280
276 -// Agentic loop — keep executing tool calls until the model responds with text
281 +// Agentic loop: keep executing tool calls until the model responds with text
282 while (response.choices[0].message.tool_calls) {
283 const results = await composio.provider.handleToolCalls("user_123", response);
284 messages.push(response.choices[0].message);
@@ -301,7 +306,7 @@ console.log(response.choices[0].message.content);
306
307 <IntegrationContent value="agents">
308
304 -The OpenAI Agents SDK provider transforms Composio tools into the Agents SDK tool format with built-in execution.
309 +The `OpenAIAgentsProvider` transforms Composio tools into the Agents SDK tool format with execution built in, so the SDK runs the tool-call loop and you only define the agent and call `run`.
310
311 <Steps>
312 <Step>
@@ -403,41 +408,16 @@ console.log(result.finalOutput);
408
409 </IntegrationTabs>
410
406 -## Multi-turn chat
411 +## Provider specifics
412
408 -For multi-turn apps, create the session once and reuse it across requests with `composio.use()`. Store the session ID in your database or chat state:
413 +The OpenAI integration ships three providers, one per API surface:
414
410 -<Tabs groupId="language" items={["Python", "TypeScript"]} persist>
411 -<Tab value="Python">
412 -```python
413 -from composio import Composio
415 +- **`OpenAIResponsesProvider`** for the Responses API. `handleToolCalls` executes the tool calls and returns `function_call_output` items keyed by `call_id`. You pair it with `previous_response_id` so you only resend new outputs each turn.
416 +- **`OpenAIProvider`** for the Chat Completions API. This is the SDK default, so `new Composio()` with no provider uses it. You keep the full message list and append each assistant message plus its `tool` results yourself.
417 +- **`OpenAIAgentsProvider`** for the Agents SDK. Tools come with execution wired in, so the SDK runs the loop and you do not call `handleToolCalls` at all.
418
415 -composio = Composio()
419 +Use the Responses or Agents provider for new agentic flows; reach for Chat Completions when you are extending an existing Chat Completions codebase.
420
417 -# First request — create and store the session ID
418 -session = composio.create(user_id="user_123")
419 -session_id = session.session_id
420 -# store session_id in your database or chat state
421 +## Next
422
422 -# Subsequent requests — reuse the session
423 -session = composio.use(session_id)
424 -tools = session.tools()
425 -```
426 -</Tab>
427 -<Tab value="TypeScript">
428 -```typescript
429 -// @noErrors
430 -import { Composio } from '@composio/core';
431 -const composio = new Composio({ apiKey: 'your_api_key' });
432 -// ---cut---
433 -// First request — create and store the session ID
434 -const session = await composio.create("user_123");
435 -const sessionId = session.sessionId;
436 -// store sessionId in your database or chat state
437 -
438 -// Subsequent requests — reuse the session
439 -const session = await composio.use(sessionId);
440 -const tools = await session.tools();
441 -```
442 -</Tab>
443 -</Tabs>
423 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/pi.mdx new
+184
@@ -0,0 +1,184 @@
1 +---
2 +title: Pi
3 +description: Use Composio tools inside Pi coding-agent sessions.
4 +keywords: [pi, coding agent, pi coding agent, provider, experimental, typescript]
5 +experimental: true
6 +---
7 +
8 +The Pi provider adapts Composio tools for [`@earendil-works/pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent). A Pi session can search tools, manage connections, execute tools, and run the remote sandbox. Unlike the other providers, `PiProvider` ships its own hook interface to intercept, allow, deny, or rewrite every helper call before the model sees the result.
9 +
10 +<Callout type="info">
11 + The Pi provider ships from `@composio/experimental` for TypeScript projects.
12 +</Callout>
13 +
14 +## Dynamic session helpers
15 +
16 +For most Pi apps, expose the dynamic helper tools. They let the model discover exact Composio tool slugs before it executes, request missing connections, and run sandbox commands when you enable them.
17 +
18 +<Steps>
19 +<Step>
20 +**Install**
21 +
22 +```bash
23 +npm install @composio/core @composio/experimental @earendil-works/pi-coding-agent
24 +```
25 +
26 +</Step>
27 +
28 +<Step>
29 +**Configure API keys**
30 +
31 +```txt title=".env"
32 +COMPOSIO_API_KEY=xxxxxxxxx
33 +```
34 +
35 +</Step>
36 +
37 +<Step>
38 +**Create a Composio session and Pi tools**
39 +
40 +```typescript
41 +// @noErrors
42 +import { Composio } from '@composio/core';
43 +import { PiProvider, createPiComposioSystemPrompt } from '@composio/experimental';
44 +import {
45 + createAgentSession,
46 + DefaultResourceLoader,
47 + getAgentDir,
48 + SessionManager,
49 +} from '@earendil-works/pi-coding-agent';
50 +
51 +const composio = new Composio({
52 + apiKey: process.env.COMPOSIO_API_KEY,
53 + provider: new PiProvider(),
54 +});
55 +
56 +const composioSession = await composio.sessions.create('user_123', {
57 + toolkits: ['github', 'gmail'],
58 + manageConnections: {
59 + enable: true,
60 + callbackUrl: 'https://your-app.example.com/auth/callback',
61 + },
62 + sandbox: { enable: true },
63 +});
64 +
65 +const composioTools = composio.provider.createSessionTools({
66 + sessionId: composioSession.sessionId,
67 + search: composioSession.search.bind(composioSession),
68 + execute: composioSession.execute.bind(composioSession),
69 + callbackUrl: 'https://your-app.example.com/auth/callback',
70 + includeWorkbenchTools: true,
71 + connections: {
72 + getToolkitStates: toolkits => composioSession.toolkits({ toolkits }),
73 + authorizeToolkit: (toolkit, options) => composioSession.authorize(toolkit, options),
74 + },
75 + hooks: {
76 + execute: (ctx, next) => {
77 + if (ctx.request.toolSlug === 'COMPOSIO_MANAGE_CONNECTIONS') {
78 + return ctx.deny('Use composio_manage_connections instead.');
79 + }
80 + return next();
81 + },
82 + onAuthLink: async ctx => {
83 + await sendConnectionLinkToUser(ctx.url);
84 + return { message: 'Connection link sent out-of-band.' };
85 + },
86 + },
87 +});
88 +
89 +const loader = new DefaultResourceLoader({
90 + cwd: process.cwd(),
91 + agentDir: getAgentDir(),
92 + systemPromptOverride: () =>
93 + createPiComposioSystemPrompt(composioSession.sessionId, {
94 + includeWorkbenchTools: true,
95 + }),
96 +});
97 +await loader.reload();
98 +
99 +const { session: piSession } = await createAgentSession({
100 + cwd: process.cwd(),
101 + resourceLoader: loader,
102 + sessionManager: SessionManager.inMemory(process.cwd()),
103 + customTools: composioTools,
104 + tools: [
105 + 'composio_search_tools',
106 + 'composio_manage_connections',
107 + 'composio_execute_tool',
108 + 'composio_remote_workbench',
109 + 'composio_remote_bash',
110 + ],
111 +});
112 +
113 +await piSession.prompt('Find my open GitHub issues and summarize the blockers.');
114 +```
115 +
116 +</Step>
117 +</Steps>
118 +
119 +The provider creates these Pi tools:
120 +
121 +- `composio_search_tools` searches Composio for exact tool slugs and schemas.
122 +- `composio_manage_connections` checks connection state and initiates auth for missing toolkits.
123 +- `composio_execute_tool` executes an exact Composio tool slug.
124 +- `composio_remote_workbench` runs Python in the Composio sandbox, and requires `includeWorkbenchTools: true`.
125 +- `composio_remote_bash` runs short bash commands in the sandbox filesystem, and requires `includeWorkbenchTools: true`.
126 +
127 +You can rename any of these helpers through the `names` option on `createSessionTools`, and the constants live on `PI_COMPOSIO_SESSION_TOOL_NAMES`.
128 +
129 +## Hooks
130 +
131 +Hooks are the Pi provider's distinctive feature: middleware that wraps each helper so you control what runs and what the model sees. Pass a `hooks` object to `createSessionTools`. Each hook is `(ctx, next)`: `await next()` runs the default behavior, returning a value replaces what the model sees, and `ctx.deny(reason)` blocks the call. `ctx.request` is mutable; `ctx.context` is read-only.
132 +
133 +```typescript
134 +// @noErrors
135 +const composioTools = composio.provider.createSessionTools({
136 + sessionId: composioSession.sessionId,
137 + search: composioSession.search.bind(composioSession),
138 + execute: composioSession.execute.bind(composioSession),
139 + hooks: {
140 + search: (ctx, next) => {
141 + ctx.request.toolkits = ctx.request.toolkits?.map(toolkit =>
142 + toolkit === 'slack' ? 'slackbot' : toolkit
143 + );
144 + return next();
145 + },
146 + execute: async (ctx, next) => {
147 + if (ctx.request.toolSlug.startsWith('COMPOSIO_')) {
148 + return ctx.deny('Meta tools are blocked.');
149 + }
150 +
151 + const result = await next();
152 + const file = await saveLargeOutput(result);
153 + return file ? { message: `Output saved to ${file}` } : result;
154 + },
155 + remoteBash: (ctx, next) => {
156 + if (ctx.request.command.includes('rm -rf')) {
157 + return ctx.deny('Destructive bash commands are blocked.');
158 + }
159 + return next();
160 + },
161 + onAuthLink: async (ctx, next) => {
162 + await sendConnectionLinkToUser(ctx.url);
163 + return shouldShowLinkToModel(ctx) ? next() : { message: 'Connection link sent out-of-band.' };
164 + },
165 + },
166 +});
167 +```
168 +
169 +Available hooks, each keyed on `PiSessionHooks`:
170 +
171 +| Hook | Wraps |
172 +| ---- | ----- |
173 +| `search` | Tool discovery; rewrite `query` or `toolkits` |
174 +| `manageConnections` | Connection checks and auth |
175 +| `execute` | Tool execution; rewrite `toolSlug`, `args`, or `account` |
176 +| `remoteWorkbench` | The remote Python helper |
177 +| `remoteBash` | The remote bash helper |
178 +| `onAuthLink` | Any auth link found in a result |
179 +
180 +Every `ctx.request` is fully typed, so your editor surfaces the exact fields. `ctx.deny` is also exported as `denyPiToolCall(reason)`.
181 +
182 +## Next
183 +
184 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/providers/vercel.mdx
+11 -21
@@ -4,7 +4,7 @@ description: Build an agent with Vercel AI SDK and enable it to use 1000+ tools
4 keywords: [ai sdk, vercel]
5 ---
6
7 -The Vercel AI SDK provider transforms Composio tools into Vercel's [tool format](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling) with built-in execution — no manual agentic loop needed.
7 +The Vercel AI SDK provider transforms Composio tools into Vercel's [tool format](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling) with built-in execution, so you don't write a manual agentic loop. Each wrapped tool carries its own `execute` function, and the AI SDK calls it for you.
8
9 <Steps>
10 <Step>
@@ -31,7 +31,7 @@ ANTHROPIC_API_KEY=xxxxxxxxx
31 <Step>
32 **Create session and run**
33
34 -The Vercel provider is **agentic** — tools include an `execute` function, so the AI SDK handles tool calls automatically via [`stopWhen`](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling).
34 +The Vercel provider is **agentic**: tools include an `execute` function, so the AI SDK handles tool calls automatically. Set [`stopWhen`](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling) to cap how many tool-calling steps a run can take.
35
36 ```typescript
37 import { anthropic } from "@ai-sdk/anthropic";
@@ -57,32 +57,22 @@ console.log(text);
57 </Step>
58 </Steps>
59
60 -## Multi-turn chat
60 +## Provider specifics
61
62 -For multi-turn apps, create the session once and reuse it across requests with `composio.use()`:
62 +**Strict mode.** Some models reject tool schemas that contain optional parameters. Pass `strict: true` to the provider to drop every non-required property from each tool's input schema before it reaches the AI SDK:
63
64 ```typescript
65 // @noErrors
66 -import { anthropic } from "@ai-sdk/anthropic";
66 import { Composio } from "@composio/core";
67 import { VercelProvider } from "@composio/vercel";
69 -import { generateText, stepCountIs } from "ai";
68
71 -const composio = new Composio({ provider: new VercelProvider() });
69 +const composio = new Composio({ provider: new VercelProvider({ strict: true }) });
70 +```
71
73 -// First request — create and store the session ID
74 -const session = await composio.create("user_123");
75 -const sessionId = session.sessionId;
76 -// store sessionId in your database or chat state
72 +<Callout type="info">
73 +The provider converts each Composio tool's JSON Schema to a Zod schema for the AI SDK and normalizes tool arguments, so it still works when a model emits tool input as a JSON string rather than an object.
74 +</Callout>
75
78 -// Subsequent requests — reuse the session
79 -const session = await composio.use(sessionId);
80 -const tools = await session.tools();
76 +## Next
77
82 -const { text } = await generateText({
83 - model: anthropic("claude-opus-4-6"),
84 - tools,
85 - prompt: "What emails did I get today?",
86 - stopWhen: stepCountIs(10),
87 -});
88 -```
78 +<Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope users, tools, and auth, and how to reuse them across requests." />
docs/content/docs/proxy-execute.mdx deleted
-346
@@ -1,346 +0,0 @@
1 ----
2 -title: Proxy execute
3 -description: Call any API endpoint on a toolkit and let Composio inject the authenticated credentials for you
4 -keywords: [proxy, proxy execute, custom api call, raw api, raw request, direct http, linkedin api, google api, microsoft api, curl, bearer token injection, oauth token]
5 -llmGuardrails: "direct-execution"
6 ----
7 -
8 -Proxy execute lets you call any HTTP endpoint on a supported toolkit using a [connected account](/docs/auth-configuration/connected-accounts). Composio injects the authentication (OAuth token, API key, basic auth, etc.) on the server side, so your code never handles raw credentials.
9 -
10 -Use it when you need an endpoint that Composio's predefined tools do not cover, or when you want the flexibility of a raw HTTP call while keeping Composio as the source of truth for user auth.
11 -
12 -<Callout type="info">
13 -Proxy execute is a form of [direct tool execution](/docs/sessions-vs-direct-execution). It bypasses session state, tool schemas, and modifiers. If you are building an agent, prefer [sessions](/docs/configuring-sessions) — use the proxy only for the specific API call that isn't available as a tool.
14 -</Callout>
15 -
16 -## When to use proxy execute
17 -
18 -### 1. Endpoints not covered by a predefined tool
19 -
20 -You need a specific endpoint on a toolkit (for example, an unusual LinkedIn or Notion endpoint) that isn't exposed as a predefined Composio tool. Instead of extracting the raw OAuth token and making the call yourself, send the request through proxy execute and let Composio attach credentials.
21 -
22 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
23 -<Tab value="Python">
24 -```python
25 -# Fetch the authenticated user's LinkedIn profile
26 -response = composio.tools.proxy(
27 - endpoint="/v2/userinfo",
28 - method="GET",
29 - connected_account_id="ca_linkedin_user_123",
30 -)
31 -
32 -print(response["data"])
33 -```
34 -</Tab>
35 -<Tab value="TypeScript">
36 -```typescript
37 -import { Composio } from '@composio/core';
38 -const composio = new Composio({ apiKey: 'your_api_key' });
39 -// ---cut---
40 -// Fetch the authenticated user's LinkedIn profile
41 -const { data } = await composio.tools.proxyExecute({
42 - endpoint: '/v2/userinfo',
43 - method: 'GET',
44 - connectedAccountId: 'ca_linkedin_user_123',
45 -});
46 -
47 -console.log(data);
48 -```
49 -</Tab>
50 -</Tabs>
51 -
52 -### 2. Request shapes a predefined tool cannot express
53 -
54 -AI workflows that talk to Gmail, Drive, Sheets, Outlook, or Teams often need request shapes beyond the pre-built actions — custom query parameters, partial field masks, advanced filters. Proxy execute gives you the full HTTP surface of the upstream API while keeping auth managed by Composio.
55 -
56 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
57 -<Tab value="Python">
58 -```python
59 -# Read a Google Sheet range with custom render options
60 -response = composio.tools.proxy(
61 - endpoint="/v4/spreadsheets/1abc.../values/Sheet1!A1:D100",
62 - method="GET",
63 - connected_account_id="ca_googlesheets_user_123",
64 - parameters=[
65 - {"name": "valueRenderOption", "value": "UNFORMATTED_VALUE", "type": "query"},
66 - {"name": "dateTimeRenderOption", "value": "SERIAL_NUMBER", "type": "query"},
67 - ],
68 -)
69 -
70 -print(response["data"])
71 -```
72 -</Tab>
73 -<Tab value="TypeScript">
74 -```typescript
75 -import { Composio } from '@composio/core';
76 -const composio = new Composio({ apiKey: 'your_api_key' });
77 -// ---cut---
78 -// Read a Google Sheet range with custom render options
79 -const { data } = await composio.tools.proxyExecute({
80 - endpoint: '/v4/spreadsheets/1abc.../values/Sheet1!A1:D100',
81 - method: 'GET',
82 - connectedAccountId: 'ca_googlesheets_user_123',
83 - parameters: [
84 - { name: 'valueRenderOption', value: 'UNFORMATTED_VALUE', in: 'query' },
85 - { name: 'dateTimeRenderOption', value: 'SERIAL_NUMBER', in: 'query' },
86 - ],
87 -});
88 -
89 -console.log(data);
90 -```
91 -</Tab>
92 -</Tabs>
93 -
94 -### 3. Terminal and CLI agents that would otherwise use raw tokens
95 -
96 -Agents running in a terminal often fall back to `curl` calls with a hardcoded bearer token. Replacing that with a call to Composio's proxy endpoint keeps user credentials server-side — no tokens in shell history, env files, or process state.
97 -
98 -```bash
99 -curl --location 'https://backend.composio.dev/api/v3.1/tools/execute/proxy' \
100 - --header "x-api-key: $COMPOSIO_API_KEY" \
101 - --header 'Content-Type: application/json' \
102 - --data '{
103 - "endpoint": "/user/repos",
104 - "method": "GET",
105 - "connected_account_id": "ca_github_user_123",
106 - "parameters": [
107 - { "name": "per_page", "value": "50", "type": "query" },
108 - { "name": "sort", "value": "updated", "type": "query" }
109 - ]
110 - }'
111 -```
112 -
113 -## Quick start
114 -
115 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
116 -<Tab value="Python">
117 -```python
118 -from composio import Composio
119 -
120 -composio = Composio(api_key="your_api_key")
121 -
122 -response = composio.tools.proxy(
123 - endpoint="/repos/composiohq/composio/issues/1",
124 - method="GET",
125 - connected_account_id="ca_github_user_123",
126 - parameters=[
127 - {"name": "Accept", "value": "application/vnd.github.v3+json", "type": "header"},
128 - ],
129 -)
130 -
131 -print(response["status"])
132 -print(response["data"])
133 -```
134 -</Tab>
135 -<Tab value="TypeScript">
136 -```typescript
137 -import { Composio } from '@composio/core';
138 -
139 -const composio = new Composio({ apiKey: 'your_api_key' });
140 -
141 -const { status, data } = await composio.tools.proxyExecute({
142 - endpoint: '/repos/composiohq/composio/issues/1',
143 - method: 'GET',
144 - connectedAccountId: 'ca_github_user_123',
145 - parameters: [
146 - { name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' },
147 - ],
148 -});
149 -
150 -console.log(status);
151 -console.log(data);
152 -```
153 -</Tab>
154 -</Tabs>
155 -
156 -The `endpoint` can be an **absolute URL** (`https://api.example.com/v1/resource`) or a **relative path** (`/v1/resource`). Relative paths are resolved against the toolkit's default base URL — only use the absolute form when calling a host that isn't the toolkit's standard API (for example, a regional Salesforce or Zendesk domain).
157 -
158 -<Callout type="warn">
159 -Proxy execute rejects cross-domain requests. The `endpoint` must resolve to the same domain as the connected account's toolkit (for example, a GitHub connection can only call `api.github.com` paths). Pointing the proxy at an arbitrary third-party host will fail — this is an intentional security boundary, not a quota, so it cannot be bypassed by adjusting the request.
160 -</Callout>
161 -
162 -## Parameters
163 -
164 -| Parameter | Required | Type | Description |
165 -|---|---|---|---|
166 -| `endpoint` | Yes | `string` | Absolute URL or path relative to the toolkit's base URL. |
167 -| `method` | Yes | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE" \| "HEAD"` | HTTP verb. |
168 -| `connected_account_id` / `connectedAccountId` | No | `string` | Which connected account to use for auth. Defaults to the most recent active account for the project. |
169 -| `body` | No | `object` | JSON request body. Used with `POST`, `PUT`, and `PATCH`. |
170 -| `parameters` | No | `Array<{ name, value, type }>` | Extra headers or query parameters. `type` is `"header"` or `"query"` (Python) / `in` is `"header"` or `"query"` (TypeScript). |
171 -| `binary_body` | No | `{ url } \| { base64, content_type? }` | Binary upload payload. Either a URL to fetch or base64-encoded bytes (up to 4 MB). |
172 -
173 -The full schema is documented in the [POST /api/v3.1/tools/execute/proxy](/reference/api-reference/tools/postToolsExecuteProxy) reference.
174 -
175 -### Response shape
176 -
177 -```json
178 -{
179 - "data": { /* parsed JSON body returned by the upstream API */ },
180 - "status": 200,
181 - "headers": { "content-type": "application/json", "...": "..." },
182 - "binary_data": {
183 - "url": "https://...",
184 - "content_type": "application/pdf",
185 - "size": 12345,
186 - "expires_at": "2026-01-01T00:00:00Z"
187 - }
188 -}
189 -```
190 -
191 -`binary_data` is only present when the upstream API returns a binary response (PDFs, images, etc.). See [Binary data support](/docs/changelog/2025/12/30) for details.
192 -
193 -## Common patterns
194 -
195 -### GET with query parameters
196 -
197 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
198 -<Tab value="Python">
199 -```python
200 -response = composio.tools.proxy(
201 - endpoint="/search/issues",
202 - method="GET",
203 - connected_account_id="ca_github_user_123",
204 - parameters=[
205 - {"name": "q", "value": "is:open label:bug repo:composiohq/composio", "type": "query"},
206 - {"name": "per_page", "value": "20", "type": "query"},
207 - ],
208 -)
209 -```
210 -</Tab>
211 -<Tab value="TypeScript">
212 -```typescript
213 -import { Composio } from '@composio/core';
214 -const composio = new Composio({ apiKey: 'your_api_key' });
215 -// ---cut---
216 -const { data } = await composio.tools.proxyExecute({
217 - endpoint: '/search/issues',
218 - method: 'GET',
219 - connectedAccountId: 'ca_github_user_123',
220 - parameters: [
221 - { name: 'q', value: 'is:open label:bug repo:composiohq/composio', in: 'query' },
222 - { name: 'per_page', value: '20', in: 'query' },
223 - ],
224 -});
225 -```
226 -</Tab>
227 -</Tabs>
228 -
229 -### POST with a JSON body
230 -
231 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
232 -<Tab value="Python">
233 -```python
234 -response = composio.tools.proxy(
235 - endpoint="/repos/composiohq/composio/issues",
236 - method="POST",
237 - connected_account_id="ca_github_user_123",
238 - body={
239 - "title": "Found a bug",
240 - "body": "Steps to reproduce: ...",
241 - "labels": ["bug"],
242 - },
243 -)
244 -```
245 -</Tab>
246 -<Tab value="TypeScript">
247 -```typescript
248 -import { Composio } from '@composio/core';
249 -const composio = new Composio({ apiKey: 'your_api_key' });
250 -// ---cut---
251 -const { data } = await composio.tools.proxyExecute({
252 - endpoint: '/repos/composiohq/composio/issues',
253 - method: 'POST',
254 - connectedAccountId: 'ca_github_user_123',
255 - body: {
256 - title: 'Found a bug',
257 - body: 'Steps to reproduce: ...',
258 - labels: ['bug'],
259 - },
260 -});
261 -```
262 -</Tab>
263 -</Tabs>
264 -
265 -### Custom headers
266 -
267 -Add vendor-specific headers (API versions, accept types, correlation IDs) via `parameters` with `type: "header"`.
268 -
269 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
270 -<Tab value="Python">
271 -```python
272 -response = composio.tools.proxy(
273 - endpoint="/crm/v3/objects/contacts",
274 - method="GET",
275 - connected_account_id="ca_hubspot_user_123",
276 - parameters=[
277 - {"name": "Accept", "value": "application/json", "type": "header"},
278 - {"name": "X-Request-Id", "value": "req_abc123", "type": "header"},
279 - {"name": "limit", "value": "100", "type": "query"},
280 - ],
281 -)
282 -```
283 -</Tab>
284 -<Tab value="TypeScript">
285 -```typescript
286 -import { Composio } from '@composio/core';
287 -const composio = new Composio({ apiKey: 'your_api_key' });
288 -// ---cut---
289 -const { data } = await composio.tools.proxyExecute({
290 - endpoint: '/crm/v3/objects/contacts',
291 - method: 'GET',
292 - connectedAccountId: 'ca_hubspot_user_123',
293 - parameters: [
294 - { name: 'Accept', value: 'application/json', in: 'header' },
295 - { name: 'X-Request-Id', value: 'req_abc123', in: 'header' },
296 - { name: 'limit', value: '100', in: 'query' },
297 - ],
298 -});
299 -```
300 -</Tab>
301 -</Tabs>
302 -
303 -<Callout type="warn">
304 -Do not set the `Authorization` header yourself — Composio injects the correct one based on the connected account's auth scheme. Setting it manually will override Composio's credential and usually produces a `401`.
305 -</Callout>
306 -
307 -### Uploading a file
308 -
309 -Use `binary_body` to upload binary content. You can point at a URL that Composio fetches server-side, or inline the bytes as base64.
310 -
311 -```bash
312 -curl --location 'https://backend.composio.dev/api/v3.1/tools/execute/proxy' \
313 - --header "x-api-key: $COMPOSIO_API_KEY" \
314 - --header 'Content-Type: application/json' \
315 - --data '{
316 - "endpoint": "/upload",
317 - "method": "POST",
318 - "connected_account_id": "ca_abc123",
319 - "binary_body": { "url": "https://example.com/report.pdf" }
320 - }'
321 -```
322 -
323 -<Callout type="warn">
324 -`binary_body` posts the file as the request body with a single `Content-Type` header. It does **not** build a `multipart/form-data` payload, so APIs that require multipart uploads (for example, Twitter / X media upload, Slack `files.upload`, some Google upload endpoints) are not supported today. For those, wrap the call in a [session custom tool](/docs/toolkits/custom-tools-and-toolkits) that constructs the multipart body yourself.
325 -</Callout>
326 -
327 -See the [binary data changelog entry](/docs/changelog/2025/12/30) for the full upload and download flow.
328 -
329 -## Error handling
330 -
331 -Proxy execute forwards the upstream response verbatim — `status`, `headers`, and `data` reflect what the toolkit API returned. Check `status` and branch on the common failures.
332 -
333 -| Status | Typical cause | How to resolve |
334 -|---|---|---|
335 -| `400 Bad Request` | Malformed endpoint path, invalid body, or unsupported `method`. | Check the upstream API docs for the expected request shape; proxy execute does not validate upstream schemas. |
336 -| `401 Unauthorized` | The connected account's token expired, was revoked, or is for the wrong project. | Re-authenticate the user, or [import fresh credentials](/docs/importing-existing-connections). Verify the `connected_account_id` belongs to the caller's project. |
337 -| `403 Forbidden` | The user's OAuth scopes or API key permissions do not cover this endpoint. | Update the [auth config scopes](/docs/auth-configuration/custom-auth-configs) and have the user re-consent. For API keys, regenerate with the required permissions. |
338 -| `429 Too Many Requests` | Upstream rate limit (GitHub, Google, etc.). | Honor the `Retry-After` header from the response, back off exponentially, and batch requests where possible. Composio does not retry automatically. |
339 -
340 -## What to read next
341 -
342 -<Cards>
343 - <Card icon={<Terminal />} title="API reference" href="/reference/api-reference/tools/postToolsExecuteProxy" description="Full request and response schema for POST /api/v3.1/tools/execute/proxy" />
344 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="Understand how Composio tools are discovered and executed in sessions" />
345 - <Card icon={<Key />} title="Authentication" href="/docs/authentication" description="How Composio manages OAuth, API keys, and connected accounts" />
346 -</Cards>
docs/content/docs/quickstart.mdx
+6 -460
@@ -4,15 +4,12 @@ description: Build an AI agent with access to 1000+ tools
4 keywords: [tutorial, setup, first agent]
5 ---
6
7 -Build your first AI agent with Composio Tools. You'll create a [session](/docs/how-composio-works) for a user, give your agent access to [tools](/docs/tools-and-toolkits), and let it take action across 1000+ apps.
7 +Build your first AI agent with Composio Tools. You'll create a [session](/docs/how-composio-works) for a user, give your agent access to [tools](/docs/how-composio-works), and let it take action across 1000+ apps.
8
9 <QuickstartFlow>
10
11 <FrameworkOption id="openai-agents" name="OpenAI Agents" logo="/images/providers/openai-logo.svg" logoDark="/images/providers/openai-logo-dark.svg">
12
13 -<IntegrationTabs>
14 -<IntegrationContent value="native">
15 -
13 <Steps>
14 <Step>
15 <StepTitle>Install</StepTitle>
@@ -152,169 +149,10 @@ readline.close();
149 </Step>
150 </Steps>
151
155 -</IntegrationContent>
156 -<IntegrationContent value="mcp">
157 -
158 -<Steps>
159 -<Step>
160 -<StepTitle>Install</StepTitle>
161 -
162 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
163 -<Tab value="Python">
164 -```bash
165 -pip install python-dotenv composio openai-agents
166 -```
167 -</Tab>
168 -<Tab value="TypeScript">
169 -```bash
170 -npm install dotenv @composio/core @openai/agents zod@3
171 -```
172 -</Tab>
173 -</Tabs>
174 -</Step>
175 -
176 -<Step>
177 -<StepTitle>Configure API Keys</StepTitle>
178 -
179 -<Callout type="info">
180 -Get your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings) and `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys).
181 -</Callout>
182 -
183 -```bash title=".env"
184 -COMPOSIO_API_KEY=your_composio_api_key
185 -OPENAI_API_KEY=your_openai_api_key
186 -```
187 -</Step>
188 -
189 -<Step>
190 -<StepTitle>Create session and run agent</StepTitle>
191 -
192 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
193 -<Tab value="Python">
194 -```python
195 -from dotenv import load_dotenv
196 -from composio import Composio
197 -from agents import Agent, Runner, HostedMCPTool, SQLiteSession
198 -
199 -load_dotenv()
200 -
201 -# Initialize Composio
202 -composio = Composio()
203 -
204 -# Create a session for your user
205 -user_id = "user_123"
206 -session = composio.create(user_id=user_id)
207 -
208 -# For multi-turn, store the session ID in your db and reuse instead of calling create() again:
209 -# session_id = session.session_id
210 -# session = composio.use(session_id)
211 -
212 -agent = Agent(
213 - name="Personal Assistant",
214 - instructions="You are a helpful personal assistant. Use Composio tools to take action.",
215 - model="gpt-5.2",
216 - tools=[
217 - HostedMCPTool(
218 - tool_config={
219 - "type": "mcp",
220 - "server_label": "composio",
221 - "server_url": session.mcp.url,
222 - "require_approval": "never",
223 - "headers": session.mcp.headers,
224 - }
225 - )
226 - ],
227 -)
228 -
229 -memory = SQLiteSession(user_id)
230 -
231 -print("""
232 -What task would you like me to help you with?
233 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
234 -(Type 'exit' to exit)
235 -Example tasks:
236 - - 'Summarize my emails from today'
237 - - 'List all open issues on the composio github repository'
238 -""")
239 -
240 -while True:
241 - user_input = input("You: ").strip()
242 - if user_input.lower() == "exit":
243 - break
244 -
245 - print("Assistant: ", end="", flush=True)
246 - result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
247 - print(f"{result.final_output}\n")
248 -```
249 -</Tab>
250 -<Tab value="TypeScript">
251 -```typescript
252 -import "dotenv/config";
253 -import { Composio } from "@composio/core";
254 -import { Agent, run, hostedMcpTool, MemorySession } from "@openai/agents";
255 -import { createInterface } from "readline/promises";
256 -
257 -// Initialize Composio
258 -const composio = new Composio();
259 -
260 -// Create a session for your user
261 -const userId = "user_123";
262 -const session = await composio.create(userId);
263 -
264 -// For multi-turn, store the session ID in your db and reuse instead of calling create() again:
265 -// const sessionId = session.sessionId;
266 -// const session = await composio.use(sessionId);
267 -
268 -const agent = new Agent({
269 - name: "Personal Assistant",
270 - instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
271 - model: "gpt-5.2",
272 - tools: [
273 - hostedMcpTool({
274 - serverLabel: "composio",
275 - serverUrl: session.mcp.url,
276 - headers: session.mcp.headers,
277 - }),
278 - ],
279 -});
280 -
281 -const memory = new MemorySession();
282 -const readline = createInterface({ input: process.stdin, output: process.stdout });
283 -
284 -console.log(`
285 -What task would you like me to help you with?
286 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
287 -(Type 'exit' to exit)
288 -Example tasks:
289 - - 'Summarize my emails from today'
290 - - 'List all open issues on the composio github repository'
291 -`);
292 -
293 -while (true) {
294 - const input = (await readline.question("You: ")).trim();
295 - if (input.toLowerCase() === "exit") break;
296 -
297 - process.stdout.write("Assistant: ");
298 - const result = await run(agent, input, { session: memory });
299 - process.stdout.write(`${result.finalOutput}\n`);
300 -}
301 -readline.close();
302 -```
303 -</Tab>
304 -</Tabs>
305 -</Step>
306 -</Steps>
307 -
308 -</IntegrationContent>
309 -</IntegrationTabs>
310 -
152 </FrameworkOption>
153
154 <FrameworkOption id="claude-agents" name="Claude Agent SDK" logo="/images/providers/anthropic-logo.svg" logoDark="/images/providers/anthropic-logo-dark.svg">
155
315 -<IntegrationTabs>
316 -<IntegrationContent value="native">
317 -
156 <Steps>
157 <Step>
158 <StepTitle>Install</StepTitle>
@@ -478,192 +316,10 @@ readline.close();
316 </Step>
317 </Steps>
318
481 -</IntegrationContent>
482 -<IntegrationContent value="mcp">
483 -
484 -<Steps>
485 -<Step>
486 -<StepTitle>Install</StepTitle>
487 -
488 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
489 -<Tab value="Python">
490 -```bash
491 -pip install python-dotenv composio claude-agent-sdk
492 -```
493 -</Tab>
494 -<Tab value="TypeScript">
495 -```bash
496 -npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
497 -```
498 -</Tab>
499 -</Tabs>
500 -</Step>
501 -
502 -<Step>
503 -<StepTitle>Configure API Keys</StepTitle>
504 -
505 -<Callout type="info">
506 -Get your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys).
507 -</Callout>
508 -
509 -```bash title=".env"
510 -COMPOSIO_API_KEY=your_composio_api_key
511 -ANTHROPIC_API_KEY=your_anthropic_api_key
512 -```
513 -</Step>
514 -
515 -<Step>
516 -<StepTitle>Create session and run agent</StepTitle>
517 -
518 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
519 -<Tab value="Python">
520 -```python
521 -import asyncio
522 -from dotenv import load_dotenv
523 -from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, AssistantMessage, TextBlock, ToolUseBlock
524 -from composio import Composio
525 -
526 -load_dotenv()
527 -
528 -# Initialize Composio
529 -composio = Composio()
530 -
531 -# Create a session for your user
532 -user_id = "user_123"
533 -session = composio.create(user_id=user_id)
534 -
535 -# For multi-turn, store the session ID in your db and reuse instead of calling create() again:
536 -# session_id = session.session_id
537 -# session = composio.use(session_id)
538 -
539 -options = ClaudeAgentOptions(
540 - system_prompt=(
541 - "You are a helpful assistant with access to external tools. "
542 - "Always use the available tools to complete user requests."
543 - ),
544 - mcp_servers={
545 - "composio": {
546 - "type": "http",
547 - "url": session.mcp.url,
548 - "headers": session.mcp.headers,
549 - }
550 - },
551 - permission_mode="bypassPermissions",
552 -)
553 -
554 -async def main():
555 - print("""
556 -What task would you like me to help you with?
557 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
558 -(Type 'exit' to exit)
559 -Example tasks:
560 - - 'Summarize my emails from today'
561 - - 'List all open issues on the composio github repository and create a notion page with the issues'
562 -""")
563 -
564 - async with ClaudeSDKClient(options) as client:
565 - while True:
566 - user_input = input("You: ").strip()
567 - if user_input.lower() == "exit":
568 - break
569 -
570 - await client.query(user_input)
571 - print("Claude: ", end="", flush=True)
572 - async for msg in client.receive_response():
573 - if isinstance(msg, AssistantMessage):
574 - for block in msg.content:
575 - if isinstance(block, ToolUseBlock):
576 - print(f"\n [Using tool: {block.name}]")
577 - elif isinstance(block, TextBlock):
578 - print(block.text, end="", flush=True)
579 - print()
580 -
581 -asyncio.run(main())
582 -```
583 -</Tab>
584 -<Tab value="TypeScript">
585 -```typescript
586 -import "dotenv/config";
587 -import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
588 -import { Composio } from "@composio/core";
589 -import { createInterface } from "readline/promises";
590 -
591 -// Initialize Composio
592 -const composio = new Composio();
593 -
594 -// Create a session for your user
595 -const userId = "user_123";
596 -const session = await composio.create(userId);
597 -
598 -// For multi-turn, store the session ID in your db and reuse instead of calling create() again:
599 -// const sessionId = session.sessionId;
600 -// const session = await composio.use(sessionId);
601 -
602 -const options: Options = {
603 - systemPrompt: `You are a helpful assistant with access to external tools. ` +
604 - `Always use the available tools to complete user requests.`,
605 - mcpServers: {
606 - composio: {
607 - type: "http",
608 - url: session.mcp.url,
609 - headers: session.mcp.headers,
610 - },
611 - },
612 - permissionMode: "bypassPermissions",
613 -};
614 -
615 -const readline = createInterface({ input: process.stdin, output: process.stdout });
616 -
617 -console.log(`
618 -What task would you like me to help you with?
619 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
620 -(Type 'exit' to exit)
621 -Example tasks:
622 - - 'Summarize my emails from today'
623 - - 'List all open issues on the composio github repository and create a Google Sheet with the issues'
624 -`);
625 -
626 -let isFirstQuery = true;
627 -
628 -while (true) {
629 - const input = (await readline.question("You: ")).trim();
630 - if (input.toLowerCase() === "exit") break;
631 -
632 - const queryOptions = isFirstQuery ? options : { ...options, continue: true };
633 - isFirstQuery = false;
634 -
635 - process.stdout.write("Claude: ");
636 - for await (const stream of query({ prompt: input, options: queryOptions })) {
637 - if (stream.type === "assistant") {
638 - for (const block of stream.message.content) {
639 - if (block.type === "tool_use") {
640 - process.stdout.write(`\n [Using tool: ${block.name}]\n`);
641 - } else if (block.type === "text") {
642 - process.stdout.write(block.text);
643 - }
644 - }
645 - }
646 - }
647 - console.log();
648 -}
649 -
650 -readline.close();
651 -```
652 -</Tab>
653 -</Tabs>
654 -</Step>
655 -</Steps>
656 -
657 -</IntegrationContent>
658 -</IntegrationTabs>
659 -
319 </FrameworkOption>
320
321 <FrameworkOption id="vercel-ai" name="Vercel AI SDK" logo="/images/providers/vercel-logo.svg" logoDark="/images/providers/vercel-logo-dark.svg">
322
664 -<IntegrationTabs>
665 -<IntegrationContent value="native">
666 -
323 <Steps>
324 <Step>
325 <StepTitle>Install</StepTitle>
@@ -755,126 +411,16 @@ readline.close();
411 </Step>
412 </Steps>
413
758 -</IntegrationContent>
759 -<IntegrationContent value="mcp">
760 -
761 -<Steps>
762 -<Step>
763 -<StepTitle>Install</StepTitle>
764 -
765 -```bash
766 -npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
767 -```
768 -</Step>
769 -
770 -<Step>
771 -<StepTitle>Configure API Keys</StepTitle>
772 -
773 -<Callout type="info">
774 -Get your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys).
775 -</Callout>
776 -
777 -```bash title=".env"
778 -COMPOSIO_API_KEY=your_composio_api_key
779 -ANTHROPIC_API_KEY=your_anthropic_api_key
780 -```
781 -</Step>
782 -
783 -<Step>
784 -<StepTitle>Create session and run agent</StepTitle>
785 -
786 -```typescript
787 -import "dotenv/config";
788 -import { anthropic } from "@ai-sdk/anthropic";
789 -import { createMCPClient } from "@ai-sdk/mcp";
790 -import { Composio } from "@composio/core";
791 -import { streamText, stepCountIs, type ModelMessage } from "ai";
792 -import { createInterface } from "readline/promises";
793 -
794 -// Initialize Composio
795 -const composio = new Composio();
796 -
797 -// Create a session for your user
798 -const userId = "user_123";
799 -const composioSession = await composio.create(userId);
800 -const { mcp } = composioSession;
801 -
802 -// For multi-turn, store the session ID in your db and reuse instead of calling create() again:
803 -// const sessionId = composioSession.sessionId;
804 -// const composioSession = await composio.use(sessionId);
805 -
806 -// Create an MCP client to connect to Composio
807 -const client = await createMCPClient({
808 - transport: {
809 - type: "http",
810 - url: mcp.url,
811 - headers: mcp.headers,
812 - },
813 -});
814 -const tools = await client.tools();
815 -
816 -const readline = createInterface({ input: process.stdin, output: process.stdout });
817 -
818 -console.log(`
819 -What task would you like me to help you with?
820 -I can use tools like Gmail, GitHub, Linear, Notion, and more.
821 -(Type 'exit' to exit)
822 -Example tasks:
823 - - 'Summarize my emails from today'
824 - - 'List all open issues on the composio github repository'
825 -`);
826 -
827 -const messages: ModelMessage[] = [];
828 -
829 -while (true) {
830 - const input = (await readline.question("You: ")).trim();
831 - if (input.toLowerCase() === "exit") break;
832 -
833 - messages.push({ role: "user", content: input });
834 - process.stdout.write("Assistant: ");
835 -
836 - const result = await streamText({
837 - system: "You are a helpful personal assistant. Use Composio tools to take action.",
838 - model: anthropic("claude-sonnet-4-6"),
839 - messages,
840 - stopWhen: stepCountIs(10),
841 - onStepFinish: (step) => {
842 - for (const toolCall of step.toolCalls) {
843 - process.stdout.write(`\n[Using tool: ${toolCall.toolName}]`);
844 - }
845 - },
846 - tools,
847 - });
848 -
849 - for await (const textPart of result.textStream) {
850 - process.stdout.write(textPart);
851 - }
852 - console.log();
853 -
854 - messages.push(...(await result.response).messages);
855 -}
856 -
857 -await client.close();
858 -readline.close();
859 -```
860 -</Step>
861 -</Steps>
862 -
863 -</IntegrationContent>
864 -</IntegrationTabs>
865 -
414 </FrameworkOption>
415
416 </QuickstartFlow>
417
418 By default, each `composio.create()` call returns a new session with access to all toolkits. Sessions are highly configurable beyond that: [Reusing a session](/docs/how-composio-works#how-sessions-behave) covers storing a session ID and calling `composio.use()` across multi-turn requests, while [Configuring Sessions](/docs/configuring-sessions) covers restricting toolkits, auth configs, and connected accounts.
419
872 -## Next steps
420 +Prefer to connect over the Model Context Protocol instead? Every session also exposes an MCP endpoint. See [Using sessions via MCP](/docs/sessions-via-mcp).
421
874 -<Cards>
875 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Restrict toolkits, set custom auth configs, and select connected accounts" />
876 - <Card icon={<Key />} title="Authenticating Users" href="/docs/authentication" description="Learn how users connect their accounts via Connect Links, OAuth, and API keys" />
877 - <Card icon={<BookOpen />} title="What is a session?" href="/docs/how-composio-works" description="Understand what happens under the hood: sessions, meta tools, and the tool execution lifecycle" />
878 - <Card icon={<Play />} title="Build a chat app" href="/cookbooks/chat-app" description="Full Next.js tutorial: tool discovery, auth, and multi-turn conversations" />
879 -</Cards>
422 +## Next
423
424 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions">
425 + Restrict toolkits, set custom auth configs, and select connected accounts
426 +</Card>
docs/content/docs/sandbox/local.mdx new
+97
@@ -0,0 +1,97 @@
1 +---
2 +title: Local sandbox
3 +experimental: true
4 +description: Run Composio tools in a sandbox you own (your filesystem, your shell, your security boundary), while Composio keeps managed auth and tool discovery.
5 +keywords: [local sandbox, sandbox, workbench, bring your own runtime, code execution, security boundary, run_composio_tool, experimental_createLocalWorkbenchSession]
6 +related:
7 + - title: Local sandbox PR reviewer
8 + href: /examples/local-sandbox-pr-reviewer
9 + description: "A worked example: clone a PR into a sandbox you own and post one grounded review."
10 +---
11 +
12 +A **local sandbox** runs your agent's code in your own infrastructure instead of Composio's hosted [remote sandbox](/docs/sandbox/remote), so code execution never leaves your security boundary.
13 +
14 +<LocalSandboxBoundary />
15 +
16 +## When to use it
17 +
18 +Reach for a local sandbox when:
19 +
20 +- **Sensitive code or data.** The agent runs untrusted code or touches data that can't leave your infrastructure.
21 +- **You already run sandboxes.** You'd rather run agent code in your own VM, container, or CI worker than a hosted runtime.
22 +- **You need your own filesystem and shell.** The task installs packages, runs a build, or shells out to local tools.
23 +
24 +If none of that applies, use the [remote sandbox](/docs/sandbox/remote). It's the same helper surface with no infrastructure to run.
25 +
26 +## Create a local sandbox session
27 +
28 +A local sandbox session is a [session](/docs/how-composio-works) created with the remote sandbox turned off. Set `workbench.enable: false`, then pass the session to `experimental_createLocalWorkbenchSession` (from the `@composio/experimental` package), which returns the two pieces you run yourself.
29 +
30 +```typescript
31 +// @noErrors
32 +import { Composio } from '@composio/core';
33 +import { experimental_createLocalWorkbenchSession } from '@composio/experimental/workbench';
34 +
35 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
36 +
37 +// Create the session with the remote sandbox disabled, so code runs in your box.
38 +const session = await composio.create('user_123', {
39 + toolkits: ['github'],
40 + workbench: { enable: false },
41 +});
42 +
43 +const { helperSource, env } = await experimental_createLocalWorkbenchSession(composio, session);
44 +```
45 +
46 +You get back two things:
47 +
48 +| Field | What it is |
49 +|---|---|
50 +| `helperSource` | A Python helper, as source you write into your sandbox (for example as `composio_helper.py`). It exposes the in-sandbox tool surface the agent calls. |
51 +| `env` | The environment variables that helper needs to reach Composio from inside your box. Pass them to the process you run the agent in. |
52 +
53 +`experimental_createLocalWorkbenchSession` validates that the session is local: it throws if the session has the remote workbench enabled, because the remote sandbox and a local one can't both run for a single session. The session you pass in must have `workbench.enable: false`.
54 +
55 +<Callout>
56 +The API ships under the `experimental_` prefix and the `@composio/experimental/workbench` entry point, so the surface may change in a future release.
57 +</Callout>
58 +
59 +## The helper contract
60 +
61 +`helperSource` is a Python module your agent imports. It exposes the same helpers the [remote sandbox](/docs/sandbox/remote#built-in-helpers) runs, with the same signatures, so the agent calls tools without knowing that execution is local:
62 +
63 +```python
64 +from composio_helper import run_composio_tool, invoke_llm, web_search
65 +
66 +response, error = run_composio_tool(
67 + "GITHUB_GET_A_PULL_REQUEST",
68 + {"owner": "composiohq", "repo": "composio", "pull_number": 1},
69 +)
70 +```
71 +
72 +Every `run_composio_tool` call routes back through the Tool Router under the session's connections, so auth and discovery stay managed.
73 +
74 +Most of the workbench helpers run in a local sandbox today. Only the file helpers, which depend on the managed `/mnt/files` mount, are remote-only:
75 +
76 +| Helper | What it does | Local sandbox |
77 +| --- | --- | --- |
78 +| `run_composio_tool` | Execute any Composio tool | ✅ |
79 +| `invoke_llm` | Call an LLM | ✅ |
80 +| `web_search` | Search the web | ✅ |
81 +| `proxy_execute` | Call a toolkit API directly when no tool exists (needs a proxy-execute-scoped key) | ✅ |
82 +| `upload_local_file` | Upload generated files to storage | ❌ |
83 +| `smart_file_extract` | Extract text from PDFs and images | ❌ |
84 +
85 +If your agent needs one of the file helpers, use the [remote sandbox](/docs/sandbox/remote) for now.
86 +
87 +## Security: the sandbox is your boundary
88 +
89 +The helper reaches Composio with your project `COMPOSIO_API_KEY`, injected into the sandbox through `env`. Any code or output in the sandbox can read it, and that key acts across every connection on the project.
90 +
91 +<Callout type="warn">
92 +The sandbox is your security boundary. Isolate it like anything else holding a project credential, and rotate `COMPOSIO_API_KEY` if a run could have leaked it.
93 +</Callout>
94 +
95 +## Next
96 +
97 +<Card icon={<Database />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope tools, auth, and sandbox state to a user" />
docs/content/docs/sandbox/meta.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "title": "Sandbox (prev Workbench)",
3 + "defaultOpen": true,
4 + "pages": [
5 + "remote",
6 + "local"
7 + ]
8 +}
docs/content/docs/sandbox/remote.mdx new
+122
@@ -0,0 +1,122 @@
1 +---
2 +title: Remote sandbox
3 +description: A persistent Python sandbox where your agent writes code, calls tools programmatically, and processes data
4 +keywords: [sandbox, remote sandbox, workbench, remote execution, bulk operations, data processing]
5 +---
6 +
7 +The **sandbox** is a persistent Python environment where your agent writes and executes code. It has programmatic access to all Composio tools, plus helper functions for calling LLMs, uploading files, and making API requests. State persists across calls within a [session](/docs/how-composio-works). Your agent runs code in it through the `COMPOSIO_REMOTE_WORKBENCH` meta tool, and shell commands through `COMPOSIO_REMOTE_BASH_TOOL`.
8 +
9 +<Callout title="Renamed from workbench">
10 +This feature used to be called the **workbench**. The preferred session config key is now `sandbox`, but `workbench` still works as a fully supported alias, in both SDKs and on the wire. It isn't deprecated, so existing code keeps running unchanged. The `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL` meta tools keep their names.
11 +</Callout>
12 +
13 +## Where it fits
14 +
15 +Use the sandbox when a task is too complex for individual tool calls. Your agent starts with [`SEARCH_TOOLS` to find the right tools, then uses `MULTI_EXECUTE`](/docs/how-composio-works#meta-tools) for straightforward calls. When the task involves bulk operations, data transformations, or multi-step logic, the agent reaches for `COMPOSIO_REMOTE_WORKBENCH` instead.
16 +
17 +<WorkbenchFlow />
18 +
19 +## What the sandbox provides
20 +
21 +### Built-in helpers
22 +
23 +These functions are pre-initialized in every sandbox, so your agent can call them without any setup:
24 +
25 +| Helper | What it does |
26 +|--------|-------------|
27 +| `run_composio_tool` | Execute any Composio tool (e.g., `GMAIL_SEND_EMAIL`, `SLACK_SEND_MESSAGE`) and get structured results |
28 +| `invoke_llm` | Call an LLM for classification, summarization, content generation, or data extraction |
29 +| `upload_local_file` | Upload generated files (reports, CSVs, images) to cloud storage and get a download URL |
30 +| `proxy_execute` | Make direct API calls to connected services when no pre-built tool exists |
31 +| `web_search` | Search the web and return results for research or data enrichment |
32 +| `smart_file_extract` | Extract text from PDFs, images, and other file formats in the sandbox |
33 +
34 +### Libraries
35 +
36 +The sandbox ships with common packages pre-installed: `pandas`, `numpy`, `matplotlib`, `Pillow`, `PyTorch`, and `reportlab`. Beyond these, the sandbox maintains a list of supported packages and their dependencies. If the agent uses a package that isn't already installed, the sandbox installs it automatically.
37 +
38 +### Error correction
39 +
40 +The sandbox corrects common mistakes in the code your agent generates. For example, if a script accesses `result["apiKey"]` but the actual field name is `api_key`, the sandbox resolves the mismatch instead of failing.
41 +
42 +### Persistent state
43 +
44 +The sandbox runs as a persistent Jupyter notebook. Variables, imports, files, and in-memory state from one call are available in the next.
45 +
46 +### Compute tier
47 +
48 +Sandboxes default to `standard` (1 vCPU, 1 GB RAM). For heavier workloads (large dataframes, ML preprocessing, or big bulk operations), pick a larger tier when creating the session via `sandbox.sandboxSize` (TypeScript) or `sandbox.sandbox_size` (Python).
49 +
50 +Available tiers:
51 +
52 +- `standard` (1 vCPU, 1 GB RAM)
53 +- `medium` (2 vCPU, 2 GB)
54 +- `large` (4 vCPU, 4 GB)
55 +- `xlarge` (8 vCPU, 8 GB)
56 +
57 +Larger tiers require `@composio/core` ≥ `0.8.1` or `composio` ≥ `0.12.1`. See [Configuring sessions → Sandbox compute tier](/docs/configuring-sessions#sandbox-compute-tier) for examples.
58 +
59 +<Callout type="info">
60 +**Pricing:** Sandboxes are not billed today. Composio plans to begin billing for sandbox usage soon (metered by tier and runtime).
61 +</Callout>
62 +
63 +## Files and mounts
64 +
65 +The sandbox has a persistent file mount at `/mnt/files/`. Code running in the sandbox reads and writes files there, and the mount survives sandbox restarts: changing the [compute tier](#compute-tier) recreates the sandbox and clears in-memory state, but `/mnt/files/` persists.
66 +
67 +Move files between your app and the mount with `session.experimental.files`. Upload an input file and the agent reads it at `/mnt/files/<path>`. When the agent writes a result, download it from your app.
68 +
69 +<Callout>
70 +The files API ships under `session.experimental`, so the surface may change in a future release.
71 +</Callout>
72 +
73 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
74 +<Tab value="Python">
75 +```python
76 +session = composio.create("user_123")
77 +
78 +# Upload a local file; the sandbox sees it at /mnt/files/sales.csv
79 +uploaded = session.experimental.files.upload("./sales.csv")
80 +print(uploaded.sandbox_mount_prefix, uploaded.mount_relative_path)
81 +# /mnt/files sales.csv
82 +
83 +# After the agent writes a result in the sandbox, download it
84 +report = session.experimental.files.download("/report.pdf")
85 +report.save("./report.pdf")
86 +```
87 +</Tab>
88 +<Tab value="TypeScript">
89 +```typescript
90 +import { Composio } from '@composio/core';
91 +const composio = new Composio({ apiKey: 'your_api_key' });
92 +// ---cut---
93 +const session = await composio.create("user_123");
94 +
95 +// Upload a local file; the sandbox sees it at /mnt/files/sales.csv
96 +const uploaded = await session.experimental.files.upload("./sales.csv");
97 +console.log(uploaded.sandboxMountPrefix, uploaded.mountRelativePath);
98 +// /mnt/files sales.csv
99 +
100 +// After the agent writes a result in the sandbox, download it
101 +const report = await session.experimental.files.download("/report.pdf");
102 +await report.save("./report.pdf");
103 +```
104 +</Tab>
105 +</Tabs>
106 +
107 +The mount exposes four methods:
108 +
109 +| Method | What it does |
110 +|---|---|
111 +| `upload(input, options?)` | Upload from a local path, URL, `File`, or buffer. Returns a `RemoteFile`. |
112 +| `list(options?)` | List files under `path` on the mount, with `cursor` and `limit` pagination. |
113 +| `download(path, options?)` | Fetch a file from the mount as a `RemoteFile`. |
114 +| `delete(path, options?)` | Remove a file or directory from the mount. |
115 +
116 +A `RemoteFile` carries the file's bytes and a presigned `downloadUrl`. Read it with `text()` or `buffer()`, or write it to disk with `save(path)`. Its `expiresAt` is when that download link expires, not a TTL on the file: the mount itself has no expiry you set.
117 +
118 +Every file lives on the session's default `files` mount, surfaced at `/mnt/files/`. Each method takes a `mountId` to address a mount by ID, but there's no SDK call to create custom mounts today, so you'll normally work with `files`.
119 +
120 +## Next
121 +
122 +<Card icon={<Terminal />} title="Local sandbox" href="/docs/sandbox/local" description="Run the same tool calls in a sandbox you own, while Composio keeps managed auth and discovery." />
docs/content/docs/sessions-via-mcp.mdx new
+170
@@ -0,0 +1,170 @@
1 +---
2 +title: Using sessions via MCP
3 +description: Connect any MCP-compatible client to a Composio session
4 +keywords: [mcp, model context protocol, sessions, remote server, hosted mcp]
5 +---
6 +
7 +By default Composio gives your agent **tools it can call directly**. Composio formats them as function schemas for your framework through a [provider package](/docs/providers). That's what the [Quickstart](/docs/quickstart) uses, and it's the right choice for most agents.
8 +
9 +If you'd rather connect over the [Model Context Protocol](https://modelcontextprotocol.io), every session also exposes a hosted MCP endpoint. This is useful when you want to plug a session into an MCP-native client like Claude Desktop, Cursor, or any framework's MCP transport. No provider package required.
10 +
11 +## The MCP endpoint
12 +
13 +Opt into MCP by passing `mcp: true` when you create the session. The session then exposes its hosted MCP server. Read the URL and headers off `session.mcp`:
14 +
15 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
16 +<Tab value="Python">
17 +```python
18 +from composio import Composio
19 +
20 +composio = Composio()
21 +session = composio.create(user_id="user_123", mcp=True)
22 +
23 +mcp_url = session.mcp.url
24 +mcp_headers = session.mcp.headers
25 +```
26 +</Tab>
27 +<Tab value="TypeScript">
28 +```typescript
29 +// @noErrors
30 +import { Composio } from "@composio/core";
31 +
32 +const composio = new Composio();
33 +const session = await composio.create("user_123", { mcp: true });
34 +
35 +const mcpUrl = session.mcp.url;
36 +const mcpHeaders = session.mcp.headers;
37 +```
38 +</Tab>
39 +</Tabs>
40 +
41 +You don't need a provider package to use the MCP endpoint, so you can drop it from your `Composio()` setup if MCP is all you need.
42 +
43 +<Callout type="info">
44 +Resuming a stored session? Pass the same flag, `composio.use(sessionId, { mcp: true })` (TypeScript) or `composio.use(session_id, mcp=True)` (Python), to surface `session.mcp` on the reused session.
45 +</Callout>
46 +
47 +<Callout type="info">
48 +The MCP endpoint and `session.tools()` are backed by the same session. Toolkits, auth configs, and connected accounts you set when [configuring the session](/docs/configuring-sessions) apply to both.
49 +</Callout>
50 +
51 +## A single URL for a fixed set of tools
52 +
53 +Combine `mcp: true` with the [direct-tools preset](/docs/configuring-sessions) to get one MCP URL that serves exactly the tools you list, with no search or meta tools in front of them. This is the closest equivalent to a classic hosted MCP server scoped to a handful of tools.
54 +
55 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
56 +<Tab value="Python">
57 +```python
58 +from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
59 +
60 +composio = Composio()
61 +
62 +session = composio.create(
63 + user_id="user_123",
64 + toolkits=["gmail"],
65 + tools={"gmail": {"enable": ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"]}},
66 + session_preset=SESSION_PRESET_DIRECT_TOOLS,
67 + mcp=True,
68 +)
69 +
70 +# A single MCP URL that exposes just these two tools
71 +print(session.mcp.url)
72 +```
73 +</Tab>
74 +<Tab value="TypeScript">
75 +```typescript
76 +// @noErrors
77 +import { Composio, SessionPreset } from "@composio/core";
78 +
79 +const composio = new Composio();
80 +
81 +const session = await composio.create("user_123", {
82 + toolkits: ["gmail"],
83 + tools: { gmail: { enable: ["GMAIL_FETCH_EMAILS", "GMAIL_CREATE_EMAIL_DRAFT"] } },
84 + sessionPreset: SessionPreset.DIRECT_TOOLS,
85 + mcp: true,
86 +});
87 +
88 +// A single MCP URL that exposes just these two tools
89 +console.log(session.mcp.url);
90 +```
91 +</Tab>
92 +</Tabs>
93 +
94 +Any MCP client pointed at that URL sees only `GMAIL_FETCH_EMAILS` and `GMAIL_CREATE_EMAIL_DRAFT`. See [Configuring Sessions](/docs/configuring-sessions) for the full set of toolkit, tool, and auth filters.
95 +
96 +## Wire it into your framework
97 +
98 +Pass `session.mcp.url` and `session.mcp.headers` to your framework's MCP client.
99 +
100 +<Tabs items={['OpenAI Agents (Python)', 'Claude Agent SDK (Python)', 'Vercel AI SDK (TypeScript)']}>
101 +<Tab value="OpenAI Agents (Python)">
102 +```python
103 +from agents import Agent, HostedMCPTool
104 +
105 +agent = Agent(
106 + name="Assistant",
107 + tools=[
108 + HostedMCPTool(
109 + tool_config={
110 + "type": "mcp",
111 + "server_label": "composio",
112 + "server_url": session.mcp.url,
113 + "headers": session.mcp.headers,
114 + "require_approval": "never",
115 + }
116 + )
117 + ],
118 +)
119 +```
120 +</Tab>
121 +<Tab value="Claude Agent SDK (Python)">
122 +```python
123 +from claude_agent_sdk import ClaudeAgentOptions
124 +
125 +options = ClaudeAgentOptions(
126 + mcp_servers={
127 + "composio": {
128 + "type": "http",
129 + "url": session.mcp.url,
130 + "headers": session.mcp.headers,
131 + }
132 + },
133 +)
134 +```
135 +</Tab>
136 +<Tab value="Vercel AI SDK (TypeScript)">
137 +```typescript
138 +// @noErrors
139 +import { Composio } from "@composio/core";
140 +import { createMCPClient } from "@ai-sdk/mcp";
141 +
142 +const composio = new Composio();
143 +const { mcp } = await composio.create("user_123", { mcp: true });
144 +
145 +const client = await createMCPClient({
146 + transport: {
147 + type: "http",
148 + url: mcp.url,
149 + headers: mcp.headers,
150 + },
151 +});
152 +const tools = await client.tools();
153 +```
154 +</Tab>
155 +</Tabs>
156 +
157 +## Trade-offs
158 +
159 +MCP is the more portable option. Any MCP-compatible client connects with just a URL, and it's supported across more frameworks and apps (Claude Desktop, Cursor, the OpenAI Responses API, and others) without a provider package.
160 +
161 +The trade-off is that the MCP client talks to Composio's server directly, so anything the SDK does *around* tool execution doesn't apply:
162 +
163 +- **Tool-call modifiers don't run.** `beforeExecute` / `afterExecute` hooks and `modifySchema` transforms live in the SDK's execution path. Over MCP the client executes tools against the server and bypasses them, so you can't intercept, reshape, log, or gate calls the way you can with tools your agent calls directly.
164 +- **Session-bound custom tools and toolkits don't work.** Tools created with `createCustomTool` / `createCustomToolkit` run in your process. The MCP server only exposes Composio's hosted tools, so your local custom tools aren't available over the endpoint.
165 +
166 +If you need any of those, call tools directly through a [provider](/docs/providers) instead of over MCP.
167 +
168 +## Next
169 +
170 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Restrict toolkits, set custom auth configs, and select connected accounts" />
docs/content/docs/sessions-vs-direct-execution.mdx
+12 -12
@@ -2,11 +2,12 @@
2 title: Sessions vs Direct Execution
3 description: When to use session-based meta tools vs direct tool fetching and execution
4 keywords: [session, direct execution, tool router, meta tools, architecture, decision]
5 +legacy: true
6 ---
7
7 -**Sessions** give your agent [meta tools](/docs/tools-and-toolkits#meta-tools). The agent discovers which app tools to use, authenticates users, and executes tools at runtime through these meta tools.
8 +A **session** is the runtime context Composio creates for one of your users with `composio.create(userId)`. It ties together the user, available toolkits, auth, and connected accounts. By default it gives your agent [meta tools](/docs/how-composio-works#meta-tools) so the agent discovers which app tools to use, authenticates users, and executes tools at runtime.
9
9 -**Direct execution** gives your code specific tool schemas. You decide which tools to fetch, manage auth yourself, and call `tools.execute()` directly.
10 +**Direct execution** skips the session. Your code fetches specific tool schemas, manages auth itself, and calls `tools.execute()` directly.
11
12 Use sessions unless you need full control over which tools are available and when they run.
13
@@ -16,16 +17,18 @@ Use sessions unless you need full control over which tools are available and whe
17 | **Context cost** | Only meta tools in context, app tools loaded on demand | Every tool schema you select is loaded upfront |
18 | **Guidance** | Search returns recommended steps and common pitfalls alongside schemas | You get tool schemas only |
19 | **Memory** | Meta tools share context across calls, storing discovered IDs and relationships | You manage state between calls |
19 -| **Auth** | [In-chat](/docs/authenticating-users/in-chat-authentication): agent prompts the user to connect when needed. Also supports [manual](/docs/authenticating-users/manually-authenticating) | You build the auth flow with [connect links](/docs/tools-direct/authenticating-tools) |
20 -| **[Workbench](/docs/workbench)** | Built in, large responses offloaded automatically | Not available |
20 +| **Auth** | [In-chat](/docs/authentication#in-chat-authentication): agent prompts the user to connect when needed. Also supports [manual](/docs/manually-authenticating) | You build the auth flow with [connect links](/docs/tools-direct/authenticating-tools) |
21 +| **[Sandbox](/docs/sandbox/remote)** | Built in, large responses offloaded automatically | Not available |
22 | **Human approval** | You configure approval rules on the session. Harder to intercept individual calls since tools are discovered dynamically | You intercept before each call in your code |
23 | **Latency** | Multiple LLM turns (search, then execute) | Single call |
24
24 -Sessions are configurable. You can [enable or disable specific toolkits](/docs/toolkits/enable-and-disable-toolkits), set [auth configs](/docs/auth-configuration/custom-auth-configs) for white-labeled OAuth, and pin specific [connected accounts](/docs/configuring-sessions#account-selection). See [Configuring Sessions](/docs/configuring-sessions) for the full list.
25 +Sessions are configurable. [Restrict toolkits](/docs/configuring-sessions), set [auth configs](/docs/auth-configuration/custom-auth-configs) for white-labeled OAuth, and pin [connected accounts](/docs/configuring-sessions#account-selection). See [Configuring Sessions](/docs/configuring-sessions) for the full list.
26 +
27 +Sessions aren't all-or-nothing. With the [direct tools preset](/docs/configuring-sessions#direct-tools-preset), a session returns a fixed set of tools directly from `session.tools()` with no search or meta tools, so the agent sees exactly the tools you list while you keep session auth, connected accounts, and the sandbox. It's the middle ground between runtime discovery and direct execution.
28
29 ## Sessions
30
28 -`composio.create()` returns [meta tools](/docs/tools-and-toolkits#meta-tools):
31 +`composio.create()` returns [meta tools](/docs/how-composio-works#meta-tools):
32
33 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
34 <Tab value="Python">
@@ -75,7 +78,7 @@ Agent: "Created issue #42 on your-org/your-repo"
78 ```
79
80 <Callout>
78 -`session.tools()` returns **meta tools** (COMPOSIO_SEARCH_TOOLS, etc.), not app tools (GMAIL_SEND_EMAIL, etc.). The agent discovers app tools at runtime through search. For app tools directly, use direct execution.
81 +`session.tools()` returns **meta tools** (`COMPOSIO_SEARCH_TOOLS`, etc.), not app tools (`GMAIL_SEND_EMAIL`, etc.). The agent discovers app tools at runtime through search. To work with app tools directly, use direct execution.
82 </Callout>
83
84 ### Configuration
@@ -182,9 +185,6 @@ With direct execution, you manage [auth configs](/docs/auth-configuration/custom
185
186 See the [migration guide](/docs/migration-guide/direct-to-sessions). Auth configs and connected accounts carry over.
187
185 -## Next steps
188 +## Next
189
187 -<Cards>
188 - <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, and connected accounts" />
189 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="How sessions discover and execute tools at runtime" />
190 -</Cards>
190 +<Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Toolkits, auth configs, and connected accounts" />
docs/content/docs/setting-up-triggers/creating-triggers.mdx
+65 -201
@@ -1,183 +1,45 @@
1 ---
2 title: Creating triggers
3 -description: Create trigger instances via the dashboard or SDK
3 +description: Activate a trigger for a user so events start flowing
4 keywords: [triggers, create trigger, trigger config]
5 ---
6
7 -Create a trigger to start receiving events. A trigger watches for a specific event (e.g., `GITHUB_COMMIT_EVENT`) on a specific user's connected account. For an overview of how triggers work, see [Triggers](/docs/triggers).
7 +A trigger watches for one event (like `GITHUB_COMMIT_EVENT`) on one user's connected account. Create one, and events start flowing to your [subscription or webhook URL](/docs/setting-up-triggers/subscribing-to-events). For the bigger picture, see [Triggers](/docs/triggers).
8
9 -<Callout type="info" title="Prerequisites">
10 -- An [auth config](/docs/authentication#how-composio-manages-authentication) for the toolkit you want to monitor
11 -- A connected account for the user whose events you want to capture
12 -- A [webhook subscription](/docs/setting-up-triggers/subscribing-to-events) on the project, so events have somewhere to land
13 -</Callout>
9 +The user needs a [connected account](/docs/authentication) for the toolkit you want to monitor. See [Authentication](/docs/authentication) if you haven't set that up.
10
15 -You can create triggers using the [SDK](#using-the-sdk) or the Composio [dashboard](#using-the-dashboard). Some webhook triggers also need a webhook endpoint configured first — covered in [Configuring the webhook endpoint](#configuring-the-webhook-endpoint) below.
11 +## Inspect the trigger type
12
17 -## Configuring the webhook endpoint
13 +Each trigger type declares the config it needs. Check it before you create, so you pass the right fields.
14
19 -Some webhook triggers require a webhook endpoint registered with the provider before they can fire. With Composio-managed OAuth, this is already done for you. You only run the steps below when you bring your own OAuth app and the trigger type's `requires_webhook_endpoint_setup` flag is `true`.
20 -
21 -Each OAuth app you bring gets its own ingress URL within a project:
22 -
23 -```
24 -https://backend.composio.dev/api/v3.1/webhook_ingress/{toolkit_slug}/{we_xxx}/trigger_event
25 -```
26 -
27 -A single OAuth app can serve at most one Composio project: providers accept only one callback URL per OAuth app, and each ingress URL routes to a single project. In return, every project becomes its own webhook tenant — with:
28 -
29 -- **Its own ingress rate limit and backpressure budget**
30 -- **Project-scoped credentials** — the signing secret and app-level token you provide are stored against this project alone, never shared across projects. Repeat verification handshakes are rejected after the endpoint is verified, so the signing secret can't be silently swapped by a forged challenge.
31 -- **Clean fan-out** — events reach only that project's trigger instances
32 -- **Per-project metering**
33 -
34 -Every inbound event is signature-checked at ingress before any trigger fires:
35 -
36 -- **HMAC-SHA256** for Slack, **Ed25519** or shared-token matching for other providers
37 -- **Timestamp replay protection** — when the provider signs a request timestamp, requests outside the allowed skew window are rejected
38 -- **Unsigned or tampered requests** are rejected with `400` at ingress, so third parties can't spoof events onto your triggers
39 -
40 -<Callout type="warn">
41 -**Sharing one OAuth app across projects?** Consolidate to a single project or register separate OAuth apps per project before continuing.
42 -</Callout>
43 -
44 -The walkthrough below uses Slack as the example and walks through the [Webhook Endpoints API](/reference/api-reference/webhook-endpoints). For setup notes specific to each toolkit, see its FAQ section — e.g., [Slack](/toolkits/slack), [Notion](/toolkits/notion).
45 -
46 -### Step 1: Discover what credentials the endpoint needs
47 -
48 -Call the schema endpoint for the toolkit. The `setup_fields` in the response tell you exactly what to collect from the provider's app dashboard.
49 -
50 -```bash
51 -curl "https://backend.composio.dev/api/v3.1/webhook_endpoints/schema?toolkit_slug=slack" \
52 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
53 -```
54 -
55 -Sample response:
56 -
57 -```json
58 -{
59 - "toolkit_slug": "slack",
60 - "setup_fields": {
61 - "webhook_signing_secret": {
62 - "display_name": "Signing Secret",
63 - "description": "Webhook request signing secret from your Slack app dashboard",
64 - "is_required": true,
65 - "is_secret": true
66 - },
67 - "app_token": {
68 - "display_name": "App-Level Token",
69 - "description": "Slack xapp- token with authorizations:read scope for event authorization",
70 - "is_required": true,
71 - "is_secret": true
72 - }
73 - }
74 -}
75 -```
76 -
77 -### Step 2: Create the endpoint
78 -
79 -```bash
80 -curl -X POST "https://backend.composio.dev/api/v3.1/webhook_endpoints" \
81 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
82 - -H "Content-Type: application/json" \
83 - -d '{
84 - "toolkit_slug": "slack",
85 - "client_id": "<YOUR_OAUTH_CLIENT_ID>"
86 - }'
87 -```
88 -
89 -Sample response:
90 -
91 -```json
92 -{
93 - "id": "we_abc123",
94 - "toolkit_slug": "slack",
95 - "client_id": "<YOUR_OAUTH_CLIENT_ID>",
96 - "webhook_url": "https://backend.composio.dev/api/v3.1/webhook_ingress/slack/we_abc123/trigger_event",
97 - "data": null,
98 - "created_at": "2026-04-24T10:00:00.000Z"
99 -}
100 -```
101 -
102 -Hold on to two values from the response: `id` (used as `<ENDPOINT_ID>` below) and `webhook_url` (you'll paste this into the provider's app dashboard in step 4). The call is **idempotent per `(toolkit_slug, client_id)` within a project** — calling it again with the same pair returns the existing endpoint without rotating the URL or wiping the secret.
103 -
104 -### Step 3: Store the credentials returned by the schema
105 -
106 -`PATCH` all the fields the schema returned in a single request. For Slack, that's the signing secret and (when needed) the app-level token together:
107 -
108 -```bash
109 -curl -X PATCH "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
110 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
111 - -H "Content-Type: application/json" \
112 - -d '{
113 - "data": {
114 - "webhook_signing_secret": "<SIGNING_SECRET>",
115 - "app_token": "xapp-..."
116 - }
117 - }'
118 -```
119 -
120 -For Slack, the credentials come from:
121 -
122 -- **Signing secret** — Slack app → Basic Information → App Credentials → Signing Secret.
123 -- **App-level token** — Slack app → Basic Information → App-Level Tokens, with scope `authorizations:read`. Required for direct messages, private channels, and reactions; omit it if you only need public-channel events.
124 -
125 -<Callout type="warn">
126 -**Store the credentials before you switch the provider's callback URL in step 4.** If the provider posts to the URL without a secret on the endpoint, every request fails with `400`, and the provider may auto-disable the endpoint after a window of consecutive failures (Slack: ~36 hours).
127 -</Callout>
128 -
129 -### Step 4: Point the provider's app dashboard at the URL
130 -
131 -Paste the `webhook_url` from step 2 into the provider's app dashboard:
132 -
133 -- **Slack** → Event Subscriptions → Request URL
134 -- **Notion** → Webhook Endpoints (in the integration's settings)
135 -
136 -For providers that issue a verification challenge on save (Slack `url_verification`, Notion's verification token, and so on), Composio responds automatically — no handshake code on your side. Once the provider accepts the URL, continue to [Using the SDK](#using-the-sdk) to create your trigger.
137 -
138 -### Updating an endpoint
139 -
140 -To rotate the signing secret or update any single field, `PATCH` it (other fields are preserved):
141 -
142 -```bash
143 -curl -X PATCH "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
144 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
145 - -H "Content-Type: application/json" \
146 - -d '{ "data": { "webhook_signing_secret": "<NEW_SECRET>" } }'
147 -```
148 -
149 -To **replace** `data` wholesale (any field you don't include is cleared), `POST` to the same URL:
150 -
151 -```bash
152 -curl -X POST "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
153 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
154 - -H "Content-Type: application/json" \
155 - -d '{ "data": { "webhook_signing_secret": "<NEW_SECRET>", "app_token": "<NEW_APP_TOKEN>" } }'
156 -```
157 -
158 -The `webhook_url` is immutable for the lifetime of the endpoint — rotating the signing secret on the provider side is a `PATCH` on the existing endpoint, not a new one.
15 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
16 + <Tab value="Python">
17 +```python
18 +from composio import Composio
19
160 -To inspect a single endpoint:
20 +composio = Composio()
21
162 -```bash
163 -curl "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
164 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
22 +trigger_type = composio.triggers.get_type("GITHUB_COMMIT_EVENT")
23 +print(trigger_type.config)
24 +# {"properties": {"owner": {...}, "repo": {...}}, "required": ["owner", "repo"]}
25 ```
26 + </Tab>
27 + <Tab value="TypeScript">
28 +```typescript
29 +import { Composio } from '@composio/core';
30
167 -To list every endpoint in the current project:
31 +const composio = new Composio();
32
169 -```bash
170 -curl "https://backend.composio.dev/api/v3.1/webhook_endpoints" \
171 - -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
33 +const triggerType = await composio.triggers.getType('GITHUB_COMMIT_EVENT');
34 +console.log(triggerType.config);
35 +// {"properties": {"owner": {...}, "repo": {...}}, "required": ["owner", "repo"]}
36 ```
37 + </Tab>
38 +</Tabs>
39
174 -## Using the SDK
175 -
176 -Before creating a trigger, inspect the trigger type to see what configuration it requires. Then create the trigger with the required config.
40 +## Create the trigger
41
178 -<Callout>
179 -When you pass a `user_id`, the SDK automatically finds the user's connected account for the relevant toolkit. If the user has multiple connected accounts for the same toolkit, it uses the most recently created one. You can also pass a `connected_account_id`/`connectedAccountId` directly if you need more control.
180 -</Callout>
42 +Pass the user, the trigger slug, and the config the type requires.
43
44 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
45 <Tab value="Python">
@@ -187,12 +49,8 @@ from composio import Composio
49 composio = Composio()
50 user_id = "user-id-123435"
51
190 -# Check what configuration is required
191 -trigger_type = composio.triggers.get_type("GITHUB_COMMIT_EVENT")
192 -print(trigger_type.config)
193 -# Returns: {"properties": {"owner": {...}, "repo": {...}}, "required": ["owner", "repo"]}
194 -
195 -# Create trigger with the required config
52 +# The user needs a connected account for this toolkit before this runs.
53 +# Set it up first. See /docs/authentication.
54 trigger = composio.triggers.create(
55 slug="GITHUB_COMMIT_EVENT",
56 user_id=user_id,
@@ -208,45 +66,51 @@ import { Composio } from '@composio/core';
66 const composio = new Composio();
67 const userId = 'user-id-123435';
68
211 -// Check what configuration is required
212 -const triggerType = await composio.triggers.getType("GITHUB_COMMIT_EVENT");
213 -console.log(triggerType.config);
214 -// Returns: {"properties": {"owner": {...}, "repo": {...}}, "required": ["owner", "repo"]}
215 -
216 -// Create trigger with the required config
217 -const trigger = await composio.triggers.create(
218 - userId,
219 - 'GITHUB_COMMIT_EVENT',
220 - {
221 - triggerConfig: {
222 - owner: 'your-repo-owner',
223 - repo: 'your-repo-name'
224 - }
225 - }
226 -);
69 +// The user needs a connected account for this toolkit before this runs.
70 +// Set it up first. See /docs/authentication.
71 +const trigger = await composio.triggers.create(userId, 'GITHUB_COMMIT_EVENT', {
72 + triggerConfig: { owner: 'your-repo-owner', repo: 'your-repo-name' },
73 +});
74 console.log(`Trigger created: ${trigger.triggerId}`);
75 ```
76 </Tab>
77 </Tabs>
78
232 -<Callout>
233 -Trigger instances default to the `'latest'` toolkit version. If your code parses trigger payloads programmatically against a fixed schema, you can pin a specific version at SDK initialization. See [Toolkit Versioning](/docs/tools-direct/toolkit-versioning#choosing-between-latest-and-a-pinned-version) for details.
234 -</Callout>
79 +You only pass a `user_id`. The SDK looks up that user's connected account for the toolkit automatically.
80
236 -## Using the dashboard
81 +### Targeting a specific connected account
82 +
83 +If a user has more than one connected account for the toolkit, the SDK uses the most recently created one. Pass a connected account ID to pick exactly which account the trigger watches.
84 +
85 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
86 + <Tab value="Python">
87 +```python
88 +trigger = composio.triggers.create(
89 + slug="GITHUB_COMMIT_EVENT",
90 + user_id=user_id,
91 + connected_account_id="ca_def456",
92 + trigger_config={"owner": "your-repo-owner", "repo": "your-repo-name"},
93 +)
94 +```
95 + </Tab>
96 + <Tab value="TypeScript">
97 +```typescript
98 +import { Composio } from '@composio/core';
99 +const composio = new Composio();
100 +const userId = 'user-id-123435';
101 +// ---cut---
102 +const trigger = await composio.triggers.create(userId, 'GITHUB_COMMIT_EVENT', {
103 + connectedAccountId: 'ca_def456',
104 + triggerConfig: { owner: 'your-repo-owner', repo: 'your-repo-name' },
105 +});
106 +```
107 + </Tab>
108 +</Tabs>
109
238 -1. Navigate to [Auth Configs](https://dashboard.composio.dev/~/project/auth-configs) and select the auth config for the relevant toolkit
239 -2. Navigate to **Active Triggers** and click **Create Trigger**
240 -3. Select the connected account for which you want to create a trigger
241 -4. Choose a trigger type and fill in the required configuration
242 -5. Click **Create Trigger**
110 +Trigger instances default to the `'latest'` toolkit version. If you parse payloads against a fixed schema, [pin a version](/docs/tools-direct/toolkit-versioning#choosing-between-latest-and-a-pinned-version) at SDK initialization.
111
244 -<Video src="/videos/triggers-creation.mp4" caption="Creating a GitHub Star Added trigger from the dashboard" />
112 +That's it. The trigger is active. Next, [receive its events](/docs/setting-up-triggers/subscribing-to-events).
113
246 -## What to read next
114 +## Next
115
248 -<Cards>
249 - <Card icon={<Plug />} title="Subscribing to events" href="/docs/setting-up-triggers/subscribing-to-events" description="Set up the webhook subscription URL Composio delivers events to" />
250 - <Card icon={<ShieldCheck />} title="Verifying webhooks" href="/docs/webhook-verification" description="Validate webhook signatures so you know payloads came from Composio" />
251 - <Card icon={<Wrench />} title="Managing triggers" href="/docs/setting-up-triggers/managing-triggers" description="List, enable, disable, and delete trigger instances" />
252 -</Cards>
116 +<Card icon={<Plug />} title="Receiving events" href="/docs/setting-up-triggers/subscribing-to-events" description="Get trigger events locally with the SDK or in production over your webhook URL" />
docs/content/docs/setting-up-triggers/custom-oauth-webhooks.mdx new
+166
@@ -0,0 +1,166 @@
1 +---
2 +title: Custom OAuth webhooks
3 +description: Register Composio's ingress URL when you bring your own OAuth app
4 +keywords: [webhook endpoint, ingress, byo oauth, custom oauth, requires_webhook_endpoint_setup]
5 +---
6 +
7 +This page is only for **realtime triggers where you bring your own OAuth app**. With Composio-managed OAuth, ingress is already set up and you can skip this entirely. Create the trigger and events flow.
8 +
9 +Some providers only deliver events to URLs you've registered on your OAuth app. When you bring your own app, you register Composio's ingress URL there once, so events can reach Composio. You need this only when the trigger type's `requires_webhook_endpoint_setup` flag is `true`.
10 +
11 +Each OAuth app you bring gets its own ingress URL within a project:
12 +
13 +```
14 +https://backend.composio.dev/api/v3.1/webhook_ingress/{toolkit_slug}/{we_xxx}/trigger_event
15 +```
16 +
17 +A single OAuth app can serve at most one Composio project: providers accept only one callback URL per OAuth app, and each ingress URL routes to a single project. In return, every project becomes its own webhook tenant, with:
18 +
19 +- **Its own ingress rate limit and backpressure budget**
20 +- **Project-scoped credentials**: the signing secret and app-level token you provide are stored against this project alone, never shared across projects. Repeat verification handshakes are rejected after the endpoint is verified, so the signing secret can't be silently swapped by a forged challenge.
21 +- **Clean fan-out**: events reach only that project's trigger instances
22 +- **Per-project metering**
23 +
24 +Every inbound event is signature-checked at ingress before any trigger fires:
25 +
26 +- **HMAC-SHA256** for Slack, **Ed25519** or shared-token matching for other providers
27 +- **Timestamp replay protection**: when the provider signs a request timestamp, requests outside the allowed skew window are rejected
28 +- **Unsigned or tampered requests** are rejected with `400` at ingress, so third parties can't spoof events onto your triggers
29 +
30 +<Callout type="warn">
31 +**Sharing one OAuth app across projects?** Consolidate to a single project or register separate OAuth apps per project before continuing.
32 +</Callout>
33 +
34 +The walkthrough below uses Slack as the example and the [Webhook Endpoints API](/reference/api-reference/webhook-endpoints). For setup notes specific to each toolkit, see its FAQ section, for example [Slack](/toolkits/slack) or [Notion](/toolkits/notion).
35 +
36 +## Step 1: Discover what credentials the endpoint needs
37 +
38 +Call the schema endpoint for the toolkit. The `setup_fields` in the response tell you exactly what to collect from the provider's app dashboard.
39 +
40 +```bash
41 +curl "https://backend.composio.dev/api/v3.1/webhook_endpoints/schema?toolkit_slug=slack" \
42 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
43 +```
44 +
45 +Sample response:
46 +
47 +```json
48 +{
49 + "toolkit_slug": "slack",
50 + "setup_fields": {
51 + "webhook_signing_secret": {
52 + "display_name": "Signing Secret",
53 + "description": "Webhook request signing secret from your Slack app dashboard",
54 + "is_required": true,
55 + "is_secret": true
56 + },
57 + "app_token": {
58 + "display_name": "App-Level Token",
59 + "description": "Slack xapp- token with authorizations:read scope for event authorization",
60 + "is_required": true,
61 + "is_secret": true
62 + }
63 + }
64 +}
65 +```
66 +
67 +## Step 2: Create the endpoint
68 +
69 +```bash
70 +curl -X POST "https://backend.composio.dev/api/v3.1/webhook_endpoints" \
71 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
72 + -H "Content-Type: application/json" \
73 + -d '{
74 + "toolkit_slug": "slack",
75 + "client_id": "<YOUR_OAUTH_CLIENT_ID>"
76 + }'
77 +```
78 +
79 +Sample response:
80 +
81 +```json
82 +{
83 + "id": "we_abc123",
84 + "toolkit_slug": "slack",
85 + "client_id": "<YOUR_OAUTH_CLIENT_ID>",
86 + "webhook_url": "https://backend.composio.dev/api/v3.1/webhook_ingress/slack/we_abc123/trigger_event",
87 + "data": null,
88 + "created_at": "2026-04-24T10:00:00.000Z"
89 +}
90 +```
91 +
92 +Hold on to two values from the response: `id` (used as `<ENDPOINT_ID>` below) and `webhook_url` (you'll paste this into the provider's app dashboard in step 4). The call is **idempotent per `(toolkit_slug, client_id)` within a project**. Calling it again with the same pair returns the existing endpoint without rotating the URL or wiping the secret.
93 +
94 +## Step 3: Store the credentials returned by the schema
95 +
96 +`PATCH` all the fields the schema returned in a single request. For Slack, that's the signing secret and (when needed) the app-level token together:
97 +
98 +```bash
99 +curl -X PATCH "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
100 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
101 + -H "Content-Type: application/json" \
102 + -d '{
103 + "data": {
104 + "webhook_signing_secret": "<SIGNING_SECRET>",
105 + "app_token": "xapp-..."
106 + }
107 + }'
108 +```
109 +
110 +For Slack, the credentials come from:
111 +
112 +- **Signing secret**: Slack app → Basic Information → App Credentials → Signing Secret.
113 +- **App-level token**: Slack app → Basic Information → App-Level Tokens, with scope `authorizations:read`. Required for direct messages, private channels, and reactions. Omit it if you only need public-channel events.
114 +
115 +<Callout type="warn">
116 +**Store the credentials before you switch the provider's callback URL in step 4.** If the provider posts to the URL without a secret on the endpoint, every request fails with `400`, and the provider may auto-disable the endpoint after a window of consecutive failures (Slack: ~36 hours).
117 +</Callout>
118 +
119 +## Step 4: Point the provider's app dashboard at the URL
120 +
121 +Paste the `webhook_url` from step 2 into the provider's app dashboard:
122 +
123 +- **Slack** → Event Subscriptions → Request URL
124 +- **Notion** → Webhook Endpoints (in the integration's settings)
125 +
126 +For providers that issue a verification challenge on save (Slack `url_verification`, Notion's verification token, and so on), Composio responds automatically, with no handshake code on your side. Once the provider accepts the URL, go [create your trigger](/docs/setting-up-triggers/creating-triggers).
127 +
128 +## Updating an endpoint
129 +
130 +To rotate the signing secret or update any single field, `PATCH` it (other fields are preserved):
131 +
132 +```bash
133 +curl -X PATCH "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
134 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
135 + -H "Content-Type: application/json" \
136 + -d '{ "data": { "webhook_signing_secret": "<NEW_SECRET>" } }'
137 +```
138 +
139 +To **replace** `data` wholesale (any field you don't include is cleared), `POST` to the same URL:
140 +
141 +```bash
142 +curl -X POST "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
143 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>" \
144 + -H "Content-Type: application/json" \
145 + -d '{ "data": { "webhook_signing_secret": "<NEW_SECRET>", "app_token": "<NEW_APP_TOKEN>" } }'
146 +```
147 +
148 +The `webhook_url` is immutable for the lifetime of the endpoint. Rotating the signing secret on the provider side is a `PATCH` on the existing endpoint, not a new one.
149 +
150 +To inspect a single endpoint:
151 +
152 +```bash
153 +curl "https://backend.composio.dev/api/v3.1/webhook_endpoints/<ENDPOINT_ID>" \
154 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
155 +```
156 +
157 +To list every endpoint in the current project:
158 +
159 +```bash
160 +curl "https://backend.composio.dev/api/v3.1/webhook_endpoints" \
161 + -H "x-api-key: <YOUR_COMPOSIO_API_KEY>"
162 +```
163 +
164 +## Next
165 +
166 +<Card icon={<Plug />} title="Creating triggers" href="/docs/setting-up-triggers/creating-triggers" description="Activate a trigger for a user so events start flowing" />
docs/content/docs/setting-up-triggers/managing-triggers.mdx
+4 -23
@@ -4,9 +4,11 @@ description: List, enable, disable, and delete trigger instances
4 keywords: [manage triggers, enable, disable, delete, discover]
5 ---
6
7 +After a trigger is created, you manage it over its lifecycle: list active instances, pause one with `disable()`, bring it back with `enable()`, or remove it for good with `delete()`.
8 +
9 ## Listing active triggers
10
9 -List trigger instances that have been created. Results are cursor-paginated.
11 +List the trigger instances you've created. Results are cursor-paginated.
12
13 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
14 <Tab value="Python">
@@ -20,7 +22,7 @@ active = composio.triggers.list_active(
22 )
23
24 for trigger in active.items:
23 - print(f"{trigger.id} ({trigger.trigger_name}) - disabled_at={trigger.disabled_at}")
25 + print(f"{trigger.id} ({trigger.trigger_name}) - disabled: {trigger.disabled_at is not None}")
26
27 # Paginate with cursor
28 if active.next_cursor:
@@ -85,19 +87,6 @@ await composio.triggers.enable('ti_abcd123');
87 </Tab>
88 </Tabs>
89
88 -You can also toggle triggers from the dashboard:
89 -
90 -1. Go to [Auth Configs](https://dashboard.composio.dev/~/project/auth-configs) and select your auth config
91 -2. Navigate to **Active Triggers**
92 -3. Toggle the trigger on or off
93 -
94 -<Figure
95 - src="/images/trigger-enable-disable.png"
96 - alt="Enable/disable triggers from the dashboard"
97 - caption="Enable/disable triggers from the dashboard"
98 - size="lg"
99 -/>
100 -
90 ## Deleting triggers
91
92 Permanently remove a trigger instance:
@@ -121,11 +110,3 @@ await composio.triggers.delete('ti_abcd123');
110 <Callout type="warn">
111 Deleting a trigger is permanent. Use `disable()` instead to temporarily stop receiving events.
112 </Callout>
124 -
125 -## What to read next
126 -
127 -<Cards>
128 - <Card icon={<ShieldCheck />} title="Verifying webhooks" href="/docs/webhook-verification" description="Validate webhook signatures to ensure payloads are authentic" />
129 - <Card icon={<Zap />} title="Creating triggers" href="/docs/setting-up-triggers/creating-triggers" description="Create trigger instances to start receiving events from connected apps" />
130 - <Card icon={<Zap />} title="Subscribing to events" href="/docs/setting-up-triggers/subscribing-to-events" description="Set up webhooks or SDK subscriptions to handle trigger events" />
131 -</Cards>
docs/content/docs/setting-up-triggers/meta.json
+3 -2
@@ -1,8 +1,9 @@
1 {
2 - "title": "Using Triggers",
2 + "title": "Setting up triggers",
3 "pages": [
4 "creating-triggers",
5 "subscribing-to-events",
6 - "managing-triggers"
6 + "managing-triggers",
7 + "custom-oauth-webhooks"
8 ]
9 }
docs/content/docs/setting-up-triggers/subscribing-to-events.mdx
+287 -121
@@ -1,101 +1,187 @@
1 ---
2 -title: Subscribing to events
3 -description: Receive trigger events via webhooks or SDK subscriptions
4 -keywords: [webhooks, subscribe, events, webhook payload, V3]
2 +title: Receiving events
3 +description: Get trigger events locally with an SDK subscription or in production over your webhook URL
4 +keywords: [webhooks, subscribe, parse, events, webhook payload, realtime, polling]
5 ---
6
7 -## Webhooks
7 +Once a trigger is active, its events come to you as the same payload, whether you're testing locally or running in production. Develop against your local handler first, then point Composio at your production URL when you ship.
8
9 -Webhooks are the recommended way to receive trigger events in production. To start receiving events, create a webhook subscription with your endpoint URL and select which event types you want to receive. You can subscribe to any combination:
9 +## Receive events locally
10
11 -| Event type | Description |
12 -|------------|-------------|
13 -| `composio.trigger.message` | Fired when a trigger receives data from an external service. |
14 -| `composio.connected_account.expired` | Fired when a connected account expires and needs re-authentication. See [Subscribing to connection expiry events](/docs/subscribing-to-connection-expiry-events). |
15 -| `composio.trigger.disabled` | **Fired when** Composio automatically disables a trigger — expired connection, webhook refresh failure, or unhealthy polling. **Not fired when** you disable a trigger through the manage API or deactivate its connected account via `PATCH /api/v3/connected_accounts/{id}/status`. |
11 +While developing, you want trigger events on your machine. The best option forwards them to the real webhook handler you'll run in production, so you test the exact path (including `parse()` and signature verification) before you ship.
12
17 -Set your webhook URL in the [dashboard settings](https://dashboard.composio.dev/~/project/settings/webhook) or via the [Webhook Subscriptions API](/reference/api-reference/webhook-subscriptions):
13 +### Quick look with `subscribe()`
14 +
15 +`subscribe()` streams events straight to your process over a WebSocket, with no webhook URL, no tunnel, and no signing. It's the fastest way to eyeball what a trigger sends, but it bypasses your real webhook handler. Use it only for basic prototyping; for anything you intend to ship, forward events to your handler with one of the options below.
16 +
17 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
18 + <Tab value="Python">
19 +```python
20 +from composio import Composio
21 +
22 +composio = Composio()
23 +
24 +subscription = composio.triggers.subscribe()
25 +
26 +@subscription.handle(trigger_id="your_trigger_id")
27 +def handle_event(data):
28 + print(f"Event received: {data}")
29 +
30 +subscription.wait_forever()
31 +```
32 + </Tab>
33 + <Tab value="TypeScript">
34 +```typescript
35 +import { Composio } from '@composio/core';
36 +
37 +const composio = new Composio();
38 +
39 +await composio.triggers.subscribe(
40 + data => {
41 + console.log('Event received:', data);
42 + },
43 + { triggerId: 'your_trigger_id' }
44 +);
45 +```
46 + </Tab>
47 +</Tabs>
48 +
49 +Filter the stream by `triggerId`, `triggerSlug`, `connectedAccountId`, `toolkits`, or `userId`, or pass no filters to receive every trigger event in the project.
50 +
51 +### Forward to your local handler with the CLI (recommended)
52 +
53 +The Composio CLI streams realtime events and forwards each one to your local URL, signed exactly like production. No public URL, no tunnel, and it runs your real handler (and [`parse()`](#handling-events)) end to end.
54
55 ```bash
20 -curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
21 - -H "X-API-KEY: <your-composio-api-key>" \
22 - -H "Content-Type: application/json" \
23 - -d '{
24 - "webhook_url": "https://example.com/webhook",
25 - "enabled_events": ["composio.trigger.message"]
26 - }'
56 +composio dev triggers listen --forward "http://localhost:8000/webhooks/composio"
57 ```
58
29 -<Callout>
30 -Your webhook endpoint must be publicly accessible — Composio's outbound IPs are dynamic, so IP allowlisting and private/VPN-only endpoints will not work. Use [signature verification](/docs/webhook-verification) to authenticate payloads instead.
31 -</Callout>
59 +Events are signed with `COMPOSIO_WEBHOOK_SECRET` if it's set, otherwise the CLI prints a generated secret to verify against. Filter the stream with `--toolkits`, `--trigger-slug`, or `--trigger-id`, and tee events to a file with `--out events.jsonl`.
60
33 -<Callout type="warn">
34 -The response includes a `secret` for [verifying webhook signatures](/docs/webhook-verification). Store it securely.
35 -</Callout>
61 +### Cloudflare Tunnel
62
37 -### Handling events
63 +Expose your local server with [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/), no account needed for quick runs:
64
39 -All events arrive at the same endpoint. Route on the `type` field to handle each event type:
65 +```bash
66 +cloudflared tunnel --url http://localhost:8000
67 +```
68
41 -<Callout>
42 -[Inspect the payload schema](#inspecting-trigger-payload-schemas) for a trigger before writing your handler. See [Webhook payload (V3)](#webhook-payload-v3) for the full event structure.
43 -</Callout>
69 +Register the printed `trycloudflare.com` URL as your [webhook URL](#receive-events-in-production), then events reach your handler at `http://localhost:8000/webhooks/composio`.
70 +
71 +### ngrok
72 +
73 +Expose your local server with [ngrok](https://ngrok.com):
74 +
75 +```bash
76 +ngrok http 8000
77 +```
78 +
79 +Register the printed `ngrok-free.app` URL as your [webhook URL](#receive-events-in-production) the same way.
80 +
81 +## Receive events in production
82 +
83 +Register your webhook URL once per project. Composio then `POST`s every trigger event to it. Set it from the SDK:
84
85 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
86 <Tab value="Python">
87 ```python
48 -from composio import WebhookEventType
88 +from composio import Composio
89
50 -@app.post("/webhook")
51 -async def webhook_handler(request: Request):
52 - payload = await request.json()
53 - event_type = payload.get("type")
90 +composio = Composio()
91 +
92 +subscription = composio.triggers.set_webhook_subscription(
93 + webhook_url="https://your-app.com/webhooks/composio",
94 +)
95 +print(f"Delivering events to {subscription['webhook_url']}")
96 +# Store subscription['secret'] to verify signatures
97 +```
98 + </Tab>
99 + <Tab value="TypeScript">
100 +```typescript
101 +// @noErrors
102 +import { Composio } from '@composio/core';
103 +
104 +const composio = new Composio();
105 +
106 +const subscription = await composio.triggers.setWebhookSubscription({
107 + webhookUrl: 'https://your-app.com/webhooks/composio',
108 +});
109 +console.log(`Delivering events to ${subscription.webhookUrl}`);
110 +// Store subscription.secret to verify signatures
111 +```
112 + </Tab>
113 +</Tabs>
114 +
115 +Your webhook endpoint must be publicly reachable. Composio's outbound IPs are dynamic, so IP allowlists and VPN-only endpoints won't work. Authenticate payloads with [signature verification](#verifying-signatures) instead.
116 +
117 +## Handling events
118
55 - if event_type == WebhookEventType.TRIGGER_MESSAGE:
56 - trigger_slug = payload["metadata"]["trigger_slug"]
57 - event_data = payload["data"]
119 +In your handler, pass the incoming request to `parse()`. It returns the typed, normalized payload. Pass `verifySecret` and it verifies the signature first, so one call both authenticates and parses.
120 +
121 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
122 + <Tab value="Python">
123 +```python
124 +import os
125 +from composio import Composio
126
59 - if trigger_slug == "GITHUB_COMMIT_EVENT":
60 - print(f"New commit by {event_data['author']}: {event_data['message']}")
127 +composio = Composio()
128
62 - # Handle connected account expired events
129 +@app.post("/webhooks/composio")
130 +async def webhook_handler(request: Request):
131 + # On async frameworks (FastAPI) read the raw body and pass body=/headers=.
132 + # On sync frameworks (Flask, Django) you can pass the request directly.
133 + # Use the raw body so the signature verifies. Omit verify_secret to skip it.
134 + result = composio.triggers.parse(
135 + body=await request.body(),
136 + headers=request.headers,
137 + verify_secret=os.environ["COMPOSIO_WEBHOOK_SECRET"],
138 + )
139 +
140 + if result["raw_payload"]["type"] == "composio.trigger.message":
141 + event = result["payload"]
142 + if event["trigger_slug"] == "GITHUB_COMMIT_EVENT":
143 + data = event["payload"]
144 + print(f"New commit by {data['author']}: {data['message']}")
145
146 return {"status": "ok"}
147 ```
148 </Tab>
149 <Tab value="TypeScript">
150 ```typescript
69 -type NextApiRequest = { body: any };
70 -type NextApiResponse = { status: (code: number) => { json: (data: any) => void } };
71 -// ---cut---
72 -export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
73 - const payload = req.body;
151 +// @noErrors
152 +import { Composio } from '@composio/core';
153
75 - if (payload.type === 'composio.trigger.message') {
76 - const triggerSlug = payload.metadata.trigger_slug;
77 - const eventData = payload.data;
154 +const composio = new Composio();
155
79 - if (triggerSlug === 'GITHUB_COMMIT_EVENT') {
80 - console.log(`New commit by ${eventData.author}: ${eventData.message}`);
156 +// Next.js App Router, Hono, or any Fetch-style handler
157 +export async function POST(request: Request) {
158 + // parse() takes a Fetch Request (shown) or an Express-style { body, headers }.
159 + // Pass the raw body so the signature verifies; omit verifySecret to skip it.
160 + const result = await composio.triggers.parse(request, {
161 + verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
162 + });
163 +
164 + if (result.rawPayload.type === 'composio.trigger.message') {
165 + const event = result.payload;
166 + if (event.triggerSlug === 'GITHUB_COMMIT_EVENT') {
167 + const data = event.payload;
168 + console.log(`New commit by ${data.author}: ${data.message}`);
169 }
170 }
171
84 - // Handle connected account expired events
85 -
86 - res.status(200).json({ status: 'ok' });
172 + return Response.json({ status: 'ok' });
173 }
174 ```
175 </Tab>
176 </Tabs>
177
92 -<Callout type="warn">
93 -Always [verify webhook signatures](/docs/webhook-verification) in production to ensure payloads are authentic.
178 +<Callout>
179 +Composio delivers other project events (like [connection expiry](/docs/authentication#connection-lifecycle)) to this same URL. `parse()` returns those too. Route on `result.payload.triggerSlug` and ignore what you don't handle.
180 </Callout>
181
182 ### Inspecting trigger payload schemas
183
98 -Each trigger type defines the schema of event data it sends. Use `get_type()`/`getType()` to inspect it before writing your handler:
184 +Each trigger type declares the shape of the `data` it sends. Inspect it before you write your handler:
185
186 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
187 <Tab value="Python">
@@ -106,7 +192,7 @@ composio = Composio()
192
193 trigger_type = composio.triggers.get_type("GITHUB_COMMIT_EVENT")
194 print(trigger_type.payload)
109 -# Returns: {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
195 +# {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
196 ```
197 </Tab>
198 <Tab value="TypeScript">
@@ -115,18 +201,28 @@ import { Composio } from '@composio/core';
201
202 const composio = new Composio();
203
118 -const triggerType = await composio.triggers.getType("GITHUB_COMMIT_EVENT");
204 +const triggerType = await composio.triggers.getType('GITHUB_COMMIT_EVENT');
205 console.log(triggerType.payload);
120 -// Returns: {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
206 +// {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
207 ```
208 </Tab>
209 </Tabs>
210
125 -The payload schema tells you what fields will be in the `data` object of the webhook event.
211 +From the CLI, inspect a single trigger type's config and payload schema:
212 +
213 +```bash
214 +composio triggers info "GITHUB_COMMIT_EVENT"
215 +```
216 +
217 +Or generate typed stubs for your project (scope to the toolkits you use with `--toolkits`), so your handler is type-checked against the trigger's payload:
218 +
219 +```bash
220 +composio generate --toolkits github # auto-detects TypeScript or Python
221 +```
222
127 -### Webhook payload (V3)
223 +### Webhook payload shape
224
129 -New organizations receive V3 payloads by default. V3 separates event metadata from the actual event data:
225 +Every trigger event arrives in the same envelope. `metadata` tells you where the event came from; `data` holds the event itself, in the shape the trigger type declares.
226
227 ```json
228 {
@@ -149,88 +245,158 @@ New organizations receive V3 payloads by default. V3 separates event metadata fr
245 }
246 ```
247
248 +| `metadata` field | What it tells you |
249 +|-------|-------------------|
250 +| `trigger_id` | Which trigger instance fired this event |
251 +| `trigger_slug` | The trigger type (for example `GITHUB_COMMIT_EVENT`) |
252 +| `connected_account_id` | Which connected account it belongs to |
253 +| `user_id` | Which user it's for |
254 +| `auth_config_id` | Which auth config was used |
255 +
256 <Callout>
153 -See [webhook payload versions](/docs/webhook-verification#webhook-payload-versions) for V2 and V1 formats.
257 +This is the V3 payload, the default for new organizations. See [webhook payload versions](#webhook-payload-versions) for V2 and V1.
258 </Callout>
259
156 -## Testing locally
260 +## Verifying signatures
261
158 -### SDK subscriptions
262 +Composio signs every webhook request. `parse({ verifySecret })` verifies the signature for you (and `verifyWebhook()` does the same at a lower level), so most handlers need nothing more. You only need this section if you're **not** using the Composio SDK.
263
160 -Subscribe to trigger events directly through the SDK without setting up a webhook endpoint. Uses WebSockets under the hood.
264 +<Callout>
265 +Store the webhook secret securely as `COMPOSIO_WEBHOOK_SECRET`. Fetch it from the [webhook subscription](/reference/api-reference/webhook-subscriptions/getWebhookSubscriptionsById) any time, or [rotate it](/reference/api-reference/webhook-subscriptions/postWebhookSubscriptionsByIdRotateSecret) if it leaks.
266 +</Callout>
267 +
268 +Every request includes `webhook-signature`, `webhook-id`, and `webhook-timestamp` headers. Compute `HMAC-SHA256` over `{webhook-id}.{webhook-timestamp}.{rawBody}` with your secret and compare it against the signature:
269
270 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
271 <Tab value="Python">
272 ```python
165 -from composio import Composio
166 -
167 -composio = Composio()
168 -
169 -subscription = composio.triggers.subscribe()
170 -
171 -@subscription.handle(trigger_id="your_trigger_id")
172 -def handle_event(data):
173 - print(f"Event received: {data}")
174 -
175 -subscription.wait_forever()
273 +import hmac
274 +import hashlib
275 +import base64
276 +import json
277 +import os
278 +
279 +def verify_webhook(webhook_id: str, webhook_timestamp: str, body: str, signature: str) -> dict:
280 + secret = os.getenv("COMPOSIO_WEBHOOK_SECRET", "")
281 + signing_string = f"{webhook_id}.{webhook_timestamp}.{body}"
282 + expected = base64.b64encode(
283 + hmac.new(secret.encode(), signing_string.encode(), hashlib.sha256).digest()
284 + ).decode()
285 + received = signature.split(",", 1)[1] if "," in signature else signature
286 + if not hmac.compare_digest(expected, received):
287 + raise ValueError("Invalid webhook signature")
288 +
289 + payload = json.loads(body)
290 + # V3 payload
291 + return {
292 + "trigger_slug": payload["metadata"]["trigger_slug"],
293 + "data": payload["data"],
294 + }
295 ```
296 </Tab>
297 <Tab value="TypeScript">
298 ```typescript
180 -import { Composio } from '@composio/core';
181 -
182 -const composio = new Composio();
299 +import crypto from 'crypto';
300 +// ---cut---
301 +function verifyWebhook(
302 + webhookId: string,
303 + webhookTimestamp: string,
304 + body: string,
305 + signature: string
306 +) {
307 + const secret = process.env.COMPOSIO_WEBHOOK_SECRET ?? '';
308 + const signingString = `${webhookId}.${webhookTimestamp}.${body}`;
309 + const expected = crypto
310 + .createHmac('sha256', secret)
311 + .update(signingString)
312 + .digest('base64');
313 + const received = signature.split(',')[1] ?? signature;
314 + if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))) {
315 + throw new Error('Invalid webhook signature');
316 + }
317
184 -await composio.triggers.subscribe(
185 - (data) => {
186 - console.log('Event received:', data);
187 - },
188 - { triggerId: 'your_trigger_id' }
189 -);
318 + const payload = JSON.parse(body);
319 + // V3 payload
320 + return {
321 + triggerSlug: payload.metadata.trigger_slug,
322 + data: payload.data,
323 + };
324 +}
325 ```
326 </Tab>
327 </Tabs>
328
194 -### Using ngrok
329 +<Callout>
330 +Reject requests whose `webhook-timestamp` is too old to block replays. The SDK's `parse()` and `verifyWebhook()` enforce a 300-second tolerance by default; pass `tolerance` to change it, or `0` to disable the check.
331 +</Callout>
332
196 -To test the full webhook flow locally, use [ngrok](https://ngrok.com) to expose your local server:
333 +## Webhook payload versions
334
198 -```bash
199 -ngrok http 8000
200 -```
335 +`parse()` and `verifyWebhook()` auto-detect the version. If you process payloads manually, here are the formats:
336
202 -Then use the ngrok URL as your webhook endpoint:
337 +<Tabs items={['V3 (default)', 'V2 (legacy)', 'V1 (legacy)']}>
338 + <Tab value="V3 (default)">
339 +Metadata is separated from event data. New organizations receive V3 payloads by default.
340
204 -```bash
205 -curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
206 - -H "X-API-KEY: <your-composio-api-key>" \
207 - -H "Content-Type: application/json" \
208 - -d '{
209 - "webhook_url": "https://your-ngrok-url.ngrok-free.app/webhook",
210 - "enabled_events": ["composio.trigger.message"]
211 - }'
341 +```json
342 +{
343 + "id": "msg_abc123",
344 + "type": "composio.trigger.message",
345 + "metadata": {
346 + "log_id": "log_abc123",
347 + "trigger_slug": "GITHUB_COMMIT_EVENT",
348 + "trigger_id": "ti_xyz789",
349 + "connected_account_id": "ca_def456",
350 + "auth_config_id": "ac_xyz789",
351 + "user_id": "user-id-123435"
352 + },
353 + "data": {
354 + "commit_sha": "a1b2c3d",
355 + "message": "fix: resolve null pointer",
356 + "author": "jane"
357 + },
358 + "timestamp": "2026-01-15T10:30:00Z"
359 +}
360 ```
361 + </Tab>
362 + <Tab value="V2 (legacy)">
363 +Metadata fields are mixed into the `data` object alongside event data.
364
214 -Events will now be forwarded to your local server at `http://localhost:8000/webhook`.
215 -
216 -## Identifying trigger events
217 -
218 -Every webhook event includes a `metadata` object that tells you exactly where it came from:
219 -
220 -| Field | What it tells you |
221 -|-------|-------------------|
222 -| `metadata.trigger_id` | Which trigger instance fired this event |
223 -| `metadata.trigger_slug` | The type of trigger (e.g., `GITHUB_COMMIT_EVENT`) |
224 -| `metadata.connected_account_id` | Which connected account it belongs to |
225 -| `metadata.user_id` | Which user it's for |
226 -| `metadata.auth_config_id` | Which auth config was used |
227 -
228 -Use `trigger_id` to match events to a specific trigger instance, or `trigger_slug` to handle all events of a certain type. These fields can also be passed as filters when using [SDK subscriptions](#sdk-subscriptions).
365 +```json
366 +{
367 + "type": "github_commit_event",
368 + "data": {
369 + "commit_sha": "a1b2c3d",
370 + "message": "fix: resolve null pointer",
371 + "author": "jane",
372 + "connection_id": "ca_def456",
373 + "connection_nano_id": "cn_abc123",
374 + "trigger_nano_id": "tn_xyz789",
375 + "trigger_id": "ti_xyz789",
376 + "user_id": "user-id-123435"
377 + },
378 + "timestamp": "2026-01-15T10:30:00Z",
379 + "log_id": "log_abc123"
380 +}
381 +```
382 + </Tab>
383 + <Tab value="V1 (legacy)">
384 +```json
385 +{
386 + "trigger_name": "github_commit_event",
387 + "trigger_id": "ti_xyz789",
388 + "connection_id": "ca_def456",
389 + "payload": {
390 + "commit_sha": "a1b2c3d",
391 + "message": "fix: resolve null pointer",
392 + "author": "jane"
393 + },
394 + "log_id": "log_abc123"
395 +}
396 +```
397 + </Tab>
398 +</Tabs>
399
230 -## What to read next
400 +## Next
401
232 -<Cards>
233 - <Card icon={<Zap />} title="Managing triggers" href="/docs/setting-up-triggers/managing-triggers" description="List, enable, disable, and delete trigger instances" />
234 - <Card icon={<ShieldCheck />} title="Verifying webhooks" href="/docs/webhook-verification" description="Validate webhook signatures to ensure payloads are authentic" />
235 - <Card icon={<Zap />} title="Troubleshooting triggers" href="/docs/troubleshooting/triggers" description="Not receiving events? Check common trigger issues and how to fix them" />
236 -</Cards>
402 +<Card icon={<Zap />} title="Managing triggers" href="/docs/setting-up-triggers/managing-triggers" description="List, enable, disable, and delete trigger instances" />
docs/content/docs/shared-connections.mdx renamed
+77 -180
@@ -1,39 +1,30 @@
1 ---
2 -title: "Shared Connections (Experimental)"
2 +title: Shared connections
3 description: Make a connected account usable by multiple users with a per-user access control list
4 keywords: [shared connection, account type, SHARED, PRIVATE, ACL, experimental, allow all users, allowed user ids, not allowed user ids]
5 llmGuardrails: "direct-execution"
6 +experimental: true
7 ---
8
8 -<Callout type="warn">
9 -Shared Connections APIs are experimental and may change in future releases. All new fields are nested under an `experimental` block on the wire, and the SDK methods that operate on them live under the `composio.experimental` namespace (`composio.experimental.update_acl` in Python, `composio.experimental.updateAcl` in TypeScript). The code samples below show the experimental shape — pin a specific SDK version if you depend on the current contract.
10 -</Callout>
11 -
12 -<Callout type="info">
13 -If you're building an agent, prefer [sessions](/docs/configuring-sessions). Sessions let you pin a shared connection into a session config; see [Using a shared connection in a session](#using-a-shared-connection) below.
14 -</Callout>
9 +By default, a connected account is **PRIVATE**: only the `userID` that created it can use it. A **SHARED** connection can be reached by other `userID`s, subject to a per-connection access control list (ACL).
10
16 -By default, a connected account is **PRIVATE** — only the `userId` that created it can use it. A **SHARED** connection can be reached by other `userId`s, subject to a per-connection access control list (ACL).
11 +You use a shared connection by [pinning it into a session](#using-a-shared-connection): the session's `userID` doesn't own the connection, but the pin makes it available. A SHARED connection is never resolved implicitly, so a session reaches one only when you pin it explicitly.
12
13 Typical use cases:
14
20 -- **Org-managed credentials** — one Gmail / Salesforce / GitHub connection that every user in your app can call against, without each user having to authenticate separately.
21 -- **Background agents acting on behalf of multiple users** — the agent runs as a single service account but executes work for many `userId`s.
22 -- **Team mailboxes** — `support@` or `sales@` accounts where any teammate can send/read mail through your app.
15 +- **Org-managed credentials.** One Gmail, Salesforce, or GitHub connection that every user in your app can call against, without each user having to authenticate separately.
16 +- **Background agents acting on behalf of multiple users.** The agent runs as a single service account but executes work for many `userID`s.
17 +- **Team mailboxes.** `support@` or `sales@` accounts where any teammate can send and read mail through your app.
18
19 ## SHARED vs PRIVATE
20
21 | | PRIVATE (default) | SHARED |
22 |---|---|---|
28 -| **Who can use it** | Only the owning `userId` | The creator + every `userId` permitted by the ACL |
29 -| **Default access for other users** | Always denied | Deny-by-default — the creator must grant access explicitly |
30 -| **How it's used** | Implicit lookup by `userId` | Must be **explicitly pinned** in a tool-router session, or referenced by `connectedAccountId` on a direct execute |
23 +| **Who can use it** | Only the owning `userID` | The creator plus every `userID` permitted by the ACL |
24 +| **Default access for other users** | Always denied | Deny-by-default (the creator must grant access explicitly) |
25 +| **How it's used** | Implicit lookup by `userID` | Must be **explicitly pinned** in a session |
26 | **ACL fields** | Ignored | `allowAllUsers`, `allowedUserIds`, `notAllowedUserIds` (inside the `experimental` block) |
27
33 -<Callout type="info">
34 -SHARED connections are never used implicitly. A session belonging to a non-creator `userId` will only resolve a SHARED connection if the developer explicitly pins it in the session config.
35 -</Callout>
36 -
28 ## Creating a SHARED connection
29
30 Pass an `experimental` block to `link()` (`accountType` in TypeScript, `account_type` in Python) set to `"SHARED"`, and optionally an initial ACL. Omit the ACL block to keep the default deny-by-default state (only the creator can use it until you grant access).
@@ -99,9 +90,54 @@ The returned `connectedAccountId` (`ca_...`) is the ID you'll pin into other use
90 ACL fields are only valid on SHARED connections. Sending an `experimental.acl_config_for_shared` block on a PRIVATE connection raises `ComposioAclOnlyForSharedError`.
91 </Callout>
92
93 +## Using a shared connection
94 +
95 +Pin the SHARED connection into a session through `connectedAccounts`. The session belongs to a *different* `userID` than the creator, and the pin is what makes the SHARED connection visible to that session.
96 +
97 +The session config itself is **not** experimental. You pin the connection by ID exactly as you would a PRIVATE one.
98 +
99 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
100 + <Tab value="Python">
101 +```python
102 +# user_alice starts a session that pins the shared Gmail connection.
103 +# Gmail tools loaded from this session will resolve to that connection
104 +# even though user_alice did not create it.
105 +session = composio.create(
106 + user_id="user_alice",
107 + connected_accounts={
108 + "gmail": ["ca_gmail_shared"],
109 + },
110 +)
111 +
112 +tools = session.tools()
113 +```
114 + </Tab>
115 + <Tab value="TypeScript">
116 +```typescript
117 +import { Composio } from '@composio/core';
118 +const composio = new Composio({ apiKey: 'your_api_key' });
119 +// ---cut---
120 +// user_alice starts a session that pins the shared Gmail connection.
121 +// Gmail tools loaded from this session will resolve to that connection
122 +// even though user_alice did not create it.
123 +const session = await composio.create("user_alice", {
124 + connectedAccounts: {
125 + gmail: ["ca_gmail_shared"],
126 + },
127 +});
128 +
129 +const tools = await session.tools();
130 +```
131 + </Tab>
132 +</Tabs>
133 +
134 +<Callout type="info">
135 +A session may pin **at most one SHARED connection per toolkit**. Pinning two SHARED Gmail connections in the same session is rejected at session create time. Mixing one SHARED with multiple PRIVATE pins is allowed.
136 +</Callout>
137 +
138 ## ACL resolution rule
139
104 -When a non-creator `userId` attempts to use a SHARED connection, the ACL is evaluated in this order:
140 +When a non-creator `userID` attempts to use a SHARED connection, the ACL is evaluated in this order:
141
142 1. `userId` ∈ `notAllowedUserIds` → **DENY**
143 2. `allowAllUsers === true` → **ALLOW**
@@ -110,11 +146,11 @@ When a non-creator `userId` attempts to use a SHARED connection, the ACL is eval
146
147 Deny wins on conflict, which lets you express *"share with everyone except a few people"* by setting `allowAllUsers: true` and naming the exceptions in `notAllowedUserIds`.
148
113 -The creator can always use their own connection — the ACL only governs other `userId`s.
149 +The creator can always use their own connection. The ACL only governs other `userID`s.
150
151 ### Common ACL patterns
152
117 -The table below shows the inner shape of the ACL block (`aclConfigForShared` in TypeScript, `acl_config_for_shared` in Python) — wrap it inside the `experimental` block at the call site. Field names are camelCase in the TypeScript samples; Python callers translate to snake_case (`allow_all_users`, `allowed_user_ids`, `not_allowed_user_ids`).
153 +The table below shows the inner shape of the ACL block (`aclConfigForShared` in TypeScript, `acl_config_for_shared` in Python). Wrap it inside the `experimental` block at the call site. Field names are camelCase in the TypeScript samples; Python callers translate to snake_case (`allow_all_users`, `allowed_user_ids`, `not_allowed_user_ids`).
154
155 | Goal | ACL block |
156 |---|---|
@@ -122,32 +158,32 @@ The table below shows the inner shape of the ACL block (`aclConfigForShared` in
158 | **Allow every `userId`** | `{ allowAllUsers: true }` |
159 | **Targeted allow list** | `{ allowedUserIds: ["user_alice", "user_bob"] }` |
160 | **Everyone except a few users** | `{ allowAllUsers: true, notAllowedUserIds: ["user_bob"] }` |
125 -| **Combined: open + targeted deny** | `{ allowAllUsers: true, notAllowedUserIds: ["user_bob"], allowedUserIds: ["user_alice"] }` — Bob still denied (deny wins) |
161 +| **Combined: open + targeted deny** | `{ allowAllUsers: true, notAllowedUserIds: ["user_bob"], allowedUserIds: ["user_alice"] }` (Bob still denied, deny wins) |
162
127 -Each list accepts up to 1000 entries; each `userId` is 1..256 characters.
163 +Each list accepts up to 1000 entries; each `userID` is 1..256 characters.
164
165 ## Updating the ACL
166
131 -Use the experimental ACL-update method to change access after creation. PATCH semantics — pass only the fields you want to change; omit a field to leave it unchanged; pass an empty array to clear an allow/deny list.
167 +Call `updateAcl()` on the connected accounts namespace to change access after creation. It follows PATCH semantics: pass only the fields you want to change, omit a field to leave it unchanged, and pass an empty array to clear an allow or deny list.
168
169 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
170 <Tab value="Python">
171 ```python
172 # Open access to everyone.
137 -composio.experimental.update_acl(
173 +composio.connected_accounts.update_acl(
174 "ca_gmail_shared",
175 allow_all_users=True,
176 )
177
178 # Add a targeted allow list (without touching the wildcard or deny list).
143 -composio.experimental.update_acl(
179 +composio.connected_accounts.update_acl(
180 "ca_gmail_shared",
181 allowed_user_ids=["user_alice", "user_bob"],
182 )
183
148 -# Revoke the allow list — only the creator can use it again
184 +# Revoke the allow list; only the creator can use it again
185 # (unless allow_all_users is True).
150 -composio.experimental.update_acl(
186 +composio.connected_accounts.update_acl(
187 "ca_gmail_shared",
188 allowed_user_ids=[],
189 )
@@ -160,18 +196,18 @@ import { Composio } from '@composio/core';
196 const composio = new Composio({ apiKey: 'your_api_key' });
197 // ---cut---
198 // Open access to everyone.
163 -await composio.experimental.updateAcl("ca_gmail_shared", {
199 +await composio.connectedAccounts.updateAcl("ca_gmail_shared", {
200 allowAllUsers: true,
201 });
202
203 // Add a targeted allow list (without touching the wildcard or deny list).
168 -await composio.experimental.updateAcl("ca_gmail_shared", {
204 +await composio.connectedAccounts.updateAcl("ca_gmail_shared", {
205 allowedUserIds: ["user_alice", "user_bob"],
206 });
207
172 -// Revoke the allow list — only the creator can use it again
208 +// Revoke the allow list; only the creator can use it again
209 // (unless allowAllUsers is true).
174 -await composio.experimental.updateAcl("ca_gmail_shared", {
210 +await composio.connectedAccounts.updateAcl("ca_gmail_shared", {
211 allowedUserIds: [],
212 });
213 ```
@@ -182,89 +218,11 @@ await composio.experimental.updateAcl("ca_gmail_shared", {
218 Passing `notAllowedUserIds: []` **clears the deny list**, which silently re-grants access to users you previously blocked. Always audit the allow side when clearing a deny list.
219 </Callout>
220
185 -ACL writes are restricted to the connection's creator or an API key caller. Other callers receive a permission error.
186 -
187 -## Using a shared connection
188 -
189 -### In a tool-router session
190 -
191 -Pin the SHARED connection into the session via `connectedAccounts`. The session belongs to a *different* `userId` than the creator — the pin is what makes the SHARED connection visible to that session.
192 -
193 -The session config itself is **not** experimental — only the connection that you're pinning is. So you pin by ID exactly as you would a PRIVATE connection.
194 -
195 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
196 - <Tab value="Python">
197 -```python
198 -# user_alice starts a session that pins the shared Gmail connection.
199 -# Gmail tools loaded from this session will resolve to that connection
200 -# even though user_alice did not create it.
201 -session = composio.create(
202 - user_id="user_alice",
203 - connected_accounts={
204 - "gmail": ["ca_gmail_shared"],
205 - },
206 -)
207 -
208 -tools = session.tools()
209 -```
210 - </Tab>
211 - <Tab value="TypeScript">
212 -```typescript
213 -import { Composio } from '@composio/core';
214 -const composio = new Composio({ apiKey: 'your_api_key' });
215 -// ---cut---
216 -// user_alice starts a session that pins the shared Gmail connection.
217 -// Gmail tools loaded from this session will resolve to that connection
218 -// even though user_alice did not create it.
219 -const session = await composio.create("user_alice", {
220 - connectedAccounts: {
221 - gmail: ["ca_gmail_shared"],
222 - },
223 -});
224 -
225 -const tools = await session.tools();
226 -```
227 - </Tab>
228 -</Tabs>
229 -
230 -<Callout type="info">
231 -A session may pin **at most one SHARED connection per toolkit**. Pinning two SHARED Gmail connections in the same session is rejected at session create time. Mixing one SHARED with multiple PRIVATE pins is allowed.
232 -</Callout>
233 -
234 -### Direct execution
235 -
236 -Pass the SHARED connection's ID explicitly via `connectedAccountId`:
237 -
238 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
239 - <Tab value="Python">
240 -```python
241 -result = composio.tools.execute(
242 - slug="GMAIL_SEND_EMAIL",
243 - user_id="user_alice",
244 - connected_account_id="ca_gmail_shared",
245 - arguments={"to": "person@example.com", "subject": "hi", "body": "..."},
246 -)
247 -```
248 - </Tab>
249 - <Tab value="TypeScript">
250 -```typescript
251 -import { Composio } from '@composio/core';
252 -const composio = new Composio({ apiKey: 'your_api_key' });
253 -// ---cut---
254 -const result = await composio.tools.execute("GMAIL_SEND_EMAIL", {
255 - userId: "user_alice",
256 - connectedAccountId: "ca_gmail_shared",
257 - arguments: { to: "person@example.com", subject: "hi", body: "..." },
258 -});
259 -```
260 - </Tab>
261 -</Tabs>
262 -
263 -If `user_alice` isn't permitted by the connection's ACL, the call raises `ComposioSharedAccessDeniedError`.
221 +ACL writes are restricted to the connection's creator or an API key caller. Other callers get a permission error.
222
223 ## Listing SHARED connections
224
267 -By default `list()` returns **PRIVATE only** — shared accounts must be requested explicitly. Pass an `account_type` (Python) / `accountType` (TypeScript) filter to scope the query.
225 +By default `list()` returns **PRIVATE only**, so shared accounts must be requested explicitly. Pass an `account_type` (Python) or `accountType` (TypeScript) filter to scope the query.
226
227 | Value | Returns |
228 |---|---|
@@ -272,7 +230,7 @@ By default `list()` returns **PRIVATE only** — shared accounts must be request
230 | `'SHARED'` | Only SHARED connections |
231 | `'ALL'` | PRIVATE + SHARED |
232
275 -The filter is a flat query param on the wire (`?account_type=...`), so it stays flat in both SDKs — unlike the create/update surfaces which nest under `experimental`.
233 +The filter is a flat query param on the wire (`?account_type=...`), so it stays flat in both SDKs, unlike the create and update surfaces, which nest under `experimental`.
234
235 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
236 <Tab value="Python">
@@ -314,7 +272,7 @@ const sharedForAlice = await composio.connectedAccounts.list({
272
273 ## Inspecting the ACL
274
317 -`get()` and `list()` responses surface `accountType` and `aclConfigForShared` under the same `experimental` block as the request shape. The `aclConfigForShared` field is populated only when the caller is the connection's creator or is using an API key — other callers see the `experimental` block without that field.
275 +`get()` and `list()` responses surface `accountType` and `aclConfigForShared` under the same `experimental` block as the request shape. The `aclConfigForShared` field is populated only when the caller is the connection's creator or is using an API key. Other callers see the `experimental` block without that field.
276
277 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
278 <Tab value="Python">
@@ -365,71 +323,10 @@ if (account.experimental) {
323 |---|---|
324 | `ComposioAclOnlyForSharedError` (400) | ACL fields sent on a PRIVATE connection (at create or update time). |
325 | `ComposioSharedAccessDeniedError` (403) | Direct execute with a SHARED `connectedAccountId` that the requesting `userId` isn't permitted to use. |
368 -| `ComposioSharedConnectionNotAccessibleError` (400) | A tool-router session pinned a SHARED connection that the session's `userId` cannot use — the error is raised at session create time, so the session never enters a state that fails mid-execution. |
326 +| `ComposioSharedConnectionNotAccessibleError` (400) | A session pinned a SHARED connection that the session's `userID` cannot use. The error is raised at session create time, so the session never enters a state that fails mid-execution. |
327
370 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
371 - <Tab value="Python">
372 -```python
373 -from composio import exceptions
374 -
375 -try:
376 - composio.experimental.update_acl(
377 - "ca_private_gmail", # this connection is PRIVATE
378 - allow_all_users=True,
379 - )
380 -except exceptions.ComposioAclOnlyForSharedError as e:
381 - print(f"ACL only applies to SHARED connections: {e}")
382 -
383 -try:
384 - composio.tools.execute(
385 - slug="GMAIL_SEND_EMAIL",
386 - user_id="user_bob", # not on the allow list
387 - connected_account_id="ca_gmail_shared",
388 - arguments={...},
389 - )
390 -except exceptions.ComposioSharedAccessDeniedError as e:
391 - print(f"Access denied: {e}")
392 -```
393 - </Tab>
394 - <Tab value="TypeScript">
395 -```typescript
396 -// @noErrors
397 -import {
398 - Composio,
399 - ComposioAclOnlyForSharedError,
400 - ComposioSharedAccessDeniedError,
401 -} from '@composio/core';
402 -const composio = new Composio({ apiKey: 'your_api_key' });
403 -// ---cut---
404 -try {
405 - await composio.experimental.updateAcl("ca_private_gmail", {
406 - allowAllUsers: true,
407 - });
408 -} catch (error) {
409 - if (error instanceof ComposioAclOnlyForSharedError) {
410 - console.log(`ACL only applies to SHARED connections: ${error.message}`);
411 - }
412 -}
413 -
414 -try {
415 - await composio.tools.execute("GMAIL_SEND_EMAIL", {
416 - userId: "user_bob", // not on the allow list
417 - connectedAccountId: "ca_gmail_shared",
418 - arguments: { /* ... */ },
419 - });
420 -} catch (error) {
421 - if (error instanceof ComposioSharedAccessDeniedError) {
422 - console.log(`Access denied: ${error.message}`);
423 - }
424 -}
425 -```
426 - </Tab>
427 -</Tabs>
328 +The access errors are caught the same way as any other Composio exception (`ComposioAclOnlyForSharedError` and `ComposioSharedAccessDeniedError` are exported from `@composio/core`, and live under `composio.exceptions` in Python).
329
429 -## What to read next
330 +## Next
331
431 -<Cards>
432 - <Card icon={<Plug />} title="Managing multiple connected accounts" href="/docs/managing-multiple-connected-accounts" description="Pin specific accounts into a session at runtime" />
433 - <Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Session config — custom auth configs, pinned connections, multi-account" />
434 - <Card icon={<Key />} title="Authentication overview" href="/docs/authentication" description="How users authenticate and how connected accounts are scoped" />
435 -</Cards>
332 +<Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Pin connected accounts, auth configs, and toolkit restrictions into a session" />
docs/content/docs/signing-up-as-an-agent.mdx deleted
-193
@@ -1,193 +0,0 @@
1 ----
2 -title: Signing Up as an Agent
3 -description: Create and reuse a Composio account programmatically from an AI agent
4 -keywords: [agent signup, agents, cli, api key, anonymous signup]
5 ----
6 -
7 -Agents can sign up for Composio directly through [`agents.composio.dev`](https://agents.composio.dev) without a human creating an account first. The flow creates an agent identity, returns Composio credentials, and gives the agent a ready-to-run CLI install/login command.
8 -
9 -The base URL for all endpoints on this page is:
10 -
11 -```text
12 -https://agents.composio.dev
13 -```
14 -
15 -## Flow
16 -
17 -1. **Check for an existing identity.** Before signing up, look for `~/.composio/anonymous_user_data.json`. If it exists, read the saved `agent_key` and call `GET /api/whoami` with `Authorization: Bearer <agent_key>`. If it returns `200` with `status: "READY"`, reuse the saved credentials.
18 -2. **Sign up.** Call `POST /api/signup`. By default, the endpoint waits until the account is ready and returns a `201` response containing the `agent_key` plus Composio credentials (`member_id`, `org_id`, `project_id`, `api_key`, and `user_api_key`). Save the full response to `~/.composio/anonymous_user_data.json` immediately so future runs do not create a new identity.
19 -3. **Install and log in to the CLI.** Call `GET /api/cli` with the `agent_key`. It returns paste-ready install and login commands.
20 -4. **Optionally claim the org.** Call `POST /api/claim` with a human email only when you want to hand the organization over to a human admin.
21 -
22 -## Sign up
23 -
24 -`POST /api/signup` creates an agent email inbox, starts the Composio signup flow, and long-polls for up to 120 seconds. Most calls complete in about 5–10 seconds.
25 -
26 -```bash
27 -mkdir -p ~/.composio
28 -
29 -curl -sS -X POST 'https://agents.composio.dev/api/signup' \
30 - -H 'content-type: application/json' \
31 - -d '{}' \
32 - -o ~/.composio/anonymous_user_data.json
33 -
34 -cat ~/.composio/anonymous_user_data.json
35 -```
36 -
37 -Successful response:
38 -
39 -```json
40 -{
41 - "status": "ready",
42 - "request_id": "req_xxx",
43 - "slug": "amber-cedar-otter",
44 - "email": "amber-cedar-otter@agent.composio.ai",
45 - "agent_key": "composio_agent_key_xxx",
46 - "composio": {
47 - "member_id": "uuid",
48 - "org_id": "org_xxx",
49 - "project_id": "proj_xxx",
50 - "api_key": "ak_xxx",
51 - "user_api_key": "uak_xxx"
52 - }
53 -}
54 -```
55 -
56 -If the 120-second wait expires, the endpoint returns `202` with `status: "pending"`. Poll `GET /api/whoami` until the status is `READY`.
57 -
58 -```json
59 -{
60 - "status": "pending",
61 - "request_id": "req_xxx",
62 - "slug": "amber-cedar-otter",
63 - "email": "amber-cedar-otter@agent.composio.ai",
64 - "agent_key": "composio_agent_key_xxx",
65 - "poll": "/api/whoami"
66 -}
67 -```
68 -
69 -To skip waiting and poll yourself, pass `?wait=0`:
70 -
71 -```bash
72 -curl -sS -X POST 'https://agents.composio.dev/api/signup?wait=0' \
73 - -H 'content-type: application/json' \
74 - -d '{}'
75 -```
76 -
77 -## Verify a saved identity
78 -
79 -Use `GET /api/whoami` to verify a saved `agent_key` and fetch the current Composio credentials. The `agent_key` authenticates only against the agent signup surface; it is not your Composio API key.
80 -
81 -```bash
82 -AGENT_KEY="$(jq -r '.agent_key' ~/.composio/anonymous_user_data.json)"
83 -
84 -curl -sS 'https://agents.composio.dev/api/whoami' \
85 - -H "Authorization: Bearer ${AGENT_KEY}"
86 -```
87 -
88 -Response:
89 -
90 -```json
91 -{
92 - "slug": "amber-cedar-otter",
93 - "email": "amber-cedar-otter@agent.composio.ai",
94 - "status": "READY",
95 - "claimed_by": null,
96 - "claimed_at": null,
97 - "composio": {
98 - "member_id": "uuid",
99 - "org_id": "org_xxx",
100 - "project_id": "proj_xxx",
101 - "api_key": "ak_xxx",
102 - "user_api_key": "uak_xxx"
103 - }
104 -}
105 -```
106 -
107 -## Install the CLI
108 -
109 -`GET /api/cli` returns install and login commands with the agent's `user_api_key` and `org_id` already filled in.
110 -
111 -```bash
112 -AGENT_KEY="$(jq -r '.agent_key' ~/.composio/anonymous_user_data.json)"
113 -
114 -curl -sS 'https://agents.composio.dev/api/cli' \
115 - -H "Authorization: Bearer ${AGENT_KEY}"
116 -```
117 -
118 -Example response:
119 -
120 -```text
121 -Install Composio CLI using this command:
122 -curl -fsSL https://composio.dev/install | bash
123 -
124 -Then log in using this command:
125 -composio login --user-api-key "uak_..." --org "ok_..."
126 -```
127 -
128 -Run the returned commands to install and authenticate the CLI.
129 -
130 -## Claim the organization
131 -
132 -Claiming is optional. Use it only when the agent wants to invite a human admin to take over the Composio organization. The endpoint issues a single-use admin invite that expires after 24 hours.
133 -
134 -```bash
135 -AGENT_KEY="$(jq -r '.agent_key' ~/.composio/anonymous_user_data.json)"
136 -
137 -curl -sS -X POST 'https://agents.composio.dev/api/claim' \
138 - -H "Authorization: Bearer ${AGENT_KEY}" \
139 - -H 'content-type: application/json' \
140 - -d '{"email":"human@example.com"}'
141 -```
142 -
143 -Response:
144 -
145 -```json
146 -{
147 - "status": "invited",
148 - "email": "human@example.com",
149 - "org_id": "org_xxx",
150 - "invite_code": "inv_xxx"
151 -}
152 -```
153 -
154 -## Read the agent inbox
155 -
156 -Each agent gets an email address at `<slug>@agent.composio.ai`. Use `GET /api/mail` to list messages for the agent inbox.
157 -
158 -```bash
159 -AGENT_KEY="$(jq -r '.agent_key' ~/.composio/anonymous_user_data.json)"
160 -
161 -curl -sS 'https://agents.composio.dev/api/mail?limit=50' \
162 - -H "Authorization: Bearer ${AGENT_KEY}"
163 -```
164 -
165 -Response:
166 -
167 -```json
168 -{
169 - "count": 1,
170 - "messages": [
171 - {
172 - "id": "msg_xxx",
173 - "thread_id": "thr_xxx",
174 - "from": "no-reply@composio.dev",
175 - "to": "amber-cedar-otter@agent.composio.ai",
176 - "subject": "Sign in to Composio",
177 - "preview": "Click the link below to sign in...",
178 - "received_at": "2026-04-13T22:00:00.000Z"
179 - }
180 - ]
181 -}
182 -```
183 -
184 -## Agent keys
185 -
186 -Agent keys are prefixed with `composio_agent_key_` and are only valid for these endpoints:
187 -
188 -- `GET /api/whoami`
189 -- `GET /api/mail`
190 -- `GET /api/cli`
191 -- `POST /api/claim`
192 -
193 -Use the real Composio API key from the `composio.api_key` field when calling Composio APIs and SDKs.
docs/content/docs/single-toolkit-mcp.mdx
+4 -13
@@ -104,10 +104,6 @@ console.log(`Server created: ${server.id}`);
104 Users must authenticate with the toolkits configured in your MCP server first. See [authentication](/docs/authentication) for details.
105 </Callout>
106
107 - <Callout type="info">
108 - Generated MCP URLs are scoped to a user. If you build an MCP URL yourself, include either `user_id` or `connected_account_id` as a query parameter.
109 - </Callout>
110 -
107 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
108 <Tab value="Python">
109 ```python
@@ -326,13 +322,8 @@ if (result.deleted) {
322 </Tab>
323 </Tabs>
324
329 -## Next steps
325 +## Next
326
331 -<Cards>
332 - <Card title="Providers" href="/docs/providers">
333 - Use with Anthropic, OpenAI, and other frameworks
334 - </Card>
335 - <Card title="Configuring Sessions" href="/docs/configuring-sessions">
336 - Configure the recommended dynamic MCP endpoint
337 - </Card>
338 -</Cards>
327 +<Card title="Providers" href="/docs/providers">
328 + Use with Anthropic, OpenAI, and other frameworks
329 +</Card>
docs/content/docs/toolkits/enable-and-disable-toolkits.mdx deleted
-277
@@ -1,277 +0,0 @@
1 ----
2 -title: Enable and disable toolkits
3 -description: Control which toolkits and tools are available in your sessions
4 ----
5 -
6 -When creating a session, you can control which toolkits are available to your agent. By default, all 1000+ toolkits are discoverable, but you can restrict or exclude specific ones.
7 -
8 -## Enabling specific toolkits
9 -
10 -To limit your session to only specific toolkits, pass an array of toolkit slugs:
11 -
12 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
13 -<Tab value="Python">
14 -```python
15 -from composio import Composio
16 -
17 -composio = Composio()
18 -
19 -# Only GitHub and Gmail will be available
20 -session = composio.create(
21 - user_id="user_123",
22 - toolkits=["github", "gmail"]
23 -)
24 -
25 -# Or use the explicit enable syntax
26 -session = composio.create(
27 - user_id="user_123",
28 - toolkits={"enable": ["github", "gmail"]}
29 -)
30 -```
31 -</Tab>
32 -<Tab value="TypeScript">
33 -```typescript
34 -import { Composio } from '@composio/core';
35 -const composio = new Composio({ apiKey: 'your_api_key' });
36 -// ---cut---
37 -// Only GitHub and Gmail will be available
38 -const session = await composio.create("user_123", {
39 - toolkits: ["github", "gmail"]
40 -});
41 -
42 -// Or use the explicit enable syntax
43 -const session2 = await composio.create("user_123", {
44 - toolkits: { enable: ["github", "gmail"] }
45 -});
46 -```
47 -</Tab>
48 -</Tabs>
49 -
50 -## Disabling specific toolkits
51 -
52 -To make all toolkits available except certain ones, use the `disable` syntax:
53 -
54 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
55 -<Tab value="Python">
56 -```python
57 -# All toolkits available except Linear and Jira
58 -session = composio.create(
59 - user_id="user_123",
60 - toolkits={"disable": ["linear", "jira"]}
61 -)
62 -```
63 -</Tab>
64 -<Tab value="TypeScript">
65 -```typescript
66 -import { Composio } from '@composio/core';
67 -const composio = new Composio({ apiKey: 'your_api_key' });
68 -// ---cut---
69 -// All toolkits available except Linear and Jira
70 -const session = await composio.create("user_123", {
71 - toolkits: { disable: ["linear", "jira"] }
72 -});
73 -```
74 -</Tab>
75 -</Tabs>
76 -
77 -## Enabling or disabling specific tools
78 -
79 -You can also control which individual tools are available within a toolkit using the `tools` configuration. The key is the toolkit slug and the value specifies which tools to enable or disable.
80 -
81 -### Enable specific tools
82 -
83 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
84 -<Tab value="Python">
85 -```python
86 -session = composio.create(
87 - user_id="user_123",
88 - tools={
89 - # Only these Gmail tools will be available
90 - "gmail": {"enable": ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]},
91 - # Only issue-related GitHub tools
92 - "github": {"enable": ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]}
93 - }
94 -)
95 -```
96 -</Tab>
97 -<Tab value="TypeScript">
98 -```typescript
99 -import { Composio } from '@composio/core';
100 -const composio = new Composio({ apiKey: 'your_api_key' });
101 -// ---cut---
102 -const session = await composio.create("user_123", {
103 - tools: {
104 - // Only these Gmail tools will be available
105 - gmail: { enable: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"] },
106 - // Only issue-related GitHub tools
107 - github: { enable: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"] }
108 - }
109 -});
110 -```
111 -</Tab>
112 -</Tabs>
113 -
114 -You can also use the shorthand array syntax which is equivalent to `enable`:
115 -
116 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
117 -<Tab value="Python">
118 -```python
119 -session = composio.create(
120 - user_id="user_123",
121 - tools={
122 - "gmail": ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"],
123 - "github": ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]
124 - }
125 -)
126 -```
127 -</Tab>
128 -<Tab value="TypeScript">
129 -```typescript
130 -import { Composio } from '@composio/core';
131 -const composio = new Composio({ apiKey: 'your_api_key' });
132 -// ---cut---
133 -const session = await composio.create("user_123", {
134 - tools: {
135 - gmail: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"],
136 - github: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_ISSUE"]
137 - }
138 -});
139 -```
140 -</Tab>
141 -</Tabs>
142 -
143 -### Disable specific tools
144 -
145 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
146 -<Tab value="Python">
147 -```python
148 -session = composio.create(
149 - user_id="user_123",
150 - tools={
151 - # All Slack tools except delete
152 - "slack": {"disable": ["SLACK_DELETE_MESSAGE"]},
153 - # All GitHub tools except destructive ones
154 - "github": {"disable": ["GITHUB_DELETE_REPO", "GITHUB_DELETE_BRANCH"]}
155 - }
156 -)
157 -```
158 -</Tab>
159 -<Tab value="TypeScript">
160 -```typescript
161 -import { Composio } from '@composio/core';
162 -const composio = new Composio({ apiKey: 'your_api_key' });
163 -// ---cut---
164 -const session = await composio.create("user_123", {
165 - tools: {
166 - // All Slack tools except delete
167 - slack: { disable: ["SLACK_DELETE_MESSAGE"] },
168 - // All GitHub tools except destructive ones
169 - github: { disable: ["GITHUB_DELETE_REPO", "GITHUB_DELETE_BRANCH"] }
170 - }
171 -});
172 -```
173 -</Tab>
174 -</Tabs>
175 -
176 -## Filtering tools by tags
177 -
178 -Tools can be filtered by their behavior tags. Available tags are:
179 -
180 -| Tag | Description |
181 -|-----|-------------|
182 -| `readOnlyHint` | Tools that only read data |
183 -| `destructiveHint` | Tools that modify or delete data |
184 -| `idempotentHint` | Tools that can be safely retried |
185 -| `openWorldHint` | Tools that operate in an open world context |
186 -
187 -### Global tag filtering
188 -
189 -Apply tag filters to all toolkits:
190 -
191 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
192 -<Tab value="Python">
193 -```python
194 -# Only include read-only and idempotent tools
195 -session = composio.create(
196 - user_id="user_123",
197 - tags=["readOnlyHint", "idempotentHint"]
198 -)
199 -
200 -# Enable some tags, disable others
201 -session = composio.create(
202 - user_id="user_123",
203 - tags={
204 - "enable": ["readOnlyHint"],
205 - "disable": ["destructiveHint"]
206 - }
207 -)
208 -```
209 -</Tab>
210 -<Tab value="TypeScript">
211 -```typescript
212 -import { Composio } from '@composio/core';
213 -const composio = new Composio({ apiKey: 'your_api_key' });
214 -// ---cut---
215 -// Only include read-only and idempotent tools
216 -const session = await composio.create("user_123", {
217 - tags: ["readOnlyHint", "idempotentHint"]
218 -});
219 -
220 -// Enable some tags, disable others
221 -const sessionWithTagConfig = await composio.create("user_123", {
222 - tags: {
223 - enable: ["readOnlyHint"],
224 - disable: ["destructiveHint"]
225 - }
226 -});
227 -```
228 -</Tab>
229 -</Tabs>
230 -
231 -### Per-toolkit tag filtering
232 -
233 -Override global tags for specific toolkits:
234 -
235 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
236 -<Tab value="Python">
237 -```python
238 -session = composio.create(
239 - user_id="user_123",
240 - # Global: only read-only tools
241 - tags=["readOnlyHint"],
242 - tools={
243 - # Override for GitHub: allow all tools except destructive
244 - "github": {"tags": {"disable": ["destructiveHint"]}},
245 - # Override for Gmail: only read-only tools (explicit)
246 - "gmail": {"tags": ["readOnlyHint"]}
247 - }
248 -)
249 -```
250 -</Tab>
251 -<Tab value="TypeScript">
252 -```typescript
253 -import { Composio } from '@composio/core';
254 -const composio = new Composio({ apiKey: 'your_api_key' });
255 -// ---cut---
256 -const session = await composio.create("user_123", {
257 - // Global: only read-only tools
258 - tags: ["readOnlyHint"],
259 - tools: {
260 - // Override for GitHub: allow all tools except destructive
261 - github: { tags: { disable: ["destructiveHint"] } },
262 - // Override for Gmail: only read-only tools (explicit)
263 - gmail: { tags: ["readOnlyHint"] }
264 - }
265 -});
266 -```
267 -</Tab>
268 -</Tabs>
269 -
270 -## What to read next
271 -
272 -<Cards>
273 - <Card icon={<Wrench />} title="Custom tools and toolkits" href="/docs/toolkits/custom-tools-and-toolkits" description="Define local tools that run alongside remote Composio tools" />
274 - <Card icon={<Wrench />} title="Fetching tools and toolkits" href="/docs/toolkits/fetching-tools-and-toolkits" description="List enabled toolkits, get meta tools, and browse the catalog" />
275 - <Card icon={<Wrench />} title="Configuring sessions" href="/docs/configuring-sessions" description="Auth configs, connected accounts, and other session options" />
276 -</Cards>
277 -
docs/content/docs/toolkits/fetching-tools-and-toolkits.mdx deleted
-182
@@ -1,182 +0,0 @@
1 ----
2 -title: Fetching tools and toolkits
3 -description: How to fetch tools and toolkits for sessions and browse the catalog
4 ----
5 -
6 -## Fetching for a session
7 -
8 -When using sessions, fetch tools through the session object.
9 -
10 -### List enabled toolkits
11 -
12 -`session.toolkits()` returns toolkits enabled for your session, sorted by popularity. By default, it returns the top 20. Each toolkit includes its `slug`, `name`, `logo`, and connection status.
13 -
14 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
15 -<Tab value="Python">
16 -```python
17 -session = composio.create(user_id="user_123")
18 -
19 -result = session.toolkits()
20 -
21 -for toolkit in result.items:
22 - print(f"{toolkit.name}: connected={toolkit.connection.is_active if toolkit.connection else 'n/a'}")
23 -```
24 -</Tab>
25 -<Tab value="TypeScript">
26 -```typescript
27 -import { Composio } from '@composio/core';
28 -const composio = new Composio({ apiKey: 'your_api_key' });
29 -// ---cut---
30 -const session = await composio.create("user_123");
31 -
32 -const result = await session.toolkits();
33 -
34 -for (const toolkit of result.items) {
35 - console.log(`${toolkit.name}: connected=${toolkit.connection?.isActive ?? 'n/a'}`);
36 -}
37 -```
38 -</Tab>
39 -</Tabs>
40 -
41 -You can filter to only show connected toolkits:
42 -
43 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
44 -<Tab value="Python">
45 -```python
46 -connected = session.toolkits(is_connected=True) # Only connected
47 -```
48 -</Tab>
49 -<Tab value="TypeScript">
50 -```typescript
51 -import { Composio } from '@composio/core';
52 -const composio = new Composio({ apiKey: 'your_api_key' });
53 -const session = await composio.create("user_123");
54 -// ---cut---
55 -const connected = await session.toolkits({ isConnected: true }); // Only connected
56 -```
57 -</Tab>
58 -</Tabs>
59 -
60 -To fetch all toolkits, paginate through the results:
61 -
62 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
63 -<Tab value="Python">
64 -```python
65 -all_toolkits = []
66 -cursor = None
67 -
68 -while True:
69 - result = session.toolkits(limit=20, next_cursor=cursor)
70 - all_toolkits.extend(result.items)
71 - cursor = result.next_cursor
72 - if not cursor:
73 - break
74 -```
75 -</Tab>
76 -<Tab value="TypeScript">
77 -```typescript
78 -import { Composio } from '@composio/core';
79 -const composio = new Composio({ apiKey: 'your_api_key' });
80 -const session = await composio.create("user_123");
81 -// ---cut---
82 -const allToolkits: any[] = [];
83 -let cursor: string | undefined;
84 -
85 -do {
86 - const { items, cursor: nextCursor } = await session.toolkits({ limit: 20, cursor });
87 - allToolkits.push(...items);
88 - cursor = nextCursor;
89 -} while (cursor);
90 -```
91 -</Tab>
92 -</Tabs>
93 -
94 -### Get meta tools
95 -
96 -`session.tools()` returns the [meta tools](/reference/meta-tools) formatted for your configured provider (OpenAI, Anthropic, etc.):
97 -
98 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
99 -<Tab value="Python">
100 -```python
101 -# Get all meta tools
102 -tools = session.tools()
103 -```
104 -</Tab>
105 -<Tab value="TypeScript">
106 -```typescript
107 -import { Composio } from '@composio/core';
108 -const composio = new Composio({ apiKey: 'your_api_key' });
109 -const session = await composio.create("user_123");
110 -// ---cut---
111 -// Get all meta tools
112 -const tools = await session.tools();
113 -```
114 -</Tab>
115 -</Tabs>
116 -
117 -To restrict which toolkits or tools are discoverable by the meta tools, configure them when [creating the session](/docs/toolkits/enable-and-disable-toolkits).
118 -
119 -## Browsing the catalog
120 -
121 -Before configuring a session, you may want to explore what toolkits and tools are available. You can browse visually at [dashboard.composio.dev](https://dashboard.composio.dev) or in the [docs](/toolkits), or fetch programmatically:
122 -
123 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
124 -<Tab value="Python">
125 -```python
126 -# List toolkits
127 -toolkits = composio.toolkits.get()
128 -
129 -# List tools within a toolkit (top 20 by default)
130 -tools = composio.tools.get("user_123", toolkits=["GITHUB"])
131 -```
132 -</Tab>
133 -<Tab value="TypeScript">
134 -```typescript
135 -import { Composio } from '@composio/core';
136 -const composio = new Composio({ apiKey: 'your_api_key' });
137 -const userId = 'user_123';
138 -// ---cut---
139 -// List toolkits
140 -const toolkits = await composio.toolkits.get();
141 -
142 -// List tools within a toolkit (top 20 by default)
143 -const tools = await composio.tools.get(userId, { toolkits: ["GITHUB"] });
144 -```
145 -</Tab>
146 -</Tabs>
147 -
148 -### Get a tool's schema
149 -
150 -To inspect a tool's input parameters and types without needing a user context, use `getRawComposioToolBySlug`:
151 -
152 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
153 -<Tab value="Python">
154 -```python
155 -tool = composio.tools.get_raw_composio_tool_by_slug("GMAIL_SEND_EMAIL")
156 -print(tool.name)
157 -print(tool.description)
158 -print(tool.input_parameters)
159 -print(tool.output_parameters)
160 -```
161 -</Tab>
162 -<Tab value="TypeScript">
163 -```typescript
164 -import { Composio } from '@composio/core';
165 -const composio = new Composio({ apiKey: 'your_api_key' });
166 -// ---cut---
167 -const tool = await composio.tools.getRawComposioToolBySlug("GMAIL_SEND_EMAIL");
168 -console.log(tool.name);
169 -console.log(tool.description);
170 -console.log(tool.inputParameters);
171 -console.log(tool.outputParameters);
172 -```
173 -</Tab>
174 -</Tabs>
175 -
176 -## What to read next
177 -
178 -<Cards>
179 - <Card icon={<Wrench />} title="Enable & disable toolkits" href="/docs/toolkits/enable-and-disable-toolkits" description="Control which toolkits and individual tools are available in sessions" />
180 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="How meta tools discover, authenticate, and execute tools at runtime" />
181 - <Card icon={<Blocks />} title="Browse toolkits" href="/toolkits" description="Explore all available toolkits and their tools" />
182 -</Cards>
docs/content/docs/toolkits/meta.json deleted
-8
@@ -1,8 +0,0 @@
1 -{
2 - "title": "Toolkits",
3 - "pages": [
4 - "fetching-tools-and-toolkits",
5 - "enable-and-disable-toolkits",
6 - "custom-tools-and-toolkits"
7 - ]
8 -}
docs/content/docs/tools-and-toolkits.mdx deleted
-100
@@ -1,100 +0,0 @@
1 ----
2 -title: Tools and toolkits
3 -description: Understand how tools and toolkits work in Composio
4 -keywords: [tools, toolkits, meta tools, context management]
5 ----
6 -
7 -A **toolkit** is a collection of related tools for a service. For example, the `github` toolkit contains tools for creating issues, managing pull requests, and starring repositories.
8 -
9 -A **tool** is an individual action your agent can execute. Each tool has an input schema (required and optional parameters) and an output schema (what it returns). Tools follow a `{TOOLKIT}_{ACTION}` naming pattern, like `GITHUB_CREATE_ISSUE`.
10 -
11 -## Meta tools
12 -
13 -When using a Composio session, your agent primarily interfaces with tools and toolkits through meta tools. These tools let the agent search the catalog, inspect schemas, authenticate users, execute app tools, and use the workbench without loading every possible tool into context.
14 -
15 -If you know exactly which tools the agent should use, you can [preload those tools or use the direct tools preset](/docs/configuring-sessions#direct-tools-preset) to expose them directly and disable meta tools.
16 -
17 -A session provides these meta tools:
18 -
19 -| Meta tool | What it does |
20 -|-----------|--------------|
21 -| [`COMPOSIO_SEARCH_TOOLS`](/reference/meta-tools/search_tools) | Discover relevant tools across 500+ apps with execution plans |
22 -| [`COMPOSIO_GET_TOOL_SCHEMAS`](/reference/meta-tools/get_tool_schemas) | Retrieve complete input schemas for specific tools |
23 -| [`COMPOSIO_MULTI_EXECUTE_TOOL`](/reference/meta-tools/multi_execute_tool) | Execute up to 50 tools in parallel |
24 -| [`COMPOSIO_MANAGE_CONNECTIONS`](/reference/meta-tools/manage_connections) | Handle OAuth, API key, and other authentication methods |
25 -| [`COMPOSIO_REMOTE_WORKBENCH`](/reference/meta-tools/remote_workbench) | Run Python code in a [persistent sandbox](/docs/workbench) |
26 -| [`COMPOSIO_REMOTE_BASH_TOOL`](/reference/meta-tools/remote_bash_tool) | Execute bash commands for file and data processing |
27 -
28 -See the [Meta Tools Reference](/reference/meta-tools) for complete input/output schemas and details.
29 -
30 -Meta tool calls in a session are correlated using a `session_id`, allowing them to share context. The tools can also store useful information (like IDs and relationships discovered during execution) in memory for subsequent calls.
31 -
32 -### How it works
33 -
34 -```
35 -User: "Create a GitHub issue for this bug"
36 - ↓
37 -1. Agent calls COMPOSIO_SEARCH_TOOLS
38 - → Returns GITHUB_CREATE_ISSUE with input schema
39 - → Returns connection status: "not connected"
40 - → Returns execution plan and tips
41 - ↓
42 -2. Agent calls COMPOSIO_MANAGE_CONNECTIONS (because not connected)
43 - → Returns auth link for GitHub
44 - → User clicks link and authenticates
45 - ↓
46 -3. Agent calls COMPOSIO_MULTI_EXECUTE_TOOL
47 - → Executes GITHUB_CREATE_ISSUE with arguments
48 - → Returns the created issue details
49 - ↓
50 -Done. (For large results, agent can use REMOTE_WORKBENCH to process)
51 -```
52 -
53 -### What SEARCH_TOOLS returns
54 -
55 -`COMPOSIO_SEARCH_TOOLS` returns:
56 -
57 -- **Tools with schemas** - Matching tools with their slugs, descriptions, and input parameters
58 -- **Connection status** - Whether the user has already authenticated with each toolkit
59 -- **Execution plan** - Recommended steps and common pitfalls for the task
60 -- **Related tools** - Prerequisites, alternatives, and follow-up tools
61 -
62 -### Processing large results
63 -
64 -For most tasks, `COMPOSIO_MULTI_EXECUTE_TOOL` returns results directly. But when dealing with large responses or bulk operations, your agent uses the workbench tools:
65 -
66 -- **`COMPOSIO_REMOTE_WORKBENCH`** - Run Python code in a [persistent sandbox](/docs/workbench). Use for bulk operations (e.g., labeling 100 emails), complex data transformations, or when results need further analysis with helper functions like `invoke_llm`.
67 -
68 -- **`COMPOSIO_REMOTE_BASH_TOOL`** - Execute bash commands for simpler file operations and data extraction using tools like `jq`, `awk`, `sed`, and `grep`.
69 -
70 -## Custom tools and toolkits
71 -
72 -You can also add local in-process tools to a session using the experimental custom tools and custom toolkits API. See [Custom tools and toolkits](/docs/toolkits/custom-tools-and-toolkits).
73 -
74 -## What toolkits does my agent have access to?
75 -
76 -All toolkits are discoverable by default. When you create a session without specifying a `toolkits` parameter, every toolkit in the Composio catalog is available through `COMPOSIO_SEARCH_TOOLS`. The agent searches for relevant tools at runtime — it doesn't load them all into context at once.
77 -
78 -To restrict which toolkits are available, pass `toolkits` when creating the session. See [Enable and disable toolkits](/docs/toolkits/enable-and-disable-toolkits).
79 -
80 -## Authentication
81 -
82 -Tools execute with the user's authenticated credentials. When a user connects their GitHub account, all GitHub tools run with their permissions.
83 -
84 -For OAuth toolkits, Composio uses [managed apps](/docs/custom-app-vs-managed-app) by default. Use a custom app when you need your own OAuth branding, scopes, or consent screen.
85 -
86 -If a tool requires authentication and the user hasn't connected yet, the agent can use `COMPOSIO_MANAGE_CONNECTIONS` to prompt them.
87 -
88 -<Cards>
89 - <Card icon={<Key />} title="Authentication" href="/docs/authentication" description="Learn how Composio handles user authentication" />
90 - <Card icon={<Key />} title="Managed vs custom apps" href="/docs/custom-app-vs-managed-app" description="Choose between Composio managed OAuth apps and your own OAuth app" />
91 -</Cards>
92 -
93 -## What to read next
94 -
95 -<Cards>
96 - <Card icon={<Wrench />} title="Fetching tools" href="/docs/toolkits/fetching-tools-and-toolkits" description="Browse the catalog and fetch tools for sessions" />
97 - <Card icon={<Wrench />} title="Enable & disable toolkits" href="/docs/toolkits/enable-and-disable-toolkits" description="Control which toolkits and individual tools are available in sessions" />
98 - <Card icon={<Monitor />} title="Workbench" href="/docs/workbench" description="Persistent Python sandbox for bulk operations and data processing" />
99 - <Card icon={<Blocks />} title="Browse toolkits" href="/toolkits" description="Explore all available toolkits" />
100 -</Cards>
docs/content/docs/tools-direct/authenticating-tools.mdx
+8 -11
@@ -3,10 +3,11 @@ title: Authenticating Tools
3 description: Create auth configs and connect user accounts
4 keywords: [oauth, api key, auth config, connect account, credentials]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
9 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. Sessions handle authentication automatically via [in-chat authentication](/docs/authenticating-users/in-chat-authentication) or [manual authentication](/docs/authenticating-users/manually-authenticating).
10 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. Sessions handle authentication automatically via [in-chat authentication](/docs/authentication#in-chat-authentication) or [manual authentication](/docs/manually-authenticating).
11 </Callout>
12
13 The first step in authenticating your users is to create an **Auth Config**. Every toolkit has its own authentication method such as `OAuth`, `API key`, `Basic Auth`, or custom schemes.
@@ -79,7 +80,7 @@ You should create multiple auth configs for the same toolkit when you need:
80 - **Different permission levels** - Limiting actions for specific use cases
81
82 <Cards>
82 - <Card title="Programmatic creation" href="/docs/auth-configuration/programmatic-auth-configs">
83 + <Card title="Programmatic creation" href="/docs/programmatic-auth-configs">
84 For managing auth configs across multiple projects, you can create them programmatically via the API
85 </Card>
86 <Card title="Production white-labeling" href="/docs/auth-configuration/white-labeling">
@@ -94,7 +95,7 @@ With an auth config created, you're ready to authenticate your users!
95 You can either use [**Connect Link**](#hosted-authentication-connect-link) for a hosted authentication flow, or use [**Direct SDK Setup**](#direct-sdk-setup).
96
97 <Callout>
97 -User authentication requires a User ID - a unique identifier that groups connected accounts together. Learn more about [User scoping](/docs/how-composio-works) to understand how to structure User IDs for your application.
98 +User authentication requires a userID - a unique identifier that groups connected accounts together. Learn more about [User scoping](/docs/how-composio-works) to understand how to structure userIDs for your application.
99 </Callout>
100
101 **Choose the section below that matches your toolkit's authentication method:**
@@ -416,7 +417,7 @@ After creating a connection, it will have one of the following statuses that ind
417 |--------|---------------|------------|
418 | **ACTIVE** | Connection is working. Tools can be executed. | Nothing — you're good. |
419 | **INITIATED** | OAuth flow started but the user hasn't completed authentication yet. Auto-expires after 10 minutes. | Redirect the user to the Connect Link to finish authentication. |
419 -| **EXPIRED** | Credentials are no longer valid and Composio cannot refresh them automatically. See [common causes](#why-connections-expire) below. | [Subscribe to expiry events](/docs/subscribing-to-connection-expiry-events) to detect this proactively, and [re-authenticate the user](/docs/subscribing-to-connection-expiry-events#re-authenticate-the-user) to refresh the connection. |
420 +| **EXPIRED** | Credentials are no longer valid and Composio cannot refresh them automatically. See [common causes](#why-connections-expire) below. | [Subscribe to expiry events](/docs/authentication#connection-lifecycle) to detect this proactively, and [re-authenticate the user](/docs/authentication#connection-lifecycle) to refresh the connection. |
421 | **FAILED** | The authentication attempt did not succeed. Common causes: user denied consent during OAuth, invalid authorization code, or misconfigured auth config. | Check the `status_reason` field for details and retry the connection. |
422 | **INACTIVE** | Manually disabled via the API. The connection is preserved but cannot be used to execute tools. | Re-enable it via the API or dashboard to restore access. |
423
@@ -430,7 +431,7 @@ Composio automatically refreshes OAuth tokens before they expire. A connection i
431 - **Provider-side revocation** — The provider revoked tokens due to policy changes, security events, or account-level restrictions.
432 - **Repeated transient failures** — If token refresh fails multiple times consecutively (e.g., due to prolonged provider outages), Composio marks the connection as expired after a threshold of failures.
433
433 -In all cases, the user must [re-authenticate](/docs/subscribing-to-connection-expiry-events#re-authenticate-the-user) to restore the connection. Check the `status_reason` field on the connected account for the specific reason. You can also [subscribe to connection expiry events](/docs/subscribing-to-connection-expiry-events) to detect this proactively.
434 +In all cases, the user must [re-authenticate](/docs/authentication#connection-lifecycle) to restore the connection. Check the `status_reason` field on the connected account for the specific reason. You can also [subscribe to connection expiry events](/docs/authentication#connection-lifecycle) to detect this proactively.
435
436 ### Waiting for Connection Establishment
437
@@ -523,10 +524,6 @@ filteredConnections.items.forEach(connection => {
524 Only connections with **ACTIVE** status can be used to execute tools. If a connection is in any other state, you'll need to take appropriate action (re-authenticate, wait for processing, etc.) before using it.
525 </Callout>
526
526 -## What to read next
527 +## Next
528
528 -<Cards>
529 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
530 - <Card icon={<Database />} title="Connected accounts" href="/docs/auth-configuration/connected-accounts" description="Manage and monitor user connections to toolkits" />
531 - <Card icon={<Palette />} title="White-labeling" href="/docs/auth-configuration/white-labeling" description="Remove Composio branding from OAuth screens and auth flows" />
532 -</Cards>
529 +<Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
docs/content/docs/tools-direct/executing-tools.mdx
+4 -7
@@ -3,6 +3,7 @@ title: Executing Tools
3 description: Learn how to execute Composio tools with different providers and frameworks
4 keywords: [execute, run, tool calling, function calling, direct execution]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
@@ -307,7 +308,7 @@ console.log(data);
308 </Tabs>
309
310 <Callout type="info">
310 -Need an API that isn't supported by any Composio toolkit, or want to extend an existing one? Learn how to [create session custom tools](/docs/toolkits/custom-tools-and-toolkits).
311 +Need an API that isn't supported by any Composio toolkit, or want to extend an existing one? Learn how to [create session custom tools](/docs/extending-sessions/custom-tools-and-toolkits).
312 </Callout>
313
314 ## Automatic File Handling
@@ -594,10 +595,6 @@ await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
595 </Tab>
596 </Tabs>
597
597 -## What to read next
598 +## Next
599
599 -<Cards>
600 - <Card icon={<Wrench />} title="Fetching tools" href="/docs/tools-direct/fetching-tools" description="Fetch and filter tools, inspect schemas, and search semantically" />
601 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
602 - <Card icon={<Wrench />} title="Custom tools" href="/docs/toolkits/custom-tools-and-toolkits" description="Create local tools that run inside sessions" />
603 -</Cards>
600 +<Card icon={<Wrench />} title="Fetching tools" href="/docs/tools-direct/fetching-tools" description="Fetch and filter tools, inspect schemas, and search semantically" />
docs/content/docs/tools-direct/fetching-tools.mdx
+4 -7
@@ -3,10 +3,11 @@ title: Fetching tools and schemas
3 description: Fetch and filter tools, and inspect schemas
4 keywords: [get tools, list tools, filter, schema]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
9 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/tools-and-toolkits) for how sessions discover and fetch tools automatically.
10 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/how-composio-works) for how sessions discover and fetch tools automatically.
11 </Callout>
12
13 Fetch specific tools, filter by permissions or search, and inspect schemas for type information. Tools are automatically formatted for your provider.
@@ -242,10 +243,6 @@ const toolkitSearchRaw = await composio.tools.getRawComposioTools({
243 When no toolkit version is specified, the API returns tools from the base version (`00000000_00`), which may be fewer than what's available. Pass `toolkit_versions="latest"` or a specific version to get all tools. Never use `latest` in production. See [toolkit versioning](/docs/tools-direct/toolkit-versioning).
244 </Callout>
245
245 -## What to read next
246 +## Next
247
247 -<Cards>
248 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
249 - <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
250 - <Card icon={<Blocks />} title="Toolkit versioning" href="/docs/tools-direct/toolkit-versioning" description="Pin specific tool versions for consistent behavior in production" />
251 -</Cards>
248 +<Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
docs/content/docs/tools-direct/modify-tool-behavior/after-execution-modifiers.mdx
+4 -7
@@ -2,10 +2,11 @@
2 title: After Execution Modifiers
3 description: Transform tool results after execution
4 llmGuardrails: "direct-execution"
5 +legacy: true
6 ---
7
8 <Callout type="info">
8 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/tools-and-toolkits#meta-tools) for how sessions handle tool discovery and execution automatically.
9 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/how-composio-works#meta-tools) for how sessions handle tool discovery and execution automatically.
10 </Callout>
11
12 After execution modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
@@ -183,10 +184,6 @@ const agenticTools = await composio.tools.get(
184 </Tab>
185 </Tabs>
186
186 -## What to read next
187 +## Next
188
188 -<Cards>
189 - <Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
190 - <Card icon={<Wrench />} title="Schema modifiers" href="/docs/tools-direct/modify-tool-behavior/schema-modifiers" description="Customize how tools appear to agents" />
191 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
192 -</Cards>
189 +<Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx
+4 -7
@@ -2,10 +2,11 @@
2 title: Before Execution Modifiers
3 description: Modify tool arguments before execution
4 llmGuardrails: "direct-execution"
5 +legacy: true
6 ---
7
8 <Callout type="info">
8 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/tools-and-toolkits#meta-tools) for how sessions handle tool discovery and execution automatically.
9 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/how-composio-works#meta-tools) for how sessions handle tool discovery and execution automatically.
10 </Callout>
11
12 Before execution modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
@@ -212,10 +213,6 @@ composio.tools.execute(
213 - **Composition:** `before_file_upload`-type modifiers in the `modifiers` list are applied in **list order** (after filtering by each modifier’s `tools` / `toolkits` scope). Chaining works like a pipeline: each hook receives the path produced by the previous one.
214 - **Relative to `before_execute`:** automatic file substitution runs **before** `before_execute` modifiers, matching TypeScript behavior (including tool router `execute_meta`).
215
215 -## What to read next
216 +## Next
217
217 -<Cards>
218 - <Card icon={<Wrench />} title="After execution modifiers" href="/docs/tools-direct/modify-tool-behavior/after-execution-modifiers" description="Transform tool results after execution" />
219 - <Card icon={<Wrench />} title="Schema modifiers" href="/docs/tools-direct/modify-tool-behavior/schema-modifiers" description="Customize how tools appear to agents" />
220 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
221 -</Cards>
218 +<Card icon={<Wrench />} title="After execution modifiers" href="/docs/tools-direct/modify-tool-behavior/after-execution-modifiers" description="Transform tool results after execution" />
docs/content/docs/tools-direct/modify-tool-behavior/schema-modifiers.mdx
+4 -7
@@ -2,10 +2,11 @@
2 title: Schema Modifiers
3 description: Customize how tools appear to agents
4 llmGuardrails: "direct-execution"
5 +legacy: true
6 ---
7
8 <Callout type="info">
8 -If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/tools-and-toolkits#meta-tools) for how sessions handle tool discovery and execution automatically.
9 +If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Tools and toolkits](/docs/how-composio-works#meta-tools) for how sessions handle tool discovery and execution automatically.
10 </Callout>
11
12 Schema modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
@@ -268,10 +269,6 @@ console.log(tools);
269 </Tab>
270 </Tabs>
271
271 -## What to read next
272 +## Next
273
273 -<Cards>
274 - <Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
275 - <Card icon={<Wrench />} title="After execution modifiers" href="/docs/tools-direct/modify-tool-behavior/after-execution-modifiers" description="Transform tool results after execution" />
276 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
277 -</Cards>
274 +<Card icon={<Wrench />} title="Before execution modifiers" href="/docs/tools-direct/modify-tool-behavior/before-execution-modifiers" description="Modify tool arguments before execution" />
docs/content/docs/tools-direct/toolkit-versioning.mdx
+3 -6
@@ -3,6 +3,7 @@ title: Toolkit Versioning
3 description: Pin specific tool versions for consistent behavior in production
4 keywords: [version, pin version, tool versioning]
5 llmGuardrails: "direct-execution"
6 +legacy: true
7 ---
8
9 <Callout type="info">
@@ -195,10 +196,6 @@ console.log("Latest Version:", toolkit.meta.availableVersions?.[0]);
196 </Tab>
197 </Tabs>
198
198 -## What to read next
199 +## Next
200
200 -<Cards>
201 - <Card icon={<Wrench />} title="Fetching tools" href="/docs/tools-direct/fetching-tools" description="Fetch and filter tools, inspect schemas, and search semantically" />
202 - <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
203 - <Card icon={<Terminal />} title="CLI" href="/docs/cli" description="Generate type-safe code from tool schemas with the Composio CLI" />
204 -</Cards>
201 +<Card icon={<Wrench />} title="Fetching tools" href="/docs/tools-direct/fetching-tools" description="Fetch and filter tools, inspect schemas, and search semantically" />
docs/content/docs/triggers.mdx
+30 -34
@@ -1,49 +1,45 @@
1 ---
2 title: Triggers
3 -description: Understand how Composio delivers event data from connected apps
4 -keywords: [triggers, webhooks, events, polling, webhook endpoint, concepts]
3 +description: React to events in connected apps. Composio delivers them to your app as structured payloads.
4 +keywords: [triggers, events, realtime, polling, webhook, concepts]
5 ---
6
7 -When events occur in apps — a new Slack message, a GitHub commit, an incoming email — triggers send event data to your application as structured payloads.
7 +When something happens in a connected app (a new Slack message, a GitHub commit, an incoming email), a **trigger** sends that event to your app as a structured payload. You write the handler. Composio handles the connection to the provider, delivery, retries, and signing.
8
9 -<Figure src="/images/triggers-flow.svg" srcDark="/images/triggers-flow-dark.svg" alt="Triggers flow: connected apps send events to Composio, which delivers them to your webhook subscription URL via HTTP POST" caption="How triggers deliver events from apps to your application" />
9 +<TriggersFlow />
10
11 -## Two trigger types
11 +## Where events arrive
12
13 -| Type | What happens | Examples |
14 -|---|---|---|
15 -| **Webhook** | The provider pushes events to a Composio-issued ingress URL in real time. Composio verifies the provider's signature, processes the payload, and fans the event out to matching trigger instances. | Slack, Asana, Notion, Outlook |
16 -| **Polling** | Composio polls the provider on a schedule. Composio managed auth has a 15-minute minimum interval; expect that as the worst-case delay between source event and delivery. | Gmail, Google Calendar |
13 +Composio delivers every event to one destination you control: your webhook URL. You register it once per project, and Composio `POST`s every trigger event there, signed so you can verify it.
14
18 -Composio handles ingress setup on most webhook triggers. For some webhook triggers — typically when you bring your own OAuth app — providers only deliver webhooks to URLs you've registered on the OAuth app, so you'll need to register the Composio-issued ingress URL there once for events to start flowing into Composio. See [Configuring the webhook endpoint](/docs/setting-up-triggers/creating-triggers#configuring-the-webhook-endpoint).
15 +## Realtime vs polling
16
20 -## Working with triggers
17 +Under the hood, Composio learns about events in one of two ways. You don't configure this. It's a property of the trigger type, and it only affects how quickly an event reaches you.
18 +
19 +| Kind | How Composio learns about the event | Latency | Examples |
20 +|---|---|---|---|
21 +| **Realtime** | The provider pushes the event to Composio the moment it happens. | Near-instant | Slack, Asana, Notion, Outlook |
22 +| **Polling** | Composio checks the provider on a schedule. | Up to ~15 min on Composio-managed auth | Gmail, Google Calendar |
23
22 -1. **Subscribe** to events so Composio knows which URL to deliver to. One-time per project.
23 -2. **Discover** available trigger types for a toolkit (e.g., `GITHUB_COMMIT_EVENT`).
24 -3. **Create** an active trigger scoped to a user's connected account — see [Creating triggers](/docs/setting-up-triggers/creating-triggers), which also covers [Configuring the webhook endpoint](/docs/setting-up-triggers/creating-triggers#configuring-the-webhook-endpoint) for triggers that need it.
25 -4. **Receive events** at your subscription URL and route on `metadata.trigger_slug`.
26 -5. **Manage** triggers — enable, disable, or delete as needed.
27 -
28 -<Accordions>
29 -<Accordion title="What is a trigger type?">
30 -A trigger type is a template that defines what event to listen for and what configuration is required. For example, `GITHUB_COMMIT_EVENT` requires an `owner` and `repo`. Each toolkit exposes its own set of trigger types.
31 -</Accordion>
32 -<Accordion title="What is a trigger instance?">
33 -When you create a trigger from a type, it's scoped to a specific [user and connected account](/docs/how-composio-works). For example, creating a `GITHUB_COMMIT_EVENT` trigger for user `alice` on the `composio` repo produces a trigger instance with its own `ti_*` ID that you can enable, disable, or delete independently.
34 -</Accordion>
35 -</Accordions>
24 +Either way, the event lands in the same place: your subscription or webhook URL, in the same payload shape.
25
26 <Callout>
38 -Triggers are scoped to a connected account. If you haven't set up authentication yet, see [Authentication](/docs/authentication).
27 +If you **bring your own OAuth app**, some providers only deliver to URLs registered on that app, so you register Composio's ingress URL there once. See [Custom OAuth webhooks](/docs/setting-up-triggers/custom-oauth-webhooks).
28 </Callout>
29
41 -## Next steps
30 +## Trigger types and instances
31 +
32 +A **trigger type** is a kind of event you can listen for, like `GITHUB_COMMIT_EVENT` or a new Slack message. Each toolkit has its own set.
33 +
34 +A **trigger instance** is a trigger type you've activated for one [user's connected account](/docs/how-composio-works). It has its own `ti_*` ID that you can enable, disable, or delete independently.
35 +
36 +## Working with triggers
37 +
38 +0. **Authenticate** the user for the toolkit: an [auth config](/docs/authentication#behind-the-scenes) and a [connected account](/docs/authentication). See [Authentication](/docs/authentication).
39 +1. **Create** a trigger for the user's connected account. See [Creating triggers](/docs/setting-up-triggers/creating-triggers).
40 +2. **Receive** its events: locally with `subscribe()`, or in production at your webhook URL. See [Receiving events](/docs/setting-up-triggers/subscribing-to-events).
41 +3. **Manage** triggers: enable, disable, or delete. See [Managing triggers](/docs/setting-up-triggers/managing-triggers).
42 +
43 +## Next
44
43 -<Cards>
44 - <Card icon={<Plug />} title="Subscribing to events" href="/docs/setting-up-triggers/subscribing-to-events" description="One-time per project: tell Composio which URL to deliver events to" />
45 - <Card icon={<Zap />} title="Creating triggers" href="/docs/setting-up-triggers/creating-triggers" description="Inspect a trigger type and create trigger instances via the SDK or dashboard" />
46 - <Card icon={<ShieldCheck />} title="Verifying webhooks" href="/docs/webhook-verification" description="Verify webhook signatures and understand payload versions" />
47 - <Card icon={<Wrench />} title="Managing triggers" href="/docs/setting-up-triggers/managing-triggers" description="Discover, list, enable, disable, and delete triggers" />
48 - <Card icon={<BookOpen />} title="Example: Gmail labeler" href="/cookbooks/gmail-labeler" description="Build an automated email labeling agent using triggers" />
49 -</Cards>
45 +<Card icon={<Plug />} title="Creating triggers" href="/docs/setting-up-triggers/creating-triggers" description="Activate a trigger for a user so events start flowing" />
docs/content/docs/troubleshooting/api.mdx deleted
-42
@@ -1,42 +0,0 @@
1 ----
2 -title: API
3 -description: Troubleshooting API issues
4 ----
5 -
6 -<Callout>
7 -For a complete list of error codes and their meanings, see [Errors Reference](/reference/errors).
8 -</Callout>
9 -
10 -## Reporting API issues
11 -
12 -When reporting API issues to support, provide the following:
13 -
14 -- **cURL command**: Include the exact cURL to reproduce the issue
15 -- **Request ID**: Add `x-request-id: <uuid>` header to your request and share the UUID (generate at [uuidgenerator.net](https://www.uuidgenerator.net/))
16 -
17 - ```bash
18 - curl 'https://backend.composio.dev/api/v3.1/tools' \
19 - -H 'x-api-key: YOUR_API_KEY' \
20 - -H 'x-request-id: YOUR_UUID_HERE'
21 - ```
22 -
23 -- **Error details**: Share the complete error message. For example:
24 -
25 - ```json
26 - {
27 - "error": {
28 - "message": "Validation error while processing request",
29 - "error_code": 10400,
30 - "suggested_fix": "Please check the payload.",
31 - "errors": [
32 - "Error in payload.text.arguments: Only one of 'text' or 'arguments' must be provided"
33 - ]
34 - }
35 - }
36 - ```
37 -- **Reproduction steps**: Include any steps needed to reproduce the issue
38 -
39 -## Getting help
40 -
41 -- **Email**: support@composio.dev
42 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/authentication.mdx deleted
-55
@@ -1,55 +0,0 @@
1 ----
2 -title: Authentication
3 -description: Troubleshooting authentication issues
4 ----
5 -
6 -## Using Composio's default OAuth app
7 -
8 -When using our default OAuth configuration:
9 -
10 -- **Don't add additional scopes** - They may not be approved in our OAuth app
11 -- Use only the pre-configured scopes provided
12 -
13 -## Using custom OAuth apps
14 -
15 -Ensure your OAuth app is configured correctly:
16 -
17 -- **Redirect URL**: Must match exactly what's configured in your OAuth provider
18 -- **Scopes**: Auth config scopes must match your OAuth app configuration
19 -- **Credentials**: Verify client ID and secret are correct
20 -
21 -For setup guides by toolkit: [OAuth Configuration Guides](https://composio.dev/oauth)
22 -
23 -## Switching to a custom OAuth app
24 -
25 -If you're moving from Composio-managed auth to your own OAuth app, existing connections are not affected. New connections will use your custom auth config. To fully migrate users, delete their old connected accounts and have them re-authenticate.
26 -
27 -- **Sessions:** Pass `authConfigs` when calling `composio.create()`. See [Switching auth configs (sessions)](/docs/white-labeling-authentication#switching-from-composio-managed-to-your-own-oauth-app).
28 -- **Direct tool execution:** Pass the new `authConfigId` when calling `initiate()`. See [Switching auth configs (direct)](/docs/auth-configuration/white-labeling#switching-from-composio-managed-to-your-own-oauth-app).
29 -
30 -## Common authentication issues
31 -
32 -- **Invalid redirect URI**: Check the callback URL matches exactly
33 -- **Scope mismatch**: Ensure requested scopes are configured in both auth config and OAuth app
34 -- **Expired tokens**: Try refreshing the connection
35 -- **Rate limits**: Some providers limit authentication attempts
36 -- **Credentials showing as `REDACTED`**: The "Mask Connected Account Secrets" setting is enabled on your account, which redacts all sensitive credential data. Navigate to **Settings → Project Settings → Project Configuration** and disable "Mask Connected Account Secrets" to view actual values
37 -
38 -## Reporting authentication issues
39 -
40 -When reporting to support, provide:
41 -
42 -- **Error message**: Complete error details and screenshots. For example:
43 -
44 - <Figure src="/images/troubleshooting/troubleshooting-auth-app-blocked.png" alt="Example: This app is blocked error screen shown by Google when un-verified sensitive scopes are configured" size="md" />
45 -
46 -- **Auth config and account IDs**: Include the `authConfigId` used for the request and, if a connection already exists, the `connected_account_id`
47 -
48 - <Figure src="/images/troubleshooting/troubleshooting-auth-config-id.png" alt="Finding authConfigId and connected account ID in the Composio dashboard" size="lg" />
49 -
50 -- **OAuth provider**: Which service you're trying to connect
51 -
52 -## Getting help
53 -
54 -- **Email**: support@composio.dev
55 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/cli.mdx deleted
-105
@@ -1,105 +0,0 @@
1 ----
2 -title: CLI
3 -description: Troubleshooting CLI issues
4 ----
5 -
6 -## Command not found
7 -
8 -Verify the CLI is installed and in your PATH:
9 -
10 -```bash
11 -which composio
12 -```
13 -
14 -If not found, reinstall:
15 -
16 -```bash
17 -curl -fsSL https://composio.dev/install | bash
18 -```
19 -
20 -Or add to PATH:
21 -
22 -```bash
23 -echo 'export PATH="$HOME/.composio:$PATH"' >> ~/.bashrc && source ~/.bashrc
24 -```
25 -
26 -## Authentication errors
27 -
28 -Check current authentication:
29 -
30 -```bash
31 -composio whoami
32 -```
33 -
34 -Re-authenticate if needed:
35 -
36 -```bash
37 -composio logout
38 -composio login
39 -```
40 -
41 -For CI/CD, use environment variable:
42 -
43 -```bash
44 -export COMPOSIO_API_KEY="your-api-key"
45 -```
46 -
47 -If a toolkit account is missing or expired, reconnect it directly:
48 -
49 -```bash
50 -composio link github
51 -```
52 -
53 -## Type generation issues
54 -
55 -### Project type not detected
56 -
57 -Use language-specific commands:
58 -
59 -```bash
60 -composio generate ts # TypeScript
61 -composio generate py # Python
62 -```
63 -
64 -### Output directory missing
65 -
66 -Specify output directory explicitly:
67 -
68 -```bash
69 -composio generate --output-dir ./my-types
70 -```
71 -
72 -If project auto-detection is wrong, initialize local developer context first or use the language-specific command explicitly:
73 -
74 -```bash
75 -composio dev init
76 -```
77 -
78 -## Debug CLI issues
79 -
80 -Enable debug logging:
81 -
82 -```bash
83 -composio --log-level debug [command]
84 -```
85 -
86 -Check version compatibility:
87 -
88 -```bash
89 -composio version
90 -```
91 -
92 -## Common issues
93 -
94 -- **API key not found**: Run `composio login`
95 -- **Toolkit account not connected**: Run `composio link <toolkit>`
96 -- **Project type detection fails**: Use language-specific commands or ensure you're in project root
97 -- **Developer commands fail due to missing project context**: Run `composio dev init`
98 -- **Network timeout**: Check internet connection and proxy settings
99 -- **Permission denied**: Check directory write permissions
100 -
101 -## Getting help
102 -
103 -- **Email**: support@composio.dev
104 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
105 -- **GitHub**: [Create an issue](https://github.com/ComposioHQ/composio/issues/new?labels=bug)
docs/content/docs/troubleshooting/dashboard.mdx deleted
-20
@@ -1,20 +0,0 @@
1 ----
2 -title: Dashboard
3 -description: Troubleshooting dashboard issues
4 ----
5 -
6 -## Reporting dashboard issues
7 -
8 -When reporting dashboard issues to support, provide:
9 -
10 -- **Screenshot or recording**: Visual evidence of the issue
11 -- **Error details**: Complete error message shown in the UI
12 -- **Network logs**: Check browser DevTools (Network tab) for failing API calls and share:
13 - - Request ID (`x-request-id` response header)
14 - - Failed endpoint URL
15 - - Status code and error response
16 -
17 -## Getting help
18 -
19 -- **Email**: support@composio.dev
20 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/index.mdx deleted
-85
@@ -1,85 +0,0 @@
1 ----
2 -title: Troubleshooting
3 -description: Common issues and quick links
4 ----
5 -
6 -import { Bug, Brain, Sparkles, MessageCircle, MessageSquare, BookOpen, Mail, AlertCircle } from 'lucide-react';
7 -
8 -This section is designed to help you quickly identify and resolve common issues encountered with Composio.
9 -
10 -## Common queries
11 -
12 -<Accordions>
13 -
14 -<Accordion title="How do I find the log ID for a failed tool execution?">
15 -Every tool execution response includes a `log_id` field. You can also find it in the [dashboard logs](https://dashboard.composio.dev/~/project/logs) under **Logs > Tools**. Use this ID when reporting issues to support.
16 -
17 -See [Troubleshooting tools](/docs/troubleshooting/tools#reporting-tool-issues) for more details.
18 -</Accordion>
19 -
20 -<Accordion title="How do I find my auth config ID or connected account ID?">
21 -Go to the [dashboard](https://dashboard.composio.dev) and navigate to **Auth Configs** for your auth config ID, or **Connected Accounts** for the connected account ID. Both IDs are visible in the detail view of each entry.
22 -
23 -See [Troubleshooting authentication](/docs/troubleshooting/authentication#reporting-authentication-issues) for screenshots.
24 -</Accordion>
25 -
26 -<Accordion title="How do I find my MCP server ID?">
27 -Your MCP server ID is the UUID in the server URL (e.g., `https://backend.composio.dev/v3/mcp/<UUID>?user_id=user_123`). You can also find it in the [dashboard](https://dashboard.composio.dev) under your MCP server's detail page. MCP URLs must include either `user_id` or `connected_account_id`.
28 -
29 -See [Troubleshooting MCP](/docs/troubleshooting/mcp#reporting-mcp-issues) for a visual guide.
30 -</Accordion>
31 -
32 -<Accordion title="How do I get the request ID for API debugging?">
33 -Add an `x-request-id` header with a UUID to your API request. This lets support trace your exact request in server logs.
34 -
35 -```bash
36 -curl 'https://backend.composio.dev/api/v3.1/tools' \
37 - -H 'x-api-key: YOUR_API_KEY' \
38 - -H 'x-request-id: YOUR_UUID_HERE'
39 -```
40 -
41 -Generate a UUID at [uuidgenerator.net](https://www.uuidgenerator.net/). See [Troubleshooting API](/docs/troubleshooting/api#reporting-api-issues).
42 -</Accordion>
43 -
44 -<Accordion title="How do I find the trigger ID for a trigger instance?">
45 -Go to the [dashboard](https://dashboard.composio.dev) and navigate to **Active Triggers**. The trigger ID is shown for each trigger instance.
46 -
47 -See [Troubleshooting triggers](/docs/troubleshooting/triggers#reporting-issues) for a screenshot.
48 -</Accordion>
49 -
50 -<Accordion title="Why does the API return fewer tools than the platform UI?">
51 -The Get Tools API defaults to the base toolkit version (`00000000_00`) when `toolkit_versions` is not specified. Pass `toolkit_versions=latest` to get all available tools.
52 -
53 -See [Troubleshooting tools](/docs/troubleshooting/tools#api-returning-fewer-tools-than-expected) for details.
54 -</Accordion>
55 -
56 -</Accordions>
57 -
58 -## Quick links
59 -
60 -<Cards>
61 - <Card title="Errors Reference" href="/reference/errors" icon={<AlertCircle />}>
62 - HTTP status codes and how to resolve common errors.
63 - </Card>
64 - <Card title="Report issues" href="https://github.com/ComposioHQ/composio/issues/new?labels=bug" icon={<Bug />}>
65 - Found a bug? Please create a Github issue!
66 - </Card>
67 - <Card title="Ask AI" href="https://deepwiki.com/ComposioHQ/composio" icon={<Brain />}>
68 - Try to use Ask AI in the docs or deepwiki to get the fastest responses on features, types, and best practices.
69 - </Card>
70 - <Card title="Feature requests" href="https://github.com/ComposioHQ/composio/issues/new?labels=enhancement" icon={<Sparkles />}>
71 - Have an idea for improving Composio? Share your feature suggestions with us and we will prioritise your requests
72 - </Card>
73 - <Card title="Ask the community" href="https://github.com/ComposioHQ/composio/discussions" icon={<MessageCircle />}>
74 - Join our GitHub discussions to get help from the community
75 - </Card>
76 - <Card title="Discord community" href="https://discord.com/channels/1170785031560646836/1268871288156323901" icon={<MessageSquare />}>
77 - Post support queries on our discord channel
78 - </Card>
79 - <Card title="Contact Support" href="mailto:support@composio.dev" icon={<Mail />}>
80 - Reach out to support for account, billing, or escalations
81 - </Card>
82 - <Card title="Migration guides" href="/docs/migration-guide" icon={<RouteIcon />}>
83 - Check out our migration guides to help you upgrade to the latest version.
84 - </Card>
85 -</Cards>
docs/content/docs/troubleshooting/mcp.mdx deleted
-63
@@ -1,63 +0,0 @@
1 ----
2 -title: MCP
3 -description: Troubleshooting MCP server issues
4 ----
5 -
6 -## Connected account not found error
7 -
8 -This error occurs when MCP cannot find a valid connected account for authentication:
9 -
10 -- **Specify an account**: Provide either `connected_account_id` or `user_id` in your MCP configuration
11 -- **Default behavior**: Without specification, MCP uses `user_id=default`. If multiple connections exist with the same user_id, the most recent is used
12 -- **Verification checklist**:
13 - - Account status is `ACTIVE` (not deleted)
14 - - Account belongs to the same auth config used to create the MCP server. MCP servers only resolve connected accounts through their bound auth configs, so connections under a different auth config will not be found.
15 -
16 -To fix a mismatched auth config, update the MCP server's `auth_config_ids` using the [`PATCH /api/v3.1/mcp/{id}`](/reference/api-reference/mcp/patchMcpById) endpoint.
17 -
18 -Learn more: [Single Toolkit MCP](/docs/single-toolkit-mcp)
19 -
20 -## Getting 404 errors
21 -
22 -Verify your URL format matches one of these patterns:
23 -
24 -- `https://apollo-<randomID>-composio.vercel.app/v3/mcp/<UUID>`
25 -- `https://apollo.composio.dev/v3/mcp/<UUID>`
26 -
27 -## Getting 401 Unauthorized errors
28 -
29 -If your MCP client gets `401 Unauthorized`, include your Composio project API key in request headers:
30 -
31 -- Header name: `x-api-key`
32 -- Value: your project API key from the Composio dashboard
33 -
34 -When `require_mcp_api_key` is enabled on your project, requests without this header are rejected.
35 -
36 -## Testing and debugging
37 -
38 -If experiencing issues, test your MCP server with:
39 -
40 -- [Postman MCP Requests](https://learning.postman.com/docs/postman-ai-developer-tools/mcp-requests/create/)
41 -- [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)
42 -
43 -This helps identify whether the issue is with your MCP client or the server.
44 -
45 -## Reporting MCP issues
46 -
47 -When reporting to support, provide:
48 -
49 -- **Error message**: Complete error details
50 -- **MCP server URL**: The exact URL you're connecting to and the corresponding `mcp_server_id`
51 -
52 - <Figure src="/images/troubleshooting/troubleshooting-mcp-server-url.png" alt="Example MCP server URL shown in the Composio dashboard" size="lg" />
53 -
54 -- **Testing results**: Whether issue reproduces in MCP Inspector/Postman or only in specific client
55 -- **Connected account ID**: If facing connection issues
56 -
57 - <Figure src="/images/troubleshooting/troubleshooting-mcp-connected-account-id.png" alt="Example connected account ID used for MCP authentication" size="lg" />
58 -- **Reproduction steps**: Clear steps to reproduce the issue
59 -
60 -## Getting help
61 -
62 -- **Email**: support@composio.dev
63 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/meta.json deleted
-13
@@ -1,13 +0,0 @@
1 -{
2 - "title": "Troubleshooting",
3 - "pages": [
4 - "api",
5 - "authentication",
6 - "cli",
7 - "dashboard",
8 - "mcp",
9 - "sdks",
10 - "tools",
11 - "triggers"
12 - ]
13 -}
docs/content/docs/troubleshooting/sdks.mdx deleted
-57
@@ -1,57 +0,0 @@
1 ----
2 -title: SDKs
3 -description: Troubleshooting SDK issues
4 ----
5 -
6 -## Debug network issues
7 -
8 -Enable debug logging to see API calls and identify if issues are SDK or API related. When contacting support, share the full debug logs **along with** the `x-request-id`.
9 -
10 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
11 - <Tab value="Python">
12 -```bash
13 -# Set environment variable
14 -COMPOSIO_LOGGING_LEVEL=debug
15 -```
16 - </Tab>
17 - <Tab value="TypeScript">
18 -```bash
19 -// Set environment variable
20 -COMPOSIO_LOG_LEVEL=debug
21 -```
22 - </Tab>
23 -</Tabs>
24 -
25 -Look for `x-request-id` in the debug output to share with support.
26 -
27 -## Check SDK version
28 -
29 -Ensure you're using the latest version:
30 -
31 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
32 - <Tab value="Python">
33 -```bash
34 -pip install --upgrade composio
35 -```
36 - </Tab>
37 - <Tab value="TypeScript">
38 -```bash
39 -npm install @composio/core@latest
40 -```
41 - </Tab>
42 -</Tabs>
43 -
44 -Check current version:
45 -- Python: [PyPI](https://pypi.org/project/composio/)
46 -- TypeScript: [npm](https://www.npmjs.com/package/@composio/core)
47 -
48 -## Common issues
49 -
50 -- **Type errors or parameter confusion**: Search [DeepWiki](https://deepwiki.com/ComposioHQ/composio) or use the Ask AI assistant
51 -- **Tool-specific issues**: Check the [specific tool's documentation](/toolkits)
52 -- **Bug reporting**: Create a [GitHub issue](https://github.com/ComposioHQ/composio/issues/new?labels=bug) with debug logs and reproduction steps
53 -
54 -## Getting help
55 -
56 -- **Email**: support@composio.dev
57 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/tools.mdx deleted
-72
@@ -1,72 +0,0 @@
1 ----
2 -title: Tools & Toolkits
3 -description: Troubleshooting tool execution issues
4 ----
5 -
6 -## Tool execution failures (401/403 errors)
7 -
8 -Authentication and permission errors typically occur due to:
9 -
10 -### Missing scopes
11 -
12 -The tool you're calling may require OAuth scopes that weren't granted when the user authenticated. Re-authenticate the user with the required scopes, or check the toolkit's documentation for which scopes each tool needs.
13 -
14 -### Insufficient permissions
15 -
16 -Verify the connected account has necessary permissions:
17 -
18 -- **Admin requirements**: Some tools require admin-level access
19 -- **Paid accounts**: Certain toolkits need paid subscriptions
20 - - Example: MS Teams requires Microsoft 365 account + Azure AD tenant
21 -
22 -## API returning fewer tools than expected
23 -
24 -If the Get Tools API (`GET /api/v3.1/tools`) returns fewer tools than what's shown on the [platform UI](https://dashboard.composio.dev), you likely need to specify a toolkit version.
25 -
26 -When `toolkit_versions` is not provided, the API defaults to the base version (`00000000_00`), which only includes tools from the initial release. Tools added in later versions won't appear.
27 -
28 -To get all available tools, pass `toolkit_versions=latest`:
29 -
30 -```bash
31 -curl 'https://backend.composio.dev/api/v3.1/tools?toolkit_slug=googledrive&toolkit_versions=latest' \
32 - -H 'x-api-key: YOUR_API_KEY'
33 -```
34 -
35 -See [Toolkit versioning](/docs/tools-direct/toolkit-versioning) for more details.
36 -
37 -## Tool not working
38 -
39 -- Check [tool-specific documentation](/toolkits) for requirements
40 -- Verify the connected account is active and properly authenticated
41 -- Test with the latest SDK version
42 -
43 -## Reporting tool issues
44 -
45 -When reporting to support, provide:
46 -
47 -
48 -- **Error message**: Complete error details. For example:
49 -
50 - ```json
51 - {
52 - "data": {
53 - "message": "{\n \"error\": {\n \"code\": 404,\n \"message\": \"Requested entity was not found.\",\n \"errors\": [\n {\n \"message\": \"Requested entity was not found.\",\n \"domain\": \"global\",\n \"reason\": \"notFound\"\n }\n ],\n \"status\": \"NOT_FOUND\"\n }\n}\n",
54 - "status_code": 404
55 - },
56 - "successful": false,
57 - "error": "404 Client Error: Not Found for url: https://gmail.googleapis.com/gmail/v1/users/me/messages/123456?format=full",
58 - "log_id": "log_tVqomBgg11-t"
59 - }
60 - ```
61 -
62 -- **Log ID**: From the error response (`log_id` field), or find it in the dashboard Logs page:
63 -
64 - <Figure src="/images/troubleshooting/troubleshooting-tool-log-id.png" alt="Example tool execution log showing log_id in the Composio dashboard" size="lg" />
65 -
66 -- **Tool name**: Exact tool slug being executed (for example, `GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID`)
67 -- **Connected account ID**: Account used for execution (for example, `ca_xxx`)
68 -
69 -## Getting help
70 -
71 -- **Email**: support@composio.dev
72 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/troubleshooting/triggers.mdx deleted
-34
@@ -1,34 +0,0 @@
1 ----
2 -title: Triggers
3 -description: Troubleshooting trigger issues
4 ----
5 -
6 -## Unable to create trigger
7 -
8 -Check the error message — the connected account might not have sufficient permissions or the required OAuth scopes. Ensure the user has authenticated with the necessary scopes for the trigger.
9 -
10 -## Not receiving payloads
11 -
12 -- **Polling triggers** (e.g., Gmail): These check for new events on an interval you configure. For Composio managed auth, intervals below 15 minutes are not supported.
13 -- **Webhook URL**: Ensure your URL is publicly accessible and returns a `2xx` status code.
14 -- **Trigger status**: Verify the trigger is enabled, not disabled.
15 -- **Logs**: Check the [trigger logs](https://dashboard.composio.dev/~/project/logs?tab=triggers) in the dashboard for delivery attempts and errors.
16 -
17 -## Type errors with trigger payloads
18 -
19 -Use `getType()` / `get_type()` to inspect the exact payload schema for a trigger type. This shows you the fields and types you should expect.
20 -
21 -## Reporting issues
22 -
23 -When contacting support, include:
24 -
25 -- **Trigger ID** and **connected account ID** — find these under Active Triggers in the dashboard:
26 -
27 - <Figure src="/images/troubleshooting/troubleshooting-trigger-id.png" alt="Trigger ID and connected account ID in the dashboard" size="lg" />
28 -
29 -- **Error message** and **reproduction steps**
30 -
31 -## Getting help
32 -
33 -- **Email**: support@composio.dev
34 -- **Discord**: [#support-form](https://discord.com/channels/1170785031560646836/1268871288156323901)
docs/content/docs/webhook-verification.mdx deleted
-204
@@ -1,204 +0,0 @@
1 ----
2 -title: Verifying webhooks
3 -description: Verify webhook signatures to ensure payloads are authentic
4 -keywords: [webhook, verification, signature, HMAC, security]
5 ----
6 -
7 -Composio signs every webhook request. Always verify signatures in production to ensure payloads are authentic.
8 -
9 -## SDK verification
10 -
11 -The SDK handles signature verification, payload parsing, and version detection (V1, V2, V3).
12 -
13 -<Callout>
14 -Store the webhook secret securely as `COMPOSIO_WEBHOOK_SECRET`. You can fetch it from the [webhook subscription](/reference/api-reference/webhook-subscriptions/getWebhookSubscriptionsById) at any time or [rotate it](/reference/api-reference/webhook-subscriptions/postWebhookSubscriptionsByIdRotateSecret) if it leaks.
15 -</Callout>
16 -
17 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
18 - <Tab value="Python">
19 -```python
20 -try:
21 - result = composio.triggers.verify_webhook(
22 - id=request.headers.get("webhook-id", ""),
23 - payload=request.get_data(as_text=True),
24 - signature=request.headers.get("webhook-signature", ""),
25 - timestamp=request.headers.get("webhook-timestamp", ""),
26 - secret=os.getenv("COMPOSIO_WEBHOOK_SECRET", ""),
27 - )
28 - # result.version, result.payload, result.raw_payload
29 -except Exception:
30 - return {"error": "Invalid signature"}, 401
31 -```
32 - </Tab>
33 - <Tab value="TypeScript">
34 -```typescript
35 -import { Composio } from '@composio/core';
36 -const composio = new Composio();
37 -const req = { headers: {} as Record<string, string>, body: '' };
38 -// ---cut---
39 -try {
40 - const result = await composio.triggers.verifyWebhook({
41 - id: req.headers['webhook-id'],
42 - payload: req.body,
43 - signature: req.headers['webhook-signature'],
44 - timestamp: req.headers['webhook-timestamp'],
45 - secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
46 - });
47 - // result.version, result.payload, result.rawPayload
48 -} catch (error) {
49 - // Return 401
50 -}
51 -```
52 - </Tab>
53 -</Tabs>
54 -
55 -<Callout>
56 -An optional `tolerance` parameter (default: `300` seconds) controls how old a webhook can be before verification fails. Set to `0` to disable timestamp validation.
57 -</Callout>
58 -
59 -## Manual verification
60 -
61 -If you are not using the Composio SDK and want to verify signatures manually.
62 -
63 -<Callout>
64 -Store the webhook secret securely as `COMPOSIO_WEBHOOK_SECRET`. You can fetch it from the [webhook subscription](/reference/api-reference/webhook-subscriptions/getWebhookSubscriptionsById) at any time or [rotate it](/reference/api-reference/webhook-subscriptions/postWebhookSubscriptionsByIdRotateSecret) if it leaks.
65 -</Callout>
66 -
67 -Every webhook request includes three headers: `webhook-signature`, `webhook-id`, and `webhook-timestamp`. Use these along with the raw request body to verify the signature:
68 -
69 -<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
70 - <Tab value="Python">
71 -```python
72 -import hmac
73 -import hashlib
74 -import base64
75 -import json
76 -import os
77 -
78 -def verify_webhook(webhook_id: str, webhook_timestamp: str, body: str, signature: str) -> dict:
79 - secret = os.getenv("COMPOSIO_WEBHOOK_SECRET", "")
80 - signing_string = f"{webhook_id}.{webhook_timestamp}.{body}"
81 - expected = base64.b64encode(
82 - hmac.new(secret.encode(), signing_string.encode(), hashlib.sha256).digest()
83 - ).decode()
84 - received = signature.split(",", 1)[1] if "," in signature else signature
85 - if not hmac.compare_digest(expected, received):
86 - raise ValueError("Invalid webhook signature")
87 -
88 - payload = json.loads(body)
89 - # V3 payload
90 - return {
91 - "trigger_slug": payload["metadata"]["trigger_slug"],
92 - "data": payload["data"],
93 - }
94 -```
95 - </Tab>
96 - <Tab value="TypeScript">
97 -```typescript
98 -import crypto from 'crypto';
99 -// ---cut---
100 -function verifyWebhook(
101 - webhookId: string,
102 - webhookTimestamp: string,
103 - body: string,
104 - signature: string
105 -) {
106 - const secret = process.env.COMPOSIO_WEBHOOK_SECRET ?? '';
107 - const signingString = `${webhookId}.${webhookTimestamp}.${body}`;
108 - const expected = crypto
109 - .createHmac('sha256', secret)
110 - .update(signingString)
111 - .digest('base64');
112 - const received = signature.split(',')[1] ?? signature;
113 - if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))) {
114 - throw new Error('Invalid webhook signature');
115 - }
116 -
117 - const payload = JSON.parse(body);
118 - // V3 payload
119 - return {
120 - triggerSlug: payload.metadata.trigger_slug,
121 - data: payload.data,
122 - };
123 -}
124 -```
125 - </Tab>
126 -</Tabs>
127 -
128 -
129 -## Webhook payload versions
130 -
131 -`verifyWebhook()` auto-detects the version. If you process payloads manually, here are the formats:
132 -
133 -<Tabs items={['V3 (default)', 'V2 (legacy)', 'V1 (legacy)']}>
134 - <Tab value="V3 (default)">
135 -Metadata is separated from event data. New organizations receive V3 payloads by default.
136 -
137 -```json
138 -{
139 - "id": "msg_abc123",
140 - "type": "composio.trigger.message",
141 - "metadata": {
142 - "log_id": "log_abc123",
143 - "trigger_slug": "GITHUB_COMMIT_EVENT",
144 - "trigger_id": "ti_xyz789",
145 - "connected_account_id": "ca_def456",
146 - "auth_config_id": "ac_xyz789",
147 - "user_id": "user-id-123435"
148 - },
149 - "data": {
150 - "commit_sha": "a1b2c3d",
151 - "message": "fix: resolve null pointer",
152 - "author": "jane"
153 - },
154 - "timestamp": "2026-01-15T10:30:00Z"
155 -}
156 -```
157 - </Tab>
158 - <Tab value="V2 (legacy)">
159 -Metadata fields are mixed into the `data` object alongside event data.
160 -
161 -```json
162 -{
163 - "type": "github_commit_event",
164 - "data": {
165 - "commit_sha": "a1b2c3d",
166 - "message": "fix: resolve null pointer",
167 - "author": "jane",
168 - "connection_id": "ca_def456",
169 - "connection_nano_id": "cn_abc123",
170 - "trigger_nano_id": "tn_xyz789",
171 - "trigger_id": "ti_xyz789",
172 - "user_id": "user-id-123435"
173 - },
174 - "timestamp": "2026-01-15T10:30:00Z",
175 - "log_id": "log_abc123"
176 -}
177 -```
178 - </Tab>
179 - <Tab value="V1 (legacy)">
180 -```json
181 -{
182 - "trigger_name": "github_commit_event",
183 - "trigger_id": "ti_xyz789",
184 - "connection_id": "ca_def456",
185 - "payload": {
186 - "commit_sha": "a1b2c3d",
187 - "message": "fix: resolve null pointer",
188 - "author": "jane"
189 - },
190 - "log_id": "log_abc123"
191 -}
192 -```
193 - </Tab>
194 -</Tabs>
195 -
196 -## What to read next
197 -
198 -<Cards>
199 - <Card icon={<Plug />} title="Subscribing to events" href="/docs/setting-up-triggers/subscribing-to-events" description="Set up webhooks and SDK subscriptions to receive trigger events" />
200 - <Card icon={<RouteIcon />} title="Creating triggers" href="/docs/setting-up-triggers/creating-triggers" description="Configure the webhook endpoint when needed and create trigger instances" />
201 - <Card icon={<Zap />} title="Triggers overview" href="/docs/triggers" description="How Composio delivers event data from connected apps" />
202 - <Card icon={<Key />} title="Connection expiry events" href="/docs/subscribing-to-connection-expiry-events" description="Detect when OAuth connections expire and prompt re-authentication" />
203 -</Cards>
204 -
docs/content/docs/white-labeling-authentication.mdx
+5 -16
@@ -17,14 +17,12 @@ There are four places where Composio branding shows up during authentication:
17
18 The Connect Link is the hosted page your users see when connecting their accounts. By default it shows Composio branding.
19
20 -<Video src="/videos/connect-link-branding.mp4" autoPlay />
21 -
20 To replace it with your own branding:
21
22 1. Go to **Project Settings** → [**Auth Screen**](https://dashboard.composio.dev/~/project/settings/auth-screen)
23 2. Upload your **Logo** and set your **App Title**
24
27 -This applies to all Connect Link flows across all toolkits, for both [in-chat](/docs/authenticating-users/in-chat-authentication) and [manual](/docs/authenticating-users/manually-authenticating) authentication. Each project has one logo and app title, so if you need different branding per product, use separate projects.
25 +This applies to all Connect Link flows across all toolkits, for both [in-chat](/docs/authentication#in-chat-authentication) and [manual](/docs/manually-authenticating) authentication. Each project has one logo and app title, so if you need different branding per product, use separate projects.
26
27 <Callout>
28 Customizing the Connect Link only changes the Composio-hosted page. For OAuth toolkits like Gmail, Google Sheets, GitHub, and Slack, users still see a consent screen saying "Composio wants to access your account." To change that, and to remove the "Secured by Composio" badge, set up your own OAuth app as described [below](#using-your-own-oauth-apps).
@@ -120,13 +118,7 @@ In the Composio dashboard, update your auth config to use your custom redirect U
118
119 Here's how the redirect flow works. Your proxy just forwards the browser redirect to Composio. It never touches the authorization code or token.
120
123 -```mermaid
124 -flowchart TD
125 - A[Your App] -->|User connects| B["OAuth toolkit (e.g. Google, GitHub)"]
126 - B -->|Redirects user| C[yourdomain.com]
127 - C -->|Forwards redirect| D[backend.composio.dev]
128 - D -.->|Redirects back| A
129 -```
121 +<WhiteLabelFlow />
122
123 <Callout type="info">
124 For FAQs and setup guides for individual toolkits, browse the [toolkits page](/toolkits).
@@ -158,11 +150,8 @@ const connectionRequest = await session.authorize("gmail", {
150 </Tab>
151 </Tabs>
152
161 -After authentication, Composio redirects the user to your callback URL instead of the default success page. For full details on the parameters appended to your callback URL, see [Manually authenticating users → Redirecting users after authentication](/docs/authenticating-users/manually-authenticating#redirecting-users-after-authentication).
153 +After authentication, Composio redirects the user to your callback URL instead of the default success page. For full details on the parameters appended to your callback URL, see [Manually authenticating users → Redirecting users after authentication](/docs/manually-authenticating#redirecting-users-after-authentication).
154
163 -## What to read next
155 +## Next
156
165 -<Cards>
166 - <Card icon={<Key />} title="Managed vs custom auth" href="/docs/custom-app-vs-managed-app" description="Set up auth configs for OAuth apps, API keys, and toolkits without managed auth" />
167 - <Card icon={<Key />} title="Authentication overview" href="/docs/authentication" description="Connect Links, OAuth, API keys, and how Composio manages auth" />
168 -</Cards>
157 +<Card icon={<Key />} title="Managed vs custom auth" href="/docs/custom-app-vs-managed-app" description="Set up auth configs for OAuth apps, API keys, and toolkits without managed auth" />
docs/content/docs/workbench.mdx deleted
-86
@@ -1,86 +0,0 @@
1 ----
2 -title: Workbench
3 -description: A persistent Python sandbox for writing code, calling tools programmatically, and processing data
4 -keywords: [workbench, sandbox, remote execution, bulk operations, data processing]
5 ----
6 -
7 -The workbench is a persistent Python sandbox where your agent can write and execute code. It has access to all Composio tools programmatically, plus helper functions for calling LLMs, uploading files, and making API requests. State persists across calls within a [session](/docs/how-composio-works). The `COMPOSIO_REMOTE_BASH_TOOL` meta tool also runs commands in the same sandbox.
8 -
9 -<Callout>
10 -The workbench is part of the [meta tools](/docs/tools-and-toolkits#meta-tools) system. It's available when you create sessions, not when [executing tools directly](/docs/tools-direct/executing-tools).
11 -</Callout>
12 -
13 -## Where it fits
14 -
15 -Your agent starts with [`SEARCH_TOOLS` to find the right tools, then uses `MULTI_EXECUTE`](/docs/tools-and-toolkits#meta-tools) for straightforward calls. When the task involves bulk operations, data transformations, or multi-step logic, the agent uses `COMPOSIO_REMOTE_WORKBENCH` instead.
16 -
17 -```mermaid
18 -graph TD
19 - U["Triage my emails, label urgent ones, log to a Google Sheet"] --> S["1. SEARCH_TOOLS"]
20 - S --> M["2. MULTI_EXECUTE"]
21 - M --> W["3. REMOTE_WORKBENCH"]
22 - W --> D["Done"]
23 -
24 - S -.- S1["Discovers Gmail and Sheets tools"]:::annotation
25 - M -.- M1["Fetches unread emails"]:::annotation
26 - W -.- W1["Classifies, labels, and logs to sheet in parallel"]:::annotation
27 -
28 - classDef annotation stroke-dasharray: 5 5
29 -```
30 -
31 -## What the sandbox provides
32 -
33 -### Built-in helpers
34 -
35 -These functions are pre-initialized in every sandbox:
36 -
37 -| Helper | What it does |
38 -|--------|-------------|
39 -| `run_composio_tool` | Execute any Composio tool (e.g., `GMAIL_SEND_EMAIL`, `SLACK_SEND_MESSAGE`) and get structured results |
40 -| `invoke_llm` | Call an LLM for classification, summarization, content generation, or data extraction |
41 -| `upload_local_file` | Upload generated files (reports, CSVs, images) to cloud storage and get a download URL |
42 -| `proxy_execute` | Make direct API calls to connected services when no pre-built tool exists |
43 -| `web_search` | Search the web and return results for research or data enrichment |
44 -| `smart_file_extract` | Extract text from PDFs, images, and other file formats in the sandbox |
45 -
46 -### Libraries
47 -
48 -Common packages like pandas, numpy, matplotlib, Pillow, PyTorch, and reportlab are pre-installed. Beyond these, the workbench maintains a list of supported packages and their dependencies. If the agent uses a package that isn't already installed, the workbench attempts to install it automatically.
49 -
50 -### Error correction
51 -
52 -The workbench corrects common mistakes in the code your agent generates. For example, if a script accesses `result["apiKey"]` but the actual field name is `api_key`, the workbench resolves the mismatch instead of failing.
53 -
54 -### Persistent state
55 -
56 -The sandbox runs as a persistent Jupyter notebook. Variables, imports, files, and in-memory state from one call are available in the next.
57 -
58 -### Compute tier
59 -
60 -Sandboxes default to `standard` (1 vCPU / 1 GB RAM). For heavier workloads — large dataframes, ML preprocessing, big bulk operations — pick a larger tier when creating the session via `workbench.sandboxSize` (TypeScript) / `workbench.sandbox_size` (Python). Available tiers: `standard`, `medium` (2 vCPU / 2 GB), `large` (4 vCPU / 4 GB), `xlarge` (8 vCPU / 8 GB). Requires `@composio/core` ≥ `0.8.1` or `composio` ≥ `0.12.1`. See [Configuring Sessions → Sandbox compute tier](/docs/configuring-sessions#sandbox-compute-tier) for examples.
61 -
62 -<Callout type="info">
63 -**Pricing:** Sandboxes are not billed today. Composio plans to begin billing for sandbox usage soon (metered by tier and runtime).
64 -</Callout>
65 -
66 -## Common patterns
67 -
68 -### Bulk operations across apps
69 -
70 -Some tasks touch hundreds of items across services. Say you need to triage 150 unread emails. The agent writes a workbench script: classify each email with `invoke_llm`, apply Gmail labels with `run_composio_tool`, and log results to a Google sheet.
71 -
72 -### Data analysis and reporting
73 -
74 -The agent can chain tools inside the sandbox. Fetch GitHub activity, aggregate with pandas, chart with matplotlib, summarize with `invoke_llm`, upload a PDF with `upload_local_file`.
75 -
76 -### Multi-step workflows
77 -
78 -The sandbox preserves variables and files across calls. The agent can paginate through records, transform them, and write to a destination over multiple calls.
79 -
80 -## What to read next
81 -
82 -<Cards>
83 - <Card icon={<Database />} title="What is a session?" href="/docs/how-composio-works" description="How sessions scope tools, auth, and workbench state to a user" />
84 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="How meta tools discover, authenticate, and execute tools at runtime" />
85 - <Card icon={<Zap />} title="Triggers" href="/docs/triggers" description="Event-driven payloads from connected apps" />
86 -</Cards>
docs/content/examples/general-agent-with-pi.mdx new
+107
@@ -0,0 +1,107 @@
1 +---
2 +title: Build a Slack bot that can do work with you and your team
3 +description: Build a general-purpose agent with Pi and Composio, then drop it into Slack so a whole team can use it. Triggers, per-user sessions, a shared workspace connection, redirected auth links, and raw API access.
4 +keywords: [general agent, pi, slack bot, triggers, sessions, shared connections, auth links, proxy, slackbot toolkit, webhook]
5 +full: true
6 +---
7 +
8 +The agent is the easy part. [Pi](https://github.com/earendil-works/pi/tree/main/packages/coding-agent) does the reasoning; Composio gives it 1000+ apps to act on. In three lines you have an agent that can open a PR, check a calendar, or search a Notion workspace for one user.
9 +
10 +The work is everything around it: putting that agent in Slack, where a whole team talks to it, and making it act as *each* person while posting as one bot. That's a handful of Composio pieces:
11 +
12 +1. **Triggers** deliver every Slack message to your server as a webhook.
13 +2. **Sessions** give each user their own scoped toolset, so the agent acts as *them*.
14 +3. **A shared connection** lets the bot speak as the workspace bot, with one install for everyone.
15 +4. **Redirected auth links** keep OAuth out of the channel: when an app isn't connected, the bot DMs the user a link and resumes on approval.
16 +5. **The proxy** reaches the Slack Web API endpoints the toolkit doesn't wrap as tools.
17 +
18 +<SlackBotFlow />
19 +
20 +Below you build the whole thing from scratch: a basic agent first, then a piece at a time up to the full server, then a browse of the real source. You bring a Composio API key and an agent runtime. Composio brings the workspace.
21 +
22 +## Setup
23 +
24 +You need a [Composio API key](https://dashboard.composio.dev), a publicly reachable URL for your server, and [Bun](https://bun.sh).
25 +
26 +<Accordions>
27 + <Accordion title="No public URL? Use a Cloudflare tunnel">
28 + Composio posts webhooks to your server, so it needs a public URL. In local development, run a [Cloudflare tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) to expose your local port:
29 +
30 + ```bash
31 + cloudflared tunnel --url http://localhost:3000
32 + ```
33 +
34 + Use the `https://…trycloudflare.com` URL it prints as your `APP_URL`.
35 + </Accordion>
36 +</Accordions>
37 +
38 +```bash
39 +bun add @composio/core @composio/experimental @earendil-works/pi-coding-agent
40 +```
41 +
42 +## Install the bot
43 +
44 +A Slack bot needs a Slack app to authenticate as and a stream of events. Composio gives you both, so you never register a webhook with Slack or hold a bot token. The `slackbot` toolkit ships with Composio-managed OAuth, and you install it as one **[shared connection](/docs/shared-connections)** for the whole workspace.
45 +
46 +This is `install.ts`, run once, built up three steps at a time:
47 +
48 +<FileBuildup name="install" />
49 +
50 +A webhook subscription is the *pipe*; each trigger is a *tap*. Together they stream channel messages and DMs to your server. The connected account id that comes back from the OAuth callback is the `SLACK_CONNECTION_ID` the server pins into every session.
51 +
52 +## Build the bot
53 +
54 +`bot.ts` starts as a bare three-line agent and grows into the server, one Composio concept at a time. Each diff below is exactly what that concept adds.
55 +
56 +### Start with a basic agent
57 +
58 +The whole idea, before any Slack: create a session for a user, hand the Pi provider the session so it can search and execute, and run a prompt. This already acts across every app that user has connected.
59 +
60 +<FileBuildup name="bot" step={1} />
61 +
62 +### Put it in a Slack thread
63 +
64 +Turn the one-shot agent into a handler. Each Slack thread gets its own [session](/docs/configuring-sessions), reused so the agent keeps context, and the reply goes back with the `SLACKBOT_SEND_MESSAGE` tool. The session is keyed to the Slack user, so when Alice asks for a GitHub issue it opens as *Alice*, against her GitHub connection.
65 +
66 +<FileBuildup name="bot" step={2} />
67 +
68 +### Share one workspace connection
69 +
70 +By default a connected account is **PRIVATE**: only its creator can use it. The install authorized the Slack connection as **SHARED**, so you pin it into every session. Now Alice's session has *her* GitHub connection but *the workspace's* Slack connection. It posts as the bot, and acts everywhere else as Alice.
71 +
72 +<FileBuildup name="bot" step={3} />
73 +
74 +### Reach the gaps with the proxy
75 +
76 +Most Slack actions are `SLACKBOT_*` tools. The few that aren't, like the typing indicator and opening a DM channel, drop down to `session.proxyExecute`, which calls the Slack Web API with the pinned connection's auth so you never touch a token.
77 +
78 +<FileBuildup name="bot" step={4} />
79 +
80 +### Redirect auth links
81 +
82 +The payoff. When the agent reaches for an app the user hasn't connected, the tool result carries a one-time Composio connect URL. You never want it in the channel or in the model's context. The bot extracts it, **redacts** it from the tool output, DMs it to the user privately, and the run resumes the moment they approve, because the session was created with `waitForConnections`.
83 +
84 +<FileBuildup name="bot" step={5} />
85 +
86 +### Serve the webhook
87 +
88 +Verify each trigger's signature with `composio.triggers.verifyWebhook`, then hand the payload to `handleSlackMessage` off the response path so a slow handler doesn't get retried. That's the whole server.
89 +
90 +<FileBuildup name="bot" step={6} />
91 +
92 +## The whole project
93 +
94 +The two files above are the spine. The real project rounds them out with grouped auth-link DMs, per-user routing, message chunking, reaction acks, and durable storage. Here's a slice of the actual source, with the Composio touch-points highlighted. Browse the tree, read the files:
95 +
96 +<RepoBrowser />
97 +
98 +The complete project lives on GitHub: [composio-slack-bot](https://github.com/ComposioHQ/composio-slack-bot).
99 +
100 +## Run it
101 +
102 +Run `bun install.ts` once to set up the bot, start the server with `bun bot.ts`, then `@mention` the bot in any channel. It opens a session as you, finds the tool it needs, runs it against your connections, and replies in thread as the workspace bot, usually within a few seconds. Ask it to do something in an app you haven't connected yet and it DMs you a link first, then continues once you approve.
103 +
104 +<Cards>
105 + <Card title="Configuring sessions" href="/docs/configuring-sessions" description="Everything a session can scope: toolkits, tools, connections, and limits" />
106 + <Card title="Shared connections" href="/docs/shared-connections" description="SHARED vs PRIVATE accounts and the per-user ACL" />
107 +</Cards>
docs/content/examples/index.mdx new
+12
@@ -0,0 +1,12 @@
1 +---
2 +title: Examples
3 +description: End-to-end guides that build real agents with Composio.
4 +---
5 +
6 +End-to-end builds that wire Composio into working agents. Each one is a complete project you can read top to bottom and run.
7 +
8 +<Cards>
9 + <Card title="General agent with Pi" href="/examples/general-agent-with-pi" description="Build a Pi + Composio agent and drop it into Slack: triggers, per-user sessions, a shared connection, redirected auth links, and the proxy." />
10 + <Card title="Daily standup bot" href="/examples/standup-slackbot" description="A Slack bot that drafts each teammate's standup from their own connected tools: your own Slack app, tool-router sessions, manual tool execution, the proxy, and per-member auth links." />
11 + <Card title="Local sandbox PR reviewer" href="/examples/local-sandbox-pr-reviewer" description="Run a PR reviewer in your own sandbox while it calls GitHub tools through a Composio session." />
12 +</Cards>
docs/content/examples/local-sandbox-pr-reviewer.mdx new
+99
@@ -0,0 +1,99 @@
1 +---
2 +title: Review pull requests in a sandbox you own
3 +description: Composio usually runs your tools for you. A local sandbox is for when you need to run them yourself, on your filesystem, in your shell, inside your security boundary. Build a GitHub PR reviewer that runs checks in a sandbox you own and posts one grounded comment.
4 +keywords: [local sandbox, sandbox, github, pull request review, tool router, e2b, code execution, run_composio_tool, security boundary]
5 +full: true
6 +---
7 +
8 +Composio usually runs your tools for you. A **local sandbox** is for the times you need to run them yourself: your filesystem, your shell, your security boundary. You still get [managed auth](/docs/authentication) and 1000+ apps; you just keep the code execution.
9 +
10 +This example builds a GitHub PR reviewer that does exactly that: it clones a pull request into a sandbox *you* own, runs the repo's real checks there, and posts one grounded comment. The sandbox here is E2B, but E2B is just the sample. The same pattern works with your own VM, container, Kubernetes job, or internal sandbox service.
11 +
12 +It comes down to a handful of Composio pieces:
13 +
14 +1. **A local sandbox session** is a [Composio session](/docs/how-composio-works) with [code execution turned off](/docs/configuring-sessions#disabling-the-sandbox). Composio still does [discovery](/docs/how-composio-works#meta-tools) and auth; it just won't run code for you.
15 +2. **The helper contract** is what comes back: a Python helper exposing the same [`run_composio_tool`, `invoke_llm`, and `web_search`](/docs/sandbox/remote) tools Composio's managed sandbox runs for you, plus the `env` it needs. You inject it into your sandbox and the agent calls it.
16 +3. **Your sandbox is the boundary.** Tool *execution* happens in a box you control. E2B is the replaceable sample runner; the contract it honors is the real interface.
17 +
18 +<Callout type="warn" title="The sandbox holds your project API key">
19 +The `env` that `experimental_createLocalWorkbenchSession` returns includes your **project** `COMPOSIO_API_KEY`, and you inject that `env` into the sandbox. Anything running there can read it, including the untrusted PR code you clone and build. Treat the sandbox as your trust boundary: run it on infrastructure you control, give the reviewer a key scoped to only what it needs, and rotate the key if a run could have leaked it.
20 +</Callout>
21 +
22 +<LocalWorkbenchFlow />
23 +
24 +Below you build the host orchestration from scratch: a bare client first, then a piece at a time up to the full run loop, then a browse of the real source. You bring a Composio API key and a place to run code. Composio brings the tools.
25 +
26 +## Setup
27 +
28 +You need a [Composio API key](https://dashboard.composio.dev), an OpenAI API key for the reviewer agent, a GitHub connection for your `COMPOSIO_USER_ID`, and [Bun](https://bun.sh).
29 +
30 +<Accordions>
31 + <Accordion title="No sandbox provider? Use the E2B sample runner">
32 + The host writes the Composio helper into a sandbox and runs the agent there, so it needs *somewhere* to run code. This example ships an [E2B](https://e2b.dev) runner in `src/sandbox/e2b.ts` so you can run it today with just an `E2B_API_KEY`. E2B is a hosted sandbox provider: that key provisions an isolated microVM to run the agent in, so you don't have to stand up a VM or container yourself. It's still real infrastructure, just E2B's to manage rather than yours.
33 +
34 + E2B is deliberately isolated to that one file. To run on your own VM, container, or CI worker, replace `createE2bSandbox` with anything that honors the same contract: create a directory, write `helperSource` into it, pass `env` to the process, stream stdout and stderr back, and tear down on your schedule.
35 + </Accordion>
36 +</Accordions>
37 +
38 +```bash
39 +bun add @composio/core @composio/experimental e2b @openai/agents
40 +```
41 +
42 +Connect GitHub once for the user id you'll review as, then keep that same id for the review run:
43 +
44 +```bash
45 +bun run connect
46 +```
47 +
48 +## Build the host
49 +
50 +`src/runner.ts` is the host: it owns orchestration, never tool execution. It starts as a bare Composio client and grows into the full run loop, one concept at a time. Each diff below is exactly what that concept adds.
51 +
52 +### Create the Composio client
53 +
54 +The whole thing acts as one stable user, against the connections they own. Start there.
55 +
56 +<FileBuildup name="reviewer" step={1} />
57 +
58 +### Check the GitHub connection
59 +
60 +A local sandbox still leans on Composio for auth and [tool discovery](/docs/how-composio-works#meta-tools); only code execution moves to your side. So before booting any infrastructure, confirm this user actually has [GitHub connected](/docs/authentication), and hand them a connect link if not.
61 +
62 +<FileBuildup name="reviewer" step={2} />
63 +
64 +### Create the local sandbox session
65 +
66 +The core of the integration. You create a [Composio session](/docs/configuring-sessions#creating-a-session) yourself with code execution off (`workbench.enable: false`, so Composio will not run code for you), then hand that session to `experimental_createLocalWorkbenchSession`. The helper validates the session is local (it errors if the session has the remote workbench enabled, because the managed workbench and a local sandbox can't both run for one session) and returns the pieces you run yourself: a `helperSource` (a Python helper with `run_composio_tool`, `invoke_llm`, and `web_search`) and the `env` that helper needs to reach Composio from inside your box.
67 +
68 +<FileBuildup name="reviewer" step={3} />
69 +
70 +### Start your sandbox, inject the helper
71 +
72 +Boot a box you control, write `helperSource` into it as `composio_helper.py`, and pass `env` to the process. That helper is the *only* Composio-specific thing your sandbox has to carry. E2B is the sample runner; swap it for anything that honors the same contract.
73 +
74 +<FileBuildup name="reviewer" step={4} />
75 +
76 +### Run the reviewer and stream output
77 +
78 +Run the agent inside the sandbox and stream its output back. Whenever the agent calls `run_composio_tool`, the helper routes that GitHub action back through Composio under this user's connection. Tool *execution* happens in your box; discovery and auth stay managed.
79 +
80 +<FileBuildup name="reviewer" step={5} />
81 +
82 +## The whole project
83 +
84 +The file above is the spine. The real project rounds it out with a CLI, a smoke/dry-run path, the E2B runner behind the sandbox contract, the reviewer agent and its review policy, and the `composio_helper.py` the helper source compiles to. Here's a slice of the actual source, with the Composio touch-points highlighted. Browse the tree, read the files:
85 +
86 +<RepoBrowser source="local-workbench" />
87 +
88 +The complete project lives on GitHub: [local-pr-reviewer](https://github.com/ComposioHQ/local-pr-reviewer).
89 +
90 +## Run it
91 +
92 +Dry-run first to validate your input with no credentials, network calls, or sandbox startup, then run it for real:
93 +
94 +```bash
95 +bun run review -- --repo ComposioHQ/composio --pr 123 --dry-run
96 +bun run review -- --repo ComposioHQ/composio --pr 123
97 +```
98 +
99 +The host opens a local sandbox session, boots the sandbox, and runs the repo's real checks inside it, then posts one grounded comment, or nothing if it can't build the PR.
docs/content/examples/meta.json new
+10
@@ -0,0 +1,10 @@
1 +{
2 + "title": "Examples",
3 + "root": true,
4 + "pages": [
5 + "index",
6 + "general-agent-with-pi",
7 + "standup-slackbot",
8 + "local-sandbox-pr-reviewer"
9 + ]
10 +}
docs/content/examples/standup-slackbot.mdx new
+227
@@ -0,0 +1,227 @@
1 +---
2 +title: Daily standup bot
3 +description: A Slack bot that writes each teammate's standup from their own connected tools. Build your own white-labelled bot, give it native Slack interactions with Composio's proxy, and let a tool-router agent write the draft.
4 +keywords: [standup bot, slack bot, slackbot toolkit, white labeling, custom auth config, tool router, sessions, connected accounts, proxy, auth links, vercel, cron, interactivity]
5 +full: true
6 +---
7 +
8 +Standup is a crucial part of running an effective engineering team, and also oh so tedious: every morning, everyone digs back through what they did and writes it up. It's worse for teams spread across timezones, where there's no shared standup to anchor the day, so it's easy to just forget.
9 +
10 +But the work you did *is* there: the PRs in <AppLogo slug="github" invert /> GitHub, the docs in <AppLogo slug="notion" invert /> Notion, the decisions in <AppLogo slug="slack" /> Slack threads. If it's all recorded somewhere, an agent should be able to at least draft it. [Composio sessions](/docs/configuring-sessions) make this *incredibly easy for agents*: a session hands the agent everything it needs, [search](/docs/how-composio-works#meta-tools) to find the right tool, [parallel execute](/docs/how-composio-works#meta-tools) to run many at once, a [sandbox](/docs/sandbox/remote) and [volumes](/docs/sandbox/remote#files-and-mounts). It uses Composio to extract, parse, and cross-reference data across all those sources and write clean summaries of the real work your team shipped. All you have to do is create a session for your teammate and let it cook.
11 +
12 +<div className="not-prose my-8 grid grid-cols-1 items-start gap-4 sm:grid-cols-2 [&_figure]:my-0">
13 + <Figure src="/images/standup-slackbot/slack-reminder.png" alt="The daily standup reminder in Slack" caption="The daily reminder, with Draft and Connect more tools buttons" size="full" />
14 + <Figure src="/images/standup-slackbot/slack-draft.png" alt="A generated standup draft in Slack" caption="The draft the agent writes, delivered to a teammate in Slack" size="full" />
15 +</div>
16 +
17 +So we built a Slack bot that does exactly that. Once a day, at a set time in each teammate's own timezone, it reminds them to post in the daily standup thread in a central channel. With one button click, they can run a subagent that uses their Composio connections to generate a clean, consolidated draft to review and post. We'll build it step by step.
18 +
19 +<Callout type="warn" title="Is this the right example for you?" className="[&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5 [&_li]:my-1 [&_li]:pl-1">
20 +
21 +This is a deliberately advanced, opinionated build. It's a strong reference for five things:
22 +
23 +- **Background-agent sessions**: the draft agent runs on a schedule, not in a conversation. It works from the tools a member already connected and never pauses to ask for auth.
24 +- **Manual execution for deterministic workflows**: outside the draft, the bot doesn't let an agent decide. It runs a fixed flow, calling tools directly with [manual execution](/docs/tools-direct/executing-tools), so a button always triggers the same exact steps.
25 +- **Manual, pre-connected auth**: members connect their tools ahead of time using [manual connections](/docs/manually-authenticating), and the agent just uses whatever is there.
26 +- **White-labelling** (advanced): your own Slack app and bot identity, via [white-labelling](/docs/white-labeling-authentication). This is *not* the easy path. We'd recommend Composio's managed apps, which require no additional configuration. Only do this if you specifically want your own branding.
27 +- **The proxy** (advanced): using [`proxyExecute`](/docs/extending-sessions/proxy-execute) to call Slack API endpoints Composio doesn't wrap as tools.
28 +
29 +It is **not** an example of [in-chat or dynamic auth](/docs/authentication) (asking a user to connect a tool mid-run), and it's more setup than many bots need. If you'd rather have a Slack bot with zero setup (Composio's managed app) or in-chat auth, start with the [general Slack bot](/examples/general-agent-with-pi) instead.
30 +</Callout>
31 +
32 +The Slack bot itself follows a deterministic flow: the same menu every day. When a member taps a button, it launches a subagent with a Composio session to produce the draft. Here's the shape of it:
33 +
34 +<Mermaid chart={`flowchart TD
35 + cron([Vercel cron]) --> thread[Find or create today's thread]
36 + thread --> dm
37 + dm@{ img: "/images/standup-slackbot/slack-reminder.png", label: "DM each due member: Draft or Connect", pos: "b", w: 300, h: 69, constraint: "on" }
38 + dm -->|Draft| agent[Create a Composio session for the user and launch a sub-agent to generate summary]
39 + agent --> review
40 + review@{ img: "/images/standup-slackbot/slack-draft.png", label: "Member reviews: Confirm or Edit", pos: "b", w: 300, h: 143, constraint: "on" }
41 + review -->|Confirm| post[Post into the thread as the member]
42 + dm -->|Connect| oauth
43 + oauth@{ img: "/images/standup-slackbot/slack-connect.png", label: "Creates buttons for the user to link their accounts to Composio via OAuth", pos: "b", w: 340, h: 58, constraint: "on" }
44 + click agent "/docs/how-composio-works#meta-tools" "Composio metatools"
45 +`} />
46 +
47 +## Setup
48 +
49 +You need a [Composio API key](https://dashboard.composio.dev/~/project/settings/api-keys), a Slack workspace you can install an app into, and Node with [tsx](https://nodejs.org). The finished bot deploys to [Vercel](https://vercel.com) as two serverless functions, a cron and an interactivity handler, so there's no long-running server.
50 +
51 +```bash
52 +npm install @composio/core @composio/vercel ai dayjs
53 +```
54 +
55 +## Make your custom Slack bot
56 +
57 +This bot doesn't post as "Composio". It posts as *my* app, with its own name, icon, and (frankly ridiculous) face:
58 +
59 +<Figure src="/images/standup-slackbot/bot-avatar.png" alt="The Daily Standup Bot avatar" size="sm" />
60 +
61 +That's [white-labelling](/docs/white-labeling-authentication): you bring your own Slack app's credentials instead of using Composio-managed ones. Composio-managed auth needs no setup at all; white-labelling is the trade-off, you register and configure your own Slack app first. It's more work, but the bot is fully yours.
62 +
63 +Slack's app-creation UI changes from time to time, so the exact screens below may differ. First, the Slack app itself.
64 +
65 +<Steps>
66 +<Step>
67 +**Create the app from scratch.** At [api.slack.com/apps](https://api.slack.com/apps), click **Create an App**, choose **From scratch**, name it (mine is `Daily Standup Bot`), and pick your workspace.
68 +
69 +<Figure src="/images/standup-slackbot/create-app.png" alt="Naming the Slack app and choosing a workspace" caption="Create the app from scratch and name it" size="lg" />
70 +</Step>
71 +
72 +<Step>
73 +**Add the Bot Token Scopes.** Under **OAuth & Permissions**, add: `chat:write`, `im:write`, `channels:history`, `channels:read`, `users:read`, `users:read.email`, `team:read`. Then turn on **Interactivity** and point its Request URL at your deployment's `/api/interactivity`.
74 +
75 +<Figure src="/images/standup-slackbot/bot-scopes.png" alt="Adding bot token scopes under OAuth & Permissions" caption="Add the bot token scopes" size="lg" />
76 +</Step>
77 +
78 +<Step>
79 +**Grab the app credentials.** On **Basic Information**, copy the **Client ID** and **Client Secret**. Composio drives the OAuth as your app with these.
80 +
81 +<Figure src="/images/standup-slackbot/app-credentials.png" alt="The app's Client ID and Secret under Basic Information" caption="Copy the Client ID and Secret" size="lg" />
82 +</Step>
83 +</Steps>
84 +
85 +## Auth the bot
86 +
87 +The Slack app exists; now connect it through Composio so your code can act as it. You create one `slackbot` auth config from your credentials, then a setup script does the OAuth once with Composio's [manual authentication](/docs/manually-authenticating) flow.
88 +
89 +<Callout type="info" title="`slackbot` vs `slack`" className="[&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5 [&_li]:my-1 [&_li]:pl-1">
90 +
91 +Composio has two Slack toolkits, and this bot uses both:
92 +
93 +- **`slackbot`** authenticates a Slack *app* and acts as the **bot** (a bot token). It posts the reminders and drafts as "Daily Standup Bot," and it's the one you white-label here.
94 +- **`slack`** authenticates an individual **user** and acts as *them* (a user token). Each teammate connects this so the bot can post their standup under their own name and read their activity for context.
95 +
96 +Rule of thumb: posting *as the bot* uses `slackbot`; doing something *as a person* uses `slack`.
97 +</Callout>
98 +
99 +<Steps>
100 +<Step>
101 +**Create an auth config and pick the `Slackbot` toolkit.** In the [Composio dashboard](https://dashboard.composio.dev/~/project/auth-configs), click **Create Auth Config** and search `slackbot`. Choose **Slackbot**, *not* `Slack`: `Slackbot` posts as the bot identity, while `Slack` acts as an individual user.
102 +
103 +<Figure src="/images/standup-slackbot/auth-config-slackbot.png" alt="Choosing the Slackbot toolkit, not Slack" caption="Pick Slackbot, not Slack" size="lg" />
104 +</Step>
105 +
106 +<Step>
107 +**Use your own credentials.** Pick **OAuth 2.0**, then **Your Own Credentials**, and paste the Client ID and Secret from before. Add `team:read` to the user token scopes. This is the white-label step: your app, your name, your face.
108 +
109 +<Figure src="/images/standup-slackbot/auth-config-credentials.png" alt="Selecting Your Own Credentials and entering the Client ID and Secret" caption="Use your own credentials" size="lg" />
110 +</Step>
111 +
112 +<Step>
113 +**Save the auth config id.** Once created, copy its `ac_...` id into `COMPOSIO_SLACKBOT_AUTH_CONFIG_ID`. This is the one auth config your app uses to take actions on behalf of your bot.
114 +
115 +<Figure src="/images/standup-slackbot/auth-config-created.png" alt="The created slackbot auth config with its ac_ id" caption="The created auth config and its ac_ id" size="lg" />
116 +</Step>
117 +
118 +<Step>
119 +**Run the setup script to connect the bot.** For this bot, we first need to connect the bot itself to Composio, which only needs to be done once. The script creates an OAuth link for you to connect your *Slack bot* to Composio, which lets you use Composio to send messages on behalf of your bot.
120 +
121 +<FileBuildup name="setup" />
122 +
123 +The first run prints a link and waits:
124 +
125 +```text
126 +╭─────────────────────────────────────────────────────────╮
127 +│ Daily Standup Bot: One-Time Setup │
128 +╰─────────────────────────────────────────────────────────╯
129 + ✅ Auth config has the required user scopes.
130 + · Bot is not connected yet. Generating an authorization link…
131 +
132 + Open this URL in your browser to authorize the bot:
133 +
134 + https://backend.composio.dev/s/AbC123xy
135 +
136 + Waiting for you to complete the OAuth flow (Ctrl+C to abort)…
137 + ✅ Bot connected to Slack.
138 +
139 +──────────────────────────────────────────────────────────────────────
140 + 🎉 Setup complete. Invite the bot to your standup channel and
141 + point your Slack app's Interactivity Request URL at
142 + https://<your-deployment>/api/interactivity
143 +──────────────────────────────────────────────────────────────────────
144 +```
145 +
146 +Open that link to approve the bot, and the connection goes live:
147 +
148 +<Figure src="/images/standup-slackbot/oauth-approve.png" alt="Approving the bot's OAuth connection" caption="Approve the bot in Slack" size="lg" />
149 +
150 +<Figure src="/images/standup-slackbot/connected.png" alt="Composio successfully connected to Slackbot" caption="Connected" size="md" />
151 +</Step>
152 +</Steps>
153 +
154 +The script is idempotent and repeatable. Forgot a scope, or hit an issue? No stress, just re-run it with `--reconnect`.
155 +
156 +## Talk to Slack
157 +
158 +To send and update messages in our deterministic bot workflow, we use Composio's `SLACKBOT_SEND_MESSAGE` and `SLACKBOT_UPDATES_A_MESSAGE` tools via [manual tool execution](/docs/tools-direct/executing-tools). `SLACKBOT_SEND_MESSAGE` takes Block Kit `blocks`, so a message with interactive buttons can go through a tool too.
159 +
160 +<FileBuildup name="proxy" step={1} />
161 +
162 +When a Slack action has no tool, like opening a modal (`views.open`), it drops to [`proxyExecute`](/docs/extending-sessions/proxy-execute): the escape hatch for anything the named tools don't cover, hitting any Slack Web API endpoint as a connected account with no token in your code.
163 +
164 +<FileBuildup name="proxy" step={2} />
165 +
166 +## Make the buttons work
167 +
168 +Our StandUp bot gives the user two options every morning: **Draft** or **Connect more tools**. Each message uses [Block Kit](https://api.slack.com/block-kit) to create those buttons. For each button we define an `action_id` that lets us recognise which button was clicked.
169 +
170 +```ts
171 +declare const memberEmail: string, dmChannel: string, dmTs: string;
172 +// ---cut---
173 +// the reminder's Draft button
174 +const draftButton = {
175 + type: 'button',
176 + style: 'primary',
177 + text: { type: 'plain_text', text: '📝 Draft' },
178 + action_id: 'draft',
179 + value: JSON.stringify({ memberEmail, dmChannel, dmTs }),
180 +};
181 +```
182 +
183 +<Figure src="/images/standup-slackbot/slack-reminder.png" alt="The daily standup reminder in Slack" caption="The daily reminder, with Draft and Connect more tools buttons" size="md" />
184 +
185 +When it's clicked, Slack POSTs to your `/api/interactivity` handler. Verify the request, ack within Slack's 3-second window, then route on the `action_id`:
186 +
187 +<FileBuildup name="buttons" />
188 +
189 +**Connect more tools** generates a per-member OAuth link for each toolkit the member hasn't connected, so they can add a source without leaving Slack:
190 +
191 +<Figure src="/images/standup-slackbot/slack-connect.png" alt="The connect-more-tools menu in Slack" caption="Connect more tools, each button a per-member OAuth link" size="lg" />
192 +
193 +**Edit** opens a modal (`views.open` through the proxy), and **Confirm** posts the draft into the day's thread as the member.
194 +
195 +## Draft the standup
196 +
197 +Now this is the cool and magical part, and the easy part: all the background agent needs is a tool-router session and a prompt. When a member taps **Draft**, you spin up a session scoped to the toolkit catalogue and let the agent research and write.
198 +
199 +### A session writes the draft
200 +
201 +A [tool-router session](/docs/configuring-sessions) gives the agent its tools. Pass the member's email and your full list of toolkits, hand the tools to the model, and let it investigate and write. You don't have to check which ones the member set up: the session only exposes tools for the accounts they've actually connected, and ignores the rest.
202 +
203 +<FileBuildup name="draft" step={1} />
204 +
205 +### Use what's connected, nothing more
206 +
207 +The router can also *manage* connections, asking the user to authorize any toolkits they haven't connected yet. During a draft you don't want that: if the agent reaches for a tool the member hasn't connected, it should skip it, not prompt them to log in. `manageConnections: false` removes those meta-tools, so the agent drafts from exactly what's already connected.
208 +
209 +<FileBuildup name="draft" step={2} />
210 +
211 +The bot posts the result back as a draft the member can confirm or edit:
212 +
213 +<Figure src="/images/standup-slackbot/slack-draft.png" alt="A generated standup draft in Slack with Confirm and Edit buttons" caption="The draft the agent writes, delivered to a teammate in Slack" size="md" />
214 +
215 +## The whole project
216 +
217 +<RepoBrowser source="standup" caption={null} />
218 +
219 +## Run it
220 +
221 +Edit `standup.config.ts` with your team (each member's Slack email and timezone, plus your channel and GitHub org), set your four environment variables, run `npx tsx scripts/setup.ts` once to connect your bot, then `vercel deploy`.
222 +<Cards>
223 + <Card title="Configuring sessions" href="/docs/configuring-sessions" description="What a session can scope: toolkits, tools, connections, and connection management" />
224 + <Card title="White-labeling authentication" href="/docs/white-labeling-authentication" description="Ship a bot under your own app's name, icon, and credentials" />
225 + <Card title="Custom vs managed auth" href="/docs/custom-app-vs-managed-app" description="Bring-your-own Slack app versus a Composio-managed connection" />
226 + <Card title="Triggers" href="/docs/triggers" description="Run agents in response to events: schedules, webhooks, and app activity" />
227 +</Cards>
docs/content/reference/api-reference/auth-configs/index.mdx
+27 -2
@@ -3,9 +3,34 @@ title: Auth Configs
3 description: "Authentication configuration management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/auth-configs.mdx, not this file. */}
7
8 -Authentication configuration management
8 +An auth config is a blueprint that defines how a toolkit authenticates across all your users. It specifies the authentication method, the scopes your tools can request, and which credentials Composio uses to run the OAuth or token flow.
9 +
10 +A single auth config applies to every user who connects that toolkit. When a user authenticates against it, Composio creates a [connected account](/reference/api-reference/connected-accounts) that stores their tokens and links them to your user ID.
11 +
12 +Each auth config defines:
13 +
14 +- **Auth scheme**: OAuth2, API key, Bearer token, or Basic Auth
15 +- **Scopes**: what your tools are allowed to do on the user's behalf
16 +- **Credentials**: Composio's managed app, or your own OAuth client and secrets
17 +
18 +Reach for a custom auth config when you need your own branding on consent screens, custom scopes, a dedicated rate-limit quota, or a custom toolkit instance. See [managed vs custom auth](/docs/custom-app-vs-managed-app) for the decision and [how Composio handles authentication](/docs/authentication) for the full picture.
19 +
20 +## Auth schemes
21 +
22 +The `auth_scheme` on an auth config determines how users authenticate to the toolkit. Composio supports four. The schemes available for a given toolkit come from the toolkit itself.
23 +
24 +| Scheme | What it is | When it's used |
25 +|---|---|---|
26 +| `OAUTH2` | OAuth 2.0 authorization-code flow. The user authorizes through a hosted consent screen, and Composio stores and automatically refreshes the access and refresh tokens. | Most apps with user accounts (Gmail, GitHub, Slack, Notion, and so on). Uses Composio's managed OAuth app by default; bring your own for custom branding or scopes. |
27 +| `API_KEY` | A static API key the user provides. There's no OAuth flow: the key is stored on the connected account and sent on each request. | Services that authenticate with a key, such as SendGrid, Tavily, or PostHog. |
28 +| `BEARER_TOKEN` | A bearer access token you already hold (for example, from your own OAuth flow). Composio sends it as `Authorization: Bearer <token>` and does not refresh it, so you keep it current. | Bringing an existing OAuth or server-to-server token into Composio, or apps that issue long-lived tokens. |
29 +| `BASIC` | HTTP Basic authentication with a username and password. | Services that use Basic Auth. |
30 +
31 +Most OAuth toolkits work out of the box with Composio managed auth. For the others you supply the credential fields. To choose or customize the scheme, see [managed vs custom auth](/docs/custom-app-vs-managed-app).
32 +
33 +These endpoints use your project API key in the `x-api-key` header. Each auth config is addressed by its `nanoid`, and you can enable or disable one without deleting it.
34
35 ## Endpoints
36
docs/content/reference/api-reference/authentication/index.mdx deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -title: Authentication
3 -description: "Authentication related endpoints"
4 ----
5 -
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
7 -
8 -Authentication related endpoints
9 -
10 -## Endpoints
11 -
12 -<ApiEndpointsTable endpoints={[{"method":"GET","pathV31":"/api/v3.1/auth/session/info","pathV3":"/api/v3/auth/session/info","summary":"Get current user session information","href":"/reference/api-reference/authentication/getAuthSessionInfo"}]} />
docs/content/reference/api-reference/connected-accounts/index.mdx
+23 -2
@@ -3,9 +3,30 @@ title: Connected Accounts
3 description: "Connected account management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/connected-accounts.mdx, not this file. */}
7
8 -Connected account management
8 +A connected account is a single user's authorized connection to a toolkit. It stores their credentials (OAuth tokens or API keys) and links them to your user ID, so your tools can act on that user's behalf.
9 +
10 +Composio creates a connected account when a user completes the flow defined by an [auth config](/reference/api-reference/auth-configs). From there you manage its full lifecycle:
11 +
12 +- **Create or link**: start a new connection, or generate an auth link session for the user to authorize. See [manually authenticating users](/docs/manually-authenticating).
13 +- **Refresh**: renew authentication for an account whose tokens have expired.
14 +- **Enable, disable, or update**: change an account's status or metadata without removing it.
15 +- **Revoke or delete**: revoke the grant at the provider, or remove the account from Composio.
16 +
17 +Each account is addressed by its `nanoid`. List endpoints accept filters so you can find accounts by user, toolkit, or auth config.
18 +
19 +## Link auth (Composio Connect Links)
20 +
21 +A Composio Connect Link is a hosted, secure sign-in page. You create one with the create auth link session endpoint, redirect the user to the returned URL, and Composio handles the rest: the user signs in, Composio creates the connected account, and Composio stores and refreshes its tokens. Credentials never pass through your app. This works for all Composio managed connections, with no OAuth credentials to set up.
22 +
23 +By default a connected account is `PRIVATE` and usable only by its owning user. Mark one `SHARED` to let other users reach it through a per-connection access control list. See [shared connections](/docs/shared-connections).
24 +
25 +These endpoints use your project API key in the `x-api-key` header.
26 +
27 +<Callout type="warning">
28 +Shared-connection ACL fields are experimental and nested under an `experimental` block on the wire. Pin a specific SDK version if you depend on the current shape.
29 +</Callout>
30
31 ## Endpoints
32
docs/content/reference/api-reference/consumer/index.mdx deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -title: Consumer
3 -description: "Consumer API endpoints"
4 ----
5 -
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
7 -
8 -Consumer API endpoints
9 -
10 -## Endpoints
11 -
12 -<ApiEndpointsTable endpoints={[{"method":"GET","pathV31":"/api/v3.1/consumer/connected_accounts/{nanoid}/permissions","pathV3":"/api/v3/consumer/connected_accounts/{nanoid}/permissions","summary":"Get consumer tool permissions for a connected account","href":"/reference/api-reference/consumer/getConsumerConnectedAccountsByNanoidPermissions"},{"method":"PATCH","pathV31":"/api/v3.1/consumer/connected_accounts/{nanoid}/permissions","pathV3":"/api/v3/consumer/connected_accounts/{nanoid}/permissions","summary":"Upsert consumer tool permissions for a connected account","href":"/reference/api-reference/consumer/patchConsumerConnectedAccountsByNanoidPermissions"},{"method":"PATCH","pathV31":"/api/v3.1/consumer/connected_accounts/{nanoid}/permissions/tools/{tool_slug}","pathV3":"/api/v3/consumer/connected_accounts/{nanoid}/permissions/tools/{tool_slug}","summary":"Upsert one consumer tool permission for a connected account","href":"/reference/api-reference/consumer/patchConsumerConnectedAccountsByNanoidPermissionsToolsByToolSlug"},{"method":"POST","pathV31":"/api/v3.1/consumer/permissions/resolve","pathV3":"/api/v3/consumer/permissions/resolve","summary":"Resolve consumer tool-router permissions","href":"/reference/api-reference/consumer/postConsumerPermissionsResolve"}]} />
docs/content/reference/api-reference/files/index.mdx
+17 -2
@@ -3,9 +3,24 @@ title: Files
3 description: "File management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/files.mdx, not this file. */}
7
8 -File management
8 +These endpoints handle files that tools read and write during execution. When a tool produces or consumes a file, Composio stores it in object storage and exchanges it through presigned URLs rather than streaming bytes through the API.
9 +
10 +You reach for these endpoints to:
11 +
12 +- **List files** that tools have generated, optionally filtered by app and action.
13 +- **Request an upload**: get a presigned S3 URL, `PUT` your file to it, then pass the returned reference into a tool's input.
14 +
15 +This keeps large payloads out of request bodies. Tools receive a file reference and resolve the underlying object on their side.
16 +
17 +<Callout type="info">
18 +File uploads are a two-step flow. Call the upload-request endpoint to mint a presigned URL, then upload the file contents directly to that URL. The API never receives the raw bytes.
19 +</Callout>
20 +
21 +If your agent works with files inside a session, prefer the session file mount, where the sandbox exposes uploaded files to running code. See the [sandbox](/docs/sandbox/remote) for the sandbox helpers (`upload_local_file`, `smart_file_extract`) that build on this storage.
22 +
23 +These endpoints use your project API key in the `x-api-key` header.
24
25 ## Endpoints
26
docs/content/reference/api-reference/invite-codes/index.mdx deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -title: Invite Codes
3 -description: "Invite Codes API endpoints"
4 ----
5 -
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
7 -
8 -Invite Codes API endpoints
9 -
10 -## Endpoints
11 -
12 -<ApiEndpointsTable endpoints={[{"method":"POST","pathV31":"/api/v3.1/org/clanker/create_claim","pathV3":"/api/v3/org/clanker/create_claim","summary":"Create a clanker-claim slug","href":"/reference/api-reference/invite-codes/postOrgClankerCreateClaim"}]} />
docs/content/reference/api-reference/logs/index.mdx renamed
+12 -15
@@ -1,10 +1,11 @@
1 ---
2 -title: Tool execution logs
3 -description: Search, filter, and inspect individual tool execution logs for debugging and forensics.
4 -keywords: ['logs', 'tool execution', 'debugging', 'observability']
2 +title: Logs
3 +description: "Logging and monitoring"
4 ---
5
7 -The Logs API returns **individual tool execution events** — one record per tool call. Use it to debug failures, inspect request/response payloads, and trace specific user activity. For aggregated counts (how many tool calls happened), use the [Usage API](/docs/observability/usage) instead.
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/logs.mdx, not this file. */}
7 +
8 +The Logs API returns **individual tool execution events**, one record per tool call. Use it to debug failures, inspect request/response payloads, and trace specific user activity. For aggregated counts (how many tool calls happened), use the [Usage API](/reference/api-reference/organization) instead.
9
10 All endpoints in this section require a **project API key** (`x-api-key`) or a valid session cookie.
11
@@ -97,12 +98,12 @@ curl https://backend.composio.dev/api/v3.1/logs/tool_execution/log_-jRTWClpBoVo
98
99 The detail response includes everything from the list shape plus:
100
100 -- `timings` — `start_time` and `end_time` in epoch ms
101 -- `context` — `session_id`, `trace_id`, `request_id`
102 -- `source` — `host` (e.g. `mcp`, `sdk`, `api`), `framework`, `language`
103 -- `data` — the full request payload and response body
101 +- `timings`: `start_time` and `end_time` in epoch ms
102 +- `context`: `session_id`, `trace_id`, `request_id`
103 +- `source`: `host` (e.g. `mcp`, `sdk`, `api`), `framework`, `language`
104 +- `data`: the full request payload and response body
105
105 -This is the endpoint to call when you need to reconstruct *exactly* what happened — e.g. when debugging a 500 from a user report.
106 +This is the endpoint to call when you need to reconstruct *exactly* what happened, for example when debugging a 500 from a user report.
107
108 ## Recipes
109
@@ -144,10 +145,6 @@ curl https://backend.composio.dev/api/v3.1/logs/tool_execution/log_-jRTWClpBoVo
145 -H "x-api-key: YOUR_PROJECT_API_KEY"
146 ```
147
147 -## What to read next
148 +## Endpoints
149
149 -<Cards>
150 - <Card icon={<Monitor />} title="Usage metering" href="/docs/observability/usage" description="Query aggregated tool call and session counts for dashboards and billing" />
151 - <Card icon={<Wrench />} title="Tools and toolkits" href="/docs/tools-and-toolkits" description="Understand how tools and toolkits work in Composio" />
152 - <Card icon={<Database />} title="Projects API reference" href="/reference/api-reference/projects" description="Full request and response schemas for project-level endpoints" />
153 -</Cards>
150 +<ApiEndpointsTable endpoints={[{"method":"POST","pathV31":"/api/v3.1/logs/tool_execution","pathV3":"/api/v3/logs/tool_execution","summary":"Search and retrieve tool execution logs","href":"/reference/api-reference/logs/postLogsToolExecution"},{"method":"GET","pathV31":"/api/v3.1/logs/tool_execution/{id}","pathV3":"/api/v3/logs/tool_execution/{id}","summary":"Get log details by ID","href":"/reference/api-reference/logs/getLogsToolExecutionById"}]} />
docs/content/reference/api-reference/mcp/index.mdx
+10 -2
@@ -3,9 +3,17 @@ title: MCP
3 description: "MCP server management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/mcp.mdx, not this file. */}
7
8 -MCP server management
8 +<Callout type="warning">
9 +This API is deprecated. Use a session's MCP endpoint instead. Create a session with `composio.create(userId, { mcp: true })`, then read the hosted URL off `session.mcp.url`. See [Using sessions via MCP](/docs/sessions-via-mcp) and [migrating MCP servers to sessions](/docs/migration-guide/mcp-servers-to-sessions).
10 +</Callout>
11 +
12 +The MCP API is the standalone, hosted [Model Context Protocol](https://modelcontextprotocol.io) server-management surface. It let you stand up and manage a separate server config per toolkit, then mint a per-user MCP URL that any MCP-compatible client could connect to.
13 +
14 +These endpoints create, list, update, and delete MCP servers, including custom servers spanning multiple apps, generate per-user MCP URLs, and manage per-user server instances and their connected accounts.
15 +
16 +Sessions replace this. A single `composio.create(...)` gives you the same MCP URL pattern, keyed by `user_id`, while handling tool discovery, authentication, context, and versioning for you. Your existing tools, auth configs (`ac_…`), and connected accounts carry over with no re-authentication. To pin a session to a fixed tool list the way a server did, use the direct-tools preset described in [Configuring sessions](/docs/configuring-sessions).
17
18 ## Endpoints
19
docs/content/reference/api-reference/migration/index.mdx
+10 -2
@@ -3,9 +3,17 @@ title: Migration
3 description: "Endpoints to help with migration from v1 to v3"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/migration.mdx, not this file. */}
7
8 -Endpoints to help with migration from v1 to v3
8 +These endpoints help you migrate from Composio v1 to v3 by translating identifiers between the two systems.
9 +
10 +Reach for this endpoint when you have a v1 UUID and need the corresponding v3 NanoId so existing references continue to resolve against the v3 API. Pass the UUID and get the NanoId back.
11 +
12 +These endpoints authenticate with your project API key in the `x-api-key` header.
13 +
14 +<Callout type="info">
15 +This is a low-level translation helper for migrating identifiers. For migrating SDK code, sessions, and toolkit versioning, see the [migration guides](/docs/migration-guide).
16 +</Callout>
17
18 ## Endpoints
19
docs/content/reference/api-reference/organization/index.mdx
+187 -2
@@ -3,9 +3,194 @@ title: Organization
3 description: "Organization management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/organization.mdx, not this file. */}
7
8 -Organization management
8 +The Usage API returns **aggregated counts** of tool calls and sessions. Use it to power billing dashboards, customer-facing analytics, or internal utilization reports. For individual events, use the [Logs API](/reference/api-reference/logs).
9 +
10 +There are two query shapes:
11 +
12 +- **Summary**: totals across one or more entity types in a time window.
13 +- **Breakdown**: one entity type, grouped by a dimension (tool, user, session, etc.).
14 +
15 +Each shape comes in an org-scoped and a project-scoped flavor. The org-scoped endpoints are documented below; the project-scoped usage endpoints (`POST /api/v3.1/project/usage/*`) also appear on the [Projects](/reference/api-reference/projects) reference page.
16 +
17 +## Authentication
18 +
19 +| Endpoint | Header | Scope |
20 +|---|---|---|
21 +| `POST /api/v3.1/org/usage/summary` | `x-org-api-key` *(or org JWT)* | All projects in your org |
22 +| `POST /api/v3.1/org/usage/{entity_type}` | `x-org-api-key` *(or org JWT)* | All projects in your org |
23 +| `POST /api/v3.1/project/usage/summary` | `x-api-key` *(or cookie)* | Single project |
24 +| `POST /api/v3.1/project/usage/{entity_type}` | `x-api-key` *(or cookie)* | Single project |
25 +
26 +The org endpoints accept a `project_id` filter so you can slice by project without rotating keys.
27 +
28 +## Entity types
29 +
30 +| Entity type | What it counts |
31 +|---|---|
32 +| `tool_calls` | Every tool execution (successful or failed) |
33 +| `sessions` | Sessions created |
34 +
35 +## Summary
36 +
37 +Totals across entity types for a time window.
38 +
39 +```bash
40 +curl -X POST https://backend.composio.dev/api/v3.1/project/usage/summary \
41 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
42 + -H "Content-Type: application/json" \
43 + -d '{
44 + "from": 1744848000000,
45 + "to": 1744934400000,
46 + "entity_types": ["tool_calls", "sessions"]
47 + }'
48 +```
49 +
50 +Response:
51 +
52 +```json
53 +{
54 + "entities": {
55 + "tool_calls": { "unit": "count", "total_quantity": "142", "event_count": 142 },
56 + "sessions": { "unit": "count", "total_quantity": "8", "event_count": 8 }
57 + }
58 +}
59 +```
60 +
61 +### Summary parameters
62 +
63 +| Field | Type | Default | Notes |
64 +|---|---|---|---|
65 +| `from` | number | 30 days ago | Epoch milliseconds |
66 +| `to` | number | now | Epoch milliseconds |
67 +| `entity_types` | string[] | all | Subset of `tool_calls`, `sessions` |
68 +| `filters.user_id` | string \| string[] | — | Filter events by initiating user |
69 +| `filters.session_id` | string \| string[] | — | Filter events by session |
70 +| `filters.project_id` | string \| string[] | — | Only meaningful on org endpoints; ignored on project endpoints |
71 +
72 +## Breakdown
73 +
74 +One entity type, grouped by a dimension. Useful for answering "top N" questions.
75 +
76 +```bash
77 +curl -X POST https://backend.composio.dev/api/v3.1/project/usage/tool_calls \
78 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
79 + -H "Content-Type: application/json" \
80 + -d '{
81 + "from": 1744848000000,
82 + "to": 1744934400000,
83 + "group_by": "toolkit_slug",
84 + "order_by": "total_quantity",
85 + "order_direction": "desc",
86 + "limit": 10
87 + }'
88 +```
89 +
90 +Response:
91 +
92 +```json
93 +{
94 + "entity_type": "tool_calls",
95 + "unit": "count",
96 + "total_quantity": "142",
97 + "event_count": 142,
98 + "groups": [
99 + { "key": "github", "total_quantity": "80", "event_count": 80 },
100 + { "key": "slack", "total_quantity": "62", "event_count": 62 }
101 + ]
102 +}
103 +```
104 +
105 +### Breakdown `group_by` options
106 +
107 +| Entity | Org scope | Project scope | Default |
108 +|---|---|---|---|
109 +| `tool_calls` | `tool_slug`, `toolkit_slug`, `connected_account_id`, `user_id`, `session_id`, `project_id` | same minus `project_id` | `tool_slug` |
110 +| `sessions` | `user_id`, `project_id` | `user_id` | `user_id` |
111 +
112 +### Breakdown parameters
113 +
114 +| Field | Type | Default | Notes |
115 +|---|---|---|---|
116 +| `from` | number | 30 days ago | Epoch ms |
117 +| `to` | number | now | Epoch ms |
118 +| `group_by` | string | see table | Dimension to group by |
119 +| `order_by` | string | `total_quantity` | One of `key`, `total_quantity`, `event_count` |
120 +| `order_direction` | `"asc"` \| `"desc"` | `"desc"` | |
121 +| `limit` | number | 50 | Max groups returned |
122 +| `filters` | object | — | See Filters below |
123 +
124 +## Filters
125 +
126 +Filters live in a `filters` object on the request body. Each filter value can be a **single string** or an **array of strings**:
127 +
128 +- Within a single field, values are OR-combined (`user_id: ["a", "b"]` matches events for user *a or b*).
129 +- Across fields, filters are AND-combined.
130 +
131 +```json
132 +{
133 + "filters": {
134 + "user_id": ["user_123", "user_456"],
135 + "session_id": "sess_abc"
136 + }
137 +}
138 +```
139 +
140 +The `project_id` filter is only meaningful on the org-scoped endpoints. Project endpoints accept the field but ignore it (your key already pins the scope to a single project).
141 +
142 +## Time ranges
143 +
144 +- `from` and `to` are **epoch milliseconds**.
145 +- `from` defaults to 30 days before `to`.
146 +- `to` defaults to the current time.
147 +- Maximum range: **366 days**. Longer ranges return a 400.
148 +
149 +## Recipes
150 +
151 +### Top 10 tools my org called last week
152 +
153 +```bash
154 +WEEK_AGO=$(( $(date +%s) - 604800 ))000
155 +NOW=$(date +%s)000
156 +curl -X POST https://backend.composio.dev/api/v3.1/org/usage/tool_calls \
157 + -H "x-org-api-key: YOUR_ORG_API_KEY" \
158 + -H "Content-Type: application/json" \
159 + -d "{
160 + \"from\": ${WEEK_AGO},
161 + \"to\": ${NOW},
162 + \"group_by\": \"tool_slug\",
163 + \"limit\": 10
164 + }"
165 +```
166 +
167 +### Tool call count per user for my project this month
168 +
169 +```bash
170 +MONTH_AGO=$(( $(date +%s) - 2592000 ))000
171 +NOW=$(date +%s)000
172 +curl -X POST https://backend.composio.dev/api/v3.1/project/usage/tool_calls \
173 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
174 + -H "Content-Type: application/json" \
175 + -d "{
176 + \"from\": ${MONTH_AGO},
177 + \"to\": ${NOW},
178 + \"group_by\": \"user_id\",
179 + \"limit\": 50
180 + }"
181 +```
182 +
183 +### Which toolkits is a specific user using?
184 +
185 +```bash
186 +curl -X POST https://backend.composio.dev/api/v3.1/project/usage/tool_calls \
187 + -H "x-api-key: YOUR_PROJECT_API_KEY" \
188 + -H "Content-Type: application/json" \
189 + -d '{
190 + "group_by": "toolkit_slug",
191 + "filters": { "user_id": "user_abc123" }
192 + }'
193 +```
194
195 ## Endpoints
196
docs/content/reference/api-reference/projects/index.mdx
+66 -2
@@ -3,9 +3,73 @@ title: Projects
3 description: "Projects API endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/projects.mdx, not this file. */}
7
8 -Projects API endpoints
8 +Projects are Composio's multi-tenancy primitive. Every Composio account belongs to an **organization**. Inside an organization, **projects** are isolated environments that scope your API keys, connected accounts, auth configs, and webhook configurations. Resources in one project are not accessible from another.
9 +
10 +```mermaid
11 +graph LR
12 + ORG["Organization (org_xxx)"] --- P1["Project: Production (proj_xxx)"]
13 + ORG --- P2["Project: Staging (proj_xxx)"]
14 + ORG --- TM["Team Members"]
15 + P1 --- A1["API Keys"]
16 + P1 --- A2["Connected Accounts"]
17 + P1 --- A3["Auth Configs"]
18 + P1 --- A4["Webhook Config"]
19 + P2 --- B1["..."]
20 +```
21 +
22 +Common reasons to use multiple projects:
23 +
24 +- **Separate environments**: keep production and staging isolated
25 +- **Separate products**: keep resources for different apps independent
26 +- **Client isolation**: give each client their own project with separate credentials and data
27 +
28 +## Managing projects
29 +
30 +Manage projects from the [dashboard](https://dashboard.composio.dev/~/org/) or via the API using an **organization API key** (`x-org-api-key`).
31 +
32 +<Callout type="info">
33 +Project management endpoints use the `x-org-api-key` header, not the regular `x-api-key`. Find your org API key in the dashboard under **Settings > Organization**.
34 +</Callout>
35 +
36 +There is no limit on the number of projects per organization. Project names must be unique within the organization. Create a project with `should_create_api_key: true` to get an API key back in the response:
37 +
38 +```bash
39 +curl -X POST https://backend.composio.dev/api/v3.1/org/owner/project/new \
40 + -H "x-org-api-key: YOUR_ORG_API_KEY" \
41 + -H "Content-Type: application/json" \
42 + -d '{
43 + "name": "my-staging-project",
44 + "should_create_api_key": true
45 + }'
46 +```
47 +
48 +```json
49 +{
50 + "id": "proj_abc123xyz456",
51 + "name": "my-staging-project",
52 + "api_key": "ak_abc123xyz456"
53 +}
54 +```
55 +
56 +The list endpoint supports pagination with `limit` and `cursor`; getting a project by ID returns the full project object including its API keys.
57 +
58 +## Project settings
59 +
60 +Each project has settings that control security, logging, and display behavior. These endpoints use your **project API key** (`x-api-key`), not the org key.
61 +
62 +```bash
63 +curl -X PATCH https://backend.composio.dev/api/v3.1/org/project/config \
64 + -H "x-api-key: YOUR_API_KEY" \
65 + -H "Content-Type: application/json" \
66 + -d '{
67 + "mask_secret_keys_in_connected_account": false,
68 + "log_visibility_setting": "show_all"
69 + }'
70 +```
71 +
72 +Notable security setting: `require_mcp_api_key`, when `true`, requires MCP server requests to include a valid `x-api-key` header. This defaults to `true` for organizations created on or after March 5, 2026. You can also view and update project settings from **Settings > Project Settings** in the [dashboard](https://dashboard.composio.dev/~/project/settings/general).
73
74 ## Endpoints
75
docs/content/reference/api-reference/tool-router/index.mdx
+13 -3
@@ -1,11 +1,21 @@
1 ---
2 -title: Tool Router
2 +title: Sessions (prev Tool Router)
3 description: "(Labs) Tool router endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/tool-router.mdx, not this file. */}
7
8 -(Labs) Tool router endpoints
8 +These are Composio's session endpoints. A **session** is the runtime context your agent uses to work for one of your users: it scopes which user's connected accounts are in play, which tools are available, how authentication happens, and where execution state lives. Read [What is a session?](/docs/how-composio-works) for the full concept.
9 +
10 +<Callout type="info">
11 +Sessions were formerly called the "tool router", which is why these endpoints live under `tool_router`. They are the same thing.
12 +</Callout>
13 +
14 +In the SDK you do not call these endpoints directly. Use `composio.create(...)` to start a session and `composio.use(...)` to resume one, then call `session.tools()`, `session.execute(...)`, and `session.authorize(...)` on the returned object.
15 +
16 +Reach for the raw API when you need lower-level control: creating and patching a session config, attaching to an existing session, searching for tools, executing tools and meta tools, opening link sessions for auth, proxying authenticated requests, and reading or writing files in a session mount.
17 +
18 +See [Configuring sessions](/docs/configuring-sessions) for toolkits, auth configs, account selection, and presets.
19
20 ## Endpoints
21
docs/content/reference/api-reference/toolkits/index.mdx
+18 -2
@@ -3,9 +3,25 @@ title: Toolkits
3 description: "Toolkit and tool management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/toolkits.mdx, not this file. */}
7
8 -Toolkit and tool management
8 +A toolkit is a collection of related tools for a single app, like `gmail`, `github`, or `slack`. Each toolkit groups the actions for that service, its authentication requirements, and the trigger types it exposes.
9 +
10 +Reach for these endpoints when you want to:
11 +
12 +- List the toolkits in the catalog, sorted by popularity, to browse what is available before configuring a session.
13 +- Fetch a single toolkit by `slug` for its name, logo, categories, and metadata.
14 +- Fetch several toolkits at once with the multi endpoint.
15 +- List the available toolkit categories to filter the catalog by use case.
16 +- Read the toolkits changelog to track when tools or schemas change.
17 +
18 +These endpoints authenticate with your project API key in the `x-api-key` header.
19 +
20 +<Callout type="info">
21 +Tools within a toolkit are versioned. When you execute a tool, resolve to a known version with `toolkit_versions=latest` or a pinned dated version. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
22 +</Callout>
23 +
24 +To browse toolkits visually, see the [toolkits catalog](/toolkits). For the concepts and SDK usage, see [Tools and toolkits](/docs/how-composio-works) and [Configuring sessions](/docs/configuring-sessions).
25
26 ## Endpoints
27
docs/content/reference/api-reference/tools/index.mdx
+45 -2
@@ -3,9 +3,52 @@ title: Tools
3 description: "Tool execution endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/tools.mdx, not this file. */}
7
8 -Tool execution endpoints
8 +Tools are the individual executable actions inside a toolkit, like `GMAIL_SEND_EMAIL` or `GITHUB_CREATE_ISSUE`. Each tool has an input schema describing its parameters and an output schema describing what it returns. Tool slugs are SCREAMING_SNAKE_CASE and follow a `{TOOLKIT}_{ACTION}` pattern.
9 +
10 +Reach for these endpoints when you want to:
11 +
12 +- List or search the catalog of available tools, optionally scoped to one or more toolkits.
13 +- Fetch a single tool's input and output schema by `tool_slug` before constructing a call.
14 +- Execute a tool on behalf of a user's connected account, or generate the inputs for an execution from natural language.
15 +- Look up the OAuth scopes a set of tools requires, or send an authenticated proxy request to an app's underlying API.
16 +
17 +These endpoints authenticate with your project API key in the `x-api-key` header.
18 +
19 +<Callout type="info">
20 +Manual tool execution requires an explicit toolkit version. Pass `toolkit_versions=latest` (or pin a dated version like `20251027_00`) so calls resolve to a known tool definition. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
21 +</Callout>
22 +
23 +For the concepts behind tools, schemas, and authentication, see [Tools and toolkits](/docs/how-composio-works).
24 +
25 +## Proxy execute
26 +
27 +Proxy execute sends an authenticated HTTP request through a toolkit's [connected account](/docs/auth-configuration/connected-accounts) without a predefined tool, and Composio injects the OAuth token, API key, or other credentials on the server side so your code never touches raw secrets. Reach for it when you need an endpoint that Composio's predefined tools do not cover, when you need a request shape (custom query parameters, field masks, or advanced filters) that a predefined tool cannot express, or when a terminal agent would otherwise hardcode a bearer token in a `curl` call.
28 +
29 +Call it with `composio.tools.proxyExecute()` in the TypeScript SDK, `composio.tools.proxy()` in the Python SDK, or `POST /api/v3.1/tools/execute/proxy` over HTTP. The `endpoint` can be an absolute URL (`https://api.example.com/v1/resource`) or a path relative to the toolkit's base URL (`/v1/resource`), `method` is the HTTP verb, `connectedAccountId` selects the account to authenticate as, `body` carries the JSON payload, and `parameters` adds extra headers and query parameters. The response forwards the upstream `status`, `headers`, and parsed `data` verbatim.
30 +
31 +```typescript
32 +// @noErrors
33 +import { Composio } from '@composio/core';
34 +
35 +const composio = new Composio({ apiKey: 'your_api_key' });
36 +
37 +const { status, data } = await composio.tools.proxyExecute({
38 + endpoint: '/repos/composiohq/composio/issues/1',
39 + method: 'GET',
40 + connectedAccountId: 'ca_github_user_123',
41 + parameters: [{ name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' }],
42 +});
43 +
44 +console.log(status, data);
45 +```
46 +
47 +<Callout type="warn">
48 +Proxy execute rejects cross-domain requests, so the `endpoint` must resolve to the same domain as the connected account's toolkit, and you should not set the `Authorization` header yourself because Composio injects the correct credential for the account's auth scheme. This is an intentional security boundary, not a quota, so it cannot be bypassed by reshaping the request.
49 +</Callout>
50 +
51 +Proxy execute is a form of [direct tool execution](/docs/sessions-vs-direct-execution): it bypasses session state, tool schemas, and modifiers. If you are building an agent, prefer [sessions](/docs/configuring-sessions), and use the proxy only for the specific API call that is not available as a tool. The full request and response schema lives in the [`POST /api/v3.1/tools/execute/proxy`](/reference/api-reference/tools/postToolsExecuteProxy) reference.
52
53 ## Endpoints
54
docs/content/reference/api-reference/triggers/index.mdx
+21 -2
@@ -3,9 +3,28 @@ title: Triggers
3 description: "Trigger management and execution"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/triggers.mdx, not this file. */}
7
8 -Trigger management and execution
8 +Triggers let you subscribe to events from a user's connected app, such as a new Gmail message, a GitHub commit, or a Slack message, and receive the event data as a structured payload at your webhook endpoint.
9 +
10 +There are two layers to understand:
11 +
12 +- A **trigger type** is a template that defines what event to listen for and what configuration it needs. For example, `GITHUB_COMMIT_EVENT` requires an `owner` and a `repo`. Each toolkit exposes its own trigger types.
13 +- A **trigger instance** is a trigger type scoped to a specific user and connected account. Creating one produces an instance with its own `ti_*` ID that you can enable, disable, or delete independently.
14 +
15 +Reach for these endpoints when you want to:
16 +
17 +- Discover the trigger types a toolkit offers, or fetch one type by `slug` to inspect its config and payload schema.
18 +- Create or update a trigger instance for a connected account with the upsert endpoint.
19 +- List active trigger instances, or enable, disable, and delete an instance by `triggerId`.
20 +
21 +These endpoints authenticate with your project API key in the `x-api-key` header.
22 +
23 +<Callout type="info">
24 +Creating a trigger instance only registers it. To actually receive events, set a webhook URL for your project once, then route incoming events on `metadata.trigger_slug`. See [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events).
25 +</Callout>
26 +
27 +For the full concept overview, see [Triggers](/docs/triggers).
28
29 ## Endpoints
30
docs/content/reference/api-reference/webhook-endpoints/index.mdx
+8 -2
@@ -3,9 +3,15 @@ title: Webhook Endpoints
3 description: "Per-OAuth-app webhook ingress endpoints. Inbound URLs the provider posts to, plus signing secret storage and verification."
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/webhook-endpoints.mdx, not this file. */}
7
8 -Per-OAuth-app webhook ingress endpoints. Inbound URLs the provider posts to, plus signing secret storage and verification.
8 +Webhook endpoints are per-OAuth-app webhook ingress configurations. They define the inbound URL a provider posts events to, along with the signing secret Composio stores and uses to verify those incoming payloads.
9 +
10 +Reach for these endpoints when an OAuth app you have configured needs to deliver provider-side events into Composio. You create an endpoint, configure or update it by its `nano_id`, and store the signing secret Composio uses to authenticate inbound requests.
11 +
12 +Each endpoint is addressed by its `nano_id`. The `POST` to `/webhook_endpoints/{nano_id}` replaces the full configuration, while `PATCH` updates it in place.
13 +
14 +This is distinct from [webhook subscriptions](/reference/api-reference/webhook-subscriptions), which control where Composio delivers outbound trigger events. To verify the signature on payloads Composio sends you, see [Webhook verification](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures). To set up the trigger events those payloads carry, see [Triggers](/docs/triggers).
15
16 ## Endpoints
17
docs/content/reference/api-reference/webhook-subscriptions/index.mdx
+133 -2
@@ -3,9 +3,140 @@ title: Webhook Subscriptions
3 description: "Webhook delivery subscriptions. Outbound URLs Composio posts trigger events to, plus signing secret rotation and event-type filters."
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/webhook-subscriptions.mdx, not this file. */}
7
8 -Webhook delivery subscriptions. Outbound URLs Composio posts trigger events to, plus signing secret rotation and event-type filters.
8 +Webhook subscriptions are outbound delivery configurations. They define the URL Composio posts [trigger](/docs/triggers) events to, along with the signing secret and the set of event types you want to receive.
9 +
10 +Reach for these endpoints to register where Composio should send events, to filter delivery to specific event types, and to manage the signing secret used to verify those deliveries. List the available event types with the `/webhook_subscriptions/event_types` endpoint, then create a subscription scoped to the ones you care about.
11 +
12 +Each subscription is addressed by its `id`. You can update its URL and filters with `PATCH`, delete it, and rotate its signing secret with `/webhook_subscriptions/{id}/rotate_secret` if the secret leaks.
13 +
14 +Every webhook request Composio sends includes `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers. Store the secret as `COMPOSIO_WEBHOOK_SECRET` and verify each payload before trusting it. See [Webhook verification](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures) for the SDK and manual verification flows.
15 +
16 +## Event types
17 +
18 +A subscription's `enabled_events` controls which events get delivered to its URL. Two broad families exist:
19 +
20 +- **Trigger events** like `composio.trigger.message` — payloads emitted by [triggers](/docs/triggers) you've enabled (new email, new issue, etc.).
21 +- **Lifecycle events** like `composio.connected_account.expired` — emitted when a [connected account](/docs/auth-configuration/connected-accounts) changes state.
22 +
23 +List everything you can subscribe to with the `/webhook_subscriptions/event_types` endpoint, then scope a subscription to the events you handle.
24 +
25 +## Detecting connection expiry
26 +
27 +Composio automatically refreshes OAuth tokens before they expire. But when a refresh token is revoked or expires, the connection enters an `EXPIRED` state and the user must re-authenticate.
28 +
29 +Subscribe to the `composio.connected_account.expired` event to detect this proactively, instead of waiting for a tool execution to fail.
30 +
31 +<Callout>
32 +This event is only available with [V3 webhook payloads](/docs/setting-up-triggers/subscribing-to-events#webhook-payload-versions). New organizations use V3 by default.
33 +</Callout>
34 +
35 +Add `composio.connected_account.expired` to the subscription's `enabled_events`:
36 +
37 +```bash
38 +curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
39 + -H "X-API-KEY: <your-composio-api-key>" \
40 + -H "Content-Type: application/json" \
41 + -d '{
42 + "webhook_url": "https://example.com/webhook",
43 + "enabled_events": [
44 + "composio.trigger.message",
45 + "composio.connected_account.expired"
46 + ]
47 + }'
48 +```
49 +
50 +When a connection expires, Composio sends a webhook with the connected account details:
51 +
52 +```json
53 +{
54 + "id": "evt_847cdfcd-d219-4f18-a6dd-91acd42ca94a",
55 + "type": "composio.connected_account.expired",
56 + "metadata": {
57 + "project_id": "pr_your-project-id",
58 + "org_id": "ok_your-org-id"
59 + },
60 + "data": {
61 + "id": "ca_your-connected-account-id",
62 + "toolkit": { "slug": "gmail" },
63 + "auth_config": {
64 + "id": "ac_your-auth-config-id",
65 + "auth_scheme": "OAUTH2"
66 + },
67 + "status": "EXPIRED",
68 + "status_reason": "OAuth refresh token expired"
69 + },
70 + "timestamp": "2026-02-06T12:00:00.000Z"
71 +}
72 +```
73 +
74 +Route on `type` to handle expiry alongside trigger events:
75 +
76 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
77 + <Tab value="Python">
78 +```python
79 +from composio import Composio, WebhookEventType
80 +
81 +composio = Composio()
82 +
83 +@app.post("/webhook")
84 +async def webhook_handler(request: Request):
85 + payload = await request.json()
86 + event_type = payload.get("type")
87 +
88 + if event_type == WebhookEventType.CONNECTION_EXPIRED:
89 + account_id = payload["data"]["id"]
90 + toolkit = payload["data"]["toolkit"]["slug"]
91 +
92 + # Look up the user and send them a re-auth link
93 + session = composio.create(user_id=lookup_user(account_id))
94 + connection_request = session.authorize(toolkit)
95 + notify_user(connection_request.redirect_url)
96 +
97 + elif event_type == WebhookEventType.TRIGGER_MESSAGE:
98 + # Handle trigger events
99 + pass
100 +
101 + return {"status": "ok"}
102 +```
103 + </Tab>
104 + <Tab value="TypeScript">
105 +```typescript
106 +import { Composio } from '@composio/core';
107 +const composio = new Composio();
108 +type NextApiRequest = { body: any };
109 +type NextApiResponse = { status: (code: number) => { json: (data: any) => void } };
110 +declare function lookupUser(accountId: string): string;
111 +declare function notifyUser(url: string): void;
112 +// ---cut---
113 +export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
114 + const payload = req.body;
115 +
116 + if (payload.type === 'composio.connected_account.expired') {
117 + const accountId = payload.data.id;
118 + const toolkit = payload.data.toolkit.slug;
119 +
120 + // Look up the user and send them a re-auth link
121 + const session = await composio.create(lookupUser(accountId));
122 + const connectionRequest = await session.authorize(toolkit);
123 + if (connectionRequest.redirectUrl) {
124 + notifyUser(connectionRequest.redirectUrl);
125 + }
126 +
127 + } else if (payload.type === 'composio.trigger.message') {
128 + // Handle trigger events
129 + }
130 +
131 + res.status(200).json({ status: 'ok' });
132 +}
133 +```
134 + </Tab>
135 +</Tabs>
136 +
137 +<Callout>
138 +Always [verify webhook signatures](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures) before processing events in production.
139 +</Callout>
140
141 ## Endpoints
142
docs/content/reference/authenticating-to-composio/index.mdx new
+68
@@ -0,0 +1,68 @@
1 +---
2 +title: Overview
3 +description: Authenticate requests to the Composio API with an API key
4 +keywords: [API authentication, API key, x-api-key, x-org-api-key, scoped api key, Composio authentication, authorization]
5 +---
6 +
7 +Every Composio API request authenticates with an API key. Send the key in a request header and Composio resolves it to your project or organization.
8 +
9 +Composio has three kinds of API key. They share the same authentication flow — they differ in what they can reach.
10 +
11 +| Key | Header | Scope |
12 +| --- | --- | --- |
13 +| Project API key | `x-api-key` | Full access to a single project. |
14 +| Organization API key | `x-org-api-key` | Access across every project in your organization. |
15 +| Scoped project API key <span style={{ color: '#059669' }}>**· New**</span> | `x-api-key` | A chosen subset of a single project's resources. |
16 +
17 +## Project API key
18 +
19 +A project API key authenticates to one project with full access. Use it for most application code.
20 +
21 +Get it from the dashboard: sign in to [composio.dev](https://composio.dev), open **Settings → Project Settings**, and copy the key from the **API Keys** section.
22 +
23 +Send it in the `x-api-key` header:
24 +
25 +```bash
26 +curl https://backend.composio.dev/api/v3.1/tools \
27 + -H "x-api-key: $COMPOSIO_API_KEY"
28 +```
29 +
30 +## Organization API key
31 +
32 +An organization API key authenticates across every project in your organization. Use it for organization-level endpoints.
33 +
34 +Get it from the dashboard: open **Organization Settings → General Settings** and copy a token under **Organization Access Tokens**.
35 +
36 +Send it in the `x-org-api-key` header:
37 +
38 +```bash
39 +curl https://backend.composio.dev/api/v3.1/org/projects \
40 + -H "x-org-api-key: $COMPOSIO_ORG_API_KEY"
41 +```
42 +
43 +## Scoped project API key
44 +
45 +A scoped project API key authenticates to a single project but reaches only the resources you grant it — for example, executing tools without managing connected accounts. It uses the same `x-api-key` header as a default project key.
46 +
47 +Scope a key to the least it needs, then send it like any project key:
48 +
49 +```bash
50 +curl https://backend.composio.dev/api/v3.1/tools/execute/HACKERNEWS_GET_USER \
51 + -H "x-api-key: $COMPOSIO_SCOPED_API_KEY" \
52 + -H "Content-Type: application/json" \
53 + -d '{"arguments": {"username": "pg"}}'
54 +```
55 +
56 +See [Scoped project API keys](/reference/authenticating-to-composio/project-api-key-permissions) for the permission areas, access levels, and the routes each one covers.
57 +
58 +<Cards>
59 + <Card title="Scoped project API keys" href="/reference/authenticating-to-composio/project-api-key-permissions">
60 + Permission areas, access levels, and covered routes
61 + </Card>
62 + <Card title="Errors" href="/reference/errors">
63 + Understanding API error responses
64 + </Card>
65 + <Card title="Rate Limits" href="/reference/rate-limits">
66 + API rate limits by plan
67 + </Card>
68 +</Cards>
docs/content/reference/authenticating-to-composio/meta.json renamed
+1 -1
@@ -1,4 +1,4 @@
1 {
2 - "title": "Authentication",
2 + "title": "Authenticating to Composio",
3 "pages": ["index", "project-api-key-permissions"]
4 }
docs/content/reference/authenticating-to-composio/project-api-key-permissions.mdx new
+240
@@ -0,0 +1,240 @@
1 +---
2 +title: Scoped Project API Key
3 +description: Choose which project resources a scoped API key can access.
4 +keywords: [project api keys, scoped api keys, permissions, access levels]
5 +isNew: true
6 +---
7 +
8 +A scoped project API key lets you choose which project resources the key can access. Reach for one when a key needs only a subset of your project, such as executing tools, reading logs, or managing connected accounts.
9 +
10 +<Callout type="warn">
11 +You pick a key's permissions when you create it, and they can't be changed afterward. To adjust them, create a new key and rotate your application to use it.
12 +</Callout>
13 +
14 +<Callout type="info">
15 +Default project API keys keep full project API key access. Scoped keys use the permission areas and access levels on this page.
16 +</Callout>
17 +
18 +## Access levels
19 +
20 +| Access level | What it allows |
21 +| -------------- | ------------------------------------------------------------------- |
22 +| No access | The key cannot use routes in that permission area. |
23 +| Read only | The key can use read routes in that permission area. |
24 +| Write only | The key can use write routes in that permission area. |
25 +| Read and write | The key can use both read and write routes in that permission area. |
26 +
27 +Some read routes use `POST` because the request body carries filters or lookup input. The access level is based on what the route does, not only the HTTP method.
28 +
29 +When v3 and v3.1 expose the same route shape, this page lists one representative version instead of repeating both. Version-specific routes are listed separately.
30 +
31 +## Permission areas
32 +
33 +Jump to each permission area to see the routes it covers.
34 +
35 +| Permission area | Available levels | Routes |
36 +| ------------------ | ------------------------------------------------ | ---------------------------------- |
37 +| Auth configs | No access, Read only, Write only, Read and write | [View routes](#auth-configs) |
38 +| Connected accounts | No access, Read only, Write only, Read and write | [View routes](#connected-accounts) |
39 +| Tools | No access, Read only | [View routes](#tools) |
40 +| Tool execution | No access, Write only | [View routes](#tool-execution) |
41 +| Proxy execute | No access, Write only | [View routes](#proxy-execute) |
42 +| Toolkits | No access, Read only, Write only, Read and write | [View routes](#toolkits) |
43 +| Triggers | No access, Read only, Write only, Read and write | [View routes](#triggers) |
44 +| Webhooks | No access, Read only, Write only, Read and write | [View routes](#webhooks) |
45 +| Observability | No access, Read only | [View routes](#observability) |
46 +| Sessions | No access, Read only, Write only, Read and write | [View routes](#sessions) |
47 +
48 +## Auth configs
49 +
50 +View and modify auth configs.
51 +
52 +| Access | Method | Endpoint |
53 +| ------ | -------- | ---------------------------------------- |
54 +| Read | `GET` | `/api/v3/auth_configs` |
55 +| Read | `GET` | `/api/v3/auth_configs/{nanoid}` |
56 +| Write | `POST` | `/api/v3/auth_configs` |
57 +| Write | `PATCH` | `/api/v3/auth_configs/{nanoid}` |
58 +| Write | `DELETE` | `/api/v3/auth_configs/{nanoid}` |
59 +| Write | `PATCH` | `/api/v3/auth_configs/{nanoid}/{status}` |
60 +
61 +## Connected accounts
62 +
63 +View and manage connected accounts.
64 +
65 +| Access | Method | Endpoint |
66 +| ------ | -------- | ---------------------------------------------- |
67 +| Read | `GET` | `/api/v3/connected_accounts` |
68 +| Read | `GET` | `/api/v3/connected_accounts/{nanoid}` |
69 +| Write | `POST` | `/api/v3/connected_accounts` |
70 +| Write | `POST` | `/api/v3/connected_accounts/link` |
71 +| Write | `PATCH` | `/api/v3/connected_accounts/{nanoid}` |
72 +| Write | `PATCH` | `/api/v3/connected_accounts/{nanoid}/status` |
73 +| Write | `POST` | `/api/v3/connected_accounts/{nanoid}/refresh` |
74 +| Write | `DELETE` | `/api/v3/connected_accounts/{nanoid}` |
75 +| Write | `POST` | `/api/v3.1/connected_accounts/{nanoid}/revoke` |
76 +
77 +## Tools
78 +
79 +View tool definitions, inputs, scopes, and versions.
80 +
81 +| Access | Method | Endpoint |
82 +| ------ | ------ | ---------------------------------------------- |
83 +| Read | `GET` | `/api/v3.1/tools` |
84 +| Read | `GET` | `/api/v3.1/tools/enum` |
85 +| Read | `GET` | `/api/v3.1/tools/{tool_slug}` |
86 +| Read | `GET` | `/api/v3/tools/{tool_slug}/get_latest_version` |
87 +| Read | `GET` | `/api/v3.1/tools/scopes/required` |
88 +| Read | `GET` | `/api/v3.1/tools/get_scopes_required` |
89 +| Read | `POST` | `/api/v3.1/tools/execute/{tool_slug}/input` |
90 +
91 +## Tool execution
92 +
93 +Execute predefined Composio tools.
94 +
95 +| Access | Method | Endpoint |
96 +| ------ | ------ | ------------------------------------- |
97 +| Write | `POST` | `/api/v3.1/tools/execute/{tool_slug}` |
98 +| Write | `POST` | `/api/v3/files/upload/request` |
99 +| Write | `POST` | `/api/v3/files/upload/response` |
100 +| Write | `GET` | `/api/v3/files/list` |
101 +
102 +## Proxy execute
103 +
104 +Execute raw proxy requests against connected accounts.
105 +
106 +Proxy execute is separate from tool execution. Grant it only when your application needs to call a connected account API through the raw proxy path.
107 +
108 +| Access | Method | Endpoint |
109 +| ------ | ------ | -------------------------------------------------------- |
110 +| Write | `POST` | `/api/v3.1/tools/execute/proxy` |
111 +| Write | `POST` | `/api/v3/tool_router/session/{session_id}/proxy_execute` |
112 +
113 +## Toolkits
114 +
115 +View and install toolkits.
116 +
117 +| Access | Method | Endpoint |
118 +| ------ | ------ | ----------------------------- |
119 +| Read | `GET` | `/api/v3/toolkits` |
120 +| Read | `GET` | `/api/v3/toolkits/{slug}` |
121 +| Read | `GET` | `/api/v3/toolkits/categories` |
122 +| Read | `GET` | `/api/v3/toolkits/changelog` |
123 +| Write | `POST` | `/api/v3/toolkits/multi` |
124 +
125 +## Triggers
126 +
127 +View trigger types, manage trigger instances, and subscribe to trigger events. The realtime routes are called by the SDK (`triggers.subscribe()`) and the CLI to receive trigger events.
128 +
129 +| Access | Method | Endpoint |
130 +| ------ | -------- | ---------------------------------------------- |
131 +| Read | `GET` | `/api/v3/triggers_types` |
132 +| Read | `GET` | `/api/v3/triggers_types/{slug}` |
133 +| Read | `GET` | `/api/v3/triggers_types/list/enum` |
134 +| Read | `GET` | `/api/v3/trigger_instances/active` |
135 +| Read | `GET` | `/api/v3/cli/realtime/credentials` |
136 +| Read | `POST` | `/api/v3/cli/realtime/auth` |
137 +| Read | `GET` | `/api/v3/internal/sdk/realtime/credentials` |
138 +| Read | `POST` | `/api/v3/internal/sdk/realtime/auth` |
139 +| Write | `POST` | `/api/v3/trigger_instances/{slug}/upsert` |
140 +| Write | `PATCH` | `/api/v3/trigger_instances/manage/{triggerId}` |
141 +| Write | `DELETE` | `/api/v3/trigger_instances/manage/{triggerId}` |
142 +
143 +## Webhooks
144 +
145 +View and manage webhook endpoints and subscriptions.
146 +
147 +| Access | Method | Endpoint |
148 +| ------ | -------- | -------------------------------------------------- |
149 +| Read | `GET` | `/api/v3/webhook_endpoints` |
150 +| Read | `GET` | `/api/v3/webhook_endpoints/{nano_id}` |
151 +| Read | `GET` | `/api/v3/webhook_endpoints/schema` |
152 +| Read | `GET` | `/api/v3/webhook_subscriptions` |
153 +| Read | `GET` | `/api/v3/webhook_subscriptions/{id}` |
154 +| Read | `GET` | `/api/v3/webhook_subscriptions/event_types` |
155 +| Write | `POST` | `/api/v3/webhook_endpoints` |
156 +| Write | `POST` | `/api/v3/webhook_endpoints/{nano_id}` |
157 +| Write | `PATCH` | `/api/v3/webhook_endpoints/{nano_id}` |
158 +| Write | `DELETE` | `/api/v3/webhook_endpoints/{nano_id}` |
159 +| Write | `POST` | `/api/v3/webhook_subscriptions` |
160 +| Write | `PATCH` | `/api/v3/webhook_subscriptions/{id}` |
161 +| Write | `DELETE` | `/api/v3/webhook_subscriptions/{id}` |
162 +| Write | `POST` | `/api/v3/webhook_subscriptions/{id}/rotate_secret` |
163 +
164 +## Observability
165 +
166 +View execution logs and project usage summaries.
167 +
168 +| Access | Method | Endpoint |
169 +| ------ | ------ | --------------------------------------- |
170 +| Read | `POST` | `/api/v3.1/logs/tool_execution` |
171 +| Read | `GET` | `/api/v3.1/logs/tool_execution/{id}` |
172 +| Read | `POST` | `/api/v3.1/project/usage/{entity_type}` |
173 +| Read | `POST` | `/api/v3.1/project/usage/summary` |
174 +
175 +## Sessions
176 +
177 +Create and operate sessions and MCP servers. This permission area covers MCP server management, the MCP runtime transport, and the tool router MCP transport.
178 +
179 +| Access | Method | Endpoint |
180 +| ------ | -------- | ------------------------------------------------------------------------- |
181 +| Read | `GET` | `/api/v3/mcp/servers` |
182 +| Read | `GET` | `/api/v3/mcp/{id}` |
183 +| Read | `GET` | `/api/v3/mcp/app/{app_key}` |
184 +| Read | `GET` | `/api/v3/mcp/servers/{server_id}/instances` |
185 +| Read | `GET` | `/tool_router/{session_id}/mcp` |
186 +| Read | `GET` | `/api/v3.1/tool_router/session/{session_id}` |
187 +| Read | `GET` | `/api/v3/tool_router/session/{session_id}/toolkits` |
188 +| Read | `GET` | `/api/v3.1/tool_router/session/{session_id}/tools` |
189 +| Read | `GET` | `/api/v3/tool_router/session/{session_id}/mounts/{mount_id}/items` |
190 +| Read | `GET` | `/api/v3.1/tool_router/session/{session_id}/config_history` |
191 +| Write | `POST` | `/api/v3/mcp/servers` |
192 +| Write | `POST` | `/api/v3/mcp/servers/generate` |
193 +| Write | `POST` | `/api/v3/mcp/servers/custom` |
194 +| Write | `PATCH` | `/api/v3/mcp/{id}` |
195 +| Write | `DELETE` | `/api/v3/mcp/{id}` |
196 +| Write | `POST` | `/api/v3/mcp/servers/{server_id}/instances` |
197 +| Write | `DELETE` | `/api/v3/mcp/servers/{server_id}/instances/{instance_id}` |
198 +| Write | `POST` | `/api/v3/mcp/{server_id}/{transport}` |
199 +| Write | `DELETE` | `/api/v3/mcp/{server_id}/{transport}` |
200 +| Write | `POST` | `/tool_router/{session_id}/mcp` |
201 +| Write | `DELETE` | `/tool_router/{session_id}/mcp` |
202 +| Write | `POST` | `/api/v3.1/tool_router/session` |
203 +| Write | `POST` | `/api/v3.1/tool_router/session/{session_id}/execute` |
204 +| Write | `POST` | `/api/v3.1/tool_router/session/{session_id}/execute_meta` |
205 +| Write | `POST` | `/api/v3/tool_router/session/{session_id}/link` |
206 +| Write | `POST` | `/api/v3.1/tool_router/session/{session_id}/search` |
207 +| Write | `PATCH` | `/api/v3.1/tool_router/session/{session_id}` |
208 +| Write | `POST` | `/api/v3/tool_router/session/{session_id}/mounts/{mount_id}/upload_url` |
209 +| Write | `POST` | `/api/v3/tool_router/session/{session_id}/mounts/{mount_id}/download_url` |
210 +| Write | `POST` | `/api/v3/tool_router/session/{session_id}/mounts/{mount_id}/delete` |
211 +| Write | `POST` | `/api/v3.1/tool_router/session/{session_id}/attach` |
212 +
213 +## What to read next
214 +
215 +<Cards>
216 + <Card
217 + icon={<Key />}
218 + title="Authenticating to Composio"
219 + href="/reference/authenticating-to-composio"
220 + description="Authenticate API requests with project and organization API keys"
221 + />
222 + <Card
223 + icon={<Key />}
224 + title="Projects"
225 + href="/reference/api-reference/projects"
226 + description="Understand projects, project API keys, and project-scoped resources"
227 + />
228 + <Card
229 + icon={<Terminal />}
230 + title="Proxy execute"
231 + href="/reference/api-reference/tools"
232 + description="Call connected account APIs through the raw proxy path"
233 + />
234 + <Card
235 + icon={<Monitor />}
236 + title="Observability"
237 + href="/reference/api-reference/logs"
238 + description="Inspect tool execution logs and usage summaries"
239 + />
240 +</Cards>
docs/content/reference/authentication/index.mdx deleted
-59
@@ -1,59 +0,0 @@
1 ----
2 -title: Overview
3 -description: How to authenticate with Composio APIs using project and organization API keys
4 -keywords: [API authentication, API key, x-api-key, x-org-api-key, Composio authentication, authorization]
5 ----
6 -
7 -All Composio API endpoints require authentication via API key.
8 -
9 -## API Key Authentication
10 -
11 -Include your API key in the `x-api-key` header.
12 -
13 -### Getting Your API Key
14 -
15 -1. Sign in to [composio.dev](https://composio.dev)
16 -2. Navigate to **Settings**
17 -3. In **Project Settings**, copy the key from the **API Keys** section
18 -
19 -<Video src="/videos/fetch-project-key.mp4" autoPlay />
20 -
21 -## Organization API Key
22 -
23 -For organization-level access across multiple projects, use the `x-org-api-key` header instead.
24 -
25 -### Getting Your Organization API Key
26 -
27 -1. Sign in to [composio.dev](https://composio.dev)
28 -2. Navigate to **Organization Settings** → **General Settings**
29 -3. Copy the token under **Organization Access Tokens**
30 -
31 -<Video src="/videos/fetch-org-key.mp4" autoPlay />
32 -
33 -## Using the API Key
34 -
35 -Include your API key in the request header:
36 -
37 -```bash
38 -curl https://backend.composio.dev/api/v3.1/tools \
39 - -H "x-api-key: $COMPOSIO_API_KEY"
40 -```
41 -
42 -For organization-level endpoints:
43 -
44 -```bash
45 -curl https://backend.composio.dev/api/v3.1/org/projects \
46 - -H "x-org-api-key: $COMPOSIO_ORG_API_KEY"
47 -```
48 -
49 -<Cards>
50 - <Card title="Scoped project API keys" href="/reference/authentication/project-api-key-permissions">
51 - Scoped project API key access levels and covered routes
52 - </Card>
53 - <Card title="Errors" href="/reference/errors">
54 - Understanding API error responses
55 - </Card>
56 - <Card title="Rate Limits" href="/reference/rate-limits">
57 - API rate limits by plan
58 - </Card>
59 -</Cards>
docs/content/reference/authentication/project-api-key-permissions.mdx deleted
-217
@@ -1,217 +0,0 @@
1 ----
2 -title: Scoped Project API Key
3 -description: Choose which project resources a scoped API key can access.
4 -keywords: [project api keys, scoped api keys, permissions, access levels]
5 ----
6 -
7 -Scoped project API keys let you choose which project resources a key can access. Use them when a key only needs a subset of your project, such as executing tools, reading logs, or managing connected accounts.
8 -
9 -Permissions are selected when the key is created and cannot be changed later. To change permissions, create a new key and rotate your application to use it.
10 -
11 -<Callout type="info">
12 -Default project API keys keep full project API key access. Scoped project API keys use the permission areas and access levels on this page.
13 -</Callout>
14 -
15 -## Access levels
16 -
17 -| Access level | What it allows |
18 -|---|---|
19 -| No access | The key cannot use routes in that permission area. |
20 -| Read only | The key can use read routes in that permission area. |
21 -| Write only | The key can use write routes in that permission area. |
22 -| Read and write | The key can use both read and write routes in that permission area. |
23 -
24 -Some read routes use `POST` because the request body carries filters or lookup input. The access level is based on what the route does, not only the HTTP method.
25 -
26 -Endpoint paths use `{version}` as a placeholder for the API version.
27 -
28 -## Permission areas
29 -
30 -Jump to each permission area to see the routes it covers.
31 -
32 -| Permission area | Available levels | Routes |
33 -|---|---|---|
34 -| Auth configs | No access, Read only, Write only, Read and write | [View routes](#auth-configs) |
35 -| Connected accounts | No access, Read only, Write only, Read and write | [View routes](#connected-accounts) |
36 -| Tools | No access, Read only | [View routes](#tools) |
37 -| Tool execution | No access, Write only | [View routes](#tool-execution) |
38 -| Proxy execute | No access, Write only | [View routes](#proxy-execute) |
39 -| Toolkits | No access, Read only, Write only, Read and write | [View routes](#toolkits) |
40 -| Triggers | No access, Read only, Write only, Read and write | [View routes](#triggers) |
41 -| Webhooks | No access, Read only, Write only, Read and write | [View routes](#webhooks) |
42 -| Observability | No access, Read only | [View routes](#observability) |
43 -| Sessions | No access, Read only, Write only, Read and write | [View routes](#sessions) |
44 -
45 -## Auth configs
46 -
47 -View and modify auth configs.
48 -
49 -| Access | Method | Endpoint |
50 -|---|---|---|
51 -| Read | `GET` | `/api/{version}/auth_configs` |
52 -| Read | `GET` | `/api/{version}/auth_configs/{nanoid}` |
53 -| Write | `POST` | `/api/{version}/auth_configs` |
54 -| Write | `PATCH` | `/api/{version}/auth_configs/{nanoid}` |
55 -| Write | `DELETE` | `/api/{version}/auth_configs/{nanoid}` |
56 -| Write | `PATCH` | `/api/{version}/auth_configs/{nanoid}/{status}` |
57 -
58 -## Connected accounts
59 -
60 -View and manage connected accounts.
61 -
62 -| Access | Method | Endpoint |
63 -|---|---|---|
64 -| Read | `GET` | `/api/{version}/connected_accounts` |
65 -| Read | `GET` | `/api/{version}/connected_accounts/{nanoid}` |
66 -| Write | `POST` | `/api/{version}/connected_accounts` |
67 -| Write | `POST` | `/api/{version}/connected_accounts/link` |
68 -| Write | `PATCH` | `/api/{version}/connected_accounts/{nanoid}` |
69 -| Write | `PATCH` | `/api/{version}/connected_accounts/{nanoid}/status` |
70 -| Write | `POST` | `/api/{version}/connected_accounts/{nanoid}/refresh` |
71 -| Write | `DELETE` | `/api/{version}/connected_accounts/{nanoid}` |
72 -| Write | `POST` | `/api/{version}/connected_accounts/{nanoid}/revoke` |
73 -
74 -## Tools
75 -
76 -View tool definitions, inputs, scopes, and versions.
77 -
78 -| Access | Method | Endpoint |
79 -|---|---|---|
80 -| Read | `GET` | `/api/{version}/tools` |
81 -| Read | `GET` | `/api/{version}/tools/enum` |
82 -| Read | `GET` | `/api/{version}/tools/{tool_slug}` |
83 -| Read | `GET` | `/api/{version}/tools/{tool_slug}/get_latest_version` |
84 -| Read | `GET` | `/api/{version}/tools/scopes/required` |
85 -| Read | `GET` | `/api/{version}/tools/get_scopes_required` |
86 -| Read | `POST` | `/api/{version}/tools/execute/{tool_slug}/input` |
87 -
88 -## Tool execution
89 -
90 -Execute predefined Composio tools.
91 -
92 -| Access | Method | Endpoint |
93 -|---|---|---|
94 -| Write | `POST` | `/api/{version}/tools/execute/{tool_slug}` |
95 -| Write | `POST` | `/api/{version}/files/upload/request` |
96 -| Write | `POST` | `/api/{version}/files/upload/response` |
97 -| Write | `GET` | `/api/{version}/files/list` |
98 -
99 -## Proxy execute
100 -
101 -Execute raw proxy requests against connected accounts.
102 -
103 -Proxy execute is separate from tool execution. Grant it only when your application needs to call a connected account API through the raw proxy path.
104 -
105 -| Access | Method | Endpoint |
106 -|---|---|---|
107 -| Write | `POST` | `/api/{version}/tools/execute/proxy` |
108 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/proxy_execute` |
109 -
110 -## Toolkits
111 -
112 -View and install toolkits.
113 -
114 -| Access | Method | Endpoint |
115 -|---|---|---|
116 -| Read | `GET` | `/api/{version}/toolkits` |
117 -| Read | `GET` | `/api/{version}/toolkits/{slug}` |
118 -| Read | `GET` | `/api/{version}/toolkits/categories` |
119 -| Read | `GET` | `/api/{version}/toolkits/changelog` |
120 -| Write | `POST` | `/api/{version}/toolkits/multi` |
121 -
122 -## Triggers
123 -
124 -View trigger types, manage trigger instances, and subscribe to trigger events. The realtime routes are called by the SDK (`triggers.subscribe()`) and the CLI to receive trigger events.
125 -
126 -| Access | Method | Endpoint |
127 -|---|---|---|
128 -| Read | `GET` | `/api/{version}/triggers_types` |
129 -| Read | `GET` | `/api/{version}/triggers_types/{slug}` |
130 -| Read | `GET` | `/api/{version}/triggers_types/list/enum` |
131 -| Read | `GET` | `/api/{version}/trigger_instances/active` |
132 -| Read | `GET` | `/api/{version}/cli/realtime/credentials` |
133 -| Read | `POST` | `/api/{version}/cli/realtime/auth` |
134 -| Read | `GET` | `/api/{version}/internal/sdk/realtime/credentials` |
135 -| Read | `POST` | `/api/{version}/internal/sdk/realtime/auth` |
136 -| Write | `POST` | `/api/{version}/trigger_instances/{slug}/upsert` |
137 -| Write | `PATCH` | `/api/{version}/trigger_instances/manage/{triggerId}` |
138 -| Write | `DELETE` | `/api/{version}/trigger_instances/manage/{triggerId}` |
139 -
140 -## Webhooks
141 -
142 -View and manage webhook endpoints and subscriptions.
143 -
144 -| Access | Method | Endpoint |
145 -|---|---|---|
146 -| Read | `GET` | `/api/{version}/webhook_endpoints` |
147 -| Read | `GET` | `/api/{version}/webhook_endpoints/{nano_id}` |
148 -| Read | `GET` | `/api/{version}/webhook_endpoints/schema` |
149 -| Read | `GET` | `/api/{version}/webhook_subscriptions` |
150 -| Read | `GET` | `/api/{version}/webhook_subscriptions/{id}` |
151 -| Read | `GET` | `/api/{version}/webhook_subscriptions/event_types` |
152 -| Write | `POST` | `/api/{version}/webhook_endpoints` |
153 -| Write | `POST` | `/api/{version}/webhook_endpoints/{nano_id}` |
154 -| Write | `PATCH` | `/api/{version}/webhook_endpoints/{nano_id}` |
155 -| Write | `DELETE` | `/api/{version}/webhook_endpoints/{nano_id}` |
156 -| Write | `POST` | `/api/{version}/webhook_subscriptions` |
157 -| Write | `PATCH` | `/api/{version}/webhook_subscriptions/{id}` |
158 -| Write | `DELETE` | `/api/{version}/webhook_subscriptions/{id}` |
159 -| Write | `POST` | `/api/{version}/webhook_subscriptions/{id}/rotate_secret` |
160 -
161 -## Observability
162 -
163 -View execution logs and project usage summaries.
164 -
165 -| Access | Method | Endpoint |
166 -|---|---|---|
167 -| Read | `POST` | `/api/{version}/logs/tool_execution` |
168 -| Read | `GET` | `/api/{version}/logs/tool_execution/{id}` |
169 -| Read | `POST` | `/api/{version}/project/usage/{entity_type}` |
170 -| Read | `POST` | `/api/{version}/project/usage/summary` |
171 -
172 -## Sessions
173 -
174 -Create and operate sessions and MCP servers. This permission area covers MCP server management, the MCP runtime transport, and the tool router MCP transport.
175 -
176 -| Access | Method | Endpoint |
177 -|---|---|---|
178 -| Read | `GET` | `/api/{version}/mcp/servers` |
179 -| Read | `GET` | `/api/{version}/mcp/{id}` |
180 -| Read | `GET` | `/api/{version}/mcp/app/{app_key}` |
181 -| Read | `GET` | `/api/{version}/mcp/servers/{server_id}/instances` |
182 -| Read | `GET` | `/tool_router/{session_id}/mcp` |
183 -| Read | `GET` | `/api/{version}/tool_router/session/{session_id}` |
184 -| Read | `GET` | `/api/{version}/tool_router/session/{session_id}/toolkits` |
185 -| Read | `GET` | `/api/{version}/tool_router/session/{session_id}/tools` |
186 -| Read | `GET` | `/api/{version}/tool_router/session/{session_id}/mounts/{mount_id}/items` |
187 -| Read | `GET` | `/api/{version}/tool_router/session/{session_id}/config_history` |
188 -| Write | `POST` | `/api/{version}/mcp/servers` |
189 -| Write | `POST` | `/api/{version}/mcp/servers/generate` |
190 -| Write | `POST` | `/api/{version}/mcp/servers/custom` |
191 -| Write | `PATCH` | `/api/{version}/mcp/{id}` |
192 -| Write | `DELETE` | `/api/{version}/mcp/{id}` |
193 -| Write | `POST` | `/api/{version}/mcp/servers/{server_id}/instances` |
194 -| Write | `DELETE` | `/api/{version}/mcp/servers/{server_id}/instances/{instance_id}` |
195 -| Write | `POST` | `/api/{version}/mcp/{server_id}/{transport}` |
196 -| Write | `DELETE` | `/api/{version}/mcp/{server_id}/{transport}` |
197 -| Write | `POST` | `/tool_router/{session_id}/mcp` |
198 -| Write | `DELETE` | `/tool_router/{session_id}/mcp` |
199 -| Write | `POST` | `/api/{version}/tool_router/session` |
200 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/execute` |
201 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/execute_meta` |
202 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/link` |
203 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/search` |
204 -| Write | `PATCH` | `/api/{version}/tool_router/session/{session_id}` |
205 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/mounts/{mount_id}/upload_url` |
206 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/mounts/{mount_id}/download_url` |
207 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/mounts/{mount_id}/delete` |
208 -| Write | `POST` | `/api/{version}/tool_router/session/{session_id}/attach` |
209 -
210 -## What to read next
211 -
212 -<Cards>
213 - <Card icon={<Key />} title="Authentication" href="/reference/authentication" description="Authenticate API requests with project and organization API keys" />
214 - <Card icon={<Key />} title="Projects" href="/docs/projects" description="Understand projects, project API keys, and project-scoped resources" />
215 - <Card icon={<Terminal />} title="Proxy execute" href="/docs/proxy-execute" description="Call connected account APIs through the raw proxy path" />
216 - <Card icon={<Monitor />} title="Observability" href="/docs/observability" description="Inspect tool execution logs and usage summaries" />
217 -</Cards>
docs/content/reference/errors.mdx
+3 -6
@@ -58,7 +58,7 @@ Composio uses two types of API keys:
58 | Insufficient permissions | The API key doesn't have access to this resource. |
59
60 <Callout>
61 -See [Authentication Troubleshooting](/docs/troubleshooting/authentication) for more help.
61 +See [Authenticating users](/docs/authentication) for more help.
62 </Callout>
63
64 ### Tool errors
@@ -72,7 +72,7 @@ Errors that occur when fetching or executing tools.
72 | Tool execution failed | The external service returned an error. Check tool parameters and user permissions. |
73
74 <Callout>
75 -See [Tools Troubleshooting](/docs/troubleshooting/tools) for more help.
75 +See [Tools and toolkits](/docs/how-composio-works) for more help.
76 </Callout>
77
78 ### Connection errors
@@ -95,7 +95,7 @@ Errors related to trigger subscriptions.
95 | Trigger instance deleted | The trigger subscription or its connected account was removed. |
96
97 <Callout>
98 -See [Triggers Troubleshooting](/docs/troubleshooting/triggers) for more help.
98 +See [Triggers](/docs/triggers) for more help.
99 </Callout>
100
101 ## Rate limiting
@@ -107,9 +107,6 @@ When you hit rate limits, you'll receive a `429` status code. See [Rate Limits](
107 When contacting support, include the `request_id` from the error response.
108
109 <Cards>
110 - <Card title="Troubleshooting" href="/docs/troubleshooting">
111 - Common issues and solutions
112 - </Card>
110 <Card title="Discord" href="https://discord.com/channels/1170785031560646836/1268871288156323901">
111 Community support
112 </Card>
docs/content/reference/glossary.mdx new
+146
@@ -0,0 +1,146 @@
1 +---
2 +title: Glossary
3 +description: Definitions of key Composio terms and concepts.
4 +llmGuardrails: "none"
5 +keywords: [glossary, definitions, terminology]
6 +---
7 +
8 +<Glossary>
9 +
10 +<GlossaryTerm name="Auth Config">
11 +A blueprint that defines how authentication works for a toolkit: the auth method (`OAUTH2`, `API_KEY`, `BEARER_TOKEN`, or `BASIC`), scopes, and credentials. A [session](/docs/how-composio-works) creates one automatically when it needs one. To use your own OAuth credentials or non-default scopes, [create a custom one](/docs/auth-configuration/custom-auth-configs).
12 +</GlossaryTerm>
13 +
14 +<GlossaryTerm name="Auth Scheme">
15 +The authentication method an auth config uses, such as `OAUTH2`, `API_KEY`, `BEARER_TOKEN`, or `BASIC`.
16 +</GlossaryTerm>
17 +
18 +<GlossaryTerm name="Callback URL">
19 +The URL a user returns to after completing an OAuth flow through a Connect Link. You pass it as `callbackUrl` when you initiate authentication.
20 +</GlossaryTerm>
21 +
22 +<GlossaryTerm name="Composio API Key">
23 +A project-scoped secret that authenticates your SDK and API requests. Every resource you create with it is scoped to that project.
24 +</GlossaryTerm>
25 +
26 +<GlossaryTerm name="Composio Managed Auth">
27 +The default mode in which Composio supplies its own OAuth app credentials for each toolkit. It requires no setup.
28 +</GlossaryTerm>
29 +
30 +<GlossaryTerm name="Connect Link">
31 +A hosted page where a user authorizes access to a toolkit. It is returned as a `redirect_url` from `session.authorize()` or `connectedAccounts.link()`, and Composio manages the full OAuth flow. See [Authentication](/docs/authentication).
32 +</GlossaryTerm>
33 +
34 +<GlossaryTerm name="Connected Account">
35 +A stored set of credentials (OAuth tokens or API keys) linked to a userID, created when a user authenticates with a toolkit. Composio refreshes OAuth tokens automatically, and a user can have [multiple connected accounts](/docs/managing-multiple-connected-accounts) for the same toolkit. IDs are prefixed `ca_`.
36 +</GlossaryTerm>
37 +
38 +<GlossaryTerm name="Connection Request">
39 +The object returned when you initiate authentication. It contains the Connect Link URL and a `waitForConnection()` method that resolves once the user completes the flow.
40 +</GlossaryTerm>
41 +
42 +<GlossaryTerm name="Custom Tool">
43 +A tool you define yourself and use alongside Composio's built-in tools. Add local experimental custom tools and custom toolkits through [Custom tools and toolkits](/docs/extending-sessions/custom-tools-and-toolkits).
44 +</GlossaryTerm>
45 +
46 +<GlossaryTerm name="In-Chat Authentication">
47 +A flow in which the agent handles authentication itself by calling `COMPOSIO_MANAGE_CONNECTIONS` to generate a Connect Link and send it to the user in the conversation. See [In-chat authentication](/docs/authentication#in-chat-authentication).
48 +</GlossaryTerm>
49 +
50 +<GlossaryTerm name="MCP (Model Context Protocol)">
51 +An open protocol for connecting AI models to external tools. Create a session with `mcp: true` to expose `session.mcp.url` and `session.mcp.headers`, an MCP-compatible endpoint any MCP client can connect to. See [Using sessions via MCP](/docs/sessions-via-mcp).
52 +</GlossaryTerm>
53 +
54 +<GlossaryTerm name="Manual Authentication">
55 +Authenticating users from your own code with `session.authorize()` or `connectedAccounts.link()`, rather than letting the agent handle it through in-chat authentication. See [Manual authentication](/docs/manually-authenticating).
56 +</GlossaryTerm>
57 +
58 +<GlossaryTerm name="Meta Tools">
59 +A set of tools included in every session: `COMPOSIO_SEARCH_TOOLS`, `COMPOSIO_GET_TOOL_SCHEMAS`, `COMPOSIO_MANAGE_CONNECTIONS`, `COMPOSIO_MULTI_EXECUTE_TOOL`, `COMPOSIO_REMOTE_WORKBENCH`, and `COMPOSIO_REMOTE_BASH_TOOL`. They let the agent discover tools, manage auth, execute in parallel, and run code without loading hundreds of tool definitions upfront. See [Meta Tools Reference](/toolkits/meta-tools).
60 +</GlossaryTerm>
61 +
62 +<GlossaryTerm name="Modifiers">
63 +Middleware that transforms tool behavior. [Schema modifiers](/docs/tools-direct/modify-tool-behavior/schema-modifiers) change a tool's schema before the agent sees it, [before-execution modifiers](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers) change arguments before a tool runs, and [after-execution modifiers](/docs/tools-direct/modify-tool-behavior/after-execution-modifiers) transform the result. In Python, [`@before_file_upload`](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) intercepts local paths for `file_uploadable` parameters before read and upload.
64 +</GlossaryTerm>
65 +
66 +<GlossaryTerm name="Native Tools">
67 +Tools you access through provider packages with `session.tools()` and call directly, rather than over MCP. Both paths give the agent the same capabilities, but tools called directly integrate with your AI framework and support modifiers and custom tools.
68 +</GlossaryTerm>
69 +
70 +<GlossaryTerm name="Organization">
71 +The top-level Composio account entity. It contains team members and projects.
72 +</GlossaryTerm>
73 +
74 +<GlossaryTerm name="Organization API Key">
75 +A key (`x-org-api-key`) for organization-level operations such as creating and managing projects. It is distinct from the project-scoped Composio API Key.
76 +</GlossaryTerm>
77 +
78 +<GlossaryTerm name="Project">
79 +An isolated environment within an organization that scopes API keys, connected accounts, auth configs, and webhooks. Resources in one project are inaccessible from another. IDs are prefixed `proj_`. See [Projects](/reference/api-reference/projects).
80 +</GlossaryTerm>
81 +
82 +<GlossaryTerm name="Proxy Execute">
83 +Making authenticated HTTP requests through a toolkit's connected account without a predefined tool. Use it for API endpoints Composio has no built-in tool for.
84 +</GlossaryTerm>
85 +
86 +<GlossaryTerm name="Provider">
87 +An adapter package that transforms Composio tools into the format an AI framework expects (OpenAI, Anthropic, LangChain, Vercel AI SDK, and others). See [Providers](/docs/providers).
88 +</GlossaryTerm>
89 +
90 +<GlossaryTerm name="Session">
91 +An ephemeral, immutable configuration object returned by `composio.create(userId)`. It ties together a userID, the available toolkits, an auth config, and connected accounts, and it exposes `tools()`, `authorize()`, and `toolkits()` (plus `mcp.url` when created with `mcp: true`). See [What is a session?](/docs/how-composio-works).
92 +</GlossaryTerm>
93 +
94 +<GlossaryTerm name="Session ID">
95 +The unique identifier for a session. Meta tools use it internally to share context across calls within the same session.
96 +</GlossaryTerm>
97 +
98 +<GlossaryTerm name="Tool">
99 +An individual action an agent can execute. It has an input schema and an output schema, and is named `{TOOLKIT}_{ACTION}` (for example, `GITHUB_CREATE_ISSUE`).
100 +</GlossaryTerm>
101 +
102 +<GlossaryTerm name="Tool Slug">
103 +A tool's unique identifier, in the `{TOOLKIT}_{ACTION}` pattern (for example, `GITHUB_CREATE_ISSUE`).
104 +</GlossaryTerm>
105 +
106 +<GlossaryTerm name="Toolkit">
107 +A collection of related tools for a single external service. Users connect to a toolkit through authentication, and all of its tools execute with the user's credentials.
108 +</GlossaryTerm>
109 +
110 +<GlossaryTerm name="Toolkit Slug">
111 +The lowercase identifier for a toolkit (for example, `github`, `gmail`, or `slack`). Use it when configuring sessions, fetching tools, or creating triggers.
112 +</GlossaryTerm>
113 +
114 +<GlossaryTerm name="Toolkit Versioning">
115 +Pinning a toolkit to a specific version so your integration keeps a consistent set of tools even as Composio updates its definitions. See [Toolkit versioning](/docs/tools-direct/toolkit-versioning).
116 +</GlossaryTerm>
117 +
118 +<GlossaryTerm name="Trigger">
119 +A source that sends structured payloads to your application when something happens in a connected app. Triggers come in two kinds: realtime (the provider pushes events the moment they happen, for example Slack, GitHub, or Asana) and polling (Composio checks the provider on a schedule, for example Gmail). Either way, events arrive at your subscription or webhook URL. See [Triggers](/docs/triggers).
120 +</GlossaryTerm>
121 +
122 +<GlossaryTerm name="Trigger Instance">
123 +A specific, active trigger scoped to a user's connected account.
124 +</GlossaryTerm>
125 +
126 +<GlossaryTerm name="Webhook Endpoint">
127 +The ingress URL Composio issues per OAuth app for webhook triggers, plus the signing secret used to verify each inbound request. Composio configures it for you in most cases. When a trigger type's `requires_webhook_endpoint_setup` flag is `true`, you configure it yourself once per OAuth app through the [Webhook Endpoints API](/reference/api-reference/webhook-endpoints). See [Custom OAuth webhooks](/docs/setting-up-triggers/custom-oauth-webhooks).
128 +</GlossaryTerm>
129 +
130 +<GlossaryTerm name="Webhook Subscription">
131 +The URL Composio delivers signed events to in your application. There is one per project, configured through the dashboard or the [Webhook Subscriptions API](/reference/api-reference/webhook-subscriptions). See [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events).
132 +</GlossaryTerm>
133 +
134 +<GlossaryTerm name="userID">
135 +An identifier from your application that Composio uses to scope connected accounts, tool executions, and authorizations. Connections are fully isolated between userIDs. See [What is a session?](/docs/how-composio-works).
136 +</GlossaryTerm>
137 +
138 +<GlossaryTerm name="White-Labeling">
139 +Customizing the auth experience so users see your brand during the OAuth flow. You provide your own OAuth credentials, redirect URIs, and branding. See [White-labeling authentication](/docs/white-labeling-authentication).
140 +</GlossaryTerm>
141 +
142 +<GlossaryTerm name="Sandbox">
143 +A persistent Python environment (previously called the workbench) exposed through the `COMPOSIO_REMOTE_WORKBENCH` meta tool. Its state persists across calls within a session, which makes it useful for bulk operations, data transformations, and processing large tool responses. Configure it with the `sandbox` session key; `workbench` still works as an alias. See [Sandbox](/docs/sandbox/remote).
144 +</GlossaryTerm>
145 +
146 +</Glossary>
docs/content/reference/index.mdx
+1 -1
@@ -9,7 +9,7 @@ Composio powers tool discovery, execution, authentication, and context managemen
9 ## Quick Reference
10
11 - **Base URL**: <ApiBaseUrl />
12 -- **[Authentication](/reference/authentication)**: `x-api-key` (project) or `x-org-api-key` (organization) header
12 +- **[Authenticating to Composio](/reference/authenticating-to-composio)**: `x-api-key` (project) or `x-org-api-key` (organization) header
13 - **[Rate Limits](/reference/rate-limits)**: 2K-10K requests per minute (plan-dependent)
14
15 ## REST API
docs/content/reference/meta-tools/index.mdx deleted
-24
@@ -1,24 +0,0 @@
1 ----
2 -title: Meta Tools
3 -description: Complete reference for all Composio meta tools available in sessions.
4 -keywords: [meta tools, session]
5 ----
6 -
7 -{/* Auto-generated by scripts/generate-meta-tools.ts — do not edit manually */}
8 -
9 -import { Callout } from 'fumadocs-ui/components/callout';
10 -
11 -<Callout type="warn">
12 -Meta tool schemas are for reference only. We do not guarantee backward compatibility for parameter names or response shapes. Do not rely on them for structured type definitions in your code.
13 -</Callout>
14 -
15 -Meta tools are system-level tools available in [sessions](/docs/tools-and-toolkits). They handle tool discovery, execution, authentication, and sandboxing.
16 -
17 -| Tool | Description |
18 -|------|-------------|
19 -| [`COMPOSIO_GET_TOOL_SCHEMAS`](/reference/meta-tools/get_tool_schemas) | Retrieve input schemas for tools by slug |
20 -| [`COMPOSIO_MANAGE_CONNECTIONS`](/reference/meta-tools/manage_connections) | Create or manage connections to user's apps |
21 -| [`COMPOSIO_MULTI_EXECUTE_TOOL`](/reference/meta-tools/multi_execute_tool) | Fast and parallel tool executor for tools discovered through COMPOSIO_SEARCH_TOOLS |
22 -| [`COMPOSIO_REMOTE_BASH_TOOL`](/reference/meta-tools/remote_bash_tool) | Execute bash commands in a REMOTE sandbox for file operations, data processing, and system tasks |
23 -| [`COMPOSIO_REMOTE_WORKBENCH`](/reference/meta-tools/remote_workbench) | Process REMOTE FILES or script BULK TOOL EXECUTIONS using Python code IN A REMOTE SANDBOX |
24 -| [`COMPOSIO_SEARCH_TOOLS`](/reference/meta-tools/search_tools) | Tool Server Info: Composio connects 500+ apps—Slack, GitHub, Notion, Google Workspace (Gmail, Sheets, Drive, Calendar... |
docs/content/reference/meta.json
+2 -2
@@ -2,12 +2,12 @@
2 "title": "Reference",
3 "pages": [
4 "index",
5 - "authentication",
5 + "authenticating-to-composio",
6 "rate-limits",
7 "errors",
8 + "glossary",
9 "api-reference",
10 "v3",
10 - "meta-tools",
11 "sdk-reference"
12 ]
13 }
docs/content/reference/rate-limits.mdx
+7 -11
@@ -4,24 +4,20 @@ description: Composio API rate limits by plan, rate limit headers, and best prac
4 keywords: [API rate limits, rate limiting, throttling, 429 too many requests, API quotas, request limits]
5 ---
6
7 -Rate limits are enforced **per organization** on a fixed one-minute window.
7 +Composio enforces rate limits **per organization** over a fixed one-minute window. Every authenticated endpoint draws from the same budget — tool execution, connected accounts, triggers, and the rest — so the limit below is your organization's total across all API calls.
8
9 ## Rate limits by plan
10
11 -| Plan | Rate Limit | Window |
11 +| Plan | Rate limit | Window |
12 |------|------------|--------|
13 | Starter | 2,000 requests | 1 minute |
14 | Hobby | 2,000 requests | 1 minute |
15 | Growth | 10,000 requests | 1 minute |
16 | Enterprise | Custom | - |
17
18 -<Callout>
19 -All authenticated API endpoints share your organization's rate limit. This includes tool execution, connected accounts, triggers, and all other API operations.
20 -</Callout>
21 -
18 ## Rate limit headers
19
24 -API responses include headers to help you track your usage:
20 +Every response includes headers so you can track usage without guessing:
21
22 | Header | Description |
23 |--------|-------------|
@@ -42,15 +38,15 @@ When you exceed the rate limit, you'll receive a `429 Too Many Requests` respons
38
39 ## Best practices
40
45 -1. **Monitor your usage** - Check the `X-RateLimit-Remaining` header to track how close you are to the limit.
41 +1. **Watch `X-RateLimit-Remaining`** — read it on each response to know how much headroom you have left in the window.
42
47 -2. **Honor `Retry-After`** - On a `429`, wait for the duration in the `Retry-After` header before retrying.
43 +2. **Honor `Retry-After`** — on a `429`, wait the number of seconds it gives you before retrying instead of hammering the endpoint.
44
49 -3. **Cache responses** - Cache tool definitions and other static data to reduce unnecessary API calls.
45 +3. **Cache what doesn't change** — keep tool definitions and other static data client-side so you don't spend requests re-fetching them.
46
47 ## Need higher limits?
48
53 -If you're hitting rate limits regularly, consider upgrading your plan or [talk to us](https://calendly.com/composiohq/enterprise) to discuss custom limits for your use case.
49 +If you hit these limits regularly, upgrade your plan or [talk to us](https://calendly.com/composiohq/enterprise) about custom limits for your use case.
50
51 <Cards>
52 <Card title="Errors" href="/reference/errors">
docs/content/reference/sdk-reference/python/connected-accounts.mdx
+34 -1
@@ -37,9 +37,42 @@ def update(nanoid: str, alias: str | None = ..., connection: connected_account_p
37
38 ---
39
40 +### update_acl()
41 +
42 +Update the per-user ACL on a SHARED connected account. Experimental — shape may change in future releases. Only valid on SHARED connections; raises ``ComposioAclOnlyForSharedError`` on a PRIVATE connection. Omit a parameter to leave it unchanged; pass an empty list to clear an allow/deny list. At least one parameter must be provided.
43 +
44 +```python
45 +def update_acl(nanoid: str, allow_all_users: bool | None = ..., allowed_user_ids: List[str | None] = ..., not_allowed_user_ids: List[str | None] = ...) -> connected_account_patch_response.ConnectedAccountPatchRes...
46 +```
47 +
48 +**Parameters**
49 +
50 +| Name | Type |
51 +|------|------|
52 +| `nanoid` | `str` |
53 +| `allow_all_users?` | `bool \| None` |
54 +| `allowed_user_ids?` | `List[str \| None]` |
55 +| `not_allowed_user_ids?` | `List[str \| None]` |
56 +
57 +**Returns**
58 +
59 +`connected_account_patch_response.ConnectedAccountPatchRes...` — Response with ``id``, ``status``, and ``success``.
60 +
61 +**Example**
62 +
63 +```python
64 +composio.connected_accounts.update_acl(
65 + 'ca_abc',
66 + allow_all_users=True,
67 + not_allowed_user_ids=['user_bob'],
68 + )
69 +```
70 +
71 +---
72 +
73 ### initiate()
74
42 -Compound function to create a new connected account. This function creates a new connected account and returns a connection request. Users can then wait for the connection to be established using the ``wait_for_connection`` method. .. deprecated:: For Composio-managed (default) auth configs on redirectable OAuth schemes (OAuth1, OAuth2, DCR_OAUTH), the legacy endpoint this method wraps is being retired: **2026-05-08** for new organizations and **2026-07-03** for all remaining organizations. After your org's cutover, this method will raise :class:`composio.exceptions.ComposioLegacyConnectedAccountsEndpointRetiredError` for that specific combination. Use :meth:`ConnectedAccounts.link` for Composio-managed OAuth — it works for every redirectable scheme regardless of whether the auth config is Composio-managed or custom, and the return shape is the same. Custom auth configs (your own OAuth app) and non-OAuth schemes (API key, bearer token, basic auth) are unaffected and continue to work on ``initiate()``. See https://docs.composio.dev/docs/changelog/2026/04/24
75 +Compound function to create a new connected account. This function creates a new connected account and returns a connection request. Users can then wait for the connection to be established using the ``wait_for_connection`` method.
76
77 ```python
78 def initiate(user_id: str, auth_config_id: str, callback_url: str | None = ..., allow_multiple: bool = ..., config: connected_account_create_params.ConnectionState | None = ..., alias: str | None = ...) -> ConnectionRequest
docs/content/reference/sdk-reference/python/index.mdx
+1 -2
@@ -30,8 +30,7 @@ uv add composio
30 | [`ConnectedAccounts`](/reference/sdk-reference/python/connected-accounts) | Manage connected accounts. This class is used to manage connected accounts in t... |
31 | [`AuthConfigs`](/reference/sdk-reference/python/auth-configs) | Manage authentication configurations. |
32 | [`MCP`](/reference/sdk-reference/python/mcp) | MCP (Model Control Protocol) class. Provides enhanced MCP server operations Thi... |
33 -| [`ToolRouterSession`](/reference/sdk-reference/python/tool-router-session) | Tool router session containing session information and methods. Generic Paramet... |
34 -| [`SessionContextImpl`](/reference/sdk-reference/python/session-context-impl) | Concrete implementation of SessionContext. One instance is created per session ... |
33 +| [`Session`](/reference/sdk-reference/python/session) | A Composio session — the object returned by ``composio.create(...)`` / ``composi... |
34
35 ## Quick Start
36
docs/content/reference/sdk-reference/python/mcp.mdx
+4
@@ -3,6 +3,10 @@ title: "MCP"
3 description: "MCP (Model Control Protocol) class. Provides enhanced MCP server operations This matches the TypeScript ExperimentalMCP class functionality."
4 ---
5
6 +<Callout type="warn" title="Deprecated">
7 +Use a session's MCP endpoint instead: `composio.create(user_id, mcp=True)` returns a session that exposes `session.mcp.url` / `session.mcp.headers`. The standalone `composio.mcp` server-management API is kept for backwards compatibility. See https://docs.composio.dev/docs/sessions-via-mcp
8 +</Callout>
9 +
10 ## Methods
11
12 ### create()
docs/content/reference/sdk-reference/python/meta.json
+1 -2
@@ -8,7 +8,6 @@
8 "connected-accounts",
9 "auth-configs",
10 "mcp",
11 - "tool-router-session",
12 - "session-context-impl"
11 + "session"
12 ]
13 }
\ No newline at end of file
docs/content/reference/sdk-reference/python/session-context-impl.mdx deleted
-59
@@ -1,59 +0,0 @@
1 ----
2 -title: "SessionContextImpl"
3 -description: "Concrete implementation of SessionContext. One instance is created per session (singleton) and shared across all custom tool invocations. When ``c..."
4 ----
5 -
6 -## Properties
7 -
8 -| Name | Type | Description |
9 -|------|------|-------------|
10 -| `user_id` | `str` | The user ID for the current session. |
11 -
12 -## Methods
13 -
14 -### execute()
15 -
16 -Execute any tool from within a custom tool. Routes to sibling local tools in-process when available, otherwise delegates to the backend API. Returns the same response model as ``session.execute()``.
17 -
18 -```python
19 -def execute(tool_slug: str, arguments: Dict[str, Any]) -> SessionExecuteResponse
20 -```
21 -
22 -**Parameters**
23 -
24 -| Name | Type |
25 -|------|------|
26 -| `tool_slug` | `str` |
27 -| `arguments` | `Dict[str, Any]` |
28 -
29 -**Returns**
30 -
31 -`SessionExecuteResponse`
32 -
33 ----
34 -
35 -### proxy_execute()
36 -
37 -Proxy API calls through Composio's auth layer. Returns the same response model as ``session.proxy_execute()``.
38 -
39 -```python
40 -def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], body: Any = ..., parameters: List[Dict[str, Any | None]] = ...) -> SessionProxyExecuteResponse
41 -```
42 -
43 -**Parameters**
44 -
45 -| Name | Type |
46 -|------|------|
47 -| `toolkit` | `str` |
48 -| `endpoint` | `str` |
49 -| `method` | `Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH']` |
50 -| `body?` | `Any` |
51 -| `parameters?` | `List[Dict[str, Any \| None]]` |
52 -
53 -**Returns**
54 -
55 -`SessionProxyExecuteResponse`
56 -
57 ----
58 -
59 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/session_context.py#L92)
docs/content/reference/sdk-reference/python/session.mdx renamed
+3 -4
@@ -1,6 +1,6 @@
1 ---
2 -title: "ToolRouterSession"
3 -description: "Tool router session containing session information and methods. Generic Parameters: TTool: The individual tool type returned by the provider. TToo..."
2 +title: "Session"
3 +description: "A Composio session \u2014 the object returned by `composio.create(...)` / `composio.use(...)`. Use it to fetch session-scoped tools, authorize toolkits,..."
4 ---
5
6 ## Properties
@@ -8,7 +8,6 @@ description: "Tool router session containing session information and methods. G
8 | Name | Type |
9 |------|------|
10 | `session_id` | `str` |
11 -| `mcp` | `Any` |
11 | `experimental` | `'ToolRouterSessionExperimental'` |
12 | `preload` | `Any` |
13
@@ -206,4 +205,4 @@ def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools:
205
206 ---
207
209 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L80)
208 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L81)
docs/content/reference/sdk-reference/python/triggers.mdx
+31 -1
@@ -5,6 +5,36 @@ description: "Triggers (instance) class"
5
6 ## Methods
7
8 +### set_webhook_subscription()
9 +
10 +Create or update the project webhook subscription used for webhook delivery. If a subscription already exists, the first subscription is updated. Otherwise a new subscription is created. By default this subscribes to V3 trigger message events.
11 +
12 +```python
13 +def set_webhook_subscription(webhook_url: str, enabled_events: Sequence[str | None] = ..., version: Union[WebhookVersion, str] = ...) -> WebhookSubscription
14 +```
15 +
16 +**Parameters**
17 +
18 +| Name | Type |
19 +|------|------|
20 +| `webhook_url` | `str` |
21 +| `enabled_events?` | `Sequence[str \| None]` |
22 +| `version?` | `Union[WebhookVersion, str]` |
23 +
24 +**Returns**
25 +
26 +`WebhookSubscription`
27 +
28 +**Example**
29 +
30 +```python
31 +composio.triggers.set_webhook_subscription(
32 + webhook_url=f"{APP_URL}/webhooks/composio",
33 + )
34 +```
35 +
36 +---
37 +
38 ### get_type()
39
40 Get a trigger type by its slug Uses the global toolkit version provided when initializing composio instance to fetch trigger for specific toolkit version
@@ -156,4 +186,4 @@ def verify_webhook(id: str, payload: str, secret: str, signature: str, timestamp
186
187 ---
188
159 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/triggers.py#L865)
189 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/triggers.py#L881)
docs/content/reference/sdk-reference/typescript/composio.mdx
+20 -8
@@ -53,25 +53,37 @@ const composio = new Composio({
53 |------|------|-------------|
54 | `authConfigs` | `AuthConfigs` | Manage authentication configurations for toolkits |
55 | `connectedAccounts` | `ConnectedAccounts` | Manage authenticated connections |
56 -| `create` | `(userId: string, routerConfig: \{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| string[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: string[] \| 'all' \}; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: ... \| ... \| ... \| ...[]; enable?: ... \| ... \| ... \| ...[] \}; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \}; tools?: Record<string, string[] \| \{ enable: ...[] \} \| \{ disable: ...[] \} \| \{ tags: ... \| ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Creates a new tool router session for a user.
56 +| `create` | `(userId: string, config: \{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| ...[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: ...[] \| 'all' \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: ... \| ... \| ... \| ...[] \| \{ disable?: ...[]; enable?: ...[] \}; toolkits?: string[] \| \{ disable: ...[] \} \| \{ enable: ...[] \}; tools?: Record<string, ...[] \| \{ enable: ... \} \| \{ disable: ... \} \| \{ tags: ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \} & \{ mcp: true \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Creates a new tool router session for a user.
57 Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
58 should be exposed directly; see `ToolRouterCreateSessionConfig`. |
59 | `experimental` | `Experimental` | Experimental SDK methods whose shape may change in future releases.
60 -Houses stateful operations like Experimental.updateAcl that
61 -take a client and perform I/O. Stateless experimental factories
62 -(e.g. `experimental_createTool`) stay at the top level. |
60 +Prefer domain-specific mounts (for example
61 +`composio.connectedAccounts.updateAcl(...)`) when available; this
62 +namespace keeps compatibility aliases while APIs are experimental.
63 +Stateless experimental factories (e.g. `experimental_createTool`) stay
64 +at the top level. |
65 | `files` | `Files` | Upload and download files |
64 -| `mcp` | `MCP` | Model Context Protocol server management |
66 +| `mcp` | `MCP` | Model Context Protocol server management. |
67 | `provider` | `TProvider` | The tool provider instance used for wrapping tools in framework-specific formats |
68 +| `sessions` | `Sessions` | Create and reuse Composio sessions.
69 +
70 +Prefer `composio.sessions.create(...)` for new code. The top-level
71 +`composio.create(...)` method is kept as an alias. |
72 | `toolkits` | `Toolkits` | Retrieve toolkit metadata and authorize user connections |
67 -| `toolRouter` | `ToolRouter` | Experimental feature, use with caution |
73 +| `toolRouter` | `ToolRouter` | Legacy alias for `composio.sessions`. |
74 | `tools` | `Tools` | List, retrieve, and execute tools |
75 | `triggers` | `Triggers` | Manage webhook triggers and event subscriptions |
70 -| `use` | `(id: string, options: \{ customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Use an existing tool router session |
76 +| `use` | `(id: string, options: \{ customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp: true \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Use an existing tool router session |
77
78 ## Methods
79
74 -### createSession()
80 +### createSession() (deprecated)
81 +
82 +<Callout type="warn" title="Deprecated">
83 +Will be removed in a future version of the SDK. Instead, construct a new
84 + instance directly with the headers you need: `new Composio(\{ ...existingConfig, defaultHeaders \})`.
85 + For one-off overrides, pass per-call `requestOptions` where supported.
86 +</Callout>
87
88 Creates a new instance of the Composio SDK with custom request options while preserving the existing configuration.
89 This method is particularly useful when you need to:
docs/content/reference/sdk-reference/typescript/connected-accounts.mdx
+47 -3
@@ -235,7 +235,7 @@ async link(userId: string, authConfigId: string, options?: CreateConnectedAccoun
235 |------|------|-------------|
236 | `userId` | `string` | \{string\} - The external user ID to create the connected account for. |
237 | `authConfigId` | `string` | \{string\} - The auth config ID to create the connected account for. |
238 -| `options?` | `CreateConnectedAccountLinkOptions` | \{CreateConnectedAccountOptions\} - Options for creating a new connected account. |
238 +| `options?` | `CreateConnectedAccountLinkOptions` | \{CreateConnectedAccountLinkOptions\} - Options for creating a new connected account link. |
239 | `requestOptions?` | `ComposioRequestOptions` | |
240
241 **Returns**
@@ -344,8 +344,7 @@ const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123')
344
345 Enable or disable a connected account. Accepts `{ enabled: boolean }`.
346
347 -For ACL writes on SHARED connections, see
348 -`composio.experimental.updateAcl()`.
347 +Use `updateAcl()` for ACL writes on SHARED connections.
348
349 ```typescript
350 async update(nanoid: string, params: UpdateConnectedAccountParams, requestOptions?: ComposioRequestOptions): Promise<ConnectedAccountUpdateStatusResponse>
@@ -372,6 +371,51 @@ await composio.connectedAccounts.update('ca_abc123', { enabled: false });
371
372 ---
373
374 +### updateAcl()
375 +
376 +Update the per-user ACL on a SHARED connected account.
377 +**Experimental — shape may change in future releases.**
378 +
379 +Only meaningful for SHARED connections — calling this on a PRIVATE
380 +connection raises `ComposioAclOnlyForSharedError` (400). ACL writes
381 +require the connection's creator or an API key.
382 +
383 +PATCH semantics: omit a field to leave it unchanged; pass an empty
384 +array to clear an allow/deny list. At least one field must be
385 +provided.
386 +
387 +```typescript
388 +async updateAcl(nanoid: string, params: UpdateConnectedAccountAclParams): Promise<ConnectedAccountPatchResponse>
389 +```
390 +
391 +**Parameters**
392 +
393 +| Name | Type | Description |
394 +|------|------|-------------|
395 +| `nanoid` | `string` | The unique identifier of the connected account |
396 +| `params` | `UpdateConnectedAccountAclParams` | The ACL fields to patch |
397 +
398 +**Returns**
399 +
400 +`Promise<ConnectedAccountPatchResponse>` — The PATCH response
401 +
402 +**Example**
403 +
404 +```typescript
405 +// Allow every userId to use this SHARED connection
406 +await composio.connectedAccounts.updateAcl('ca_abc123', { allowAllUsers: true });
407 +
408 +// Targeted allow list
409 +await composio.connectedAccounts.updateAcl('ca_abc123', {
410 + allowedUserIds: ['user_alice', 'user_bob'],
411 +});
412 +
413 +// Clear the allow list (back to deny-by-default unless allowAllUsers is true)
414 +await composio.connectedAccounts.updateAcl('ca_abc123', { allowedUserIds: [] });
415 +```
416 +
417 +---
418 +
419 ### updateStatus()
420
421 Update the status of a connected account
docs/content/reference/sdk-reference/typescript/experimental.mdx
+11 -6
@@ -1,6 +1,6 @@
1 ---
2 title: "Experimental"
3 -description: "`composio.experimental` namespace. Mirrors the Python SDK's `composio.experimental` mount, with one method per experimental surface. **Shape may change in future releases.**"
3 +description: "Experimental class reference"
4 ---
5
6 ## Usage
@@ -14,8 +14,13 @@ const result = await composio.experimental.list();
14
15 ## Methods
16
17 -### updateAcl()
17 +### updateAcl() (deprecated)
18
19 +<Callout type="warn" title="Deprecated">
20 +Use `composio.connectedAccounts.updateAcl(...)` instead — ACL updates graduated onto the `connectedAccounts` mount. This experimental alias is kept only for backwards compatibility and will be removed once the API graduates. Prefer the `connectedAccounts` mount; do not generate new code against this alias.
21 +</Callout>
22 +
23 +Compatibility alias for `composio.connectedAccounts.updateAcl(...)`.
24 Update the per-user ACL on a SHARED connected account.
25 **Experimental — shape may change in future releases.**
26
@@ -59,21 +64,21 @@ import { Composio } from '@composio/core';
64 const composio = new Composio({ apiKey: '...' });
65
66 // Allow every userId to use this connection
62 -await composio.experimental.updateAcl('ca_abc', { allowAllUsers: true });
67 +await composio.connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true });
68
69 // Everyone except a specific user
65 -await composio.experimental.updateAcl('ca_abc', {
70 +await composio.connectedAccounts.updateAcl('ca_abc', {
71 allowAllUsers: true,
72 notAllowedUserIds: ['user_bob'],
73 });
74
75 // Targeted allow
71 -await composio.experimental.updateAcl('ca_abc', {
76 +await composio.connectedAccounts.updateAcl('ca_abc', {
77 allowedUserIds: ['user_alice', 'user_bob'],
78 });
79
80 // Revoke a previously-granted allow list (back to deny-by-default)
76 -await composio.experimental.updateAcl('ca_abc', { allowedUserIds: [] });
81 +await composio.connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
82 ```
83
84 **Empty-array semantics — read carefully.** Passing `[]` for either
docs/content/reference/sdk-reference/typescript/index.mdx
+4 -4
@@ -35,13 +35,13 @@ bun add @composio/core
35 | [`Composio`](/reference/sdk-reference/typescript/composio) | This is the core class for Composio. |
36 | [`AuthConfigs`](/reference/sdk-reference/typescript/auth-configs) | AuthConfigs class |
37 | [`ConnectedAccounts`](/reference/sdk-reference/typescript/connected-accounts) | ConnectedAccounts class |
38 -| [`Experimental`](/reference/sdk-reference/typescript/experimental) | `composio.experimental` namespace. Mirrors the Python SDK's |
38 +| [`Experimental`](/reference/sdk-reference/typescript/experimental) | Experimental API |
39 | [`MCP`](/reference/sdk-reference/typescript/mcp) | MCP (Model Control Protocol) class |
40 | [`RemoteFile`](/reference/sdk-reference/typescript/remote-file) | Represents a file stored in a tool router session's file mount. |
41 -| [`SessionContextImpl`](/reference/sdk-reference/typescript/session-context-impl) | Concrete implementation of SessionContext. |
41 +| [`Sessions`](/reference/sdk-reference/typescript/sessions) | First-class API for creating and reusing Composio sessions. |
42 | [`Toolkits`](/reference/sdk-reference/typescript/toolkits) | Toolkits class |
43 -| [`ToolRouterSession`](/reference/sdk-reference/typescript/tool-router-session) | ToolRouterSession API |
44 -| [`ToolRouterSessionFilesMount`](/reference/sdk-reference/typescript/tool-router-session-files-mount) | ToolRouterSessionFilesMount API |
43 +| [`Session`](/reference/sdk-reference/typescript/session) | A Composio session — the object returned by `composio.sessions.create(...)` |
44 +| [`Session files`](/reference/sdk-reference/typescript/session-files) | File mount for a Composio session, reached via `session.experimental.files` |
45 | [`Tools`](/reference/sdk-reference/typescript/tools) | This class is used to manage tools in the Composio SDK. |
46 | [`Triggers`](/reference/sdk-reference/typescript/triggers) | Trigger (Instance) class |
47
docs/content/reference/sdk-reference/typescript/mcp.mdx
+8
@@ -3,6 +3,14 @@ title: "MCP"
3 description: "MCP (Model Control Protocol) class Handles MCP server operations. When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`."
4 ---
5
6 +<Callout type="warn" title="Deprecated">
7 +Use a session's MCP endpoint instead: `composio.create(userId, \{ mcp: true \})`
8 +returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now
9 +opt-in per session; the standalone `composio.mcp` server-management API is kept only for
10 +backwards compatibility. Prefer the session MCP endpoint; do not generate new code against
11 +`composio.mcp`. See https://docs.composio.dev/docs/sessions-via-mcp
12 +</Callout>
13 +
14 ## Usage
15
16 Access this class through the `composio.mcp` property:
docs/content/reference/sdk-reference/typescript/meta.json
+3 -3
@@ -7,10 +7,10 @@
7 "experimental",
8 "mcp",
9 "remote-file",
10 - "session-context-impl",
10 + "sessions",
11 "toolkits",
12 - "tool-router-session",
13 - "tool-router-session-files-mount",
12 + "session",
13 + "session-files",
14 "tools",
15 "triggers"
16 ]
docs/content/reference/sdk-reference/typescript/session-context-impl.mdx deleted
-71
@@ -1,71 +0,0 @@
1 ----
2 -title: "SessionContextImpl"
3 -description: "Concrete implementation of SessionContext. One instance is created per session (or per multi-execute batch) and shared across all custom tool invocations, including sibling routing. When `customToolsMap` is provided, `execute()` checks local tools first before falling back to the backend API. This allows tool A to call tool B via `session.execute('B', ...)` without hitting the network."
4 ----
5 -
6 -## Usage
7 -
8 -Access this class through the `composio.sessionContextImpl` property:
9 -
10 -```typescript
11 -const composio = new Composio({ apiKey: 'your-api-key' });
12 -const result = await composio.sessionContextImpl.list();
13 -```
14 -
15 -## Properties
16 -
17 -| Name | Type | Description |
18 -|------|------|-------------|
19 -| `signal` | `AbortSignal` | Per-execution AbortSignal. Never set on the base instance; `executeCustomTool`
20 -grafts it onto a per-call `Object.create` child so concurrent executions
21 -sharing this context don't observe each other's signal. Declared here (rather
22 -than read via a cast) so the contract is explicit. |
23 -| `userId` | `string` | The user ID for this session |
24 -
25 -## Methods
26 -
27 -### execute()
28 -
29 -Execute any tool from within a custom tool.
30 -Routes to sibling local tools in-process when available,
31 -otherwise delegates to the backend API.
32 -
33 -Returns the same response shape as session.execute().
34 -
35 -```typescript
36 -async execute(toolSlug: string, arguments_: Record<string, unknown>): Promise<ToolRouterSessionExecuteResponse>
37 -```
38 -
39 -**Parameters**
40 -
41 -| Name | Type |
42 -|------|------|
43 -| `toolSlug` | `string` |
44 -| `arguments_` | `Record<string, unknown>` |
45 -
46 -**Returns**
47 -
48 -`Promise<ToolRouterSessionExecuteResponse>`
49 -
50 ----
51 -
52 -### proxyExecute()
53 -
54 -Proxy API calls through Composio's auth layer.
55 -The backend resolves the connected account from the toolkit within the session.
56 -
57 -```typescript
58 -async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>
59 -```
60 -
61 -**Parameters**
62 -
63 -| Name | Type |
64 -|------|------|
65 -| `params` | `SessionProxyExecuteParams` |
66 -
67 -**Returns**
68 -
69 -`Promise<ToolRouterSessionProxyExecuteResponse>`
70 -
71 ----
docs/content/reference/sdk-reference/typescript/session-files.mdx renamed
+2 -11
@@ -1,17 +1,8 @@
1 ---
2 -title: "ToolRouterSessionFilesMount"
3 -description: "ToolRouterSessionFilesMount class reference"
2 +title: "Session files"
3 +description: "File mount for a Composio session, reached via `session.experimental.files` on a session created with `composio.sessions.create(...)`. Upload, list, download, and delete files scoped to a single session."
4 ---
5
6 -## Usage
7 -
8 -Access this class through the `composio.toolRouterSessionFilesMount` property:
9 -
10 -```typescript
11 -const composio = new Composio({ apiKey: 'your-api-key' });
12 -const result = await composio.toolRouterSessionFilesMount.list();
13 -```
14 -
6 ## Methods
7
8 ### delete()
docs/content/reference/sdk-reference/typescript/session.mdx renamed
+11 -19
@@ -1,27 +1,19 @@
1 ---
2 -title: "ToolRouterSession"
3 -description: "ToolRouterSession class reference"
2 +title: "Session"
3 +description: "A Composio session — the object returned by `composio.sessions.create(...)` and `composio.sessions.use(...)` (also reachable via the top-level `composio.create(...)` / `composio.use(...)` aliases). This is the canonical session surface. Use it to fetch session-scoped tools, authorize toolkits, search, and execute tools. The public return type is `Session` (with `mcp` surfaced, returned when `{ mcp: true }` is passed) or `SessionWithoutMcp` (the default, with `mcp` omitted from the type); this class is the concrete runtime form behind both."
4 ---
5
6 -## Usage
7 -
8 -Access this class through the `composio.toolRouterSession` property:
9 -
10 -```typescript
11 -const composio = new Composio({ apiKey: 'your-api-key' });
12 -const result = await composio.toolRouterSession.list();
13 -```
14 -
6 ## Properties
7
17 -| Name | Type |
18 -|------|------|
19 -| `configVersion` | `number` |
20 -| `experimental` | `SessionExperimental` |
21 -| `mcp` | `\{ headers?: Record<string, string>; type: 'http' \| 'sse'; url: string \}` |
22 -| `preload` | `Preload` |
23 -| `sessionId` | `string` |
24 -| `warnings` | `Warning[]` |
8 +| Name | Type | Description |
9 +|------|------|-------------|
10 +| `configVersion` | `number` | |
11 +| `experimental` | `SessionExperimental` | |
12 +| `mcp` | `\{ headers?: Record<string, string>; type: 'http' \| 'sse'; url: string \}` | Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `\{ mcp: true \}` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp |
13 +| `preload` | `Preload` | |
14 +| `sandbox` | `Workbench` | Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. |
15 +| `sessionId` | `string` | |
16 +| `warnings` | `Warning[]` | |
17
18 ## Methods
19
docs/content/reference/sdk-reference/typescript/sessions.mdx new
+131
@@ -0,0 +1,131 @@
1 +---
2 +title: "Sessions"
3 +description: "First-class API for creating and reusing Composio sessions. `composio.sessions.create(...)` is the canonical session creation entrypoint. The top-level `composio.create(...)` method remains as a backwards-compatible alias for `composio.sessions.create(...)`."
4 +---
5 +
6 +## Usage
7 +
8 +Access this class through the `composio.sessions` property:
9 +
10 +```typescript
11 +const composio = new Composio({ apiKey: 'your-api-key' });
12 +const result = await composio.sessions.list();
13 +```
14 +
15 +## Methods
16 +
17 +### create()
18 +
19 +Creates a new tool router session for a user.
20 +Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
21 +should be exposed directly; see `ToolRouterCreateSessionConfig`.
22 +
23 +**Overload 1**
24 +
25 +```typescript
26 +async create(userId: string, config: ToolRouterCreateSessionConfig & { mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
27 +```
28 +
29 +**Parameters**
30 +
31 +| Name | Type | Description |
32 +|------|------|-------------|
33 +| `userId` | `string` | \{string\} The user id to create the session for |
34 +| `config` | `ToolRouterCreateSessionConfig & \{ mcp: true \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
35 +| `requestOptions?` | `ComposioRequestOptions` | |
36 +
37 +**Returns**
38 +
39 +`Promise<Session<TToolCollection, TTool, TProvider>>` — The tool router session
40 +
41 +**Overload 2**
42 +
43 +```typescript
44 +async create(userId: string, config?: ToolRouterCreateSessionConfig, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
45 +```
46 +
47 +**Parameters**
48 +
49 +| Name | Type | Description |
50 +|------|------|-------------|
51 +| `userId` | `string` | \{string\} The user id to create the session for |
52 +| `config?` | `ToolRouterCreateSessionConfig` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
53 +| `requestOptions?` | `ComposioRequestOptions` | |
54 +
55 +**Returns**
56 +
57 +`Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>` — The tool router session
58 +
59 +**Example**
60 +
61 +```typescript
62 +import { Composio } from '@composio/core';
63 +
64 +const composio = new Composio();
65 +
66 +const session = await composio.sessions.create('user_123', {
67 + toolkits: ['gmail'],
68 + manageConnections: true,
69 + experimental: {
70 + customTools: [myCustomTool],
71 + customToolkits: [myToolkit],
72 + },
73 +});
74 +```
75 +
76 +---
77 +
78 +### use()
79 +
80 +Use an existing session
81 +
82 +**Overload 1**
83 +
84 +```typescript
85 +async use(id: string, options: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
86 +```
87 +
88 +**Parameters**
89 +
90 +| Name | Type | Description |
91 +|------|------|-------------|
92 +| `id` | `string` | \{string\} The id of the session to use |
93 +| `options` | `\{ customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp: true \}` | |
94 +| `requestOptions?` | `ComposioRequestOptions` | |
95 +
96 +**Returns**
97 +
98 +`Promise<Session<TToolCollection, TTool, TProvider>>` — The tool router session
99 +
100 +**Overload 2**
101 +
102 +```typescript
103 +async use(id: string, options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean }, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
104 +```
105 +
106 +**Parameters**
107 +
108 +| Name | Type | Description |
109 +|------|------|-------------|
110 +| `id` | `string` | \{string\} The id of the session to use |
111 +| `options?` | `\{ customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean \}` | |
112 +| `requestOptions?` | `ComposioRequestOptions` | |
113 +
114 +**Returns**
115 +
116 +`Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>` — The tool router session
117 +
118 +**Example**
119 +
120 +```typescript
121 +import { Composio } from '@composio/core';
122 +
123 +const composio = new Composio();
124 +const id = 'session_123';
125 +const session = await composio.sessions.use(id);
126 +
127 +console.log(session.mcp.url);
128 +console.log(session.mcp.headers);
129 +```
130 +
131 +---
docs/content/reference/sdk-reference/typescript/triggers.mdx
+110
@@ -196,6 +196,116 @@ async listTypes(query?: TriggersTypeListParams, requestOptions?: ComposioRequest
196
197 ---
198
199 +### parse()
200 +
201 +Parse an incoming webhook HTTP request into a typed, normalized trigger payload.
202 +
203 +Dump the incoming request in and get back the parsed Composio trigger event.
204 +When `verifySecret` is provided, the request signature is verified before the
205 +payload is returned (delegating to verifyWebhook); without it, the body
206 +is parsed without verification.
207 +
208 +The `request` may be either a Fetch API `Request` (Next.js App Router, Hono,
209 +Remix) or a plain `{ body, headers }` object (Express with `express.raw`,
210 +Next.js Pages Router `req`). The signature headers (`webhook-id`,
211 +`webhook-timestamp`, `webhook-signature`) are read case-insensitively.
212 +
213 +```typescript
214 +async parse(request: WebhookRequestLike, options?: ParseWebhookOptions): Promise<VerifyWebhookResult>
215 +```
216 +
217 +**Parameters**
218 +
219 +| Name | Type | Description |
220 +|------|------|-------------|
221 +| `request` | `WebhookRequestLike` | The incoming webhook HTTP request |
222 +| `options?` | `ParseWebhookOptions` | Parse options |
223 +
224 +**Returns**
225 +
226 +`Promise<VerifyWebhookResult>` — The parsed (and optionally verified) webhook payload
227 +
228 +**Example**
229 +
230 +```typescript
231 +// Express with express.raw (verify the signature)
232 +app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => {
233 + try {
234 + const result = await composio.triggers.parse(req, {
235 + verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
236 + });
237 + console.log('Trigger:', result.payload.triggerSlug);
238 + console.log('Event data:', result.payload.payload);
239 + res.sendStatus(200);
240 + } catch (error) {
241 + res.sendStatus(401);
242 + }
243 +});
244 +
245 +// Express without verifying (parse only)
246 +app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => {
247 + const result = await composio.triggers.parse(req);
248 + console.log('Trigger:', result.payload.triggerSlug);
249 + res.sendStatus(200);
250 +});
251 +```
252 +
253 +```typescript
254 +// Next.js App Router (Request) — verify the signature
255 +export async function POST(request: Request) {
256 + try {
257 + const result = await composio.triggers.parse(request, {
258 + verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
259 + });
260 + console.log('Trigger:', result.payload.triggerSlug);
261 + console.log('Event data:', result.payload.payload);
262 + return new Response('OK', { status: 200 });
263 + } catch (error) {
264 + return new Response('Unauthorized', { status: 401 });
265 + }
266 +}
267 +
268 +// Next.js App Router — parse only (no verification)
269 +export async function POST(request: Request) {
270 + const result = await composio.triggers.parse(request);
271 + console.log('Trigger:', result.payload.triggerSlug);
272 + return new Response('OK', { status: 200 });
273 +}
274 +```
275 +
276 +---
277 +
278 +### setWebhookSubscription()
279 +
280 +Create or update the project webhook subscription used for webhook delivery.
281 +
282 +If a subscription already exists, the first subscription is updated. Otherwise a new
283 +subscription is created. By default this subscribes to V3 trigger message events.
284 +
285 +```typescript
286 +async setWebhookSubscription(params: SetWebhookSubscriptionParams): Promise<WebhookSubscription>
287 +```
288 +
289 +**Parameters**
290 +
291 +| Name | Type |
292 +|------|------|
293 +| `params` | `SetWebhookSubscriptionParams` |
294 +
295 +**Returns**
296 +
297 +`Promise<WebhookSubscription>`
298 +
299 +**Example**
300 +
301 +```typescript
302 +await composio.triggers.setWebhookSubscription({
303 + webhookUrl: `${APP_URL}/webhooks/composio`,
304 +});
305 +```
306 +
307 +---
308 +
309 ### subscribe()
310
311 Subscribe to all the triggers
docs/content/reference/v3/api-reference/auth-configs/index.mdx
+27 -2
@@ -3,9 +3,34 @@ title: Auth Configs
3 description: "Authentication configuration management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/auth-configs.mdx, not this file. */}
7
8 -Authentication configuration management
8 +An auth config is a blueprint that defines how a toolkit authenticates across all your users. It specifies the authentication method, the scopes your tools can request, and which credentials Composio uses to run the OAuth or token flow.
9 +
10 +A single auth config applies to every user who connects that toolkit. When a user authenticates against it, Composio creates a [connected account](/reference/api-reference/connected-accounts) that stores their tokens and links them to your user ID.
11 +
12 +Each auth config defines:
13 +
14 +- **Auth scheme**: OAuth2, API key, Bearer token, or Basic Auth
15 +- **Scopes**: what your tools are allowed to do on the user's behalf
16 +- **Credentials**: Composio's managed app, or your own OAuth client and secrets
17 +
18 +Reach for a custom auth config when you need your own branding on consent screens, custom scopes, a dedicated rate-limit quota, or a custom toolkit instance. See [managed vs custom auth](/docs/custom-app-vs-managed-app) for the decision and [how Composio handles authentication](/docs/authentication) for the full picture.
19 +
20 +## Auth schemes
21 +
22 +The `auth_scheme` on an auth config determines how users authenticate to the toolkit. Composio supports four. The schemes available for a given toolkit come from the toolkit itself.
23 +
24 +| Scheme | What it is | When it's used |
25 +|---|---|---|
26 +| `OAUTH2` | OAuth 2.0 authorization-code flow. The user authorizes through a hosted consent screen, and Composio stores and automatically refreshes the access and refresh tokens. | Most apps with user accounts (Gmail, GitHub, Slack, Notion, and so on). Uses Composio's managed OAuth app by default; bring your own for custom branding or scopes. |
27 +| `API_KEY` | A static API key the user provides. There's no OAuth flow: the key is stored on the connected account and sent on each request. | Services that authenticate with a key, such as SendGrid, Tavily, or PostHog. |
28 +| `BEARER_TOKEN` | A bearer access token you already hold (for example, from your own OAuth flow). Composio sends it as `Authorization: Bearer <token>` and does not refresh it, so you keep it current. | Bringing an existing OAuth or server-to-server token into Composio, or apps that issue long-lived tokens. |
29 +| `BASIC` | HTTP Basic authentication with a username and password. | Services that use Basic Auth. |
30 +
31 +Most OAuth toolkits work out of the box with Composio managed auth. For the others you supply the credential fields. To choose or customize the scheme, see [managed vs custom auth](/docs/custom-app-vs-managed-app).
32 +
33 +These endpoints use your project API key in the `x-api-key` header. Each auth config is addressed by its `nanoid`, and you can enable or disable one without deleting it.
34
35 ## Endpoints
36
docs/content/reference/v3/api-reference/authentication/index.mdx deleted
-12
@@ -1,12 +0,0 @@
1 ----
2 -title: Authentication
3 -description: "Authentication related endpoints"
4 ----
5 -
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
7 -
8 -Authentication related endpoints
9 -
10 -## Endpoints
11 -
12 -<ApiEndpointsTable endpoints={[{"method":"GET","pathV31":"/api/v3.1/auth/session/info","pathV3":"/api/v3/auth/session/info","summary":"Get current user session information","href":"/reference/v3/api-reference/authentication/getAuthSessionInfo"}]} />
docs/content/reference/v3/api-reference/connected-accounts/index.mdx
+23 -2
@@ -3,9 +3,30 @@ title: Connected Accounts
3 description: "Connected account management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/connected-accounts.mdx, not this file. */}
7
8 -Connected account management
8 +A connected account is a single user's authorized connection to a toolkit. It stores their credentials (OAuth tokens or API keys) and links them to your user ID, so your tools can act on that user's behalf.
9 +
10 +Composio creates a connected account when a user completes the flow defined by an [auth config](/reference/api-reference/auth-configs). From there you manage its full lifecycle:
11 +
12 +- **Create or link**: start a new connection, or generate an auth link session for the user to authorize. See [manually authenticating users](/docs/manually-authenticating).
13 +- **Refresh**: renew authentication for an account whose tokens have expired.
14 +- **Enable, disable, or update**: change an account's status or metadata without removing it.
15 +- **Revoke or delete**: revoke the grant at the provider, or remove the account from Composio.
16 +
17 +Each account is addressed by its `nanoid`. List endpoints accept filters so you can find accounts by user, toolkit, or auth config.
18 +
19 +## Link auth (Composio Connect Links)
20 +
21 +A Composio Connect Link is a hosted, secure sign-in page. You create one with the create auth link session endpoint, redirect the user to the returned URL, and Composio handles the rest: the user signs in, Composio creates the connected account, and Composio stores and refreshes its tokens. Credentials never pass through your app. This works for all Composio managed connections, with no OAuth credentials to set up.
22 +
23 +By default a connected account is `PRIVATE` and usable only by its owning user. Mark one `SHARED` to let other users reach it through a per-connection access control list. See [shared connections](/docs/shared-connections).
24 +
25 +These endpoints use your project API key in the `x-api-key` header.
26 +
27 +<Callout type="warning">
28 +Shared-connection ACL fields are experimental and nested under an `experimental` block on the wire. Pin a specific SDK version if you depend on the current shape.
29 +</Callout>
30
31 ## Endpoints
32
docs/content/reference/v3/api-reference/files/index.mdx
+17 -2
@@ -3,9 +3,24 @@ title: Files
3 description: "File management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/files.mdx, not this file. */}
7
8 -File management
8 +These endpoints handle files that tools read and write during execution. When a tool produces or consumes a file, Composio stores it in object storage and exchanges it through presigned URLs rather than streaming bytes through the API.
9 +
10 +You reach for these endpoints to:
11 +
12 +- **List files** that tools have generated, optionally filtered by app and action.
13 +- **Request an upload**: get a presigned S3 URL, `PUT` your file to it, then pass the returned reference into a tool's input.
14 +
15 +This keeps large payloads out of request bodies. Tools receive a file reference and resolve the underlying object on their side.
16 +
17 +<Callout type="info">
18 +File uploads are a two-step flow. Call the upload-request endpoint to mint a presigned URL, then upload the file contents directly to that URL. The API never receives the raw bytes.
19 +</Callout>
20 +
21 +If your agent works with files inside a session, prefer the session file mount, where the sandbox exposes uploaded files to running code. See the [sandbox](/docs/sandbox/remote) for the sandbox helpers (`upload_local_file`, `smart_file_extract`) that build on this storage.
22 +
23 +These endpoints use your project API key in the `x-api-key` header.
24
25 ## Endpoints
26
docs/content/reference/v3/api-reference/mcp/index.mdx
+10 -2
@@ -3,9 +3,17 @@ title: MCP
3 description: "MCP server management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/mcp.mdx, not this file. */}
7
8 -MCP server management
8 +<Callout type="warning">
9 +This API is deprecated. Use a session's MCP endpoint instead. Create a session with `composio.create(userId, { mcp: true })`, then read the hosted URL off `session.mcp.url`. See [Using sessions via MCP](/docs/sessions-via-mcp) and [migrating MCP servers to sessions](/docs/migration-guide/mcp-servers-to-sessions).
10 +</Callout>
11 +
12 +The MCP API is the standalone, hosted [Model Context Protocol](https://modelcontextprotocol.io) server-management surface. It let you stand up and manage a separate server config per toolkit, then mint a per-user MCP URL that any MCP-compatible client could connect to.
13 +
14 +These endpoints create, list, update, and delete MCP servers, including custom servers spanning multiple apps, generate per-user MCP URLs, and manage per-user server instances and their connected accounts.
15 +
16 +Sessions replace this. A single `composio.create(...)` gives you the same MCP URL pattern, keyed by `user_id`, while handling tool discovery, authentication, context, and versioning for you. Your existing tools, auth configs (`ac_…`), and connected accounts carry over with no re-authentication. To pin a session to a fixed tool list the way a server did, use the direct-tools preset described in [Configuring sessions](/docs/configuring-sessions).
17
18 ## Endpoints
19
docs/content/reference/v3/api-reference/migration/index.mdx
+10 -2
@@ -3,9 +3,17 @@ title: Migration
3 description: "Endpoints to help with migration from v1 to v3"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/migration.mdx, not this file. */}
7
8 -Endpoints to help with migration from v1 to v3
8 +These endpoints help you migrate from Composio v1 to v3 by translating identifiers between the two systems.
9 +
10 +Reach for this endpoint when you have a v1 UUID and need the corresponding v3 NanoId so existing references continue to resolve against the v3 API. Pass the UUID and get the NanoId back.
11 +
12 +These endpoints authenticate with your project API key in the `x-api-key` header.
13 +
14 +<Callout type="info">
15 +This is a low-level translation helper for migrating identifiers. For migrating SDK code, sessions, and toolkit versioning, see the [migration guides](/docs/migration-guide).
16 +</Callout>
17
18 ## Endpoints
19
docs/content/reference/v3/api-reference/projects/index.mdx
+66 -2
@@ -3,9 +3,73 @@ title: Projects
3 description: "Projects API endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/projects.mdx, not this file. */}
7
8 -Projects API endpoints
8 +Projects are Composio's multi-tenancy primitive. Every Composio account belongs to an **organization**. Inside an organization, **projects** are isolated environments that scope your API keys, connected accounts, auth configs, and webhook configurations. Resources in one project are not accessible from another.
9 +
10 +```mermaid
11 +graph LR
12 + ORG["Organization (org_xxx)"] --- P1["Project: Production (proj_xxx)"]
13 + ORG --- P2["Project: Staging (proj_xxx)"]
14 + ORG --- TM["Team Members"]
15 + P1 --- A1["API Keys"]
16 + P1 --- A2["Connected Accounts"]
17 + P1 --- A3["Auth Configs"]
18 + P1 --- A4["Webhook Config"]
19 + P2 --- B1["..."]
20 +```
21 +
22 +Common reasons to use multiple projects:
23 +
24 +- **Separate environments**: keep production and staging isolated
25 +- **Separate products**: keep resources for different apps independent
26 +- **Client isolation**: give each client their own project with separate credentials and data
27 +
28 +## Managing projects
29 +
30 +Manage projects from the [dashboard](https://dashboard.composio.dev/~/org/) or via the API using an **organization API key** (`x-org-api-key`).
31 +
32 +<Callout type="info">
33 +Project management endpoints use the `x-org-api-key` header, not the regular `x-api-key`. Find your org API key in the dashboard under **Settings > Organization**.
34 +</Callout>
35 +
36 +There is no limit on the number of projects per organization. Project names must be unique within the organization. Create a project with `should_create_api_key: true` to get an API key back in the response:
37 +
38 +```bash
39 +curl -X POST https://backend.composio.dev/api/v3.1/org/owner/project/new \
40 + -H "x-org-api-key: YOUR_ORG_API_KEY" \
41 + -H "Content-Type: application/json" \
42 + -d '{
43 + "name": "my-staging-project",
44 + "should_create_api_key": true
45 + }'
46 +```
47 +
48 +```json
49 +{
50 + "id": "proj_abc123xyz456",
51 + "name": "my-staging-project",
52 + "api_key": "ak_abc123xyz456"
53 +}
54 +```
55 +
56 +The list endpoint supports pagination with `limit` and `cursor`; getting a project by ID returns the full project object including its API keys.
57 +
58 +## Project settings
59 +
60 +Each project has settings that control security, logging, and display behavior. These endpoints use your **project API key** (`x-api-key`), not the org key.
61 +
62 +```bash
63 +curl -X PATCH https://backend.composio.dev/api/v3.1/org/project/config \
64 + -H "x-api-key: YOUR_API_KEY" \
65 + -H "Content-Type: application/json" \
66 + -d '{
67 + "mask_secret_keys_in_connected_account": false,
68 + "log_visibility_setting": "show_all"
69 + }'
70 +```
71 +
72 +Notable security setting: `require_mcp_api_key`, when `true`, requires MCP server requests to include a valid `x-api-key` header. This defaults to `true` for organizations created on or after March 5, 2026. You can also view and update project settings from **Settings > Project Settings** in the [dashboard](https://dashboard.composio.dev/~/project/settings/general).
73
74 ## Endpoints
75
docs/content/reference/v3/api-reference/tool-router/index.mdx
+13 -3
@@ -1,11 +1,21 @@
1 ---
2 -title: Tool Router
2 +title: Sessions (prev Tool Router)
3 description: "(Labs) Tool router endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/tool-router.mdx, not this file. */}
7
8 -(Labs) Tool router endpoints
8 +These are Composio's session endpoints. A **session** is the runtime context your agent uses to work for one of your users: it scopes which user's connected accounts are in play, which tools are available, how authentication happens, and where execution state lives. Read [What is a session?](/docs/how-composio-works) for the full concept.
9 +
10 +<Callout type="info">
11 +Sessions were formerly called the "tool router", which is why these endpoints live under `tool_router`. They are the same thing.
12 +</Callout>
13 +
14 +In the SDK you do not call these endpoints directly. Use `composio.create(...)` to start a session and `composio.use(...)` to resume one, then call `session.tools()`, `session.execute(...)`, and `session.authorize(...)` on the returned object.
15 +
16 +Reach for the raw API when you need lower-level control: creating and patching a session config, attaching to an existing session, searching for tools, executing tools and meta tools, opening link sessions for auth, proxying authenticated requests, and reading or writing files in a session mount.
17 +
18 +See [Configuring sessions](/docs/configuring-sessions) for toolkits, auth configs, account selection, and presets.
19
20 ## Endpoints
21
docs/content/reference/v3/api-reference/toolkits/index.mdx
+18 -2
@@ -3,9 +3,25 @@ title: Toolkits
3 description: "Toolkit and tool management"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/toolkits.mdx, not this file. */}
7
8 -Toolkit and tool management
8 +A toolkit is a collection of related tools for a single app, like `gmail`, `github`, or `slack`. Each toolkit groups the actions for that service, its authentication requirements, and the trigger types it exposes.
9 +
10 +Reach for these endpoints when you want to:
11 +
12 +- List the toolkits in the catalog, sorted by popularity, to browse what is available before configuring a session.
13 +- Fetch a single toolkit by `slug` for its name, logo, categories, and metadata.
14 +- Fetch several toolkits at once with the multi endpoint.
15 +- List the available toolkit categories to filter the catalog by use case.
16 +- Read the toolkits changelog to track when tools or schemas change.
17 +
18 +These endpoints authenticate with your project API key in the `x-api-key` header.
19 +
20 +<Callout type="info">
21 +Tools within a toolkit are versioned. When you execute a tool, resolve to a known version with `toolkit_versions=latest` or a pinned dated version. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
22 +</Callout>
23 +
24 +To browse toolkits visually, see the [toolkits catalog](/toolkits). For the concepts and SDK usage, see [Tools and toolkits](/docs/how-composio-works) and [Configuring sessions](/docs/configuring-sessions).
25
26 ## Endpoints
27
docs/content/reference/v3/api-reference/tools/index.mdx
+45 -2
@@ -3,9 +3,52 @@ title: Tools
3 description: "Tool execution endpoints"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/tools.mdx, not this file. */}
7
8 -Tool execution endpoints
8 +Tools are the individual executable actions inside a toolkit, like `GMAIL_SEND_EMAIL` or `GITHUB_CREATE_ISSUE`. Each tool has an input schema describing its parameters and an output schema describing what it returns. Tool slugs are SCREAMING_SNAKE_CASE and follow a `{TOOLKIT}_{ACTION}` pattern.
9 +
10 +Reach for these endpoints when you want to:
11 +
12 +- List or search the catalog of available tools, optionally scoped to one or more toolkits.
13 +- Fetch a single tool's input and output schema by `tool_slug` before constructing a call.
14 +- Execute a tool on behalf of a user's connected account, or generate the inputs for an execution from natural language.
15 +- Look up the OAuth scopes a set of tools requires, or send an authenticated proxy request to an app's underlying API.
16 +
17 +These endpoints authenticate with your project API key in the `x-api-key` header.
18 +
19 +<Callout type="info">
20 +Manual tool execution requires an explicit toolkit version. Pass `toolkit_versions=latest` (or pin a dated version like `20251027_00`) so calls resolve to a known tool definition. See the [toolkit versioning migration guide](/docs/migration-guide/toolkit-versioning).
21 +</Callout>
22 +
23 +For the concepts behind tools, schemas, and authentication, see [Tools and toolkits](/docs/how-composio-works).
24 +
25 +## Proxy execute
26 +
27 +Proxy execute sends an authenticated HTTP request through a toolkit's [connected account](/docs/auth-configuration/connected-accounts) without a predefined tool, and Composio injects the OAuth token, API key, or other credentials on the server side so your code never touches raw secrets. Reach for it when you need an endpoint that Composio's predefined tools do not cover, when you need a request shape (custom query parameters, field masks, or advanced filters) that a predefined tool cannot express, or when a terminal agent would otherwise hardcode a bearer token in a `curl` call.
28 +
29 +Call it with `composio.tools.proxyExecute()` in the TypeScript SDK, `composio.tools.proxy()` in the Python SDK, or `POST /api/v3.1/tools/execute/proxy` over HTTP. The `endpoint` can be an absolute URL (`https://api.example.com/v1/resource`) or a path relative to the toolkit's base URL (`/v1/resource`), `method` is the HTTP verb, `connectedAccountId` selects the account to authenticate as, `body` carries the JSON payload, and `parameters` adds extra headers and query parameters. The response forwards the upstream `status`, `headers`, and parsed `data` verbatim.
30 +
31 +```typescript
32 +// @noErrors
33 +import { Composio } from '@composio/core';
34 +
35 +const composio = new Composio({ apiKey: 'your_api_key' });
36 +
37 +const { status, data } = await composio.tools.proxyExecute({
38 + endpoint: '/repos/composiohq/composio/issues/1',
39 + method: 'GET',
40 + connectedAccountId: 'ca_github_user_123',
41 + parameters: [{ name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' }],
42 +});
43 +
44 +console.log(status, data);
45 +```
46 +
47 +<Callout type="warn">
48 +Proxy execute rejects cross-domain requests, so the `endpoint` must resolve to the same domain as the connected account's toolkit, and you should not set the `Authorization` header yourself because Composio injects the correct credential for the account's auth scheme. This is an intentional security boundary, not a quota, so it cannot be bypassed by reshaping the request.
49 +</Callout>
50 +
51 +Proxy execute is a form of [direct tool execution](/docs/sessions-vs-direct-execution): it bypasses session state, tool schemas, and modifiers. If you are building an agent, prefer [sessions](/docs/configuring-sessions), and use the proxy only for the specific API call that is not available as a tool. The full request and response schema lives in the [`POST /api/v3.1/tools/execute/proxy`](/reference/api-reference/tools/postToolsExecuteProxy) reference.
52
53 ## Endpoints
54
docs/content/reference/v3/api-reference/triggers/index.mdx
+21 -2
@@ -3,9 +3,28 @@ title: Triggers
3 description: "Trigger management and execution"
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/triggers.mdx, not this file. */}
7
8 -Trigger management and execution
8 +Triggers let you subscribe to events from a user's connected app, such as a new Gmail message, a GitHub commit, or a Slack message, and receive the event data as a structured payload at your webhook endpoint.
9 +
10 +There are two layers to understand:
11 +
12 +- A **trigger type** is a template that defines what event to listen for and what configuration it needs. For example, `GITHUB_COMMIT_EVENT` requires an `owner` and a `repo`. Each toolkit exposes its own trigger types.
13 +- A **trigger instance** is a trigger type scoped to a specific user and connected account. Creating one produces an instance with its own `ti_*` ID that you can enable, disable, or delete independently.
14 +
15 +Reach for these endpoints when you want to:
16 +
17 +- Discover the trigger types a toolkit offers, or fetch one type by `slug` to inspect its config and payload schema.
18 +- Create or update a trigger instance for a connected account with the upsert endpoint.
19 +- List active trigger instances, or enable, disable, and delete an instance by `triggerId`.
20 +
21 +These endpoints authenticate with your project API key in the `x-api-key` header.
22 +
23 +<Callout type="info">
24 +Creating a trigger instance only registers it. To actually receive events, set a webhook URL for your project once, then route incoming events on `metadata.trigger_slug`. See [Subscribing to events](/docs/setting-up-triggers/subscribing-to-events).
25 +</Callout>
26 +
27 +For the full concept overview, see [Triggers](/docs/triggers).
28
29 ## Endpoints
30
docs/content/reference/v3/api-reference/webhook-endpoints/index.mdx
+8 -2
@@ -3,9 +3,15 @@ title: Webhook Endpoints
3 description: "Per-OAuth-app webhook ingress endpoints. Inbound URLs the provider posts to, plus signing secret storage and verification."
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/webhook-endpoints.mdx, not this file. */}
7
8 -Per-OAuth-app webhook ingress endpoints. Inbound URLs the provider posts to, plus signing secret storage and verification.
8 +Webhook endpoints are per-OAuth-app webhook ingress configurations. They define the inbound URL a provider posts events to, along with the signing secret Composio stores and uses to verify those incoming payloads.
9 +
10 +Reach for these endpoints when an OAuth app you have configured needs to deliver provider-side events into Composio. You create an endpoint, configure or update it by its `nano_id`, and store the signing secret Composio uses to authenticate inbound requests.
11 +
12 +Each endpoint is addressed by its `nano_id`. The `POST` to `/webhook_endpoints/{nano_id}` replaces the full configuration, while `PATCH` updates it in place.
13 +
14 +This is distinct from [webhook subscriptions](/reference/api-reference/webhook-subscriptions), which control where Composio delivers outbound trigger events. To verify the signature on payloads Composio sends you, see [Webhook verification](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures). To set up the trigger events those payloads carry, see [Triggers](/docs/triggers).
15
16 ## Endpoints
17
docs/content/reference/v3/api-reference/webhook-subscriptions/index.mdx
+133 -2
@@ -3,9 +3,140 @@ title: Webhook Subscriptions
3 description: "Webhook delivery subscriptions. Outbound URLs Composio posts trigger events to, plus signing secret rotation and event-type filters."
4 ---
5
6 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
6 +{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/webhook-subscriptions.mdx, not this file. */}
7
8 -Webhook delivery subscriptions. Outbound URLs Composio posts trigger events to, plus signing secret rotation and event-type filters.
8 +Webhook subscriptions are outbound delivery configurations. They define the URL Composio posts [trigger](/docs/triggers) events to, along with the signing secret and the set of event types you want to receive.
9 +
10 +Reach for these endpoints to register where Composio should send events, to filter delivery to specific event types, and to manage the signing secret used to verify those deliveries. List the available event types with the `/webhook_subscriptions/event_types` endpoint, then create a subscription scoped to the ones you care about.
11 +
12 +Each subscription is addressed by its `id`. You can update its URL and filters with `PATCH`, delete it, and rotate its signing secret with `/webhook_subscriptions/{id}/rotate_secret` if the secret leaks.
13 +
14 +Every webhook request Composio sends includes `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers. Store the secret as `COMPOSIO_WEBHOOK_SECRET` and verify each payload before trusting it. See [Webhook verification](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures) for the SDK and manual verification flows.
15 +
16 +## Event types
17 +
18 +A subscription's `enabled_events` controls which events get delivered to its URL. Two broad families exist:
19 +
20 +- **Trigger events** like `composio.trigger.message` — payloads emitted by [triggers](/docs/triggers) you've enabled (new email, new issue, etc.).
21 +- **Lifecycle events** like `composio.connected_account.expired` — emitted when a [connected account](/docs/auth-configuration/connected-accounts) changes state.
22 +
23 +List everything you can subscribe to with the `/webhook_subscriptions/event_types` endpoint, then scope a subscription to the events you handle.
24 +
25 +## Detecting connection expiry
26 +
27 +Composio automatically refreshes OAuth tokens before they expire. But when a refresh token is revoked or expires, the connection enters an `EXPIRED` state and the user must re-authenticate.
28 +
29 +Subscribe to the `composio.connected_account.expired` event to detect this proactively, instead of waiting for a tool execution to fail.
30 +
31 +<Callout>
32 +This event is only available with [V3 webhook payloads](/docs/setting-up-triggers/subscribing-to-events#webhook-payload-versions). New organizations use V3 by default.
33 +</Callout>
34 +
35 +Add `composio.connected_account.expired` to the subscription's `enabled_events`:
36 +
37 +```bash
38 +curl -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
39 + -H "X-API-KEY: <your-composio-api-key>" \
40 + -H "Content-Type: application/json" \
41 + -d '{
42 + "webhook_url": "https://example.com/webhook",
43 + "enabled_events": [
44 + "composio.trigger.message",
45 + "composio.connected_account.expired"
46 + ]
47 + }'
48 +```
49 +
50 +When a connection expires, Composio sends a webhook with the connected account details:
51 +
52 +```json
53 +{
54 + "id": "evt_847cdfcd-d219-4f18-a6dd-91acd42ca94a",
55 + "type": "composio.connected_account.expired",
56 + "metadata": {
57 + "project_id": "pr_your-project-id",
58 + "org_id": "ok_your-org-id"
59 + },
60 + "data": {
61 + "id": "ca_your-connected-account-id",
62 + "toolkit": { "slug": "gmail" },
63 + "auth_config": {
64 + "id": "ac_your-auth-config-id",
65 + "auth_scheme": "OAUTH2"
66 + },
67 + "status": "EXPIRED",
68 + "status_reason": "OAuth refresh token expired"
69 + },
70 + "timestamp": "2026-02-06T12:00:00.000Z"
71 +}
72 +```
73 +
74 +Route on `type` to handle expiry alongside trigger events:
75 +
76 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
77 + <Tab value="Python">
78 +```python
79 +from composio import Composio, WebhookEventType
80 +
81 +composio = Composio()
82 +
83 +@app.post("/webhook")
84 +async def webhook_handler(request: Request):
85 + payload = await request.json()
86 + event_type = payload.get("type")
87 +
88 + if event_type == WebhookEventType.CONNECTION_EXPIRED:
89 + account_id = payload["data"]["id"]
90 + toolkit = payload["data"]["toolkit"]["slug"]
91 +
92 + # Look up the user and send them a re-auth link
93 + session = composio.create(user_id=lookup_user(account_id))
94 + connection_request = session.authorize(toolkit)
95 + notify_user(connection_request.redirect_url)
96 +
97 + elif event_type == WebhookEventType.TRIGGER_MESSAGE:
98 + # Handle trigger events
99 + pass
100 +
101 + return {"status": "ok"}
102 +```
103 + </Tab>
104 + <Tab value="TypeScript">
105 +```typescript
106 +import { Composio } from '@composio/core';
107 +const composio = new Composio();
108 +type NextApiRequest = { body: any };
109 +type NextApiResponse = { status: (code: number) => { json: (data: any) => void } };
110 +declare function lookupUser(accountId: string): string;
111 +declare function notifyUser(url: string): void;
112 +// ---cut---
113 +export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
114 + const payload = req.body;
115 +
116 + if (payload.type === 'composio.connected_account.expired') {
117 + const accountId = payload.data.id;
118 + const toolkit = payload.data.toolkit.slug;
119 +
120 + // Look up the user and send them a re-auth link
121 + const session = await composio.create(lookupUser(accountId));
122 + const connectionRequest = await session.authorize(toolkit);
123 + if (connectionRequest.redirectUrl) {
124 + notifyUser(connectionRequest.redirectUrl);
125 + }
126 +
127 + } else if (payload.type === 'composio.trigger.message') {
128 + // Handle trigger events
129 + }
130 +
131 + res.status(200).json({ status: 'ok' });
132 +}
133 +```
134 + </Tab>
135 +</Tabs>
136 +
137 +<Callout>
138 +Always [verify webhook signatures](/docs/setting-up-triggers/subscribing-to-events#verifying-signatures) before processing events in production.
139 +</Callout>
140
141 ## Endpoints
142
docs/content/reference/v3/authentication.mdx
+8 -20
@@ -4,33 +4,21 @@ description: How to authenticate with Composio APIs using project and organizati
4 keywords: [API authentication, API key, x-api-key, x-org-api-key, Composio authentication, authorization]
5 ---
6
7 -All Composio API endpoints require authentication via API key.
7 +Every Composio API request authenticates with an API key. Send the key in a request header and Composio resolves it to your project or organization.
8
9 -## API Key Authentication
9 +## Project API key
10
11 -Include your API key in the `x-api-key` header.
11 +A project API key authenticates to one project with full access. Send it in the `x-api-key` header.
12
13 -### Getting Your API Key
13 +Get it from the dashboard: sign in to [composio.dev](https://composio.dev), open **Settings → Project Settings**, and copy the key from the **API Keys** section.
14
15 -1. Sign in to [composio.dev](https://composio.dev)
16 -2. Navigate to **Settings**
17 -3. In **Project Settings**, copy the key from the **API Keys** section
15 +## Organization API key
16
19 -<Video src="/videos/fetch-project-key.mp4" autoPlay />
17 +An organization API key authenticates across every project in your organization. Send it in the `x-org-api-key` header.
18
21 -## Organization API Key
19 +Get it from the dashboard: open **Organization Settings → General Settings** and copy a token under **Organization Access Tokens**.
20
23 -For organization-level access across multiple projects, use the `x-org-api-key` header instead.
24 -
25 -### Getting Your Organization API Key
26 -
27 -1. Sign in to [composio.dev](https://composio.dev)
28 -2. Navigate to **Organization Settings** → **General Settings**
29 -3. Copy the token under **Organization Access Tokens**
30 -
31 -<Video src="/videos/fetch-org-key.mp4" autoPlay />
32 -
33 -## Using the API Key
21 +## Using the API key
22
23 Include your API key in the request header:
24
docs/content/reference/v3/errors.mdx
+3 -6
@@ -58,7 +58,7 @@ Composio uses two types of API keys:
58 | Insufficient permissions | The API key doesn't have access to this resource. |
59
60 <Callout>
61 -See [Authentication Troubleshooting](/docs/troubleshooting/authentication) for more help.
61 +See [Authenticating users](/docs/authentication) for more help.
62 </Callout>
63
64 ### Tool errors
@@ -72,7 +72,7 @@ Errors that occur when fetching or executing tools.
72 | Tool execution failed | The external service returned an error. Check tool parameters and user permissions. |
73
74 <Callout>
75 -See [Tools Troubleshooting](/docs/troubleshooting/tools) for more help.
75 +See [Tools and toolkits](/docs/how-composio-works) for more help.
76 </Callout>
77
78 ### Connection errors
@@ -95,7 +95,7 @@ Errors related to trigger subscriptions.
95 | Trigger instance deleted | The trigger subscription or its connected account was removed. |
96
97 <Callout>
98 -See [Triggers Troubleshooting](/docs/troubleshooting/triggers) for more help.
98 +See [Triggers](/docs/triggers) for more help.
99 </Callout>
100
101 ## Rate limiting
@@ -107,9 +107,6 @@ When you hit rate limits, you'll receive a `429` status code. See [Rate Limits](
107 When contacting support, include the `request_id` from the error response.
108
109 <Cards>
110 - <Card title="Troubleshooting" href="/docs/troubleshooting">
111 - Common issues and solutions
112 - </Card>
110 <Card title="Discord" href="https://discord.com/channels/1170785031560646836/1268871288156323901">
111 Community support
112 </Card>
docs/content/reference/v3/rate-limits.mdx
+7 -11
@@ -4,24 +4,20 @@ description: Composio API rate limits by plan, rate limit headers, and best prac
4 keywords: [API rate limits, rate limiting, throttling, 429 too many requests, API quotas, request limits]
5 ---
6
7 -Rate limits are enforced **per organization** on a fixed one-minute window.
7 +Composio enforces rate limits **per organization** over a fixed one-minute window. Every authenticated endpoint draws from the same budget — tool execution, connected accounts, triggers, and the rest — so the limit below is your organization's total across all API calls.
8
9 ## Rate limits by plan
10
11 -| Plan | Rate Limit | Window |
11 +| Plan | Rate limit | Window |
12 |------|------------|--------|
13 | Starter | 2,000 requests | 1 minute |
14 | Hobby | 2,000 requests | 1 minute |
15 | Growth | 10,000 requests | 1 minute |
16 | Enterprise | Custom | - |
17
18 -<Callout>
19 -All authenticated API endpoints share your organization's rate limit. This includes tool execution, connected accounts, triggers, and all other API operations.
20 -</Callout>
21 -
18 ## Rate limit headers
19
24 -API responses include headers to help you track your usage:
20 +Every response includes headers so you can track usage without guessing:
21
22 | Header | Description |
23 |--------|-------------|
@@ -42,15 +38,15 @@ When you exceed the rate limit, you'll receive a `429 Too Many Requests` respons
38
39 ## Best practices
40
45 -1. **Monitor your usage** - Check the `X-RateLimit-Remaining` header to track how close you are to the limit.
41 +1. **Watch `X-RateLimit-Remaining`** — read it on each response to know how much headroom you have left in the window.
42
47 -2. **Honor `Retry-After`** - On a `429`, wait for the duration in the `Retry-After` header before retrying.
43 +2. **Honor `Retry-After`** — on a `429`, wait the number of seconds it gives you before retrying instead of hammering the endpoint.
44
49 -3. **Cache responses** - Cache tool definitions and other static data to reduce unnecessary API calls.
45 +3. **Cache what doesn't change** — keep tool definitions and other static data client-side so you don't spend requests re-fetching them.
46
47 ## Need higher limits?
48
53 -If you're hitting rate limits regularly, consider upgrading your plan or [talk to us](https://calendly.com/composiohq/enterprise) to discuss custom limits for your use case.
49 +If you hit these limits regularly, upgrade your plan or [talk to us](https://calendly.com/composiohq/enterprise) about custom limits for your use case.
50
51 <Cards>
52 <Card title="Errors" href="/reference/v3/errors">
docs/content/toolkits/faq/gmail.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Gmail API must be enabled in the Google
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/google_classroom.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Classroom API must be enabled in
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/google_maps.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Maps API must be enabled in the
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googlecalendar.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Calendar API must be enabled in
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googledocs.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Docs API must be enabled in the
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googledrive.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Drive API must be enabled in the
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googlemeet.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Meet API must be enabled in the
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googlesheets.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Sheets API must be enabled in th
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googleslides.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Slides API must be enabled in th
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googlesuper.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the required Google API must be enabled in
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/googletasks.md
+1 -1
@@ -14,7 +14,7 @@ When using custom OAuth credentials, the Google Tasks API must be enabled in the
14
15 ## Why am I getting "Error 400: invalid_scope"?
16
17 -The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/auth-configuration/programmatic-auth-configs).
17 +The requested scopes are invalid or incorrectly formatted in the authorization URL. Verify your scope values against the [Google OAuth scopes docs](https://developers.google.com/identity/protocols/oauth2). If you're creating auth configs programmatically, see the [programmatic auth config guide](/docs/programmatic-auth-configs).
18
19 ## Why does the OAuth consent screen show "Composio" instead of my app?
20
docs/content/toolkits/faq/notion.md
+1 -1
@@ -46,6 +46,6 @@ With Composio-managed Notion credentials, the webhook ingress endpoint is alread
46
47 The token is in `data.webhook_signing_secret`.
48
49 -4. **Paste the token back into Notion's verify field** to complete setup. Continue with [Creating triggers](https://docs.composio.dev/docs/setting-up-triggers/creating-triggers#using-the-sdk).
49 +4. **Paste the token back into Notion's verify field** to complete setup. Continue with [Creating triggers](https://docs.composio.dev/docs/setting-up-triggers/creating-triggers#create-the-trigger).
50
51 ---
docs/content/toolkits/faq/slack.md
+2 -2
@@ -47,7 +47,7 @@ Update the redirect URL in your Slack App under OAuth & Permissions → Redirect
47
48 ## How do I set up Slack event webhooks?
49
50 -With Composio-managed Slack credentials, the webhook endpoint is already provisioned — just create the trigger. If you bring your own Slack OAuth app, see [Configuring the webhook endpoint](https://docs.composio.dev/docs/setting-up-triggers/creating-triggers#configuring-the-webhook-endpoint).
50 +With Composio-managed Slack credentials, the webhook endpoint is already provisioned, so just create the trigger. If you bring your own Slack OAuth app, see [Custom OAuth webhooks](https://docs.composio.dev/docs/setting-up-triggers/custom-oauth-webhooks).
51
52 ## Why am I getting scope errors on Slack?
53
@@ -59,6 +59,6 @@ For the Slack toolkit, set `as_user=True` to post as the authenticated user. For
59
60 ## Why aren't my Slack triggers working?
61
62 -See [Triggers troubleshooting](https://docs.composio.dev/docs/troubleshooting/triggers).
62 +See [Triggers](/docs/triggers).
63
64 ---
docs/content/toolkits/managed-auth.mdx
+50 -6
@@ -1,17 +1,61 @@
1 ---
2 title: Managed Auth
3 -description: Check which toolkits have Composio managed authentication
3 +description: Find out which toolkits work with Composio managed authentication and when you need your own credentials
4 +keywords: [managed auth, oauth, auth config, own developer credentials, toolkit list]
5 ---
6
6 -Toolkits with managed auth work out of the box with no OAuth setup. For toolkits without managed auth, you need to provide your own credentials.
7 +Managed auth means Composio registers and maintains the OAuth app for a toolkit, so your users can connect their accounts with no OAuth credentials for you to set up. Most popular toolkits (GitHub, Gmail, Slack, and many more) ship with managed auth and work the moment you create a session.
8
8 -You can also check programmatically whether a toolkit has managed auth:
9 +When a tool needs an account, the [`COMPOSIO_MANAGE_CONNECTIONS`](/toolkits/meta-tools/manage_connections) meta tool returns a secure [Connect Link](/docs/tools-direct/authenticating-tools#hosted-authentication-connect-link). The user signs in there, and Composio stores and refreshes their tokens. You write no auth code. See [Authentication](/docs/authentication) for the full flow.
10 +
11 +## When you don't need to do anything
12 +
13 +For any toolkit with managed auth, you don't register an OAuth app, manage credentials, or handle token refresh. Create a session and start calling tools:
14 +
15 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
16 +<Tab value="Python">
17 +```python
18 +from composio import Composio
19 +
20 +composio = Composio()
21 +session = composio.create(user_id="user_123")
22 +# Tools that need an account return a Connect Link automatically
23 +```
24 +</Tab>
25 +<Tab value="TypeScript">
26 +```typescript
27 +import { Composio } from '@composio/core';
28 +
29 +const composio = new Composio();
30 +const session = await composio.create("user_123");
31 +// Tools that need an account return a Connect Link automatically
32 +```
33 +</Tab>
34 +</Tabs>
35 +
36 +## When you need your own credentials
37 +
38 +You need a custom auth config when you want to:
39 +
40 +- **Bring your own OAuth app**, so users see your app name on the consent screen instead of "Composio."
41 +- **Request specific scopes** beyond Composio's defaults.
42 +- **Use a toolkit without managed auth**, where you supply an API key, bearer token, or instance details.
43 +
44 +See [Managed vs custom auth](/docs/custom-app-vs-managed-app) for the full decision guide and setup steps. You can mix the two: use your own credentials for some toolkits and managed auth for the rest.
45 +
46 +## Find a toolkit
47 +
48 +Search the list below to check whether a toolkit has managed auth. Toolkits under **Composio Managed App Available** work out of the box. Toolkits under **Requires your own credentials** need a custom auth config.
49 +
50 +<ManagedAuthList />
51 +
52 +## Check programmatically
53 +
54 +To check a single toolkit from a script, call the toolkit endpoint and read its managed auth schemes:
55
56 ```bash
57 curl 'https://backend.composio.dev/api/v3.1/toolkits/posthog' \
58 -H 'x-api-key: YOUR_API_KEY'
59 ```
60
15 -See [When to use your own developer credentials](/docs/custom-app-vs-managed-app) for help deciding which approach fits your use case.
16 -
17 -<ManagedAuthList />
61 +A toolkit that lists managed auth schemes in the response has managed auth. An empty list means you need to supply your own credentials.
docs/content/toolkits/meta-tools/get_tool_schemas.mdx renamed
docs/content/toolkits/meta-tools/index.mdx new
+28
@@ -0,0 +1,28 @@
1 +---
2 +title: Meta Tools
3 +description: The system tools every Composio session gives your agent to discover, authenticate, execute, and process tools at runtime.
4 +keywords: [meta tools, session]
5 +---
6 +
7 +{/* Auto-generated by scripts/generate-meta-tools.ts — do not edit manually. To change the intro prose or a tool's one-line summary, edit the template and the override map in lib/meta-tool-overrides.ts. */}
8 +
9 +import { Callout } from 'fumadocs-ui/components/callout';
10 +
11 +Every Composio [session](/docs/how-composio-works) hands your agent a small set of meta tools instead of hundreds of raw tool definitions. The agent uses them to find the right tools for a task, connect the accounts those tools need, execute them, and process the results, all at runtime and all sharing one `session_id`.
12 +
13 +This keeps your context window small: you load a handful of meta tools, not a catalog of 500+ apps. The agent searches for what it needs when it needs it.
14 +
15 +A typical workflow runs in order: call `COMPOSIO_SEARCH_TOOLS` to discover tools and open a session, call `COMPOSIO_MANAGE_CONNECTIONS` if a toolkit is not yet connected, then run the tools with `COMPOSIO_MULTI_EXECUTE_TOOL`. Reach for the workbench and bash tools when responses are large enough to process out of context.
16 +
17 +| Tool | What it does |
18 +|------|--------------|
19 +| [`COMPOSIO_GET_TOOL_SCHEMAS`](/toolkits/meta-tools/get_tool_schemas) | Returns the full input schema for tools you already know the slug for, so you can build schema-compliant arguments before executing |
20 +| [`COMPOSIO_MANAGE_CONNECTIONS`](/toolkits/meta-tools/manage_connections) | Checks connection status for a toolkit and returns a branded authentication link when the user needs to connect, covering OAuth, API keys, and every other auth type |
21 +| [`COMPOSIO_MULTI_EXECUTE_TOOL`](/toolkits/meta-tools/multi_execute_tool) | Executes up to 50 tools in parallel and returns structured outputs ready for immediate analysis |
22 +| [`COMPOSIO_REMOTE_BASH_TOOL`](/toolkits/meta-tools/remote_bash_tool) | Runs bash commands in a remote sandbox for file operations, data processing, and system tasks |
23 +| [`COMPOSIO_REMOTE_WORKBENCH`](/toolkits/meta-tools/remote_workbench) | Runs Python in a persistent remote sandbox to process large remote files and script bulk or repeated tool executions |
24 +| [`COMPOSIO_SEARCH_TOOLS`](/toolkits/meta-tools/search_tools) | Discovers the right tools across 500+ apps for a task and returns them with an execution plan, connection status, and the `session_id` that ties the rest of the workflow together |
25 +
26 +<Callout type="warn">
27 +These schemas are for reference only. We do not guarantee backward compatibility for parameter names or response shapes, so do not rely on them as structured type definitions in your code.
28 +</Callout>
docs/content/toolkits/meta-tools/manage_connections.mdx renamed
docs/content/toolkits/meta-tools/meta.json renamed
docs/content/toolkits/meta-tools/multi_execute_tool.mdx renamed
docs/content/toolkits/meta-tools/remote_bash_tool.mdx renamed
docs/content/toolkits/meta-tools/remote_workbench.mdx renamed
docs/content/toolkits/meta-tools/search_tools.mdx renamed
docs/content/toolkits/pro-tools.mdx renamed
+8 -8
@@ -1,11 +1,11 @@
1 ---
2 -title: Premium Tools
3 -description: Pricing and limits for premium tools in Composio
2 +title: Pro Tools
3 +description: Pricing and limits for pro tools in Composio
4 ---
5
6 -Some tool calls cost more to run — search APIs, code sandboxes, ML inference. We call those premium tools and price them separately.
6 +Some tool calls cost more to run — search APIs, code sandboxes, ML inference. We call those pro tools and price them separately.
7
8 -## What counts as a premium tool?
8 +## What counts as a pro tool?
9
10 <Cards>
11 <Card icon={<Search />} title="Search APIs" href="/toolkits/composio_search" description="Composio Search, Perplexity, Exa, SerpAPI" />
@@ -18,9 +18,9 @@ Some tool calls cost more to run — search APIs, code sandboxes, ML inference.
18
19 ## Pricing
20
21 -Premium tool calls are roughly 3x the cost of a standard tool call. Full pricing is on the [pricing page](https://composio.dev/pricing).
21 +Pro tool calls are roughly 3x the cost of a standard tool call. Full pricing is on the [pricing page](https://composio.dev/pricing).
22
23 -| Plan | Included Standard Tool Calls | Included Premium Tool Calls | Usage Based Standard Tool Calls | Usage Based Premium Tool Calls |
23 +| Plan | Included Standard Tool Calls | Included Pro Tool Calls | Usage Based Standard Tool Calls | Usage Based Pro Tool Calls |
24 |------|------------------------------|-----------------------------|---------------------------------|--------------------------------|
25 | Totally Free | 20k | 1k | – | – |
26 | Ridiculously Cheap | 200k | 5k | $0.299/1k | $0.897/1k |
@@ -29,9 +29,9 @@ Premium tool calls are roughly 3x the cost of a standard tool call. Full pricing
29
30 ## Rate limits
31
32 -Premium tools have lower rate limits than standard tool calls. If you need more, [contact us](mailto:billing@composio.dev).
32 +Pro tools have lower rate limits than standard tool calls. If you need more, [contact us](mailto:billing@composio.dev).
33
34 -| Spending Tier | Standard Tool Calls Rate Limit | Premium Tool Calls Rate Limit |
34 +| Spending Tier | Standard Tool Calls Rate Limit | Pro Tool Calls Rate Limit |
35 |---------------|--------------------------------|-------------------------------|
36 | Free | 100/min | 1,000/hour |
37 | Paid | 5,000/min | 10,000/hour |
docs/examples/standup-slackbot/.env.local.example new
+8
@@ -0,0 +1,8 @@
1 +# Composio API key: https://app.composio.dev/settings
2 +COMPOSIO_API_KEY=
3 +# The "slackbot" auth config the bot connects through (ac_...)
4 +COMPOSIO_SLACKBOT_AUTH_CONFIG_ID=
5 +# Slack app signing secret, verifies interactivity requests
6 +SLACK_SIGNING_SECRET=
7 +# Shared secret the Vercel cron sends as `Authorization: Bearer <CRON_SECRET>`
8 +CRON_SECRET=
docs/examples/standup-slackbot/.gitignore new
+5
@@ -0,0 +1,5 @@
1 +node_modules/
2 +dist/
3 +.env.local
4 +.vercel/
5 +.vercel
docs/examples/standup-slackbot/README.md new
+95
@@ -0,0 +1,95 @@
1 +# Daily Standup Slack Bot
2 +
3 +An AI-powered Slack bot that runs daily standups. On a schedule it DMs each team member a reminder with a **Draft** button. Tapping it spins up a Composio tool-router session scoped to whatever that member has connected (GitHub, Linear, Notion, Calendar, and more), researches their recent activity, and writes a draft standup. The member reviews, edits if needed, and confirms, then the bot posts it into a daily thread in your standup channel as that member.
4 +
5 +## How It Works
6 +
7 +1. **On a schedule** (`vercel.json` cron, evaluated per-member in their timezone), the bot finds or creates today's thread in your standup channel and DMs each due member a reminder menu: **📝 Draft** and **🔌 Connect more tools**.
8 +2. **Draft** opens a Composio tool-router session scoped to the member's connected toolkits, researches their activity, and writes the draft. No tools connected yet → the menu nudges them to connect first.
9 +3. The member can **✏️ Edit** (a modal) or **✅ Confirm & Post**.
10 +4. On confirm, the bot **posts into the daily thread as the member** (via their personal Slack connection). If they haven't connected personal Slack, it gives them copyable text instead.
11 +
12 +Everything runs through Slack **interactivity** (buttons + modals): there are no inbound DM triggers to wire up.
13 +
14 +## Stack
15 +
16 +- **Runtime:** Vercel Serverless Functions (TypeScript)
17 +- **AI:** Vercel AI SDK via AI Gateway
18 +- **Integrations:** Composio SDK (slackbot + the toolkit catalogue you configure)
19 +- **Database:** None
20 +
21 +## Project Layout
22 +
23 +```
24 +standup.config.ts ← edit this: team, channel, schedule, toolkit catalogue
25 +.env.local ← secrets (copy from .env.local.example)
26 +api/
27 + cron/standup.ts ← scheduled reminder
28 + interactivity.ts ← button + modal handler
29 + _utils/ ← shared helpers (Vercel ignores _-prefixed dirs as routes)
30 + schedule.ts ← per-member due-checks, lookback window, name/date helpers
31 + composio.ts ← Composio client, connections, tool-router session
32 + slack.ts ← Slack Web API via Composio proxyExecute
33 + agent.ts ← draft generation + the draft prompt
34 + blocks.ts ← Block Kit message builders
35 +scripts/setup.ts ← one-time: connect the bot's Slack account
36 +```
37 +
38 +## Setup
39 +
40 +### 1. Create a Slack App
41 +
42 +1. Go to [api.slack.com/apps](https://api.slack.com/apps) and create an app.
43 +2. Add these **Bot Token Scopes** under OAuth & Permissions:
44 + `chat:write`, `im:write`, `channels:history`, `channels:read`, `users:read`, `users:read.email`, `team:read`.
45 +3. Under **Interactivity & Shortcuts**, turn Interactivity on and set the Request URL to:
46 + `https://<your-deployment>/api/interactivity`
47 +4. Install the app to your workspace and invite the bot to your standup channel.
48 +5. Note your Slack app's **Client ID**, **Client Secret**, and **Signing Secret**.
49 +
50 +### 2. Create a `slackbot` Auth Config in Composio
51 +
52 +1. Open Auth Configs in the [Composio dashboard](https://app.composio.dev).
53 +2. Toolkit: `slackbot`. Auth scheme: `OAUTH2`.
54 +3. Toggle "Use your own developer credentials" and enter the Slack Client ID/Secret.
55 +4. Add `team:read` to the **User Token Scopes**.
56 +5. Create it and save the auth config ID (`ac_...`).
57 +
58 +### 3. Configure secrets and your team
59 +
60 +Copy `.env.local.example` to `.env.local` and fill it in:
61 +
62 +| Variable | Value |
63 +|----------|-------|
64 +| `COMPOSIO_API_KEY` | Your Composio API key |
65 +| `COMPOSIO_SLACKBOT_AUTH_CONFIG_ID` | The `ac_...` from step 2 |
66 +| `SLACK_SIGNING_SECRET` | Your Slack app signing secret |
67 +| `CRON_SECRET` | Any random string (secures the Vercel cron) |
68 +
69 +Then edit `standup.config.ts`: set `standupChannel`, your `team` (slack email + github username, optional per-person time/timezone), and prune the `TOOLKITS` catalogue to the integrations you want.
70 +
71 +### 4. Connect the bot's Slack account
72 +
73 +```bash
74 +npm install
75 +npx tsx scripts/setup.ts # opens a browser OAuth link for the bot
76 +npx tsx scripts/setup.ts --reconnect # re-run after changing Slack scopes
77 +```
78 +
79 +### 5. Deploy
80 +
81 +```bash
82 +vercel deploy --prod
83 +```
84 +
85 +Set the same four environment variables in the Vercel dashboard. Adjust the cron cadence in `vercel.json` (default: every 30 min on weekdays; each member is reminded only in the slot matching their configured time).
86 +
87 +## Connecting member tools
88 +
89 +Each member connects their own accounts (GitHub, Linear, etc.) by tapping **🔌 Connect more tools** on the reminder DM, and the bot generates per-member OAuth links on the fly. Drafts only ever pull from what a member has actually connected.
90 +
91 +## Customizing
92 +
93 +- **Add or remove a toolkit:** edit the `TOOLKITS` array in `standup.config.ts`. Each entry is a slug, label, emoji, and a `draftInstruction` that tells the agent what to pull and how to summarize it. No other code changes needed.
94 +- **Change scope/wording:** the `draftInstruction` is where source-specific rules live (e.g. GitHub is scoped to a single org there).
95 +- **Demo mode:** set `DEMO_MODE = true` in `standup.config.ts` to make every member due on every cron run.
docs/examples/standup-slackbot/api/_utils/agent.ts new
+72
@@ -0,0 +1,72 @@
1 +import { generateText, stepCountIs } from "ai";
2 +import { Member, MODEL, TOOLKITS, GITHUB_ORG } from "../../standup.config";
3 +import { lookbackWindow } from "./schedule";
4 +import { createToolRouterSession } from "./composio";
5 +
6 +/** The standup draft prompt, adapted to whichever toolkits the member connected. */
7 +function buildDraftPrompt(
8 + member: Member,
9 + window: { date: string; label: string },
10 + connectedSlugs: string[]
11 +): string {
12 + const connected = TOOLKITS.filter((t) => connectedSlugs.includes(t.slug));
13 + const sources = connected.map((t) => ` - ${t.draftInstruction}`).join("\n");
14 + const emojiLegend = connected.map((t) => `${t.emoji} ${t.label}`).join(", ");
15 +
16 + return `You are writing @${member.githubUsername}'s daily standup, covering
17 +${window.label} (everything since ${window.date}).
18 +
19 +You have a Composio tool-router session with these tools connected:
20 +${connected.map((t) => t.label).join(", ")}.
21 +Use the meta-tools to research yourself: search for the right tool per source,
22 +then execute it. Do NOT guess activity. Investigate first, then write.
23 +
24 +IMPORTANT: All tools above are ALREADY connected. Do NOT attempt to connect,
25 +authenticate, or generate OAuth links. If a tool call fails, skip that source.
26 +Never ask the user to connect anything.
27 +
28 +What to look at (ONLY these connected sources):
29 +${sources}
30 +
31 +Keep tool requests small (filter by date, ~10 items, no full transcripts).
32 +
33 +Output rules:
34 + - 2 to 5 atomic, one-line updates. Prune noise.
35 + - Start each line with the right source emoji: ${emojiLegend}. GitHub PRs use
36 + 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed and include the *#number*.
37 + - State WHAT they did and WHY it matters, plainly. Facts only, no speculation.
38 + - NEVER use em dashes. Use colons, commas, or separate sentences.
39 + - LINKS: this is posted to Slack, which does NOT support Markdown links. NEVER
40 + write [text](url). Use Slack's link syntax <url|text> instead, e.g.
41 + <https://github.com/${GITHUB_ORG}/repo/pull/893|#893>. A bare URL is also fine.
42 + - CRITICAL: your reply is posted to Slack VERBATIM. It must contain ONLY the
43 + bullet lines, each starting with its source emoji. No preamble ("Here's the
44 + standup"), no narration ("I found 3 PRs"), no headings, no closing remarks,
45 + no sign-off. The very first character of your reply is the first bullet's emoji.
46 + - If no activity in range, your entire reply is exactly: "📭 No tracked activity ${window.label}."`;
47 +}
48 +
49 +/**
50 + * Generate a member's standup draft by researching their CONNECTED tools. Spins
51 + * up a Composio tool-router session scoped to those toolkits and lets the agent
52 + * drive the meta-tools to gather activity. Returns the draft text only.
53 + */
54 +export async function generateDraftText(
55 + member: Member,
56 + connectedSlugs: string[]
57 +): Promise<string> {
58 + if (connectedSlugs.length === 0) return "";
59 +
60 + const session = await createToolRouterSession(member.slackEmail, connectedSlugs);
61 + const tools = await session.tools();
62 +
63 + const { text } = await generateText({
64 + model: MODEL,
65 + system: buildDraftPrompt(member, lookbackWindow(member.standupTimezone), connectedSlugs),
66 + prompt: `Research and write @${member.githubUsername}'s standup update.`,
67 + tools,
68 + stopWhen: stepCountIs(40),
69 + });
70 +
71 + return text.trim();
72 +}
docs/examples/standup-slackbot/api/_utils/blocks.ts new
+212
@@ -0,0 +1,212 @@
1 +// Block Kit builders for the standup menu / confirm / edit / connect flow.
2 +// Plain data (no agent involvement) keeps the interactive messages deterministic.
3 +
4 +export const ACTION_DRAFT = "standup_draft";
5 +export const ACTION_CONNECT = "standup_connect";
6 +export const ACTION_CONFIRM = "standup_confirm";
7 +export const ACTION_EDIT = "standup_edit";
8 +export const MODAL_EDIT_SUBMIT = "standup_edit_submit";
9 +export const EDIT_INPUT_BLOCK = "standup_edit_block";
10 +export const EDIT_INPUT_ACTION = "standup_edit_input";
11 +// Stable id for the draft-body section, so the handler can recover the draft
12 +// text by block_id instead of a fragile positional index.
13 +export const DRAFT_BODY_BLOCK = "standup_draft_body";
14 +
15 +// Context threaded through buttons/modals so the handler knows who/where without
16 +// re-deriving it. Kept small (button `value` is capped at 2000 chars).
17 +export type StandupContext = {
18 + memberEmail: string;
19 + threadTs: string; // parent daily-thread message ts
20 + channelId: string; // the standup channel's ID
21 +};
22 +
23 +/** The daily reminder "menu": a nudge + Draft button (+ Connect if applicable). */
24 +export function buildReminderMenu(
25 + threadUrl: string,
26 + ctx: StandupContext,
27 + showConnect: boolean
28 +) {
29 + const value = JSON.stringify(ctx);
30 + const buttons: Record<string, unknown>[] = [
31 + {
32 + type: "button",
33 + style: "primary",
34 + text: { type: "plain_text", text: "📝 Draft", emoji: true },
35 + action_id: ACTION_DRAFT,
36 + value,
37 + },
38 + ];
39 + if (showConnect) {
40 + buttons.push({
41 + type: "button",
42 + text: { type: "plain_text", text: "🔌 Connect more tools", emoji: true },
43 + action_id: ACTION_CONNECT,
44 + value,
45 + });
46 + }
47 + return {
48 + text: "Daily standup reminder",
49 + blocks: [
50 + {
51 + type: "section",
52 + text: {
53 + type: "mrkdwn",
54 + text: `📅 Time for your standup. Post your update in <${threadUrl}|today's thread>.\nTap *Draft* and I'll put together a draft from your connected tools.`,
55 + },
56 + },
57 + { type: "actions", elements: buttons },
58 + ],
59 + };
60 +}
61 +
62 +/** "Researching…" placeholder shown while the draft is generated. */
63 +export function buildLoadingMessage(label = "Researching your activity and drafting your standup…") {
64 + return {
65 + text: label,
66 + blocks: [{ type: "section", text: { type: "mrkdwn", text: `⏳ ${label}` } }],
67 + };
68 +}
69 +
70 +/** The draft DM: the draft text + Confirm/Edit buttons. */
71 +export function buildDraftMessage(draft: string, ctx: StandupContext) {
72 + const value = JSON.stringify(ctx);
73 + const body = draft.trim()
74 + ? draft
75 + : "_No draft yet. Tap ✏️ Edit to write your update._";
76 + return {
77 + text: "Your standup draft is ready for review.",
78 + blocks: [
79 + {
80 + type: "section",
81 + text: { type: "mrkdwn", text: "*Your standup draft.* Review and post 👇" },
82 + },
83 + { type: "section", block_id: DRAFT_BODY_BLOCK, text: { type: "mrkdwn", text: body } },
84 + { type: "divider" },
85 + {
86 + type: "actions",
87 + elements: [
88 + {
89 + type: "button",
90 + style: "primary",
91 + text: { type: "plain_text", text: "✅ Confirm & Post", emoji: true },
92 + action_id: ACTION_CONFIRM,
93 + value,
94 + },
95 + {
96 + type: "button",
97 + text: { type: "plain_text", text: "✏️ Edit", emoji: true },
98 + action_id: ACTION_EDIT,
99 + value,
100 + },
101 + ],
102 + },
103 + ],
104 + };
105 +}
106 +
107 +type DraftMessage = {
108 + blocks?: Array<{ block_id?: string; text?: { text?: string } }>;
109 +};
110 +
111 +/** Recover the draft text from a posted draft message, by stable block_id. */
112 +export function extractDraft(message: DraftMessage): string {
113 + const block = (message.blocks ?? []).find(
114 + (b) => b.block_id === DRAFT_BODY_BLOCK
115 + );
116 + return block?.text?.text ?? "";
117 +}
118 +
119 +/** Shown after posting from the user's own Slack account. */
120 +export function buildPostedMessage(draft: string) {
121 + return {
122 + text: "Standup posted.",
123 + blocks: [
124 + { type: "section", text: { type: "mrkdwn", text: "✅ *Posted to the standup thread.*" } },
125 + { type: "section", text: { type: "mrkdwn", text: draft } },
126 + ],
127 + };
128 +}
129 +
130 +/** Fallback when the member has no personal Slack: copyable text + thread link. */
131 +export function buildCopyMessage(draft: string, threadUrl: string) {
132 + return {
133 + text: "Copy your standup into the thread.",
134 + blocks: [
135 + {
136 + type: "section",
137 + text: {
138 + type: "mrkdwn",
139 + text: `Here's your standup. Copy it and paste it into <${threadUrl}|today's thread>:`,
140 + },
141 + },
142 + { type: "section", text: { type: "mrkdwn", text: "```" + draft + "```" } },
143 + {
144 + type: "context",
145 + elements: [
146 + {
147 + type: "mrkdwn",
148 + text: "_Connect your Slack (tap Connect on the reminder) to have me post it for you next time._",
149 + },
150 + ],
151 + },
152 + ],
153 + };
154 +}
155 +
156 +/** Connect menu: one URL button per unconnected tool (opens its OAuth link). */
157 +export function buildConnectMenu(links: { label: string; url: string }[]) {
158 + // Slack actions blocks allow max 5 elements; chunk into rows of 5.
159 + const rows: Record<string, unknown>[] = [];
160 + for (let i = 0; i < links.length; i += 5) {
161 + rows.push({
162 + type: "actions",
163 + elements: links.slice(i, i + 5).map((l) => ({
164 + type: "button",
165 + text: { type: "plain_text", text: `Connect ${l.label}`, emoji: true },
166 + url: l.url,
167 + })),
168 + });
169 + }
170 + return {
171 + text: "Connect tools to enrich your standup drafts.",
172 + blocks: [
173 + {
174 + type: "section",
175 + text: {
176 + type: "mrkdwn",
177 + text: "*Connect your tools* so I can draft from your real activity. All optional:",
178 + },
179 + },
180 + ...rows,
181 + ],
182 + };
183 +}
184 +
185 +/** Edit modal: multiline input prefilled with the current draft. */
186 +export function buildEditModal(
187 + draft: string,
188 + ctx: StandupContext,
189 + dm: { channel: string; ts: string }
190 +) {
191 + return {
192 + type: "modal",
193 + callback_id: MODAL_EDIT_SUBMIT,
194 + private_metadata: JSON.stringify({ ...ctx, dmChannel: dm.channel, dmTs: dm.ts }),
195 + title: { type: "plain_text", text: "Edit standup" },
196 + submit: { type: "plain_text", text: "Save" },
197 + close: { type: "plain_text", text: "Cancel" },
198 + blocks: [
199 + {
200 + type: "input",
201 + block_id: EDIT_INPUT_BLOCK,
202 + label: { type: "plain_text", text: "Your standup update" },
203 + element: {
204 + type: "plain_text_input",
205 + action_id: EDIT_INPUT_ACTION,
206 + multiline: true,
207 + initial_value: draft,
208 + },
209 + },
210 + ],
211 + };
212 +}
docs/examples/standup-slackbot/api/_utils/composio.ts new
+111
@@ -0,0 +1,111 @@
1 +import { Composio } from "@composio/core";
2 +import { VercelProvider } from "@composio/vercel";
3 +import { TOOLKIT_SLUGS } from "../../standup.config";
4 +import { env } from "./env";
5 +
6 +export const composio = new Composio({
7 + apiKey: env.COMPOSIO_API_KEY,
8 + provider: new VercelProvider(),
9 +});
10 +
11 +// The bot's own Composio user. The slackbot OAuth connection lives here, so all
12 +// bot Slack actions (posting to the channel, DMing members) execute as the bot.
13 +export const BOT_USER = "default";
14 +
15 +/** Active connected accounts for a user, optionally filtered to one toolkit.
16 + * Filters server-side via `statuses` so we never see stale/expired ones. */
17 +export async function listActiveAccounts(userId: string, toolkitSlug?: string) {
18 + const res = await composio.connectedAccounts.list({
19 + userIds: [userId],
20 + statuses: ["ACTIVE"],
21 + ...(toolkitSlug ? { toolkitSlugs: [toolkitSlug] } : {}),
22 + });
23 + return res.items;
24 +}
25 +
26 +// The bot's slackbot connected-account ID. proxyExecute needs it so the call
27 +// authenticates as the bot (the project has several connections, so we can't
28 +// rely on a default-account fallback). Resolved once and memoized.
29 +let botAccountIdPromise: Promise<string | undefined> | undefined;
30 +function getBotAccountId(): Promise<string | undefined> {
31 + botAccountIdPromise ??= listActiveAccounts(BOT_USER, "slackbot")
32 + .then((accounts) => accounts[0]?.id)
33 + .then((id) => {
34 + // Don't cache a miss: if the bot isn't connected yet, retry next call so a
35 + // later setup/OAuth is picked up without waiting for a cold start.
36 + if (!id) botAccountIdPromise = undefined;
37 + return id;
38 + });
39 + return botAccountIdPromise;
40 +}
41 +
42 +// Wraps Composio's proxyExecute to call any Slack Web API endpoint as the bot
43 +// (or a member, via accountId). Covers what the named SLACKBOT_* tools don't,
44 +// like views.open for modals.
45 +export async function slackApi<T = unknown>(
46 + endpoint: string,
47 + method: "GET" | "POST",
48 + body?: Record<string, unknown>,
49 + accountId?: string // override the bot account (e.g. post as a member)
50 +): Promise<T> {
51 + const connectedAccountId = accountId ?? (await getBotAccountId());
52 + const res = await composio.tools.proxyExecute({
53 + endpoint,
54 + method,
55 + ...(body ? { body } : {}),
56 + ...(connectedAccountId ? { connectedAccountId } : {}),
57 + });
58 + // proxyExecute wraps Slack's JSON response in `data`.
59 + return ((res as { data?: unknown }).data ?? res) as T;
60 +}
61 +
62 +/** Run a named Composio tool as a user (the bot by default). This is the normal
63 + * path for actions a SLACKBOT or SLACK tool covers (sending a message, even
64 + * one with Block Kit buttons, updating one, posting as a member). Returns the
65 + * tool's `data`, which is the Slack API response. */
66 +export async function slackTool<T = Record<string, unknown>>(
67 + slug: string,
68 + args: Record<string, unknown>,
69 + userId: string = BOT_USER
70 +): Promise<T> {
71 + const res = await composio.tools.execute(slug, { userId, arguments: args });
72 + return (res.data ?? {}) as T;
73 +}
74 +
75 +/** Which catalogue toolkits the member has actively connected. */
76 +export async function getConnectedIntegrations(
77 + memberEmail: string
78 +): Promise<string[]> {
79 + const active = await listActiveAccounts(memberEmail);
80 + const slugs = new Set(active.map((a) => a.toolkit.slug));
81 + return TOOLKIT_SLUGS.filter((s) => slugs.has(s));
82 +}
83 +
84 +/** Generate an OAuth connect link for one toolkit, for one member. */
85 +export async function getConnectLink(
86 + memberEmail: string,
87 + toolkitSlug: string
88 +): Promise<string | null> {
89 + try {
90 + const conn = await composio.toolkits.authorize(memberEmail, toolkitSlug);
91 + return conn.redirectUrl ?? null;
92 + } catch {
93 + return null;
94 + }
95 +}
96 +
97 +/**
98 + * A tool-router session scoped to the given toolkits. `session.tools()` returns
99 + * Composio's research meta-tools (search/execute/workbench) limited to these
100 + * toolkits. `manageConnections: false` strips the connection meta-tools so the
101 + * draft agent can research but never initiate an OAuth flow mid-draft.
102 + */
103 +export async function createToolRouterSession(
104 + memberEmail: string,
105 + toolkitSlugs: string[]
106 +) {
107 + return composio.create(memberEmail, {
108 + toolkits: toolkitSlugs,
109 + manageConnections: false,
110 + });
111 +}
docs/examples/standup-slackbot/api/_utils/env.ts new
+31
@@ -0,0 +1,31 @@
1 +import { config } from "dotenv";
2 +
3 +// Load .env.local for local runs (scripts, `vercel dev`). Harmless on Vercel,
4 +// where the file is absent and real environment variables are already set.
5 +config({ path: ".env.local" });
6 +
7 +// Validate every required var once at import time, so a misconfigured deploy
8 +// fails fast with a clear message instead of a vague error mid-request.
9 +const REQUIRED = [
10 + "COMPOSIO_API_KEY",
11 + "COMPOSIO_SLACKBOT_AUTH_CONFIG_ID", // the "slackbot" auth config (ac_...)
12 + "SLACK_SIGNING_SECRET", // verifies Slack interactivity requests
13 + "CRON_SECRET", // shared secret the Vercel cron presents
14 +] as const;
15 +
16 +type EnvKey = (typeof REQUIRED)[number];
17 +
18 +function loadEnv(): Record<EnvKey, string> {
19 + const missing = REQUIRED.filter((key) => !process.env[key]);
20 + if (missing.length > 0) {
21 + throw new Error(
22 + `Missing required environment variable(s): ${missing.join(", ")}.\n` +
23 + `Copy .env.local.example to .env.local and fill them in.`
24 + );
25 + }
26 + return Object.fromEntries(
27 + REQUIRED.map((key) => [key, process.env[key]!])
28 + ) as Record<EnvKey, string>;
29 +}
30 +
31 +export const env = loadEnv();
docs/examples/standup-slackbot/api/_utils/schedule.ts new
+53
@@ -0,0 +1,53 @@
1 +import dayjs from "dayjs";
2 +import utc from "dayjs/plugin/utc";
3 +import timezone from "dayjs/plugin/timezone";
4 +import {
5 + Member,
6 + DEFAULT_STANDUP_TIME,
7 + DEFAULT_STANDUP_TIMEZONE,
8 + CRON_SLOT_MINUTES,
9 + DEMO_MODE,
10 +} from "../../standup.config";
11 +
12 +dayjs.extend(utc);
13 +dayjs.extend(timezone);
14 +
15 +/** "soham.basu@…" → "Soham Basu". Keeps raw emails out of the public channel. */
16 +export function memberName(member: Member): string {
17 + return member.slackEmail
18 + .split("@")[0]
19 + .split(/[._]/)
20 + .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
21 + .join(" ");
22 +}
23 +
24 +export function formatToday(): string {
25 + return dayjs().tz(DEFAULT_STANDUP_TIMEZONE).format("dddd, MMMM D, YYYY");
26 +}
27 +
28 +/** Draft lookback: Monday reaches back to Friday, else the previous day.
29 + * Computed in the member's own timezone so the window matches their day. */
30 +export function lookbackWindow(
31 + timezone: string = DEFAULT_STANDUP_TIMEZONE
32 +): { date: string; label: string } {
33 + const now = dayjs().tz(timezone);
34 + const days = now.day() === 1 ? 3 : 1;
35 + return {
36 + date: now.subtract(days, "day").format("YYYY-MM-DD"),
37 + label: days === 1 ? "since yesterday" : "since your last standup",
38 + };
39 +}
40 +
41 +const memberStandupTime = (m: Member) => m.standupTime ?? DEFAULT_STANDUP_TIME;
42 +const memberTimezone = (m: Member) => m.standupTimezone ?? DEFAULT_STANDUP_TIMEZONE;
43 +
44 +/** Is this member due in the current cron slot, evaluated in their timezone? */
45 +export function isMemberDue(member: Member): boolean {
46 + if (DEMO_MODE) return true;
47 + const now = dayjs().tz(memberTimezone(member));
48 + const nowMin = now.hour() * 60 + now.minute();
49 + const slotStart = Math.floor(nowMin / CRON_SLOT_MINUTES) * CRON_SLOT_MINUTES;
50 + const [h, m] = memberStandupTime(member).split(":").map(Number);
51 + const memberMin = h * 60 + m;
52 + return memberMin >= slotStart && memberMin < slotStart + CRON_SLOT_MINUTES;
53 +}
docs/examples/standup-slackbot/api/_utils/slack.ts new
+146
@@ -0,0 +1,146 @@
1 +import { slackApi, slackTool, listActiveAccounts } from "./composio";
2 +
3 +// The subset of Slack Web API response fields this bot reads. proxyExecute
4 +// returns the raw Slack JSON, so one shared shape keeps call sites typed.
5 +type SlackResponse = {
6 + ok?: boolean;
7 + error?: string;
8 + ts?: string;
9 + channel?: string;
10 + permalink?: string;
11 + user?: { id?: string };
12 + channels?: Array<{ id: string; name: string }>;
13 + messages?: Array<{ ts: string; text?: string }>;
14 + response_metadata?: { next_cursor?: string };
15 +};
16 +
17 +export async function findUserIdByEmail(email: string): Promise<string | null> {
18 + const data = await slackApi<SlackResponse>(
19 + `/users.lookupByEmail?email=${encodeURIComponent(email)}`,
20 + "GET"
21 + );
22 + return data.user?.id ?? null;
23 +}
24 +
25 +/** Resolve a channel ID from a "#channel-name" (or bare name). */
26 +export async function findChannelId(channelName: string): Promise<string | null> {
27 + const name = channelName.replace(/^#/, "");
28 + let cursor: string | undefined;
29 + for (let i = 0; i < 10; i++) {
30 + const qs = new URLSearchParams({
31 + types: "public_channel,private_channel",
32 + limit: "200",
33 + ...(cursor ? { cursor } : {}),
34 + });
35 + const data = await slackApi<SlackResponse>(`/conversations.list?${qs.toString()}`, "GET");
36 + const match = (data.channels ?? []).find((c) => c.name === name);
37 + if (match) return match.id;
38 + cursor = data.response_metadata?.next_cursor || undefined;
39 + if (!cursor) break;
40 + }
41 + return null;
42 +}
43 +
44 +/** Fetch recent top-level messages in a channel (newest first; threaded replies excluded). */
45 +export async function getRecentMessages(
46 + channelId: string,
47 + limit = 50
48 +): Promise<Array<{ ts: string; text: string }>> {
49 + const data = await slackApi<SlackResponse>(
50 + `/conversations.history?channel=${encodeURIComponent(channelId)}&limit=${limit}`,
51 + "GET"
52 + );
53 + return (data.messages ?? []).map((m) => ({ ts: m.ts, text: m.text ?? "" }));
54 +}
55 +
56 +export async function postMessage(
57 + channel: string,
58 + text: string,
59 + opts?: { thread_ts?: string; blocks?: unknown[] }
60 +): Promise<{ ts: string } | null> {
61 + // SLACKBOT_SEND_MESSAGE is the named tool: markdown_text for prose, or Block
62 + // Kit `blocks` (buttons included). channel must be a channel/DM id, not a user id.
63 + const data = await slackTool<SlackResponse>("SLACKBOT_SEND_MESSAGE", {
64 + channel,
65 + ...(opts?.blocks ? { blocks: opts.blocks } : { markdown_text: text }),
66 + ...(opts?.thread_ts ? { thread_ts: opts.thread_ts } : {}),
67 + });
68 + return data.ts ? { ts: data.ts } : null;
69 +}
70 +
71 +// Stays on the proxy: this opens a DM by passing a user id as the channel, which
72 +// the raw chat.postMessage allows but SLACKBOT_SEND_MESSAGE rejects (it wants a
73 +// pre-opened D… channel id). The proxy lets us DM the member in one call.
74 +export async function sendDmBlocks(
75 + userId: string,
76 + text: string,
77 + blocks: unknown[]
78 +): Promise<{ channel: string; ts: string } | null> {
79 + const data = await slackApi<SlackResponse>("/chat.postMessage", "POST", {
80 + channel: userId,
81 + text,
82 + blocks,
83 + });
84 + if (!data.ok || !data.channel || !data.ts) return null;
85 + return { channel: data.channel, ts: data.ts };
86 +}
87 +
88 +/** Update an existing message (e.g. swap the draft after an edit). The named
89 + * tool SLACKBOT_UPDATES_A_MESSAGE takes Block Kit blocks just like sending. */
90 +export async function updateMessage(
91 + channel: string,
92 + ts: string,
93 + _text: string,
94 + blocks: unknown[]
95 +): Promise<boolean> {
96 + const data = await slackTool<SlackResponse>("SLACKBOT_UPDATES_A_MESSAGE", { channel, ts, blocks });
97 + return data.ok !== false;
98 +}
99 +
100 +/** Permalink to a message (used to link members to today's thread). */
101 +export async function getPermalink(
102 + channel: string,
103 + ts: string
104 +): Promise<string | null> {
105 + const data = await slackApi<SlackResponse>(
106 + `/chat.getPermalink?channel=${encodeURIComponent(channel)}&message_ts=${ts}`,
107 + "GET"
108 + );
109 + return data.permalink ?? null;
110 +}
111 +
112 +/** The member's OWN active Slack connected-account id (for posting as them). */
113 +async function getMemberSlackAccountId(
114 + memberEmail: string
115 +): Promise<string | undefined> {
116 + const [active] = await listActiveAccounts(memberEmail, "slack");
117 + return active?.id;
118 +}
119 +
120 +/**
121 + * Post into the thread AS the member, using their personal Slack connection.
122 + * SLACK_SEND_MESSAGE (the slack user toolkit) run under their email as the
123 + * userId, so it posts under their name. Returns false if they have no active
124 + * personal Slack account.
125 + */
126 +export async function postAsUser(
127 + memberEmail: string,
128 + channel: string,
129 + text: string,
130 + threadTs: string
131 +): Promise<boolean> {
132 + const accountId = await getMemberSlackAccountId(memberEmail);
133 + if (!accountId) return false;
134 + const data = await slackTool<SlackResponse>(
135 + "SLACK_SEND_MESSAGE",
136 + { channel, markdown_text: text, thread_ts: threadTs },
137 + memberEmail
138 + );
139 + return data.ok !== false;
140 +}
141 +
142 +/** Open a modal in response to a button click (needs trigger_id, <3s). */
143 +export async function openModal(triggerId: string, view: unknown): Promise<boolean> {
144 + const data = await slackApi<SlackResponse>("/views.open", "POST", { trigger_id: triggerId, view });
145 + return !!data.ok;
146 +}
docs/examples/standup-slackbot/api/cron/standup.ts new
+98
@@ -0,0 +1,98 @@
1 +import type { VercelRequest, VercelResponse } from "@vercel/node";
2 +import { team, standupChannel, TOOLKITS } from "../../standup.config";
3 +import { formatToday, isMemberDue } from "../_utils/schedule";
4 +import { getConnectedIntegrations } from "../_utils/composio";
5 +import { buildReminderMenu } from "../_utils/blocks";
6 +import {
7 + findChannelId,
8 + getRecentMessages,
9 + postMessage,
10 + getPermalink,
11 + findUserIdByEmail,
12 + sendDmBlocks,
13 +} from "../_utils/slack";
14 +import { env } from "../_utils/env";
15 +
16 +export const maxDuration = 300;
17 +
18 +export default async function handler(req: VercelRequest, res: VercelResponse) {
19 + if (req.headers.authorization !== `Bearer ${env.CRON_SECRET}`) {
20 + return res.status(401).json({ error: "Unauthorized" });
21 + }
22 +
23 + const results: { member: string; status: string }[] = [];
24 + // One shared thread per calendar day, keyed to the team timezone on purpose:
25 + // everyone posts into the same thread even though reminders fire in each
26 + // member's local time. (Per-member timezone here would fork the thread.)
27 + const today = formatToday();
28 +
29 + // Only members whose configured time falls in this 30-minute slot.
30 + const dueMembers = team.filter(isMemberDue);
31 + if (dueMembers.length === 0) {
32 + return res.status(200).json({ status: "no members due this slot" });
33 + }
34 +
35 + try {
36 + // Resolve the channel and find or create today's thread.
37 + const channelId = await findChannelId(standupChannel);
38 + if (!channelId) {
39 + return res.status(500).json({
40 + error: `Channel ${standupChannel} not found. Is the bot a member?`,
41 + });
42 + }
43 +
44 + const parentText = `📅 *Daily Standup: ${today}*\n_Standups are posted in this thread as folks confirm._`;
45 + // Scan a generous window for today's parent. A high-volume channel could push
46 + // it past this; a production bot would paginate or persist the thread ts.
47 + const recent = await getRecentMessages(channelId, 200);
48 + const threadTs =
49 + recent.find((m) => m.text.includes("Daily Standup") && m.text.includes(today))
50 + ?.ts ?? (await postMessage(channelId, parentText))?.ts;
51 + if (!threadTs) {
52 + return res.status(500).json({ error: "Failed to create daily thread" });
53 + }
54 + // Narrowed const so the per-member closure below sees a plain string.
55 + const thread = threadTs;
56 + const threadUrl = (await getPermalink(channelId, thread)) ?? "";
57 +
58 + // DM each due member the reminder menu, in parallel.
59 + async function processMember(
60 + member: (typeof team)[number]
61 + ): Promise<{ member: string; status: string }> {
62 + try {
63 + const [connected, userId] = await Promise.all([
64 + getConnectedIntegrations(member.slackEmail),
65 + findUserIdByEmail(member.slackEmail),
66 + ]);
67 + const showConnect = connected.length < TOOLKITS.length;
68 +
69 + if (!userId) {
70 + return { member: member.slackEmail, status: "error: no slack user" };
71 + }
72 +
73 + const menu = buildReminderMenu(
74 + threadUrl,
75 + { memberEmail: member.slackEmail, threadTs: thread, channelId: channelId! },
76 + showConnect
77 + );
78 + const dm = await sendDmBlocks(userId, menu.text, menu.blocks);
79 + return {
80 + member: member.slackEmail,
81 + status: dm ? "reminded" : "error: dm failed",
82 + };
83 + } catch (error) {
84 + const errMsg = error instanceof Error ? error.message : String(error);
85 + return { member: member.slackEmail, status: `error: ${errMsg}` };
86 + }
87 + }
88 +
89 + results.push(...(await Promise.all(dueMembers.map(processMember))));
90 + return res.status(200).json({ threadTs, threadUrl, results });
91 + } catch (err) {
92 + return res.status(500).json({
93 + error: "Internal server error",
94 + message: err instanceof Error ? err.message : String(err),
95 + results,
96 + });
97 + }
98 +}
docs/examples/standup-slackbot/api/interactivity.ts new
+249
@@ -0,0 +1,249 @@
1 +import type { VercelRequest, VercelResponse } from "@vercel/node";
2 +import { waitUntil } from "@vercel/functions";
3 +import crypto from "crypto";
4 +import { team, TOOLKITS } from "../standup.config";
5 +import { memberName } from "./_utils/schedule";
6 +import {
7 + ACTION_DRAFT,
8 + ACTION_CONNECT,
9 + ACTION_CONFIRM,
10 + ACTION_EDIT,
11 + MODAL_EDIT_SUBMIT,
12 + EDIT_INPUT_BLOCK,
13 + EDIT_INPUT_ACTION,
14 + buildLoadingMessage,
15 + buildDraftMessage,
16 + buildPostedMessage,
17 + buildCopyMessage,
18 + buildConnectMenu,
19 + buildEditModal,
20 + extractDraft,
21 + StandupContext,
22 +} from "./_utils/blocks";
23 +import { getConnectedIntegrations, getConnectLink } from "./_utils/composio";
24 +import { generateDraftText } from "./_utils/agent";
25 +import {
26 + openModal,
27 + postMessage,
28 + updateMessage,
29 + postAsUser,
30 + getPermalink,
31 +} from "./_utils/slack";
32 +import { env } from "./_utils/env";
33 +
34 +export const maxDuration = 300;
35 +
36 +// Disable Vercel's body parsing: Slack signs the EXACT raw bytes.
37 +export const config = { api: { bodyParser: false } };
38 +
39 +// The subset of a Slack interaction payload this handler reads.
40 +type SlackAction = { action_id?: string; value?: string };
41 +type SlackInteraction = {
42 + type?: string;
43 + trigger_id?: string;
44 + actions?: SlackAction[];
45 + message?: { ts?: string; blocks?: Array<{ block_id?: string; text?: { text?: string } }> };
46 + container?: { channel_id?: string };
47 + channel?: { id?: string };
48 + view?: {
49 + callback_id?: string;
50 + private_metadata?: string;
51 + state?: { values?: Record<string, Record<string, { value?: string }>> };
52 + };
53 +};
54 +// What buildEditModal stuffs into the modal's private_metadata.
55 +type StoredMeta = StandupContext & { dmChannel?: string; dmTs?: string };
56 +
57 +function readRawBody(req: VercelRequest): Promise<string> {
58 + return new Promise((resolve) => {
59 + if (typeof req.body === "string") return resolve(req.body);
60 + if (req.body && Buffer.isBuffer(req.body)) return resolve(req.body.toString("utf8"));
61 + let data = "";
62 + req.setEncoding?.("utf8");
63 + req.on("data", (c) => (data += c));
64 + req.on("end", () => resolve(data));
65 + req.on("error", () => resolve(data));
66 + });
67 +}
68 +
69 +// Implements Slack's documented request-verification algorithm (v0 basestring,
70 +// 5-minute replay window, constant-time HMAC-SHA256 compare):
71 +// https://docs.slack.dev/authentication/verifying-requests-from-slack
72 +function verifySlackSignature(
73 + rawBody: string,
74 + signature: string | undefined,
75 + timestamp: string | undefined,
76 + signingSecret: string
77 +): boolean {
78 + if (!signature || !timestamp) return false;
79 + const age = Math.abs(Date.now() / 1000 - Number(timestamp));
80 + if (!Number.isFinite(age) || age > 300) return false;
81 + const hmac =
82 + "v0=" +
83 + crypto
84 + .createHmac("sha256", signingSecret)
85 + .update(`v0:${timestamp}:${rawBody}`)
86 + .digest("hex");
87 + try {
88 + return crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(signature));
89 + } catch {
90 + return false;
91 + }
92 +}
93 +
94 +export default async function handler(req: VercelRequest, res: VercelResponse) {
95 + if (req.method !== "POST") {
96 + return res.status(405).json({ error: "Method not allowed" });
97 + }
98 +
99 + const rawBody = await readRawBody(req);
100 + if (
101 + !verifySlackSignature(
102 + rawBody,
103 + req.headers["x-slack-signature"] as string,
104 + req.headers["x-slack-request-timestamp"] as string,
105 + env.SLACK_SIGNING_SECRET
106 + )
107 + ) {
108 + return res.status(401).json({ error: "Invalid signature" });
109 + }
110 +
111 + const payload: SlackInteraction = JSON.parse(
112 + new URLSearchParams(rawBody).get("payload") || "{}"
113 + );
114 +
115 + // Modal submit (edits): fast, respond inline.
116 + if (payload.type === "view_submission") {
117 + if (payload.view?.callback_id === MODAL_EDIT_SUBMIT) {
118 + const meta: StoredMeta = JSON.parse(payload.view.private_metadata || "{}");
119 + const ctx: StandupContext = {
120 + memberEmail: meta.memberEmail,
121 + threadTs: meta.threadTs,
122 + channelId: meta.channelId,
123 + };
124 + const edited =
125 + payload.view.state?.values?.[EDIT_INPUT_BLOCK]?.[EDIT_INPUT_ACTION]
126 + ?.value ?? "";
127 + const msg = buildDraftMessage(edited, ctx);
128 + if (meta.dmChannel && meta.dmTs) {
129 + await updateMessage(meta.dmChannel, meta.dmTs, msg.text, msg.blocks);
130 + }
131 + }
132 + return res.status(200).send("");
133 + }
134 +
135 + if (payload.type !== "block_actions") return res.status(200).send("");
136 +
137 + const action = payload.actions?.[0];
138 + const ctx: StandupContext = JSON.parse(action?.value || "{}");
139 + const dmChannel = payload.container?.channel_id ?? payload.channel?.id;
140 + const dmTs = payload.message?.ts;
141 + if (!dmChannel || !dmTs) return res.status(200).send("");
142 +
143 + // Edit opens a modal: must use trigger_id within ~3s, so handle inline.
144 + if (action?.action_id === ACTION_EDIT) {
145 + const draft = extractDraft(payload.message ?? {});
146 + await openModal(
147 + payload.trigger_id ?? "",
148 + buildEditModal(draft, ctx, { channel: dmChannel, ts: dmTs })
149 + );
150 + return res.status(200).send("");
151 + }
152 +
153 + // Slow work (AI draft, OAuth links, posting): ack within Slack's 3s window,
154 + // then run via waitUntil, which keeps the function alive after the response is
155 + // sent. A plain post-send await would be frozen by Vercel.
156 + waitUntil(
157 + processSlowAction(action, ctx, dmChannel, dmTs, payload).catch(async (err) => {
158 + // Don't leave the member stuck on the loading message: log and tell them.
159 + console.error("standup interaction failed:", err);
160 + await postMessage(
161 + dmChannel,
162 + "⚠️ Something went wrong handling that. Please try again."
163 + ).catch(() => {});
164 + })
165 + );
166 + return res.status(200).send("");
167 +}
168 +
169 +async function processSlowAction(
170 + action: SlackAction | undefined,
171 + ctx: StandupContext,
172 + dmChannel: string,
173 + dmTs: string,
174 + payload: SlackInteraction
175 +) {
176 + const member = team.find((m) => m.slackEmail === ctx.memberEmail);
177 +
178 + if (action?.action_id === ACTION_DRAFT) {
179 + const loading = buildLoadingMessage();
180 + await updateMessage(dmChannel, dmTs, loading.text, loading.blocks);
181 +
182 + const connected = await getConnectedIntegrations(ctx.memberEmail);
183 + const draft =
184 + member && connected.length
185 + ? await generateDraftText(member, connected)
186 + : "";
187 + const msg = buildDraftMessage(draft, ctx);
188 + await updateMessage(dmChannel, dmTs, msg.text, msg.blocks);
189 + return;
190 + }
191 +
192 + if (action?.action_id === ACTION_CONNECT) {
193 + const connected = await getConnectedIntegrations(ctx.memberEmail);
194 + const unconnected = TOOLKITS.filter((t) => !connected.includes(t.slug));
195 + const links = (
196 + await Promise.all(
197 + unconnected.map(async (t) => {
198 + const url = await getConnectLink(ctx.memberEmail, t.slug);
199 + return url ? { label: t.label, url } : null;
200 + })
201 + )
202 + ).filter(Boolean) as { label: string; url: string }[];
203 +
204 + if (unconnected.length === 0) {
205 + await postMessage(dmChannel, "You're already connected to everything! 🎉");
206 + } else if (links.length === 0) {
207 + // Toolkits remain, but every connect link failed to generate.
208 + await postMessage(
209 + dmChannel,
210 + "⚠️ Couldn't generate connect links right now. Please try again in a moment."
211 + );
212 + } else {
213 + const menu = buildConnectMenu(links);
214 + await postMessage(dmChannel, menu.text, { blocks: menu.blocks });
215 + }
216 + return;
217 + }
218 +
219 + if (action?.action_id === ACTION_CONFIRM) {
220 + const draft = extractDraft(payload.message ?? {});
221 + // Swap the buttons out immediately so a double-click can't post twice.
222 + const posting = buildLoadingMessage("Posting your standup…");
223 + await updateMessage(dmChannel, dmTs, posting.text, posting.blocks);
224 +
225 + const name = member ? memberName(member) : ctx.memberEmail;
226 + const connected = await getConnectedIntegrations(ctx.memberEmail);
227 +
228 + let posted = false;
229 + if (connected.includes("slack")) {
230 + posted = await postAsUser(
231 + ctx.memberEmail,
232 + ctx.channelId,
233 + `*${name}'s standup*\n${draft}`,
234 + ctx.threadTs
235 + );
236 + }
237 +
238 + if (posted) {
239 + const m = buildPostedMessage(draft);
240 + await updateMessage(dmChannel, dmTs, m.text, m.blocks);
241 + } else {
242 + // No personal Slack (or post failed): give them copyable text.
243 + const url = (await getPermalink(ctx.channelId, ctx.threadTs)) ?? "";
244 + const m = buildCopyMessage(draft, url);
245 + await updateMessage(dmChannel, dmTs, m.text, m.blocks);
246 + }
247 + return;
248 + }
249 +}
docs/examples/standup-slackbot/package.json new
+24
@@ -0,0 +1,24 @@
1 +{
2 + "name": "standup-slackbot",
3 + "version": "1.0.0",
4 + "private": true,
5 + "scripts": {
6 + "dev": "vercel dev",
7 + "build": "tsc",
8 + "typecheck": "tsc --noEmit"
9 + },
10 + "dependencies": {
11 + "@composio/core": "latest",
12 + "@composio/vercel": "latest",
13 + "@vercel/functions": "^3.7.2",
14 + "ai": "latest",
15 + "dayjs": "^1.11.21",
16 + "dotenv": "^17.4.2"
17 + },
18 + "devDependencies": {
19 + "@types/node": "^20",
20 + "@vercel/node": "^5.8.18",
21 + "typescript": "^5",
22 + "vercel": "latest"
23 + }
24 +}
docs/examples/standup-slackbot/scripts/setup.ts new
+139
@@ -0,0 +1,139 @@
1 +import { Composio } from "@composio/core";
2 +import { env } from "../api/_utils/env";
3 +
4 +// One-time setup: connect the bot's Slack ("slackbot") account so it can post to
5 +// the channel and DM members. Run with `npx tsx scripts/setup.ts`, or
6 +// `--reconnect` to clear and re-do the OAuth (needed after changing Slack scopes).
7 +const COMPOSIO_BASE_URL = "https://backend.composio.dev";
8 +const TOOLKIT_SLUG = "slackbot";
9 +
10 +// Scopes the bot's OAuth *user* token must carry. Composio freezes the scopes at
11 +// connect time, so we check them before connecting and tell the user what to add.
12 +const REQUIRED_USER_SCOPES = ["team:read"];
13 +
14 +const log = {
15 + ok: (msg: string) => console.log(` ✅ ${msg}`),
16 + info: (msg: string) => console.log(` · ${msg}`),
17 + warn: (msg: string) => console.log(` ⚠️ ${msg}`),
18 +};
19 +
20 +function errMessage(err: unknown): string {
21 + if (err && typeof err === "object") {
22 + const e = err as {
23 + error?: { error?: { message?: string }; message?: string };
24 + message?: string;
25 + };
26 + return e.error?.error?.message ?? e.error?.message ?? e.message ?? String(err);
27 + }
28 + return String(err);
29 +}
30 +
31 +async function main() {
32 + const RECONNECT = process.argv.includes("--reconnect");
33 +
34 + console.log("\n╭─────────────────────────────────────────────────────────╮");
35 + console.log("│ Daily Standup Bot: One-Time Setup │");
36 + console.log("╰─────────────────────────────────────────────────────────╯");
37 + if (RECONNECT) {
38 + console.log(" (--reconnect: will clear and re-do the bot's Slack auth)");
39 + }
40 +
41 + const composio = new Composio({ apiKey: env.COMPOSIO_API_KEY });
42 + const authConfigId = env.COMPOSIO_SLACKBOT_AUTH_CONFIG_ID;
43 +
44 + // Check the auth config requests the scopes the bot needs.
45 + // READ-ONLY on purpose. GET returns secrets MASKED, and a PATCH that echoes
46 + // those masked values back overwrites the real client_secret with the mask.
47 + // So we never write credentials here; we only check and warn.
48 + const cfgRes = await fetch(`${COMPOSIO_BASE_URL}/api/v3/auth_configs/${authConfigId}`, {
49 + headers: { "x-api-key": env.COMPOSIO_API_KEY },
50 + });
51 + if (cfgRes.ok) {
52 + const cfg = (await cfgRes.json().catch(() => ({}))) as {
53 + credentials?: { user_scopes?: string[] };
54 + };
55 + const userScopes = cfg.credentials?.user_scopes ?? [];
56 + const missing = REQUIRED_USER_SCOPES.filter((s) => !userScopes.includes(s));
57 + if (missing.length > 0) {
58 + log.warn(`Auth config is missing required user scope(s): ${missing.join(", ")}`);
59 + console.log(
60 + " Add them under the auth config's User Token Scopes in the Composio\n" +
61 + " dashboard (Auth Configs → slackbot), then re-run with --reconnect."
62 + );
63 + } else {
64 + log.ok("Auth config has the required user scopes.");
65 + }
66 + }
67 +
68 + // Ensure the bot's Slack connection is active.
69 + const session = await composio.create("default", {
70 + authConfigs: { slackbot: authConfigId },
71 + });
72 +
73 + async function listSlackbotAccounts() {
74 + try {
75 + const res = await composio.connectedAccounts.list({
76 + userIds: ["default"],
77 + toolkitSlugs: [TOOLKIT_SLUG],
78 + });
79 + return res.items;
80 + } catch {
81 + return [];
82 + }
83 + }
84 +
85 + if (RECONNECT) {
86 + const accounts = await listSlackbotAccounts();
87 + if (accounts.length === 0) {
88 + log.info("No existing connections to clear.");
89 + } else {
90 + for (const acc of accounts) {
91 + try {
92 + await composio.connectedAccounts.delete(acc.id);
93 + log.ok(`Removed old connection ${acc.id}.`);
94 + } catch (err) {
95 + log.warn(`Could not remove ${acc.id}: ${errMessage(err)}`);
96 + }
97 + }
98 + }
99 + }
100 +
101 + let connected = false;
102 + if (!RECONNECT) {
103 + const toolkits = await session.toolkits({ toolkits: [TOOLKIT_SLUG] });
104 + connected = !!toolkits.items.find((t) => t.slug === TOOLKIT_SLUG)?.connection
105 + ?.isActive;
106 + }
107 +
108 + if (connected) {
109 + log.ok("Bot is already connected to Slack.");
110 + } else {
111 + log.info("Bot is not connected yet. Generating an authorization link…");
112 + // Manual authentication: authorize() returns a Connect Link, then
113 + // waitForConnection() resolves once the bot finishes OAuth in the browser.
114 + // https://docs.composio.dev/docs/manually-authenticating
115 + const connectionRequest = await session.authorize(TOOLKIT_SLUG);
116 + if (!connectionRequest.redirectUrl) {
117 + throw new Error("Composio did not return an authorization link.");
118 + }
119 +
120 + console.log("\n Open this URL in your browser to authorize the bot:\n");
121 + console.log(` ${connectionRequest.redirectUrl}\n`);
122 + console.log(" Waiting for you to complete the OAuth flow (Ctrl+C to abort)…");
123 +
124 + const TIMEOUT_MS = 5 * 60 * 1000;
125 + const account = await connectionRequest.waitForConnection(TIMEOUT_MS);
126 + log.ok(`Bot connected to Slack (${account.id}).`);
127 + }
128 +
129 + console.log(`\n${"─".repeat(70)}`);
130 + console.log(" 🎉 Setup complete. Invite the bot to your standup channel and");
131 + console.log(" point your Slack app's Interactivity Request URL at");
132 + console.log(" https://<your-deployment>/api/interactivity");
133 + console.log(`${"─".repeat(70)}\n`);
134 +}
135 +
136 +main().catch((err) => {
137 + console.error(`\n ❌ ${errMessage(err)}\n`);
138 + process.exit(1);
139 +});
docs/examples/standup-slackbot/standup.config.ts new
+110
@@ -0,0 +1,110 @@
1 +// ─────────────────────────────────────────────────────────────────────────────
2 +// Standup bot setup. Edit this file to configure your team and tools.
3 +// Secrets (API keys, IDs) live in .env.local, never here.
4 +// ─────────────────────────────────────────────────────────────────────────────
5 +
6 +export type Member = {
7 + slackEmail: string; // used to look up their Slack user + Composio connections
8 + githubUsername: string;
9 + standupTime?: string; // "HH:MM" 24h in THEIR timezone; defaults below
10 + standupTimezone?: string; // IANA tz, e.g. "Europe/Rome"; defaults below
11 +};
12 +
13 +export type Toolkit = {
14 + slug: string; // Composio toolkit slug
15 + label: string; // shown on Connect buttons
16 + emoji: string; // leads the bullet in the draft
17 + draftInstruction: string; // injected into the draft prompt when connected
18 +};
19 +
20 +// Model used to write the draft, via the Vercel AI Gateway.
21 +export const MODEL = "anthropic/claude-sonnet-4-5" as const;
22 +
23 +// ─── Schedule ────────────────────────────────────────────────────────────────
24 +// The cron runs every 30 min on weekdays; each member is reminded in the slot
25 +// containing their standupTime, evaluated in their own timezone.
26 +export const DEFAULT_STANDUP_TIMEZONE = "America/Los_Angeles";
27 +export const DEFAULT_STANDUP_TIME = "10:00";
28 +export const CRON_SLOT_MINUTES = 30;
29 +// When true, every member is "due" on every cron run, ignoring standupTime.
30 +// Set false in production so per-person times are honored.
31 +export const DEMO_MODE = false;
32 +
33 +// ─── Team ────────────────────────────────────────────────────────────────────
34 +export const standupChannel = "#standup";
35 +
36 +export const team: Member[] = [
37 + { slackEmail: "you@example.com", githubUsername: "your-handle" },
38 + { slackEmail: "teammate@example.com", githubUsername: "teammate-handle" },
39 + // A per-person time and timezone override the defaults below:
40 + { slackEmail: "alberto@example.com", githubUsername: "alberto-handle", standupTimezone: "Europe/Rome" },
41 +];
42 +
43 +// GitHub org that standup drafts are scoped to. Activity in other orgs and
44 +// personal repos is ignored. Change this to your org.
45 +export const GITHUB_ORG = "your-github-org";
46 +
47 +// ─── Toolkit catalogue ───────────────────────────────────────────────────────
48 +// Every toolkit a member can connect. The draft agent gets a Composio tool-router
49 +// session scoped to whichever of these each member has connected. Delete what you
50 +// don't want; edit draftInstruction to change how each source is summarized.
51 +export const TOOLKITS: Toolkit[] = [
52 + {
53 + slug: "github",
54 + label: "GitHub",
55 + emoji: "🔧",
56 + draftInstruction:
57 + `GitHub: find PRs they opened or merged in the time range, SCOPED TO THE ${GITHUB_ORG} ORG ONLY. Always include \`org:${GITHUB_ORG}\` in the search query. Ignore other orgs and personal repos. For each meaningful PR write a one-liner explaining its PURPOSE, prefixed with a status emoji: 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed. Include the *#number*.`,
58 + },
59 + {
60 + slug: "linear",
61 + label: "Linear",
62 + emoji: "📋",
63 + draftInstruction:
64 + "Linear: find issues they created, updated, or completed in the time range. Summarize the meaningful ones (📋), focusing on what moved forward.",
65 + },
66 + {
67 + slug: "notion",
68 + label: "Notion",
69 + emoji: "📝",
70 + draftInstruction:
71 + "Notion: find pages/docs they created or edited in the time range. Summarize the doc work as a one-liner (📝) describing what the doc is for.",
72 + },
73 + {
74 + slug: "googlecalendar",
75 + label: "Google Calendar",
76 + emoji: "📅",
77 + draftInstruction:
78 + "Google Calendar: find their meetings/events in the time range. Only mention notable ones that reflect real work (📅), not routine blocks.",
79 + },
80 + {
81 + slug: "googlemeet",
82 + label: "Google Meet",
83 + emoji: "🎥",
84 + draftInstruction:
85 + "Google Meet (context only): optionally read meeting details/transcripts for context. Do not list meetings just for existing.",
86 + },
87 + {
88 + slug: "zoom",
89 + label: "Zoom",
90 + emoji: "🎥",
91 + draftInstruction:
92 + "Zoom (context only): optionally read meeting info/recordings in the time range for extra context.",
93 + },
94 + {
95 + slug: "granola_mcp",
96 + label: "Granola",
97 + emoji: "🎙️",
98 + draftInstruction:
99 + "Granola (context only): optionally read meeting transcripts in the time range for additional context.",
100 + },
101 + {
102 + slug: "slack",
103 + label: "Slack",
104 + emoji: "💬",
105 + draftInstruction:
106 + "Slack (context only): optionally look at messages they sent in public channels for context. Do not quote verbatim.",
107 + },
108 +];
109 +
110 +export const TOOLKIT_SLUGS = TOOLKITS.map((t) => t.slug);
docs/examples/standup-slackbot/tsconfig.json new
+18
@@ -0,0 +1,18 @@
1 +{
2 + "compilerOptions": {
3 + "target": "ES2022",
4 + "module": "CommonJS",
5 + "moduleResolution": "node",
6 + "strict": true,
7 + "esModuleInterop": true,
8 + "skipLibCheck": true,
9 + "outDir": "dist",
10 + "rootDir": ".",
11 + "baseUrl": ".",
12 + "paths": {
13 + "@/*": ["./*"]
14 + }
15 + },
16 + "include": ["api/**/*.ts", "standup.config.ts", "scripts/**/*.ts"],
17 + "exclude": ["node_modules", "dist"]
18 +}
docs/examples/standup-slackbot/vercel.json new
+10
@@ -0,0 +1,10 @@
1 +{
2 + "buildCommand": "",
3 + "outputDirectory": "",
4 + "crons": [
5 + {
6 + "path": "/api/cron/standup",
7 + "schedule": "*/30 * * * 1-5"
8 + }
9 + ]
10 +}
docs/hooks/use-detected-terminal-theme.ts new
+41
@@ -0,0 +1,41 @@
1 +"use client"
2 +
3 +import {
4 + TERMINAL_THEMES,
5 + type TerminalTheme,
6 +} from "@/lib/terminal-themes"
7 +import * as React from "react"
8 +
9 +function readThemeFromElement(element: Element | null): TerminalTheme {
10 + if (!element) return "default"
11 +
12 + for (const theme of TERMINAL_THEMES) {
13 + if (theme === "default") continue
14 + if (element.classList.contains(`terminal-theme-${theme}`)) return theme
15 + }
16 +
17 + return "default"
18 +}
19 +
20 +/** Reads the active palette from the nearest `.terminal-theme` ancestor. */
21 +export function useDetectedTerminalTheme() {
22 + const ref = React.useRef<HTMLDivElement>(null)
23 + const [theme, setTheme] = React.useState<TerminalTheme>("default")
24 +
25 + React.useLayoutEffect(() => {
26 + const root = ref.current?.closest(".terminal-theme")
27 + if (!root) {
28 + setTheme("default")
29 + return
30 + }
31 +
32 + const sync = () => setTheme(readThemeFromElement(root))
33 + sync()
34 +
35 + const observer = new MutationObserver(sync)
36 + observer.observe(root, { attributes: true, attributeFilter: ["class"] })
37 + return () => observer.disconnect()
38 + }, [])
39 +
40 + return { ref, theme }
41 +}
docs/hooks/use-resolved-terminal-theme.ts new
+25
@@ -0,0 +1,25 @@
1 +"use client"
2 +
3 +import { useTerminalThemeOptional } from "@/components/terminal-theme-provider"
4 +import { useDetectedTerminalTheme } from "@/hooks/use-detected-terminal-theme"
5 +import {
6 + terminalLayoutMode,
7 + type TerminalLayoutMode,
8 +} from "@/lib/terminal-layout"
9 +import type { TerminalTheme } from "@/lib/terminal-themes"
10 +
11 +export function useResolvedTerminalTheme() {
12 + const providerTheme = useTerminalThemeOptional()
13 + const { ref, theme: detectedTheme } = useDetectedTerminalTheme()
14 + const theme: TerminalTheme = providerTheme?.theme ?? detectedTheme
15 + const layoutMode: TerminalLayoutMode = terminalLayoutMode(theme)
16 +
17 + return {
18 + ref,
19 + theme,
20 + layoutMode,
21 + isBubble: layoutMode === "bubble",
22 + isCompact: layoutMode === "compact",
23 + isClaude: layoutMode === "claude",
24 + }
25 +}
docs/lib/decorate-sidebar-badges.tsx new
+66
@@ -0,0 +1,66 @@
1 +/**
2 + * Adds badges to sidebar entries, frontmatter-driven:
3 + * - pages with `experimental: true` get an amber "Experimental" badge
4 + * - pages with `isNew: true` get a green "New" badge
5 + *
6 + * Legacy pages are NOT badged here: the sidebar already groups them under a
7 + * "...(Legacy)" section header, so a per-item "Legacy" pill is redundant
8 + * (and stacked right under that header it reads as a double "Legacy").
9 + */
10 +import type { ReactNode } from 'react';
11 +import type { Root, Node, Item } from 'fumadocs-core/page-tree';
12 +
13 +function SidebarBadge({ label, tone }: { label: string; tone: 'experimental' | 'new' }) {
14 + const toneClass =
15 + tone === 'experimental'
16 + ? 'bg-amber-100 text-amber-700 ring-amber-600/20 dark:bg-amber-500/10 dark:text-amber-400 dark:ring-amber-500/25'
17 + : 'bg-emerald-100 text-emerald-700 ring-emerald-600/20 dark:bg-emerald-500/10 dark:text-emerald-400 dark:ring-emerald-500/25';
18 + return (
19 + <span
20 + className={`ml-2 inline-flex shrink-0 items-center rounded px-1.5 py-px text-[10px] font-medium uppercase tracking-wide ring-1 ring-inset ${toneClass}`}
21 + >
22 + {label}
23 + </span>
24 + );
25 +}
26 +
27 +function withBadge(name: ReactNode, badge: ReactNode): ReactNode {
28 + return (
29 + <span className="inline-flex w-full items-center justify-between gap-2">
30 + <span className="truncate">{name}</span>
31 + {badge}
32 + </span>
33 + );
34 +}
35 +
36 +function decorateNode(node: Node, experimental: Set<string>, isNew: Set<string>): Node {
37 + if (node.type === 'folder') {
38 + return {
39 + ...node,
40 + children: node.children.map((child) => decorateNode(child, experimental, isNew)),
41 + };
42 + }
43 + if (node.type === 'page' && experimental.has(node.url)) {
44 + return { ...node, name: withBadge(node.name, <SidebarBadge label="Exp" tone="experimental" />) } as Item;
45 + }
46 + if (node.type === 'page' && isNew.has(node.url)) {
47 + return { ...node, name: withBadge(node.name, <SidebarBadge label="New" tone="new" />) } as Item;
48 + }
49 + return node;
50 +}
51 +
52 +/**
53 + * Returns a new page tree with experimental/new sidebar badges applied.
54 + * No-op when all sets are empty so the original tree is reused.
55 + */
56 +export function decorateSidebarBadges(
57 + tree: Root,
58 + experimentalUrls: Set<string>,
59 + newUrls: Set<string>,
60 +): Root {
61 + if (experimentalUrls.size === 0 && newUrls.size === 0) return tree;
62 + return {
63 + ...tree,
64 + children: tree.children.map((node) => decorateNode(node, experimentalUrls, newUrls)),
65 + };
66 +}
docs/lib/eve-empty-module.js new
+4
@@ -0,0 +1,4 @@
1 +// Browser stub for `node:module`. eve's bundled rolldown CJS-interop helper
2 +// has a bare, unused `import "node:module"` that Turbopack can't put in a
3 +// browser chunk. Nothing reads from it, so an empty module is safe.
4 +export {};
docs/lib/file-builds.ts new
+14
@@ -0,0 +1,14 @@
1 +/**
2 + * Registry that merges every example's FileBuildup stages into one map, so the
3 + * <FileBuildup> component isn't hardwired to a single example. Each example
4 + * contributes its own keys; they must not collide.
5 + *
6 + * - slack-bot-build: `bot`, `install` (general-agent-with-pi)
7 + * - local-workbench-build: `reviewer` (local-sandbox-pr-reviewer)
8 + * - standup-bot-build: `setup`, `proxy`, `buttons`, `draft` (daily standup bot)
9 + */
10 +import { FILE_BUILDS as slackBot } from './slack-bot-build';
11 +import { FILE_BUILDS as localWorkbench } from './local-workbench-build';
12 +import { FILE_BUILDS as standup } from './standup-bot-build';
13 +
14 +export const FILE_BUILDS = { ...slackBot, ...localWorkbench, ...standup };
docs/lib/filter-api-version.ts
+60 -1
@@ -21,6 +21,63 @@ interface PageTreeRoot {
21 [key: string]: unknown;
22 }
23
24 +/**
25 + * API-reference tags that we intentionally hide on our side even though the
26 + * upstream OpenAPI spec (from hermes) still includes them. Matched by tag slug.
27 + *
28 + * Hiding happens in two places that must stay in sync:
29 + * - `scripts/generate-api-index.ts` skips generating (and deletes) their
30 + * `index.mdx` overview pages.
31 + * - `filterHiddenTags` (below) drops their folders/pages from the reference
32 + * page tree so the fumadocs-openapi operation pages disappear from the
33 + * sidebar, llms.txt walk, and search.
34 + */
35 +export const HIDDEN_API_TAGS: ReadonlySet<string> = new Set([
36 + 'consumer',
37 + 'invite-codes',
38 + 'authentication',
39 +]);
40 +
41 +/** True if a URL points at a hidden tag's pages (v3.1 or v3.0). */
42 +function isHiddenTagUrl(url: string): boolean {
43 + for (const tag of HIDDEN_API_TAGS) {
44 + if (
45 + url.startsWith(`/reference/api-reference/${tag}/`) ||
46 + url === `/reference/api-reference/${tag}` ||
47 + url.startsWith(`/reference/v3/api-reference/${tag}/`) ||
48 + url === `/reference/v3/api-reference/${tag}`
49 + ) {
50 + return true;
51 + }
52 + }
53 + return false;
54 +}
55 +
56 +/** True if a node (page or folder) belongs entirely to a hidden tag. */
57 +function isHiddenTagNode(node: PageTreeNode): boolean {
58 + if (node.type === 'page' && typeof node.url === 'string') {
59 + return isHiddenTagUrl(node.url);
60 + }
61 + if (node.type === 'folder') {
62 + if (node.index && isHiddenTagNode(node.index)) return true;
63 + // A folder whose every child is hidden (and has at least one) is itself hidden.
64 + const children = node.children ?? [];
65 + if (children.length > 0 && children.every(isHiddenTagNode)) return true;
66 + }
67 + return false;
68 +}
69 +
70 +/** Recursively drops folders/pages whose tag slug is in HIDDEN_API_TAGS. */
71 +function filterHiddenTags(nodes: PageTreeNode[]): PageTreeNode[] {
72 + return nodes
73 + .filter((node) => !isHiddenTagNode(node))
74 + .map((node) =>
75 + node.type === 'folder' && node.children
76 + ? { ...node, children: filterHiddenTags(node.children) }
77 + : node,
78 + );
79 +}
80 +
81 function isV3Node(node: PageTreeNode): boolean {
82 if (node.type === 'page' && typeof node.url === 'string') {
83 return node.url.startsWith('/reference/v3/') || node.url === '/reference/v3';
@@ -50,7 +107,9 @@ function isV31ApiFolder(node: PageTreeNode): boolean {
107 }
108
109 export function prepareTree<T extends PageTreeRoot>(tree: T, version: string): T {
53 - const children = tree.children as PageTreeNode[];
110 + // Drop intentionally-hidden tags (consumer, invite-codes) from the whole tree
111 + // first, so neither version surfaces their operation pages.
112 + const children = filterHiddenTags(tree.children as PageTreeNode[]);
113
114 if (version === '3.1') {
115 // Just hide the V3 folder
docs/lib/layout.shared.tsx
+5 -5
@@ -49,6 +49,11 @@ export function baseOptions(): BaseLayoutProps {
49 url: '/docs',
50 active: 'nested-url',
51 },
52 + {
53 + text: 'Examples',
54 + url: '/examples',
55 + active: 'nested-url',
56 + },
57 {
58 text: 'Toolkits',
59 url: '/toolkits',
@@ -59,11 +64,6 @@ export function baseOptions(): BaseLayoutProps {
64 url: '/reference',
65 active: 'nested-url',
66 },
62 - {
63 - text: 'Cookbooks',
64 - url: '/cookbooks',
65 - active: 'nested-url',
66 - },
67 {
68 type: 'icon',
69 label: 'GitHub',
docs/lib/local-workbench-build.ts new
+144
@@ -0,0 +1,144 @@
1 +/**
2 + * Cumulative stages of the local-workbench PR reviewer's host orchestration
3 + * file, built up one piece at a time. Each stage's `code` is the full file at
4 + * that point; <FileBuildup> diffs consecutive stages so the reader watches
5 + * `src/runner.ts` grow from a bare client into the full run loop.
6 + *
7 + * These are *teaching* stages: distilled and inlined from the real source
8 + * (src/runner.ts + src/workbench.ts + src/sandbox/e2b.ts) so each Composio
9 + * concept reads on its own, the way slack-bot-build.ts simplifies the Slack bot.
10 + *
11 + * Source: ComposioHQ/local-pr-reviewer @ c3baff810a6b8dbf1e2c1eff45ddc9785998e3e8
12 + * Refresh this map (and local-workbench-source.json) when that repo changes.
13 + *
14 + * This data is rendered via @pierre/diffs, NOT twoslash, so it is not
15 + * type-checked, because it deliberately uses the unreleased
16 + * experimental_createLocalWorkbenchSession export.
17 + */
18 +import type { BuildStage } from './slack-bot-build';
19 +
20 +const imports = `import { Composio } from '@composio/core';
21 +import { experimental_createLocalWorkbenchSession } from '@composio/experimental/workbench';
22 +import { createE2bSandbox } from './sandbox/e2b';
23 +
24 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
25 +const userId = process.env.COMPOSIO_USER_ID ?? 'local-pr-reviewer-user';
26 +`;
27 +
28 +const stage1 = imports;
29 +
30 +const stage2 = `${imports}
31 +// Composio runs tools as a user. Before anything else, make sure this user has
32 +// an active GitHub connection. There's no point booting a sandbox without one.
33 +async function requireGithubConnection() {
34 + const list = await composio.connectedAccounts.list({
35 + userIds: [userId],
36 + toolkitSlugs: ['github'],
37 + statuses: ['ACTIVE'],
38 + });
39 + if (list.items?.[0]) return;
40 +
41 + const request = await composio.toolkits.authorize(userId, 'github');
42 + throw new Error(\`Connect GitHub first: \${request.redirectUrl}\`);
43 +}
44 +`;
45 +
46 +const stage3 = `${stage2}
47 +// The local sandbox session. Create a normal Composio session yourself with
48 +// \`workbench.enable: false\` (Composio won't run code for you), then hand that
49 +// session to the helper, which validates it's local and gives you the pieces to
50 +// run code yourself, wherever you choose.
51 +async function createWorkbench() {
52 + const session = await composio.create(userId, {
53 + toolkits: ['github'],
54 + workbench: { enable: false },
55 + });
56 + return experimental_createLocalWorkbenchSession(composio, session);
57 + // returns { helperSource, env }:
58 + // helperSource: a Python helper exposing run_composio_tool / invoke_llm / web_search
59 + // env: the variables that helper needs to reach Composio from inside your box
60 +}
61 +`;
62 +
63 +const stage4 = `${stage3}
64 +export async function runReview(repo: string, pr: number) {
65 + await requireGithubConnection();
66 + const workbench = await createWorkbench();
67 +
68 + // Start a sandbox you own, inject the helper, and pass the env. E2B is just
69 + // the sample runner; swap createE2bSandbox for any box that honors the same
70 + // contract: write a file, set env, run a command, stream output, tear down.
71 + const sandbox = await createE2bSandbox({
72 + apiKey: process.env.E2B_API_KEY,
73 + helperSource: workbench.helperSource, // written as composio_helper.py
74 + env: workbench.env,
75 + });
76 +}
77 +`;
78 +
79 +const stage5 = `${stage3}
80 +export async function runReview(repo: string, pr: number) {
81 + await requireGithubConnection();
82 + const workbench = await createWorkbench();
83 +
84 + // Start a sandbox you own, inject the helper, and pass the env. E2B is just
85 + // the sample runner; swap createE2bSandbox for any box that honors the same
86 + // contract: write a file, set env, run a command, stream output, tear down.
87 + const sandbox = await createE2bSandbox({
88 + apiKey: process.env.E2B_API_KEY,
89 + helperSource: workbench.helperSource, // written as composio_helper.py
90 + env: workbench.env,
91 + });
92 +
93 + // Run the reviewer agent inside the sandbox and stream its output back. The
94 + // agent calls run_composio_tool from composio_helper.py, which routes GitHub
95 + // actions back through Composio under this user's connection.
96 + const task = \`Review PR #\${pr} on \${repo}. Run the repo's real checks in this sandbox.\`;
97 + try {
98 + await sandbox.run('npx --yes tsx agent.ts', {
99 + env: { ...workbench.env, TASK: task, OPENAI_API_KEY: process.env.OPENAI_API_KEY },
100 + onStdout: (chunk) => process.stdout.write(chunk),
101 + onStderr: (chunk) => process.stderr.write(chunk),
102 + });
103 + } finally {
104 + await sandbox.teardown();
105 + }
106 +}
107 +`;
108 +
109 +const STAGES: { title: string; description: string; code: string }[] = [
110 + {
111 + title: 'Create the Composio client',
112 + description:
113 + 'Start from scratch. One client, one stable user id. Everything below acts as this user, against the connections they own.',
114 + code: stage1,
115 + },
116 + {
117 + title: 'Check the GitHub connection',
118 + description:
119 + 'A local sandbox still uses Composio for auth and tool discovery. Before booting any infrastructure, confirm this user has an active GitHub connection, and hand them a connect link if not.',
120 + code: stage2,
121 + },
122 + {
123 + title: 'Create the local sandbox session',
124 + description:
125 + 'The whole idea. Create a Composio session yourself with workbench.enable: false (Composio will not run code for you), then hand that session to experimental_createLocalWorkbenchSession, which validates it is local and returns the helper source and env you run yourself.',
126 + code: stage3,
127 + },
128 + {
129 + title: 'Start your sandbox, inject the helper',
130 + description:
131 + 'Boot a box you control, write helperSource into it as composio_helper.py, and pass env to the process. E2B is the sample runner; this is the only Composio-specific thing your sandbox must carry.',
132 + code: stage4,
133 + },
134 + {
135 + title: 'Run the reviewer and stream output',
136 + description:
137 + 'Run the agent inside the sandbox. Whenever it calls run_composio_tool, the helper routes that GitHub action back through Composio under this user, so tool execution happens in your box, but discovery and auth stay managed.',
138 + code: stage5,
139 + },
140 +];
141 +
142 +export const FILE_BUILDS: Record<string, { file: string; stages: BuildStage[] }> = {
143 + reviewer: { file: 'src/runner.ts', stages: STAGES },
144 +};
docs/lib/local-workbench-source.json new
+42
@@ -0,0 +1,42 @@
1 +[
2 +{
3 +"path": "src/index.ts",
4 +"contents": "import { loadConfig, requireLiveConfig } from './config.js';\nimport { buildReviewTask, runReview, type ReviewTarget } from './runner.js';\nimport { createComposioClient, createGithubConnectUrl, getActiveGithubConnection } from './workbench.js';\n\ntype Command = 'review' | 'connect-github' | 'help';\n\ninterface CliOptions {\n command: Command;\n repo?: string;\n pr?: number;\n userId?: string;\n dryRun: boolean;\n}\n\nfunction usage(): string {\n return `Local PR Reviewer\n\nUsage:\n bun run review -- --repo <owner/repo> --pr <number>\n bun run connect\n bun run smoke\n\nOptions:\n --repo <owner/repo> GitHub repository to review\n --pr <number> Pull request number\n --user-id <id> Override COMPOSIO_USER_ID for this run\n --dry-run Validate inputs and print the planned local-workbench flow\n --help Show this message`;\n}\n\nfunction parseArgs(argv: string[]): CliOptions {\n const args = [...argv];\n const command = (args[0] && !args[0].startsWith('--') ? args.shift() : 'review') as Command;\n const options: CliOptions = {\n command: command === 'connect-github' || command === 'review' || command === 'help' ? command : 'help',\n dryRun: false,\n };\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n const next = args[index + 1];\n\n if (arg === '--repo') {\n options.repo = next;\n index += 1;\n } else if (arg === '--pr') {\n options.pr = Number(next);\n index += 1;\n } else if (arg === '--user-id') {\n options.userId = next;\n index += 1;\n } else if (arg === '--dry-run') {\n options.dryRun = true;\n } else if (arg === '--help' || arg === '-h') {\n options.command = 'help';\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n\n return options;\n}\n\nfunction parseTarget(options: CliOptions): ReviewTarget {\n if (!options.repo || !/^[^/\\s]+\\/[^/\\s]+$/.test(options.repo)) {\n throw new Error('--repo must be in owner/repo format');\n }\n const pr = options.pr;\n if (!Number.isInteger(pr) || (pr ?? 0) <= 0) {\n throw new Error('--pr must be a positive integer');\n }\n return { repo: options.repo, pr: pr as number };\n}\n\nasync function connectGithub(options: CliOptions): Promise<void> {\n const config = loadConfig();\n if (options.userId) config.userId = options.userId;\n if (!config.composioApiKey) throw new Error('COMPOSIO_API_KEY is required to create a GitHub connect URL');\n\n const composio = createComposioClient(config);\n const existing = await getActiveGithubConnection(composio, config.userId);\n if (existing) {\n console.log(`GitHub is already connected for ${config.userId} (${existing.id}).`);\n return;\n }\n\n const url = await createGithubConnectUrl(composio, config.userId);\n console.log(`Open this URL to connect GitHub for ${config.userId}:`);\n console.log(url);\n}\n\nfunction dryRun(target: ReviewTarget, userId: string): void {\n console.log('Dry run OK.');\n console.log(`User: ${userId}`);\n console.log(`Task: ${buildReviewTask(target)}`);\n console.log('Flow: create Tool Router session with workbench.enable=false, boot E2B, upload helper + reviewer, run checks, post one grounded PR comment.');\n}\n\nasync function review(options: CliOptions): Promise<void> {\n const config = loadConfig();\n if (options.userId) config.userId = options.userId;\n const target = parseTarget(options);\n\n if (options.dryRun) {\n dryRun(target, config.userId);\n return;\n }\n\n requireLiveConfig(config);\n const result = await runReview({\n config,\n target,\n onEvent: (event) => console.log(`[${event.type}] ${event.detail}`),\n });\n console.log('\\nReview result:\\n');\n console.log(result);\n}\n\nasync function main(): Promise<void> {\n const options = parseArgs(process.argv.slice(2));\n\n if (options.command === 'help') {\n console.log(usage());\n return;\n }\n\n if (options.command === 'connect-github') {\n await connectGithub(options);\n return;\n }\n\n await review(options);\n}\n\nmain().catch((error) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n});\n",
5 +"composio": false
6 +},
7 +{
8 +"path": "src/runner.ts",
9 +"contents": "import type { AppConfig } from './config.js';\nimport { createE2bSandbox } from './sandbox/e2b.js';\nimport { createComposioClient, createLocalWorkbench, requireGithubConnection } from './workbench.js';\nimport { executeReviewerAgent, installReviewerRuntime, uploadReviewerAgent } from './reviewer/runner.js';\nimport type { ReviewEventSink } from './reviewer/events.js';\n\nexport interface ReviewTarget {\n repo: string;\n pr: number;\n}\n\nexport interface RunReviewOptions {\n config: AppConfig;\n target: ReviewTarget;\n onEvent?: ReviewEventSink;\n}\n\nexport function buildReviewTask(target: ReviewTarget): string {\n return `Review PR #${target.pr} on ${target.repo}. Run the repository's real checks in this sandbox and post one grounded GitHub PR comment only if checks actually run.`;\n}\n\nexport async function runReview(options: RunReviewOptions): Promise<string> {\n const onEvent = options.onEvent ?? (() => {});\n const composio = createComposioClient(options.config);\n\n onEvent({ type: 'info', detail: 'checking GitHub connection' });\n await requireGithubConnection(composio, options.config.userId);\n\n onEvent({ type: 'info', detail: 'creating local workbench session' });\n const workbench = await createLocalWorkbench(composio, options.config.userId);\n\n onEvent({ type: 'sandbox', detail: 'booting E2B sandbox' });\n const sandbox = await createE2bSandbox({\n apiKey: options.config.e2bApiKey ?? '',\n timeoutMs: options.config.e2bTimeoutMs,\n remoteDir: options.config.sandboxRemoteDir,\n helperSource: workbench.helperSource,\n env: workbench.env,\n });\n\n try {\n await uploadReviewerAgent(sandbox);\n await installReviewerRuntime(sandbox, onEvent);\n return await executeReviewerAgent(\n sandbox,\n buildReviewTask(options.target),\n {\n OPENAI_API_KEY: options.config.openaiApiKey ?? '',\n COMPOSIO_USER_ID: options.config.userId,\n },\n onEvent\n );\n } finally {\n onEvent({ type: 'sandbox', detail: 'tearing down sandbox' });\n await sandbox.teardown();\n }\n}\n",
10 +"composio": true
11 +},
12 +{
13 +"path": "src/workbench.ts",
14 +"contents": "import { Composio } from '@composio/core';\nimport {\n experimental_createLocalWorkbenchSession,\n type LocalWorkbenchSession,\n} from '@composio/experimental/workbench';\nimport type { AppConfig } from './config.js';\n\ntype ConnectedAccount = {\n id: string;\n status?: string;\n};\n\nexport function createComposioClient(config: AppConfig): Composio {\n return new Composio({\n apiKey: config.composioApiKey,\n baseURL: config.composioBaseUrl,\n });\n}\n\nexport async function getActiveGithubConnection(composio: Composio, userId: string): Promise<ConnectedAccount | undefined> {\n const list = (await composio.connectedAccounts.list({\n userIds: [userId],\n toolkitSlugs: ['github'],\n statuses: ['ACTIVE'],\n })) as { items?: ConnectedAccount[] };\n\n return list.items?.[0];\n}\n\nexport async function createGithubConnectUrl(composio: Composio, userId: string): Promise<string> {\n const request = await composio.toolkits.authorize(userId, 'github');\n if (!request.redirectUrl) throw new Error('Composio did not return a GitHub connect URL');\n return request.redirectUrl;\n}\n\nexport async function requireGithubConnection(composio: Composio, userId: string): Promise<ConnectedAccount> {\n const account = await getActiveGithubConnection(composio, userId);\n if (account) return account;\n\n const url = await createGithubConnectUrl(composio, userId);\n throw new Error(\n [\n `No active GitHub connection found for COMPOSIO_USER_ID=\"${userId}\".`,\n 'Open this URL, complete GitHub authorization, then run the reviewer again:',\n url,\n ].join('\\n')\n );\n}\n\nexport async function createLocalWorkbench(composio: Composio, userId: string): Promise<LocalWorkbenchSession> {\n // Create the session with the remote workbench disabled so code execution runs in our own sandbox,\n // then hand it to the helper (which validates workbench.enable === false).\n const session = await composio.create(userId, {\n toolkits: ['github'],\n workbench: { enable: false },\n });\n return experimental_createLocalWorkbenchSession(composio, session);\n}\n",
15 +"composio": true
16 +},
17 +{
18 +"path": "src/sandbox/e2b.ts",
19 +"contents": "import { Sandbox } from 'e2b';\n\nexport interface SandboxOptions {\n apiKey: string;\n timeoutMs: number;\n remoteDir: string;\n helperSource: string;\n env: Record<string, string>;\n}\n\nexport interface UserSandbox {\n remoteDir: string;\n env: Record<string, string>;\n writeFile(path: string, contents: string): Promise<void>;\n run(command: string, options?: RunOptions): Promise<void>;\n teardown(): Promise<void>;\n}\n\nexport interface RunOptions {\n timeoutMs?: number;\n env?: Record<string, string>;\n onStdout?: (chunk: string) => void;\n onStderr?: (chunk: string) => void;\n}\n\ntype CommandError = {\n result?: {\n exitCode?: number;\n stdout?: string;\n stderr?: string;\n };\n};\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport function commandErrorText(error: unknown): string {\n const result = (error as CommandError).result;\n if (result) {\n const output = result.stderr || result.stdout || '';\n return `exit ${result.exitCode ?? 'unknown'}\\n${output.slice(-1200)}`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\nexport async function createE2bSandbox(options: SandboxOptions): Promise<UserSandbox> {\n const sandbox = await Sandbox.create({\n apiKey: options.apiKey,\n timeoutMs: options.timeoutMs,\n });\n\n await sandbox.commands.run(`mkdir -p ${shellQuote(options.remoteDir)}`, {\n timeoutMs: 30_000,\n });\n await sandbox.files.write(`${options.remoteDir}/composio_helper.py`, options.helperSource);\n\n return {\n remoteDir: options.remoteDir,\n env: options.env,\n async writeFile(path, contents) {\n await sandbox.files.write(path, contents);\n },\n async run(command, runOptions = {}) {\n await sandbox.commands.run(command, {\n timeoutMs: runOptions.timeoutMs,\n envs: runOptions.env,\n onStdout: runOptions.onStdout,\n onStderr: runOptions.onStderr,\n });\n },\n async teardown() {\n await sandbox.kill();\n },\n };\n}\n",
20 +"composio": true
21 +},
22 +{
23 +"path": "src/config.ts",
24 +"contents": "import 'dotenv/config';\n\nexport interface AppConfig {\n composioApiKey?: string;\n composioBaseUrl?: string;\n openaiApiKey?: string;\n e2bApiKey?: string;\n userId: string;\n sandboxRemoteDir: string;\n e2bTimeoutMs: number;\n}\n\nconst DEFAULT_USER_ID = 'local-pr-reviewer-user';\nconst DEFAULT_REMOTE_DIR = '/home/user/local-pr-reviewer';\nconst DEFAULT_E2B_TIMEOUT_MS = 1_800_000;\n\nfunction optionalEnv(name: string): string | undefined {\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction optionalNumberEnv(name: string, fallback: number): number {\n const value = optionalEnv(name);\n if (!value) return fallback;\n\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`${name} must be a positive number`);\n }\n return parsed;\n}\n\nexport function loadConfig(): AppConfig {\n return {\n composioApiKey: optionalEnv('COMPOSIO_API_KEY'),\n composioBaseUrl: optionalEnv('COMPOSIO_BASE_URL'),\n openaiApiKey: optionalEnv('OPENAI_API_KEY'),\n e2bApiKey: optionalEnv('E2B_API_KEY'),\n userId: optionalEnv('COMPOSIO_USER_ID') ?? DEFAULT_USER_ID,\n sandboxRemoteDir: optionalEnv('SANDBOX_REMOTE_DIR') ?? DEFAULT_REMOTE_DIR,\n e2bTimeoutMs: optionalNumberEnv('E2B_TIMEOUT_MS', DEFAULT_E2B_TIMEOUT_MS),\n };\n}\n\nexport function requireLiveConfig(config: AppConfig): Required<Pick<AppConfig, 'composioApiKey' | 'openaiApiKey' | 'e2bApiKey'>> {\n const missing = [\n ['COMPOSIO_API_KEY', config.composioApiKey],\n ['OPENAI_API_KEY', config.openaiApiKey],\n ['E2B_API_KEY', config.e2bApiKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length) {\n throw new Error(`Missing required env var${missing.length === 1 ? '' : 's'} for a live run: ${missing.join(', ')}`);\n }\n\n return {\n composioApiKey: config.composioApiKey,\n openaiApiKey: config.openaiApiKey,\n e2bApiKey: config.e2bApiKey,\n } as Required<Pick<AppConfig, 'composioApiKey' | 'openaiApiKey' | 'e2bApiKey'>>;\n}\n",
25 +"composio": false
26 +},
27 +{
28 +"path": "src/reviewer/runner.ts",
29 +"contents": "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { parseAgentEvent, type ReviewEventSink } from './events.js';\nimport { commandErrorText, shellQuote, type UserSandbox } from '../sandbox/e2b.js';\n\nconst INSTALL_TIMEOUT_MS = 300_000;\nconst AGENT_TIMEOUT_MS = 1_500_000;\nconst AGENT_DIR = join(process.cwd(), 'agent');\n\nconst AGENT_FILES = [\n ['agent.ts', 'agent.ts'],\n ['instructions.md', 'instructions.md'],\n ['package.json', 'package.json'],\n] as const;\n\nfunction createOutputCollector(onEvent: ReviewEventSink) {\n let output = '';\n\n return {\n onStdout(data: string) {\n output += data;\n\n for (const line of data.split('\\n')) {\n if (!line.trim()) continue;\n\n const event = parseAgentEvent(line);\n if (event) onEvent(event);\n else console.log(line);\n }\n },\n\n onStderr(data: string) {\n output += data;\n for (const line of data.split('\\n')) {\n if (line.trim()) console.error(line);\n }\n },\n\n result() {\n const match = output.match(/::result::(.*)$/m);\n if (!match) return undefined;\n\n try {\n return JSON.parse(match[1]) as string;\n } catch {\n return match[1];\n }\n },\n\n tail() {\n return output.slice(-2000);\n },\n };\n}\n\nexport async function uploadReviewerAgent(sandbox: UserSandbox): Promise<void> {\n await Promise.all(\n AGENT_FILES.map(async ([localName, remoteName]) => {\n const contents = await readFile(join(AGENT_DIR, localName), 'utf8');\n await sandbox.writeFile(`${sandbox.remoteDir}/${remoteName}`, contents);\n })\n );\n}\n\nexport async function installReviewerRuntime(sandbox: UserSandbox, onEvent: ReviewEventSink): Promise<void> {\n onEvent({ type: 'info', detail: 'installing reviewer runtime' });\n\n try {\n await sandbox.run(`cd ${shellQuote(sandbox.remoteDir)} && npm install --no-audit --no-fund --loglevel=error`, {\n timeoutMs: INSTALL_TIMEOUT_MS,\n });\n } catch (error) {\n throw new Error(`npm install failed:\\n${commandErrorText(error)}`);\n }\n}\n\nexport async function executeReviewerAgent(\n sandbox: UserSandbox,\n task: string,\n env: Record<string, string>,\n onEvent: ReviewEventSink\n): Promise<string> {\n onEvent({ type: 'run', detail: 'reviewer running inside your sandbox' });\n\n const output = createOutputCollector(onEvent);\n try {\n await sandbox.run(`cd ${shellQuote(sandbox.remoteDir)} && npx --yes tsx agent.ts`, {\n timeoutMs: AGENT_TIMEOUT_MS,\n env: {\n ...sandbox.env,\n ...env,\n AGENT_REMOTE_DIR: sandbox.remoteDir,\n TASK: task,\n },\n onStdout: output.onStdout,\n onStderr: output.onStderr,\n });\n } catch (error) {\n const result = output.result();\n if (result) return result;\n throw new Error(`agent run failed:\\n${commandErrorText(error)}`);\n }\n\n return output.result() ?? output.tail() ?? '(no output)';\n}\n",
30 +"composio": false
31 +},
32 +{
33 +"path": "agent/agent.ts",
34 +"contents": "import { Agent, run, tool } from '@openai/agents';\nimport { execSync } from 'node:child_process';\nimport { readFileSync, writeFileSync } from 'node:fs';\n\nconst REMOTE = process.env.AGENT_REMOTE_DIR || '/home/user/local-pr-reviewer';\nconst CELL_TIMEOUT_MS = 900_000;\nconst MAX_BUFFER_BYTES = 32 * 1024 * 1024;\nconst TASK = process.env.TASK || 'Review the pull request.';\nconst INSTRUCTIONS = readFileSync(new URL('./instructions.md', import.meta.url), 'utf8');\n\ntype RunPythonInput = {\n note: string;\n code: string;\n};\n\ntype ExecError = {\n status?: number;\n stdout?: string;\n stderr?: string;\n};\n\nlet cellNumber = 0;\n\nfunction nextCellFile(): string {\n cellNumber += 1;\n return `cell-${cellNumber}.py`;\n}\n\nfunction cellLabel(file: string): string {\n return file.replace('cell-', 'cell ').replace('.py', '');\n}\n\nfunction buildCellSource(code: string): string {\n return [\n 'from composio_helper import run_composio_tool, invoke_llm, web_search',\n 'import json',\n 'import os',\n 'import pathlib',\n 'import shutil',\n 'import subprocess',\n 'import textwrap',\n '',\n 'def run(cmd, cwd=None, timeout=900):',\n ' completed = subprocess.run(cmd, cwd=cwd, shell=True, text=True, capture_output=True, timeout=timeout)',\n ' output = (completed.stdout or \"\") + (completed.stderr or \"\")',\n ' print(output[-12000:])',\n ' return {\"exit_code\": completed.returncode, \"output\": output}',\n '',\n code,\n '',\n ].join('\\n');\n}\n\nfunction summarizeFailure(error: ExecError): string {\n return (error.stderr || error.stdout || '').trim().split('\\n').slice(-3).join(' | ').slice(-300);\n}\n\nfunction runCell(file: string): string {\n return execSync(`python3 ${file}`, {\n cwd: REMOTE,\n encoding: 'utf8',\n timeout: CELL_TIMEOUT_MS,\n maxBuffer: MAX_BUFFER_BYTES,\n shell: '/bin/bash',\n });\n}\n\nconst runPython = tool({\n name: 'run_python',\n description:\n 'Execute a Python cell in THIS sandbox. Pre-imported and in scope: ' +\n '`run_composio_tool(slug, arguments)` to call Composio tools, `invoke_llm(query)`, `web_search(query)`, ' +\n '`run(cmd, cwd=None, timeout=900)` for shell commands, and Python stdlib modules json/os/pathlib/shutil/subprocess/textwrap. ' +\n 'Print anything you want to observe; stdout+stderr are returned to you.',\n parameters: {\n type: 'object',\n properties: {\n note: {\n type: 'string',\n description:\n 'A short present-tense description of what this cell does, shown live to the user (<=10 words). ' +\n 'e.g. \"fetching PR #1 metadata\", \"downloading repo archive\", \"running node --test\", \"posting review comment\".',\n },\n code: { type: 'string', description: 'Python to run. Do not include markdown fences.' },\n },\n required: ['note', 'code'],\n additionalProperties: false,\n },\n strict: true,\n execute: async (raw: unknown) => {\n const { note, code } = raw as RunPythonInput;\n const file = nextCellFile();\n\n console.log(`::event::step::${note} (${cellLabel(file)})`);\n writeFileSync(`${REMOTE}/${file}`, buildCellSource(code));\n\n try {\n return runCell(file);\n } catch (e: unknown) {\n const error = e as ExecError;\n console.log(`::event::error::${note} failed: ${summarizeFailure(error)}`);\n return `exit ${error.status}\\n--- stdout ---\\n${error.stdout ?? ''}\\n--- stderr ---\\n${error.stderr ?? ''}`;\n }\n },\n});\n\nconst agent = new Agent({\n name: 'Local PR Reviewer',\n instructions: INSTRUCTIONS,\n tools: [runPython],\n});\n\nconst result = await run(agent, TASK, { maxTurns: 40 });\nconsole.log('::result::' + JSON.stringify(result.finalOutput ?? '(no output)'));\n",
35 +"composio": true
36 +},
37 +{
38 +"path": "agent/instructions.md",
39 +"contents": "# Local PR Reviewer\n\nYou are reviewing a GitHub pull request from inside the user's own sandbox.\nVerify by running commands. Do not guess.\n\nYour only tool is `run_python`. Each cell runs in this sandbox and has:\n\n- `run_composio_tool(slug, arguments)` for Composio tools.\n- `invoke_llm(query)` for model calls.\n- `web_search(query)` for web research.\n- `run(cmd, cwd=None, timeout=900)` for shell commands.\n\nUse a short, specific `note` on every `run_python` call because it is shown live\nto the user.\n\n## Composio Tool Rules\n\nUse Composio for GitHub auth and tool discovery. Do not hardcode GitHub tokens,\ntool slugs, or argument shapes.\n\nBefore every new GitHub action:\n\n1. Call `COMPOSIO_SEARCH_TOOLS` with the use case.\n2. Call `COMPOSIO_GET_TOOL_SCHEMAS` for the selected slug.\n3. Call the tool with the exact schema arguments.\n\n`run_composio_tool` returns `(response, error)`. Check `error` before using\n`response`. If a call fails because a slug or argument is invalid, fetch the\nschema again and correct the call instead of guessing another tool.\n\n## Review Workflow\n\n1. Require an explicit `owner/repo` and PR number. If either is missing, stop.\n2. Fetch the PR metadata and changed files through Composio, then print the key\n details.\n3. Download the PR source into the sandbox through Composio-managed GitHub auth.\n Prefer a GitHub archive or signed codeload URL for the PR head ref/SHA. Do\n not use a personal token or a bare `api.github.com/.../tarball` URL.\n4. Verify the extracted directory contains real source files before running\n checks.\n5. Detect the package manager from lockfiles, install dependencies, and run the\n checks the repository actually defines. Prefer `test`, `lint`, `typecheck`,\n `type-check`, `tsc`, then `build` when those scripts exist.\n6. If a required runtime is missing, install it in the sandbox and retry the\n same check. Keep the output needed to explain failures.\n7. Post one general PR comment only after checks actually ran. Cite the commands\n that passed or failed and include concrete failure output when relevant.\n\nDo not approve, request changes, or post duplicate comments. If the repository\ncould not be downloaded or no checks could run, post nothing and return the\nblocker instead.\n\nFinish with a concise summary. Include the review URL only when a comment was\nposted successfully.\n",
40 +"composio": false
41 +}
42 +]
docs/lib/meta-tool-overrides.ts new
+75
@@ -0,0 +1,75 @@
1 +/**
2 + * Hand-written copy overrides for meta tool reference pages.
3 + *
4 + * The meta tool JSON (`public/data/meta-tools.json`) and the generated MDX are
5 + * regenerated from the Tool Router API by `scripts/generate-meta-tools.ts`, so
6 + * editing those gets clobbered. This map survives regeneration: it is merged
7 + * over the API data at read time in `lib/meta-tools-data.ts`.
8 + *
9 + * Each entry provides Modal-voice display copy. The API still owns the input
10 + * and response schemas; we only override the prose.
11 + */
12 +
13 +export interface MetaToolOverride {
14 + /** One confident sentence on what the tool does. Replaces the API description for display. */
15 + summary: string;
16 + /** When you should reach for this tool in a session. */
17 + whenToUse: string;
18 + /** Optional short note on usage, ordering, or gotchas. */
19 + usageNote?: string;
20 +}
21 +
22 +export const META_TOOL_OVERRIDES: Record<string, MetaToolOverride> = {
23 + COMPOSIO_SEARCH_TOOLS: {
24 + summary:
25 + 'Discovers the right tools across 500+ apps for a task and returns them with an execution plan, connection status, and the `session_id` that ties the rest of the workflow together.',
26 + whenToUse:
27 + 'Call `COMPOSIO_SEARCH_TOOLS` first, at the start of any task that touches an external app or service. Run it again whenever the user pivots to a new use case so you get a fresh `session_id` and a plan scoped to the new work.',
28 + usageNote:
29 + 'Split a request into atomic queries (one query per tool call) and name the app in each query so intent stays scoped. The response tells you which toolkits already have an active connection and which need `COMPOSIO_MANAGE_CONNECTIONS`.',
30 + },
31 + COMPOSIO_GET_TOOL_SCHEMAS: {
32 + summary:
33 + 'Returns the full input schema for tools you already know the slug for, so you can build schema-compliant arguments before executing.',
34 + whenToUse:
35 + 'Reach for `COMPOSIO_GET_TOOL_SCHEMAS` when `COMPOSIO_SEARCH_TOOLS` hands you a tool with a `schemaRef` instead of an inline `input_schema`, or when you need the `output_schema` to validate a response in the workbench.',
36 + usageNote:
37 + 'Only pass slugs that `COMPOSIO_SEARCH_TOOLS` returned. Never guess or fabricate a slug. If a slug is not found, the response suggests close matches you can call again with.',
38 + },
39 + COMPOSIO_MANAGE_CONNECTIONS: {
40 + summary:
41 + 'Checks connection status for a toolkit and returns a branded authentication link when the user needs to connect, covering OAuth, API keys, and every other auth type.',
42 + whenToUse:
43 + 'Call `COMPOSIO_MANAGE_CONNECTIONS` when `COMPOSIO_SEARCH_TOOLS` reports that a toolkit has no active connection. You must have an active connection before you execute any tool from that toolkit.',
44 + usageNote:
45 + 'When the tool returns a `redirect_url`, show it to the user as a formatted markdown link and wait for the connection to go active before executing. Set `reinitiate_all` to force a fresh connection when credentials are stale.',
46 + },
47 + COMPOSIO_MULTI_EXECUTE_TOOL: {
48 + summary:
49 + 'Executes up to 50 tools in parallel and returns structured outputs ready for immediate analysis.',
50 + whenToUse:
51 + 'Use `COMPOSIO_MULTI_EXECUTE_TOOL` to run tools that `COMPOSIO_SEARCH_TOOLS` discovered. Batch tools into one call only when they are logically independent, with no ordering or output-to-input dependencies between them.',
52 + usageNote:
53 + 'Pass strictly schema-compliant arguments and make sure each toolkit has an active connection first. Set `sync_response_to_workbench` to true when a response may be large or needed for later scripting; otherwise process small responses inline.',
54 + },
55 + COMPOSIO_REMOTE_WORKBENCH: {
56 + summary:
57 + 'Runs Python in a persistent remote sandbox to process large remote files and script bulk or repeated tool executions.',
58 + whenToUse:
59 + 'Reach for `COMPOSIO_REMOTE_WORKBENCH` when data lives in a remote file rather than inline in the chat, when you need to run a known tool in bulk (for example, label 100 emails), or when you want to call an API via `proxy_execute` because no Composio tool exists for it.',
60 + usageNote:
61 + 'State persists across calls like a Jupyter notebook, and helper functions such as `run_composio_tool` and `invoke_llm` are preloaded. There is a hard 3-minute execution limit per cell, so split work into steps and checkpoint intermediate results to `/mnt/files/`. Do not use it for data you can already see inline.',
62 + },
63 + COMPOSIO_REMOTE_BASH_TOOL: {
64 + summary:
65 + 'Runs bash commands in a remote sandbox for file operations, data processing, and system tasks.',
66 + whenToUse:
67 + 'Use `COMPOSIO_REMOTE_BASH_TOOL` to work with large tool responses that `COMPOSIO_MULTI_EXECUTE_TOOL` saved to remote files, or to run quick file and shell operations with tools like `jq`, `awk`, `sed`, and `grep`.',
68 + usageNote:
69 + 'Commands run from `/home/user` by default and share the same 3-minute execution limit, so break large tasks into smaller commands.',
70 + },
71 +};
72 +
73 +export function getMetaToolOverride(slug: string): MetaToolOverride | undefined {
74 + return META_TOOL_OVERRIDES[slug];
75 +}
docs/lib/meta-tools-data.ts
+13 -1
@@ -1,5 +1,6 @@
1 import { readFile } from 'fs/promises';
2 import { join } from 'path';
3 +import { getMetaToolOverride } from './meta-tool-overrides';
4
5 export interface MetaToolParameter {
6 type: string;
@@ -26,6 +27,10 @@ export interface MetaTool {
27 tags: string[];
28 inputParameters: MetaToolSchema;
29 responseSchema: MetaToolSchema;
30 + /** Hand-written Modal-voice copy, merged over the API data at read time. */
31 + summary?: string;
32 + whenToUse?: string;
33 + usageNote?: string;
34 }
35
36 const META_TOOLS_PATH = join(process.cwd(), 'public/data/meta-tools.json');
@@ -40,6 +45,13 @@ function buildCache(tools: MetaTool[]) {
45 return cached;
46 }
47
48 +/** Merge the hand-written override copy over the API-sourced tool. */
49 +function applyOverride(tool: MetaTool): MetaTool {
50 + const override = getMetaToolOverride(tool.slug);
51 + if (!override) return tool;
52 + return { ...tool, ...override };
53 +}
54 +
55 function parse(data: string): MetaTool[] {
56 const tools = JSON.parse(data) as MetaTool[];
57
@@ -47,7 +59,7 @@ function parse(data: string): MetaTool[] {
59 throw new Error('meta-tools.json must contain an array');
60 }
61
50 - return tools;
62 + return tools.map(applyOverride);
63 }
64
65 export async function getAllMetaTools(): Promise<MetaTool[]> {
docs/lib/search-index.ts
+52 -18
@@ -2,7 +2,7 @@
2 import { createHash } from 'node:crypto';
3 import { existsSync, readdirSync, readFileSync } from 'node:fs';
4 import { join, relative } from 'node:path';
5 -import { docs, reference, cookbooks, toolkits } from 'fumadocs-mdx:collections/server';
5 +import { docs, reference, examples, toolkits } from 'fumadocs-mdx:collections/server';
6 import { loader, multiple } from 'fumadocs-core/source';
7 import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons';
8 import { openapiSource, openapiPlugin } from 'fumadocs-openapi/server';
@@ -20,6 +20,12 @@ const MAX_CHUNK_BYTES = 9_000;
20 const MAX_TOOL_ALIAS_ITEMS = 80;
21 const MAX_TOOL_ALIAS_BYTES = 2_500;
22
23 +// Pages flagged `legacy: true` or `deprecated: true` in frontmatter are pushed to
24 +// the bottom of custom ranking so current content always wins on close matches.
25 +// They stay indexed (an exact-term query still finds them) but never outrank live
26 +// docs. Sits below changelog (300), just above the legacy v3 reference (25).
27 +const LEGACY_PAGE_RANK = 50;
28 +
29 // Create loaders directly here to avoid the problematic lib/source.ts import in the
30 // fallback route. This route is intentionally still Fumadocs/Orama-backed for local
31 // development when Algolia env vars aren't configured.
@@ -29,9 +35,9 @@ const docsSource = loader({
35 plugins: [lucideIconsPlugin()],
36 });
37
32 -const cookbooksSource = loader({
33 - baseUrl: '/cookbooks',
34 - source: cookbooks.toFumadocsSource(),
38 +const examplesSource = loader({
39 + baseUrl: '/examples',
40 + source: examples.toFumadocsSource(),
41 plugins: [lucideIconsPlugin()],
42 });
43
@@ -161,6 +167,16 @@ function contentHash(value: string): string {
167 return createHash('sha1').update(value).digest('hex').slice(0, 10);
168 }
169
170 +// Sections intentionally kept out of search entirely (not just deprioritized).
171 +// Direct tool execution is the legacy pre-sessions flow — we don't want it
172 +// surfacing in results at all. Matches the prefix and anything beneath it.
173 +const SEARCH_EXCLUDED_PREFIXES = ['/docs/tools-direct'];
174 +
175 +function isExcludedFromSearch(url: string): boolean {
176 + const path = url.replace(/\/$/, '');
177 + return SEARCH_EXCLUDED_PREFIXES.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
178 +}
179 +
180 function urlFromContentPath(path: string): { url: string; type: string } | undefined {
181 const rel = relative(join(process.cwd(), 'content'), path).replace(/\\/g, '/');
182 const withoutExt = rel.replace(/\.mdx?$/, '');
@@ -171,8 +187,8 @@ function urlFromContentPath(path: string): { url: string; type: string } | undef
187 if (collection === 'docs') {
188 return { url: `/docs/${parts.join('/')}`.replace(/\/index$/, ''), type: 'docs' };
189 }
174 - if (collection === 'cookbooks') {
175 - return { url: `/cookbooks/${parts.join('/')}`.replace(/\/index$/, ''), type: 'cookbooks' };
190 + if (collection === 'examples') {
191 + return { url: `/examples/${parts.join('/')}`.replace(/\/index$/, ''), type: 'examples' };
192 }
193 if (collection === 'reference') {
194 const url = `/reference/${parts.join('/')}`.replace(/\/index$/, '');
@@ -198,7 +214,7 @@ function slugTokens(url: string): string {
214
215 const typeLabels: Record<string, string> = {
216 docs: 'Docs',
201 - cookbooks: 'Cookbook',
217 + examples: 'Example',
218 reference: 'Reference',
219 'v3-reference': 'Legacy v3 Reference',
220 toolkits: 'Toolkit',
@@ -221,7 +237,7 @@ function titleizeSlug(value: string): string {
237 function breadcrumbsForUrl(url: string, type: string): string[] {
238 const label = typeLabels[type] ?? titleizeSlug(type);
239
224 - if (type === 'toolkits' || type === 'cookbooks' || type === 'changelog') {
240 + if (type === 'toolkits' || type === 'examples' || type === 'changelog') {
241 return [label];
242 }
243
@@ -272,16 +288,24 @@ function pageRank(url: string, type: string): number {
288 // Prefer conceptual docs over generated/reference material when textual
289 // relevance is otherwise close. Toolkit aliases can still win earlier via
290 // searchableAttributes when the query matches a tool name/slug exactly.
291 + //
292 + // Hints use precise path matches against the current (nested) docs structure.
293 + // When pages move, update these — a stale `.includes()` hint silently boosts
294 + // nothing. See content/docs/ for the canonical layout.
295 if (type === 'docs') {
276 - if (url === '/docs' || url === '/docs/') return 2_400;
277 - if (url.includes('/quickstart')) return 2_300;
278 - if (url.includes('/authentication')) return 2_220;
279 - if (url.includes('/tools-and-toolkits')) return 2_180;
280 - if (url.includes('/configuring-sessions')) return 2_120;
296 + const path = url.replace(/\/$/, '');
297 + if (path === '/docs') return 2_400;
298 + if (path === '/docs/quickstart') return 2_300;
299 + if (path === '/docs/how-composio-works') return 2_250;
300 + if (path === '/docs/authentication') return 2_220;
301 + if (path.startsWith('/docs/tools-direct/')) return 2_180;
302 + if (path === '/docs/configuring-sessions') return 2_120;
303 + if (path.startsWith('/docs/auth-configuration/')) return 2_080;
304 + if (path === '/docs/triggers' || path.startsWith('/docs/setting-up-triggers/')) return 2_060;
305 return 2_000;
306 }
307
284 - if (type === 'cookbooks') return 1_500;
308 + if (type === 'examples') return 1_500;
309 if (type === 'toolkits') return 1_250;
310 // Current v3.1 reference should be available, but conceptual docs should
311 // win whenever both match. Legacy v3 reference is only a last-resort result.
@@ -303,7 +327,11 @@ function recordsFromMarkdownPage(input: {
327 tags?: string[];
328 toolNames?: string[];
329 toolSlugs?: string[];
330 + legacy?: boolean;
331 }): AlgoliaDocsRecord[] {
332 + const isLegacy = input.legacy === true;
333 + const resolvedPageRank = isLegacy ? LEGACY_PAGE_RANK : pageRank(input.url, input.type);
334 + const resolvedTags = isLegacy ? [...(input.tags ?? []), 'legacy'] : input.tags;
335 const clean = mdxToCleanMarkdown(input.markdown);
336 const lines = clean.split('\n');
337 const headingSlugs = new Map<string, number>();
@@ -379,8 +407,8 @@ function recordsFromMarkdownPage(input: {
407 tool_slugs: includeToolkitAliases ? input.toolSlugs : undefined,
408 type: input.type,
409 lang: 'en',
382 - tags: input.tags,
383 - page_rank: pageRank(input.url, input.type),
410 + tags: resolvedTags,
411 + page_rank: resolvedPageRank,
412 toolkit_popularity: toolkitPopularity(input.url, input.type),
413 section_rank: sectionRank,
414 position,
@@ -426,6 +454,7 @@ function getFilesystemRecords(): AlgoliaDocsRecord[] {
454 return listContentFiles(contentDir).flatMap((file) => {
455 const route = urlFromContentPath(file);
456 if (!route) return [];
457 + if (isExcludedFromSearch(route.url)) return [];
458
459 const source = readFileSync(file, 'utf8');
460 const frontmatter = getFrontmatter(source);
@@ -436,6 +465,10 @@ function getFilesystemRecords(): AlgoliaDocsRecord[] {
465 ? getToolkitSearchFields(route.url.replace(/^\/toolkits\//, ''))
466 : {};
467
468 + const legacy =
469 + getFrontmatterValue(frontmatter, 'legacy') === 'true' ||
470 + getFrontmatterValue(frontmatter, 'deprecated') === 'true';
471 +
472 return recordsFromMarkdownPage({
473 url: route.url,
474 type: route.type,
@@ -444,6 +477,7 @@ function getFilesystemRecords(): AlgoliaDocsRecord[] {
477 keywords: getFrontmatterList(frontmatter, 'keywords'),
478 markdown: source,
479 breadcrumbs: breadcrumbsForUrl(route.url, route.type),
480 + legacy,
481 ...toolkitFields,
482 });
483 });
@@ -558,10 +592,10 @@ export async function getDocsSearchIndexes(): Promise<SearchIndex[]> {
592
593 const mdxIndexes = [
594 ...docsSource.getPages(),
561 - ...cookbooksSource.getPages(),
595 + ...examplesSource.getPages(),
596 ...toolkitsSource.getPages(),
597 ...fullReferenceSource.getPages(),
564 - ].map((page) => ({
598 + ].filter((page) => !isExcludedFromSearch(page.url)).map((page) => ({
599 id: page.url,
600 title: page.data.title ?? 'Untitled',
601 description: page.data.description,
docs/lib/slack-bot-build.ts new
+398
@@ -0,0 +1,398 @@
1 +/**
2 + * Cumulative stages of the example's files, built up one piece at a time. Each
3 + * stage's `code` is the full file at that point; <FileBuildup> diffs consecutive
4 + * stages so the reader watches the file grow from a basic agent to the full bot.
5 + */
6 +
7 +export interface BuildStage {
8 + title: string;
9 + description: string;
10 + /** Full file contents at this stage. */
11 + code: string;
12 +}
13 +
14 +// ── shared bot.ts parts ─────────────────────────────────────────────────────
15 +
16 +const head1 = `import { Composio } from '@composio/core';
17 +import { PiProvider } from '@composio/experimental';
18 +import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
19 +
20 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
21 +const piProvider = new PiProvider();
22 +`;
23 +
24 +const head2 = `import { Composio } from '@composio/core';
25 +import type { IncomingTriggerPayload } from '@composio/core';
26 +import { PiProvider } from '@composio/experimental';
27 +import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
28 +
29 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
30 +const piProvider = new PiProvider();
31 +const callbackUrl = \`\${process.env.APP_URL}/connections/callback\`;
32 +`;
33 +
34 +const head2Shared = `import { Composio } from '@composio/core';
35 +import type { IncomingTriggerPayload } from '@composio/core';
36 +import { PiProvider } from '@composio/experimental';
37 +import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
38 +
39 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
40 +const piProvider = new PiProvider();
41 +const callbackUrl = \`\${process.env.APP_URL}/connections/callback\`;
42 +
43 +// One Slack connection, shared by the whole workspace. The bot posts as this
44 +// identity while acting in every other app as the individual user.
45 +const SHARED_SLACK_CONNECTION_ID = process.env.SLACK_CONNECTION_ID;
46 +`;
47 +
48 +const runPi = `
49 +// Run the Pi agent over a session's tools and return its final text.
50 +async function runPi(tools: unknown, prompt: string) {
51 + const { session: pi } = await createAgentSession({
52 + sessionManager: SessionManager.inMemory(process.cwd()),
53 + customTools: tools,
54 + tools: ['composio_search_tools', 'composio_manage_connections', 'composio_execute_tool'],
55 + });
56 + let reply = '';
57 + pi.subscribe((e) => {
58 + if (e.type === 'message_update' && e.assistantMessageEvent.type === 'text_delta') {
59 + reply += e.assistantMessageEvent.delta;
60 + }
61 + });
62 + await pi.prompt(prompt);
63 + pi.dispose();
64 + return reply;
65 +}
66 +`;
67 +
68 +const runAgent = `
69 +// The smallest agent: one session, its tools, one prompt.
70 +export async function runAgent(userId: string, prompt: string) {
71 + const session = await composio.create(userId);
72 + const tools = piProvider.createSessionTools({
73 + sessionId: session.sessionId,
74 + search: (params) => session.search(params),
75 + execute: (slug, args, options) => session.execute(slug, args, options),
76 + });
77 + return runPi(tools, prompt);
78 +}
79 +`;
80 +
81 +const memNoPin = `
82 +// One session per Slack thread, reused so the agent keeps context, with a short
83 +// transcript for memory across turns.
84 +const threads = new Map<string, { sessionId: string; history: { role: string; content: string }[] }>();
85 +const threadKey = (event: IncomingTriggerPayload) =>
86 + \`\${event.payload?.channel}:\${event.payload?.thread_ts ?? event.payload?.ts}\`;
87 +
88 +async function sessionForThread(event: IncomingTriggerPayload) {
89 + const key = threadKey(event);
90 + const existing = threads.get(key);
91 + if (existing) return { session: await composio.use(existing.sessionId), memory: existing };
92 +
93 + const session = await composio.create(event.userId, {
94 + manageConnections: { enable: true, callbackUrl, waitForConnections: true },
95 + });
96 + const memory = { sessionId: session.sessionId, history: [] as { role: string; content: string }[] };
97 + threads.set(key, memory);
98 + return { session, memory };
99 +}
100 +`;
101 +
102 +const memPin = `
103 +// One session per Slack thread, reused so the agent keeps context, with a short
104 +// transcript for memory across turns.
105 +const threads = new Map<string, { sessionId: string; history: { role: string; content: string }[] }>();
106 +const threadKey = (event: IncomingTriggerPayload) =>
107 + \`\${event.payload?.channel}:\${event.payload?.thread_ts ?? event.payload?.ts}\`;
108 +
109 +async function sessionForThread(event: IncomingTriggerPayload) {
110 + const key = threadKey(event);
111 + const existing = threads.get(key);
112 + if (existing) return { session: await composio.use(existing.sessionId), memory: existing };
113 +
114 + const session = await composio.create(event.userId, {
115 + // Pin the shared Slack connection; the session still resolves every other
116 + // toolkit against this user's own connections.
117 + connectedAccounts: { slackbot: [SHARED_SLACK_CONNECTION_ID] },
118 + manageConnections: { enable: true, callbackUrl, waitForConnections: true },
119 + });
120 + const memory = { sessionId: session.sessionId, history: [] as { role: string; content: string }[] };
121 + threads.set(key, memory);
122 + return { session, memory };
123 +}
124 +`;
125 +
126 +const proxy = `
127 +// Anything the toolkit doesn't wrap as a tool, reach via the proxy: it calls the
128 +// Slack Web API with the pinned connection's auth, so you never touch a token.
129 +async function setStatus(session, event: IncomingTriggerPayload, status: string) {
130 + await session
131 + .proxyExecute({
132 + toolkit: 'slackbot',
133 + endpoint: 'https://slack.com/api/assistant.threads.setStatus',
134 + method: 'POST',
135 + body: { channel_id: event.payload?.channel, thread_ts: event.payload?.thread_ts, status },
136 + })
137 + .catch(() => {});
138 +}
139 +
140 +async function openDm(session, userId: string): Promise<string> {
141 + const res = await session.proxyExecute({
142 + toolkit: 'slackbot',
143 + endpoint: 'https://slack.com/api/conversations.open',
144 + method: 'POST',
145 + body: { users: userId },
146 + });
147 + return res.data?.channel?.id;
148 +}
149 +`;
150 +
151 +const auth = `
152 +// Redirect auth links. When a tool hits an app the user hasn't connected, the
153 +// result carries a one-time Composio connect URL. Never let the model or the
154 +// channel see it: redact it from the tool output and DM the user privately. The
155 +// session's manageConnections + waitForConnections resumes the run on approval.
156 +const CONNECT_LINK = /https:\\/\\/(?:connect\\.composio\\.dev|[^\\s"']*composio[^\\s"']*\\/link)\\/[^\\s"')]+/gi;
157 +
158 +function redactLinks<T>(value: T): T {
159 + if (typeof value === 'string') return value.replace(CONNECT_LINK, '[connection link sent via DM]') as T;
160 + if (Array.isArray(value)) return value.map(redactLinks) as T;
161 + if (value && typeof value === 'object') {
162 + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactLinks(v)])) as T;
163 + }
164 + return value;
165 +}
166 +
167 +async function handleAuthLinks<T>(session, event: IncomingTriggerPayload, value: T): Promise<T> {
168 + const links = [...new Set([...JSON.stringify(value ?? '').matchAll(CONNECT_LINK)].map((m) => m[0]))];
169 + if (links.length > 0) {
170 + const dm = await openDm(session, event.userId);
171 + for (const url of links) {
172 + await session.execute('SLACKBOT_SEND_MESSAGE', {
173 + channel: dm,
174 + text: \`*Connection needed.* Approve access and I'll continue automatically:\\n<\${url}|Connect>\`,
175 + });
176 + }
177 + }
178 + return redactLinks(value); // hand the model a result with the raw URL stripped
179 +}
180 +`;
181 +
182 +const toolsNoAuth = `
183 +function toolsForSession(session) {
184 + return piProvider.createSessionTools({
185 + sessionId: session.sessionId,
186 + callbackUrl,
187 + search: (params) => session.search(params),
188 + execute: (slug, args, options) => session.execute(slug, args, options),
189 + connections: {
190 + getToolkitStates: (toolkits) => session.toolkits({ toolkits }),
191 + authorizeToolkit: async (toolkit) => {
192 + const request = await session.authorize(toolkit, { callbackUrl });
193 + return { status: 'needs_connection', redirectUrl: request.redirectUrl };
194 + },
195 + isConnected: (state) => state.connection?.isActive ?? false,
196 + },
197 + });
198 +}
199 +`;
200 +
201 +const toolsAuth = `
202 +function toolsForSession(session, event: IncomingTriggerPayload) {
203 + return piProvider.createSessionTools({
204 + sessionId: session.sessionId,
205 + callbackUrl,
206 + search: (params) => session.search(params),
207 + // Every tool result passes through handleAuthLinks: connect URLs get DM'd to
208 + // the user and redacted before the model ever sees them.
209 + execute: async (slug, args, options) => handleAuthLinks(session, event, await session.execute(slug, args, options)),
210 + connections: {
211 + getToolkitStates: (toolkits) => session.toolkits({ toolkits }),
212 + authorizeToolkit: async (toolkit) => {
213 + const request = await session.authorize(toolkit, { callbackUrl });
214 + await handleAuthLinks(session, event, request.redirectUrl);
215 + return { status: 'needs_connection', redirectUrl: request.redirectUrl };
216 + },
217 + isConnected: (state) => state.connection?.isActive ?? false,
218 + },
219 + });
220 +}
221 +`;
222 +
223 +const handleNoStatus = `
224 +// Reply to one Slack message as the user who sent it.
225 +async function handleSlackMessage(event: IncomingTriggerPayload) {
226 + const { session, memory } = await sessionForThread(event);
227 + const prompt = [...memory.history.map((m) => \`\${m.role}: \${m.content}\`), \`user: \${event.payload?.text}\`].join('\\n');
228 +
229 + const reply = await runPi(toolsForSession(session), prompt);
230 +
231 + await session.execute('SLACKBOT_SEND_MESSAGE', {
232 + channel: event.payload?.channel,
233 + thread_ts: event.payload?.thread_ts,
234 + text: reply,
235 + });
236 + memory.history.push({ role: 'user', content: event.payload?.text ?? '' }, { role: 'assistant', content: reply });
237 +}
238 +`;
239 +
240 +const handleStatus = `
241 +// Reply to one Slack message as the user who sent it.
242 +async function handleSlackMessage(event: IncomingTriggerPayload) {
243 + const { session, memory } = await sessionForThread(event);
244 + await setStatus(session, event, 'Working on it…');
245 +
246 + const prompt = [...memory.history.map((m) => \`\${m.role}: \${m.content}\`), \`user: \${event.payload?.text}\`].join('\\n');
247 + const reply = await runPi(toolsForSession(session, event), prompt);
248 +
249 + await session.execute('SLACKBOT_SEND_MESSAGE', {
250 + channel: event.payload?.channel,
251 + thread_ts: event.payload?.thread_ts,
252 + text: reply,
253 + });
254 + memory.history.push({ role: 'user', content: event.payload?.text ?? '' }, { role: 'assistant', content: reply });
255 +}
256 +`;
257 +
258 +// handleStatus calls toolsForSession(session, event); for the proxy stage (before
259 +// auth) toolsForSession still takes one arg, so use a variant without the event.
260 +const handleStatusNoAuth = handleStatus.replace('toolsForSession(session, event)', 'toolsForSession(session)');
261 +
262 +const serve = `
263 +Bun.serve({
264 + port: 3000,
265 + async fetch(req) {
266 + const url = new URL(req.url);
267 + if (req.method === 'POST' && url.pathname === '/webhooks/composio') {
268 + const { payload } = await composio.triggers.verifyWebhook({
269 + payload: await req.text(),
270 + secret: process.env.COMPOSIO_WEBHOOK_SECRET,
271 + id: req.headers.get('webhook-id'),
272 + timestamp: req.headers.get('webhook-timestamp'),
273 + signature: req.headers.get('webhook-signature'),
274 + });
275 + void handleSlackMessage(payload);
276 + return Response.json({ ok: true });
277 + }
278 + return new Response('Not found', { status: 404 });
279 + },
280 +});
281 +`;
282 +
283 +const BOT_STAGES: { title: string; description: string; parts: string[] }[] = [
284 + {
285 + title: 'A basic agent',
286 + description:
287 + 'Start from scratch. The smallest possible agent: create a session for a user, hand the Pi provider the session so it can search and execute, run a prompt. This already works against every app that user has connected, with no Slack yet.',
288 + parts: [head1, runPi, runAgent],
289 + },
290 + {
291 + title: 'Wire it to Slack threads',
292 + description:
293 + 'Turn the one-shot agent into a handler. Each Slack thread gets its own session (reused for memory), the agent runs over the session tools, and the reply is posted with the SLACKBOT_SEND_MESSAGE tool.',
294 + parts: [head2, memNoPin, toolsNoAuth, runPi, handleNoStatus],
295 + },
296 + {
297 + title: 'Share one workspace connection',
298 + description:
299 + 'Pin a single SHARED Slack connection into every session. Now the bot posts as the workspace bot, but still acts in GitHub, Gmail, and everything else as the individual user.',
300 + parts: [head2Shared, memPin, toolsNoAuth, runPi, handleNoStatus],
301 + },
302 + {
303 + title: 'Reach the gaps with the proxy',
304 + description:
305 + 'Add a typing indicator and a DM-channel opener. Neither has a SLACKBOT_* tool, so they drop down to the proxy, which calls the Slack Web API with the pinned connection.',
306 + parts: [head2Shared, memPin, proxy, toolsNoAuth, runPi, handleStatusNoAuth],
307 + },
308 + {
309 + title: 'Redirect auth links',
310 + description:
311 + 'The payoff. When the agent touches an app the user has not connected, the tool result carries a one-time connect URL. Redact it from the model and the channel, DM it to the user privately, and let the run resume on approval.',
312 + parts: [head2Shared, memPin, proxy, auth, toolsAuth, runPi, handleStatus],
313 + },
314 + {
315 + title: 'Serve the webhook',
316 + description:
317 + 'Verify each trigger signature and dispatch the work off the response path. This is the whole server.',
318 + parts: [head2Shared, memPin, proxy, auth, toolsAuth, runPi, handleStatus, serve],
319 + },
320 +];
321 +
322 +export const BOT_BUILD_STAGES: BuildStage[] = BOT_STAGES.map((s) => ({
323 + title: s.title,
324 + description: s.description,
325 + code: s.parts.join('').replace(/^\n/, ''),
326 +}));
327 +
328 +// ── install.ts ──────────────────────────────────────────────────────────────
329 +
330 +const installAuth = `import { Composio } from '@composio/core';
331 +
332 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
333 +
334 +// The scopes the bot needs. The slackbot toolkit ships Composio-managed OAuth,
335 +// so you never register your own Slack app.
336 +const authConfig = await composio.authConfigs.create('slackbot', {
337 + type: 'use_composio_managed_auth',
338 + name: 'workspace-bot',
339 + credentials: {
340 + scopes: ['app_mentions:read', 'channels:history', 'chat:write', 'reactions:write', 'users:read'],
341 + user_scopes: ['search:read'],
342 + },
343 +});
344 +`;
345 +
346 +const installAuthorize = `
347 +// One connection for the whole workspace: authorize it as SHARED.
348 +const setup = await composio.create('setup:workspace-bot', {
349 + toolkits: ['slackbot'],
350 + authConfigs: { slackbot: authConfig.id },
351 + manageConnections: true,
352 +});
353 +const request = await setup.authorize('slackbot', {
354 + callbackUrl: \`\${process.env.APP_URL}/setup/callback\`,
355 + experimental: { accountType: 'SHARED' },
356 +});
357 +console.log('Approve the install:', request.redirectUrl);
358 +`;
359 +
360 +const installWire = `
361 +// On the OAuth callback: open the ACL, subscribe your webhook, create triggers.
362 +// Persist connectedAccountId as SLACK_CONNECTION_ID for the bot server.
363 +export async function onSetupCallback(connectedAccountId: string) {
364 + await composio.connectedAccounts.updateAcl(connectedAccountId, { allowAllUsers: true });
365 + await composio.triggers.setWebhookSubscription({ webhookUrl: \`\${process.env.APP_URL}/webhooks/composio\` });
366 + await composio.triggers.create('setup:workspace-bot', 'SLACKBOT_CHANNEL_MESSAGE_RECEIVED', { triggerConfig: { is_bot_message: false } });
367 + await composio.triggers.create('setup:workspace-bot', 'SLACKBOT_DIRECT_MESSAGE_RECEIVED', { triggerConfig: {} });
368 +}
369 +`;
370 +
371 +const INSTALL_STAGES: { title: string; description: string; parts: string[] }[] = [
372 + {
373 + title: 'Declare the scopes',
374 + description: 'Create a Composio-managed auth config for the slackbot toolkit. No Slack app of your own to register.',
375 + parts: [installAuth],
376 + },
377 + {
378 + title: 'Authorize one shared connection',
379 + description: 'Start a setup session and authorize slackbot as a SHARED connection, so a single approval serves every user.',
380 + parts: [installAuth, installAuthorize],
381 + },
382 + {
383 + title: 'Open it up and wire events',
384 + description: 'On the callback, open the ACL to the workspace, subscribe your webhook, and create the message triggers.',
385 + parts: [installAuth, installAuthorize, installWire],
386 + },
387 +];
388 +
389 +export const INSTALL_BUILD_STAGES: BuildStage[] = INSTALL_STAGES.map((s) => ({
390 + title: s.title,
391 + description: s.description,
392 + code: s.parts.join(''),
393 +}));
394 +
395 +export const FILE_BUILDS: Record<string, { file: string; stages: BuildStage[] }> = {
396 + install: { file: 'install.ts', stages: INSTALL_BUILD_STAGES },
397 + bot: { file: 'bot.ts', stages: BOT_BUILD_STAGES },
398 +};
docs/lib/slack-bot-source.json new
+42
@@ -0,0 +1,42 @@
1 +[
2 +{
3 +"path": "src/index.ts",
4 +"composio": false,
5 +"contents": "import { Composio } from '@composio/core';\n\nimport { createAuthCallbackHandler } from './api/auth-callback';\nimport { createComposioWebhookHandler } from './api/composio-webhook';\nimport { createApiHandler } from './api/router';\nimport { createSlackComposioAgent } from './agent/slack-composio-agent';\nimport { createSlackbotSetupService } from './composio/slackbot-setup';\nimport { loadConfig } from './config/env';\nimport { createSlackTransport } from './slack/transport';\nimport { createFileStore } from './store/file-store';\n\nconst config = loadConfig();\nconst store = await createFileStore(config.dataDir);\nconst composio = new Composio({ apiKey: config.composioApiKey });\nconst slack = createSlackTransport({ config, store });\nconst agent = createSlackComposioAgent({ config, slack, store });\nconst slackbotSetup = createSlackbotSetupService({ composio, config, store });\nconst composioWebhook = createComposioWebhookHandler({ agent, config, store });\nconst authCallback = createAuthCallbackHandler({ agent, slack, store });\n\nconst server = Bun.serve({\n hostname: config.host,\n port: config.port,\n fetch: createApiHandler({ authCallback, composioWebhook, slackbotSetup }),\n});\n\nconsole.log(`Composio Slack Pi bot listening on http://${server.hostname}:${server.port}`);\nconsole.log(`Setup URL: ${config.appUrl}/setup/slackbot/start`);\n\n"
6 +},
7 +{
8 +"path": "src/config/env.ts",
9 +"composio": false,
10 +"contents": "import 'dotenv/config';\nimport { join } from 'node:path';\n\nconst DEFAULT_SLACKBOT_BOT_SCOPES = [\n 'app_mentions:read',\n 'assistant:write',\n 'channels:history',\n 'channels:read',\n 'chat:write',\n 'files:read',\n 'files:write',\n 'groups:history',\n 'groups:read',\n 'im:history',\n 'im:read',\n 'im:write',\n 'links:read',\n 'links:write',\n 'mpim:history',\n 'mpim:read',\n 'mpim:write',\n 'reactions:read',\n 'reactions:write',\n 'team:read',\n 'users:read',\n];\n\nconst DEFAULT_SLACKBOT_USER_SCOPES = [\n 'channels:history',\n 'channels:read',\n 'files:read',\n 'groups:history',\n 'groups:read',\n 'im:history',\n 'im:read',\n 'mpim:history',\n 'mpim:read',\n 'reactions:read',\n 'search:read',\n 'search:read.public',\n 'users.profile:read',\n 'users:read',\n 'users:read.email',\n];\n\nexport interface AppConfig {\n appUrl: string;\n composioApiKey: string;\n composioToolkits?: string[];\n composioAuthConfigs?: Record<string, string>;\n autoAnalyzeMainUserMessages: boolean;\n autoPromoteFirstMainUser: boolean;\n composioWorkbenchEnabled: boolean;\n dataDir: string;\n host: string;\n piCwd: string;\n ignoreReactionName: string;\n mainSlackUserIds: string[];\n piWorkbenchEnabled: boolean;\n port: number;\n postPublicAuthDmNotice: boolean;\n slackBotUserId?: string;\n slackbotAuthConfigId?: string;\n slackbotAuthConfigName: string;\n slackbotBotScopes: string[];\n slackbotSharedConnectedAccountId?: string;\n slackbotTransportUserId?: string;\n slackbotUserScopes: string[];\n}\n\nfunction requiredEnv(name: string): string {\n const value = process.env[name];\n if (!value || value.trim().length === 0) {\n throw new Error(`Missing required environment variable ${name}`);\n }\n return value.trim();\n}\n\nfunction optionalList(name: string): string[] | undefined {\n return optionalRawList(name)?.map((value) => value.toLowerCase());\n}\n\nfunction optionalRawList(name: string): string[] | undefined {\n const raw = process.env[name];\n if (!raw) return undefined;\n\n const values = raw\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean);\n\n return values.length > 0 ? values : undefined;\n}\n\nfunction booleanEnv(name: string, defaultValue: boolean): boolean {\n const raw = process.env[name];\n if (!raw) return defaultValue;\n return ['1', 'true', 'yes', 'y', 'on'].includes(raw.trim().toLowerCase());\n}\n\nfunction numberEnv(name: string, defaultValue: number): number {\n const raw = process.env[name];\n if (!raw) return defaultValue;\n\n const value = Number(raw);\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid numeric environment variable ${name}: ${raw}`);\n }\n return value;\n}\n\nfunction optionalEnv(name: string): string | undefined {\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction parseAuthConfigs(): Record<string, string> | undefined {\n const configs: Record<string, string> = {};\n\n const json = process.env.COMPOSIO_AUTH_CONFIGS_JSON;\n if (json && json.trim() && json.trim() !== '{}') {\n const parsed = JSON.parse(json) as Record<string, unknown>;\n for (const [toolkit, authConfigId] of Object.entries(parsed)) {\n if (typeof authConfigId === 'string' && authConfigId.trim()) {\n configs[toolkit.toLowerCase()] = authConfigId.trim();\n }\n }\n }\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!key.startsWith('COMPOSIO_AUTH_CONFIG_') || key === 'COMPOSIO_AUTH_CONFIGS_JSON') {\n continue;\n }\n if (!value || !value.trim()) continue;\n\n const toolkit = key\n .slice('COMPOSIO_AUTH_CONFIG_'.length)\n .toLowerCase()\n .replaceAll('__', '-')\n .replaceAll('_', '');\n\n configs[toolkit] = value.trim();\n }\n\n return Object.keys(configs).length > 0 ? configs : undefined;\n}\n\nexport function loadConfig(): AppConfig {\n const port = numberEnv('PORT', 3000);\n const rawAppUrl = optionalEnv('APP_URL');\n const appUrl = (!rawAppUrl || rawAppUrl.includes('your-public-url.example.com')\n ? `http://localhost:${port}`\n : rawAppUrl\n ).replace(/\\/$/, '');\n const dataDir = process.env.DATA_DIR?.trim() || '.data';\n const piWorkbenchEnabled = booleanEnv('PI_LOCAL_WORKBENCH_ENABLED', false);\n\n return {\n appUrl,\n autoAnalyzeMainUserMessages: booleanEnv('AUTO_ANALYZE_MAIN_USER_MESSAGES', true),\n autoPromoteFirstMainUser: booleanEnv('AUTO_PROMOTE_FIRST_MAIN_USER', true),\n composioApiKey: requiredEnv('COMPOSIO_API_KEY'),\n composioToolkits: optionalList('COMPOSIO_TOOLKITS'),\n composioAuthConfigs: parseAuthConfigs(),\n composioWorkbenchEnabled: booleanEnv('COMPOSIO_WORKBENCH_ENABLED', true),\n dataDir,\n host: process.env.HOST?.trim() || '0.0.0.0',\n ignoreReactionName: process.env.IGNORE_REACTION_NAME?.trim() || 'ignore',\n mainSlackUserIds: optionalRawList('MAIN_SLACK_USER_IDS') ?? [],\n piCwd: process.env.PI_CWD?.trim() || (piWorkbenchEnabled ? join(dataDir, 'pi-local-workbench') : process.cwd()),\n piWorkbenchEnabled,\n port,\n postPublicAuthDmNotice: booleanEnv('POST_PUBLIC_AUTH_DM_NOTICE', true),\n slackBotUserId: optionalEnv('SLACK_BOT_USER_ID'),\n slackbotAuthConfigId: optionalEnv('SLACKBOT_AUTH_CONFIG_ID'),\n slackbotAuthConfigName: optionalEnv('SLACKBOT_AUTH_CONFIG_NAME') ?? 'slackbot-expanded-scopes',\n slackbotBotScopes: optionalRawList('SLACKBOT_BOT_SCOPES') ?? DEFAULT_SLACKBOT_BOT_SCOPES,\n slackbotSharedConnectedAccountId: optionalEnv('SLACKBOT_SHARED_CONNECTED_ACCOUNT_ID'),\n slackbotTransportUserId: optionalEnv('SLACKBOT_TRANSPORT_USER_ID'),\n slackbotUserScopes: optionalRawList('SLACKBOT_USER_SCOPES') ?? DEFAULT_SLACKBOT_USER_SCOPES,\n };\n}\n"
11 +},
12 +{
13 +"path": "src/composio/slackbot-setup.ts",
14 +"composio": true,
15 +"contents": "import { createHash, randomUUID } from 'node:crypto';\n\nimport { Composio } from '@composio/core';\n\nimport { jsonResponse } from '../api/http';\nimport type { AppConfig } from '../config/env';\nimport { htmlPages } from '../html/pages';\nimport { htmlFileResponse, htmlTemplateResponse } from '../html/render';\nimport { proxySlack } from '../slack/transport';\nimport type { Store } from '../store/file-store';\nimport { firstString, jsonObject } from '../utils/decode';\nimport type { JsonObject, JsonValue } from '../utils/json';\nimport { createComposioApiClient } from './api';\n\ntype ComposioSession = Awaited<ReturnType<Composio['create']>>;\n\ninterface SharedSlackbotAuthorizeOptions {\n callbackUrl: string;\n experimental: {\n accountType: 'SHARED';\n };\n}\n\ninterface SlackbotSetupDeps {\n composio: Composio;\n config: AppConfig;\n store: Store;\n}\n\nexport interface SlackbotSetupService {\n completeSetup(url: URL): Promise<Response>;\n ensureSlackbotAuthConfig(): Promise<string | undefined>;\n ensureSlackbotTriggers(connectedAccountId: string): Promise<void>;\n ensureWebhookSubscription(): Promise<void>;\n startSetup(): Promise<Response>;\n}\n\n/**\n * Owns the install-time Slackbot plumbing:\n * - create/reuse a managed Slackbot auth config with the requested scopes\n * - request a shared Slackbot connection\n * - persist the team-scoped connected account\n * - ensure Composio webhook subscription + Slackbot triggers exist\n */\nexport function createSlackbotSetupService({ composio, config, store }: SlackbotSetupDeps): SlackbotSetupService {\n const composioApi = createComposioApiClient(config);\n\n const ensureSlackbotAuthConfig = async (): Promise<string | undefined> => {\n if (config.slackbotAuthConfigId) {\n return config.slackbotAuthConfigId;\n }\n\n const botScopes = uniqueSorted(config.slackbotBotScopes);\n const userScopes = uniqueSorted(config.slackbotUserScopes);\n if (botScopes.length === 0 && userScopes.length === 0) {\n return undefined;\n }\n\n const name = slackbotAuthConfigName(config, botScopes, userScopes);\n const existing = await composio.authConfigs.list({ toolkit: 'slackbot', isComposioManaged: true, limit: 100 });\n const match = authConfigItems(existing).find((item) => item.name === name);\n if (match?.id) {\n return match.id;\n }\n\n const created = await composio.authConfigs.create('slackbot', {\n type: 'use_composio_managed_auth',\n name,\n credentials: {\n scopes: botScopes,\n user_scopes: userScopes,\n },\n });\n console.log(`Created Slackbot Composio auth config ${created.id} (${name})`);\n return created.id;\n };\n\n const ensureWebhookSubscription = async (): Promise<void> => {\n const webhookUrl = `${config.appUrl}/webhooks/composio`;\n const body = {\n webhook_url: webhookUrl,\n enabled_events: ['composio.trigger.message'],\n version: 'V3',\n };\n\n const existing = await composioApi.request('/api/v3.1/webhook_subscriptions', { method: 'GET' });\n const subscription = firstObjectItem(existing?.items);\n const subscriptionId = firstString(subscription?.id);\n\n if (subscriptionId) {\n await composioApi.request(`/api/v3.1/webhook_subscriptions/${subscriptionId}`, {\n method: 'PATCH',\n body,\n });\n return;\n }\n\n await composioApi.request('/api/v3.1/webhook_subscriptions', {\n method: 'POST',\n body,\n });\n };\n\n const ensureSlackbotTriggers = async (connectedAccountId: string): Promise<void> => {\n const connectedAccount = await composioApi.request(`/api/v3/connected_accounts/${connectedAccountId}`, { method: 'GET' });\n const ownerUserId = firstString(connectedAccount?.user_id);\n if (!ownerUserId) {\n throw new Error(`Could not determine owner user_id for connected account ${connectedAccountId}`);\n }\n\n await upsertTrigger(composioApi.request, 'SLACKBOT_CHANNEL_MESSAGE_RECEIVED', connectedAccountId, ownerUserId, {\n is_bot_message: false,\n });\n\n await upsertTrigger(composioApi.request, 'SLACKBOT_DIRECT_MESSAGE_RECEIVED', connectedAccountId, ownerUserId, {});\n };\n\n const startSetup = async (): Promise<Response> => {\n const setupId = randomUUID();\n const setupUserId = `setup:slackbot:${setupId}`;\n const authConfigId = await ensureSlackbotAuthConfig();\n const session = await composio.create(setupUserId, {\n toolkits: ['slackbot'],\n authConfigs: authConfigId ? { slackbot: authConfigId } : {},\n manageConnections: true,\n workbench: { enable: false },\n });\n await store.setSlackbotSetup(setupId, session.sessionId, setupUserId);\n\n const connectionRequest = await session.authorize('slackbot', sharedSlackbotAuthorizeOptions(config, setupId));\n if (!connectionRequest.redirectUrl) {\n return jsonResponse({ ok: false, error: 'missing_redirect_url' }, 500);\n }\n\n return Response.redirect(connectionRequest.redirectUrl, 302);\n };\n\n const completeSetup = async (url: URL): Promise<Response> => {\n const setupId = url.searchParams.get('setup');\n const connectedAccountId = url.searchParams.get('connected_account_id');\n const status = url.searchParams.get('status');\n const setup = setupId ? store.getSlackbotSetup(setupId) : undefined;\n\n if (!setupId || !setup) {\n return htmlFileResponse(htmlPages.slackbotSetupExpired, 400);\n }\n\n if (!connectedAccountId || status !== 'success') {\n return htmlFileResponse(htmlPages.slackbotSetupFailed, 400);\n }\n\n const setupSession = await composio.use(setup.sessionId);\n await setupSession.update({ connectedAccounts: { slackbot: [connectedAccountId] } });\n const slackAuth = await slackAuthTest(setupSession);\n const teamId = slackAuth.teamId;\n await composio.experimental.updateAcl(connectedAccountId, { allowAllUsers: true });\n\n await store.setSlackbotConnection(teamId, connectedAccountId, {\n botUserId: slackAuth.botUserId,\n teamName: slackAuth.teamName,\n });\n await store.deleteSlackbotSetup(setupId);\n\n await ensureWebhookSubscription().catch((error) => {\n console.error('Failed to configure Composio webhook subscription after setup', error);\n });\n await ensureSlackbotTriggers(connectedAccountId).catch((error) => {\n console.error('Failed to create Slackbot triggers after setup', error);\n });\n\n return htmlTemplateResponse(htmlPages.slackbotConnected, { teamName: slackAuth.teamName ?? teamId });\n };\n\n return {\n completeSetup,\n ensureSlackbotAuthConfig,\n ensureSlackbotTriggers,\n ensureWebhookSubscription,\n startSetup,\n };\n}\n\nfunction sharedSlackbotAuthorizeOptions(config: AppConfig, setupId: string): SharedSlackbotAuthorizeOptions {\n const callbackUrl = new URL('/setup/slackbot/callback', config.appUrl);\n callbackUrl.searchParams.set('setup', setupId);\n\n return {\n callbackUrl: callbackUrl.toString(),\n experimental: {\n accountType: 'SHARED',\n },\n };\n}\n\nfunction slackbotAuthConfigName(config: AppConfig, botScopes: string[], userScopes: string[]): string {\n const scopeHash = createHash('sha256')\n .update(JSON.stringify({ botScopes, userScopes }))\n .digest('hex')\n .slice(0, 8);\n return `${config.slackbotAuthConfigName}-${scopeHash}`;\n}\n\nasync function slackAuthTest(session: ComposioSession): Promise<{ botUserId?: string; teamId: string; teamName?: string }> {\n return decodeSlackAuthTest(await proxySlack(session, 'auth.test', {}));\n}\n\nfunction decodeSlackAuthTest(response: unknown): { botUserId?: string; teamId: string; teamName?: string } {\n const responseObject = jsonObject(response) ?? {};\n const data = jsonObject(responseObject.data) ?? responseObject;\n const nestedData = jsonObject(data.data);\n\n if (data.ok === false) {\n throw new Error(`Slack auth.test failed: ${firstString(data.error) ?? JSON.stringify(data)}`);\n }\n\n const teamId = firstString(data.team_id, data.teamId, nestedData?.team_id, nestedData?.teamId);\n if (!teamId) {\n throw new Error(`Slack auth.test did not return team_id: ${JSON.stringify(data)}`);\n }\n\n return {\n botUserId: firstString(data.user_id, data.userId, data.bot_user_id, data.botUserId, nestedData?.user_id),\n teamId,\n teamName: firstString(data.team, data.team_name, data.teamName, nestedData?.team),\n };\n}\n\nfunction authConfigItems(value: unknown): Array<{ id?: string; name?: string }> {\n const record = jsonObject(value) ?? {};\n const items = Array.isArray(record.items) ? record.items : [];\n return items.flatMap((item): Array<{ id?: string; name?: string }> => {\n const object = jsonObject(item);\n if (!object) return [];\n return [\n {\n id: firstString(object.id),\n name: firstString(object.name),\n },\n ];\n });\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter(Boolean))].sort();\n}\n\nfunction firstObjectItem(value: JsonValue | undefined): JsonObject | undefined {\n return Array.isArray(value) ? jsonObject(value[0]) : undefined;\n}\n\nasync function upsertTrigger(\n request: (path: string, init: { method: string; body?: JsonValue }) => Promise<JsonObject | undefined>,\n slug: string,\n connectedAccountId: string,\n userId: string,\n triggerConfig: JsonObject,\n): Promise<void> {\n await request(`/api/v3/trigger_instances/${slug}/upsert`, {\n method: 'POST',\n body: {\n connected_account_id: connectedAccountId,\n user_id: userId,\n trigger_config: triggerConfig,\n },\n });\n}\n"
16 +},
17 +{
18 +"path": "src/composio/routing-with-pi-provider.ts",
19 +"composio": true,
20 +"contents": "import { Composio } from '@composio/core';\nimport { PiProvider, type PiSessionToolCapabilities } from '@composio/experimental';\n\nimport {\n authCallbackUrl,\n isSlackbotToolkit,\n isSlackbotToolSlug,\n isUserSlackToolSlug,\n normalizeRequestedToolkits,\n normalizeSearchToolkits,\n normalizeToolkitKey,\n normalizeToolkitStates,\n toolkitIsConnected,\n} from './helpers';\nimport type { AppConfig } from '../config/env';\nimport { assertSlackbotManualAcl } from '../slack/acl';\nimport type { NormalizedSlackTriggerEvent } from '../slack/events';\nimport type { Store } from '../store/file-store';\nimport type { JsonObject } from '../utils/json';\nimport type { ComposioRouting } from './routing';\n\ntype ComposioSession = Awaited<ReturnType<Composio['create']>>;\ntype HandleAuthLinks = <T>(value: T, sourceTool: string, requestedToolkits?: string[]) => Promise<T>;\n\ninterface ComposioRoutingWithPiProviderDeps {\n composio: Composio;\n config: AppConfig;\n store: Store;\n}\n\ninterface CapabilityDeps {\n config: AppConfig;\n event: NormalizedSlackTriggerEvent;\n handleAuthLinks: HandleAuthLinks;\n userSession: ComposioSession;\n}\n\nconst piProvider = new PiProvider();\n\n/**\n * Side-by-side experiment for using @composio/experimental's Pi provider.\n *\n * This uses the newer capability API rather than a fake session adapter:\n * app code owns search normalization, execution policy, connection state,\n * authorization, auth-link routing, and Slackbot shared-connection ACLs.\n */\nexport function createComposioRoutingWithPiProvider({\n composio,\n config,\n store,\n}: ComposioRoutingWithPiProviderDeps): ComposioRouting {\n const getOrCreateUserSession = async (\n event: NormalizedSlackTriggerEvent,\n userId: string,\n threadKey: string,\n ): Promise<ComposioSession> => {\n const slackbotConnectedAccountId = slackbotConnectedAccountIdForEvent(config, store, event);\n const existing = store.getThreadSession(threadKey);\n if (existing) {\n const session = await composio.use(existing.sessionId);\n await pinSlackbotConnectionIfAllowed(config, event, session, existing.userId, slackbotConnectedAccountId);\n return session;\n }\n\n if (slackbotConnectedAccountId) {\n assertSlackbotManualAcl(event, userId);\n }\n\n const session = await composio.sessions.create(userId, {\n manageConnections: {\n enable: true,\n callbackUrl: authCallbackUrl(config, event),\n waitForConnections: true,\n },\n workbench: {\n enable: config.composioWorkbenchEnabled,\n },\n ...(config.composioToolkits ? { toolkits: withSlackbotToolkit(config.composioToolkits, slackbotConnectedAccountId) } : {}),\n ...(config.composioAuthConfigs ? { authConfigs: config.composioAuthConfigs } : {}),\n ...(slackbotConnectedAccountId\n ? {\n connectedAccounts: {\n slackbot: [slackbotConnectedAccountId],\n },\n }\n : {}),\n });\n\n await store.setThreadSession(threadKey, session.sessionId, userId);\n return session;\n };\n\n const createPiComposioTools: ComposioRouting['createPiComposioTools'] = (event, userSession, handleAuthLinks) =>\n piProvider.createSessionTools(createPiCapabilities({ config, event, handleAuthLinks, userSession }));\n\n return {\n createPiComposioTools,\n getOrCreateUserSession,\n };\n}\n\nfunction createPiCapabilities({ config, event, handleAuthLinks, userSession }: CapabilityDeps): PiSessionToolCapabilities {\n const callbackUrl = authCallbackUrl(config, event);\n const includeWorkbenchTools = config.composioWorkbenchEnabled;\n\n return {\n callbackUrl,\n includeWorkbenchTools,\n sessionId: userSession.sessionId,\n search: (params) =>\n userSession.search({\n query: params.query,\n ...(params.toolkits ? { toolkits: params.toolkits } : {}),\n }),\n execute: async (toolSlug, args, options) => {\n if (isSlackbotToolSlug(toolSlug)) {\n assertSlackbotManualAcl(event, slackUserComposioId(event));\n }\n\n return userSession.execute(toolSlug, args, {\n ...(options?.account ? { account: options.account } : {}),\n });\n },\n connections: {\n getToolkitStates: async (toolkits) => {\n const normalizedToolkits = normalizeRequestedToolkits(toolkits) ?? [];\n const userToolkits = normalizedToolkits.filter(isUserAuthToolkit);\n const userStates = userToolkits.length > 0 ? normalizeToolkitStates(await userSession.toolkits({ toolkits: userToolkits })) : [];\n return {\n items: [\n ...normalizedToolkits.filter((toolkit) => !isUserAuthToolkit(toolkit)).map(syntheticConnectedToolkitState),\n ...userStates,\n ],\n };\n },\n authorizeToolkit: async (toolkit) => {\n if (!isUserAuthToolkit(toolkit)) {\n return slackbotAlreadyConnectedResult([toolkit]);\n }\n\n const request = await userSession.authorize(toolkit, { callbackUrl });\n return {\n status: 'needs_connection',\n redirectUrl: request.redirectUrl ?? null,\n };\n },\n isConnected: (state) => toolkitIsConnectedFromUnknown(state),\n },\n hooks: {\n search: (context, next) => {\n context.request.toolkits = normalizeSearchToolkits(context.request.toolkits) ?? undefined;\n return next();\n },\n execute: (context, next) => {\n const trimmedSlug = context.request.toolSlug.trim();\n\n if (isUserSlackToolSlug(trimmedSlug)) {\n return context.deny(USE_SLACKBOT_INSTEAD_ERROR);\n }\n\n if (trimmedSlug === 'COMPOSIO_MANAGE_CONNECTIONS') {\n return context.deny(USE_DEDICATED_MANAGE_CONNECTIONS_ERROR);\n }\n\n if (isSlackbotToolSlug(trimmedSlug)) {\n assertSlackbotManualAcl(event, slackUserComposioId(event));\n }\n\n context.request.toolSlug = trimmedSlug;\n return next();\n },\n onAuthLink: (context) => handleAuthLinks(context.result, context.sourceTool, context.toolkit ? [context.toolkit] : undefined),\n },\n transformResult: async ({ value, tool, requestedToolkits, context }) => {\n const sourceTool = context?.sourceTool ?? providerToolName(tool);\n return handleAuthLinks(value, sourceTool, requestedToolkits);\n },\n };\n}\n\nasync function pinSlackbotConnectionIfAllowed(\n config: AppConfig,\n event: NormalizedSlackTriggerEvent,\n session: ComposioSession,\n userId: string,\n slackbotConnectedAccountId: string | undefined,\n): Promise<void> {\n if (!slackbotConnectedAccountId) return;\n\n assertSlackbotManualAcl(event, userId);\n await session.update({\n ...(config.composioToolkits ? { toolkits: withSlackbotToolkit(config.composioToolkits, slackbotConnectedAccountId) } : {}),\n connectedAccounts: {\n slackbot: [slackbotConnectedAccountId],\n },\n });\n}\n\nfunction slackbotConnectedAccountIdForEvent(\n config: AppConfig,\n store: Store,\n event: NormalizedSlackTriggerEvent,\n): string | undefined {\n return config.slackbotSharedConnectedAccountId ?? store.getSlackbotConnection(event.teamId)?.connectedAccountId ?? event.connectedAccountId;\n}\n\nfunction withSlackbotToolkit(toolkits: string[], slackbotConnectedAccountId: string | undefined): string[] {\n if (!slackbotConnectedAccountId || toolkits.includes('slackbot')) return toolkits;\n return [...toolkits, 'slackbot'];\n}\n\nfunction isUserAuthToolkit(toolkit: string): boolean {\n const normalized = normalizeToolkitKey(toolkit);\n return Boolean(normalized && normalized !== 'slack' && normalized !== 'slackbot');\n}\n\nfunction syntheticConnectedToolkitState(toolkit: string): JsonObject {\n return {\n slug: normalizeToolkitKey(toolkit) === 'slack' ? 'slackbot' : toolkit,\n isNoAuth: true,\n connection: {\n isActive: true,\n connectedAccount: {\n status: 'ACTIVE',\n },\n },\n };\n}\n\nfunction toolkitIsConnectedFromUnknown(value: unknown): boolean {\n const states = normalizeToolkitStates({ items: [value] });\n return toolkitIsConnected(states[0]);\n}\n\nfunction providerToolName(tool: string): string {\n const names: Record<string, string> = {\n execute: 'composio_execute_tool',\n manageConnections: 'COMPOSIO_MANAGE_CONNECTIONS',\n remoteBash: 'COMPOSIO_REMOTE_BASH_TOOL',\n remoteWorkbench: 'COMPOSIO_REMOTE_WORKBENCH',\n search: 'composio_search_tools',\n };\n return names[tool] ?? tool;\n}\n\nfunction slackUserComposioId(event: NormalizedSlackTriggerEvent): string {\n return `slack:${event.teamId}:${event.userId}`;\n}\n\nfunction slackbotAlreadyConnectedResult(toolkits: string[]): JsonObject {\n return {\n successful: true,\n data: {\n message:\n 'Slack workspace actions use the already-connected shared Slackbot connection. Search the slackbot toolkit and execute SLACKBOT_* tools. Do not ask the user to connect Slack.',\n toolkits,\n },\n };\n}\n\nconst USE_DEDICATED_MANAGE_CONNECTIONS_ERROR =\n 'COMPOSIO_MANAGE_CONNECTIONS is not executable through composio_execute_tool. Use the dedicated composio_manage_connections helper, which checks session.toolkits and calls session.authorize for missing accounts.';\n\nconst USE_SLACKBOT_INSTEAD_ERROR =\n 'Use the slackbot toolkit for Slack workspace actions in this bot. Search with toolkits [\"slackbot\"] and execute a SLACKBOT_* tool instead of using the user-scoped Slack toolkit.';\n"
21 +},
22 +{
23 +"path": "src/agent/slack-composio-agent.ts",
24 +"composio": true,
25 +"contents": "import { Composio } from '@composio/core';\n\nimport { redactString } from '../auth/links';\nimport { createAuthLinkCollector, authLabelsForLinks, formatAuthLabelList, formatConnectionDm } from '../auth/ui';\nimport { createComposioRouting } from '../composio/routing';\nimport type { AppConfig } from '../config/env';\nimport { runPiAgent, shouldRespondToMainUserMessage } from '../pi/runner';\nimport {\n cleanSlackPrompt,\n composioUserIdForSlack,\n slackThreadKey,\n type NormalizedSlackTriggerEvent,\n} from '../slack/events';\nimport { claudeStyleStatus } from '../slack/status';\nimport type { SlackThreadMessage, SlackTransport, SlackUserContext } from '../slack/transport';\nimport type { Store } from '../store/file-store';\n\nexport interface HandleSlackMessageOptions {\n autoAnalyze?: boolean;\n}\n\nexport interface SlackComposioAgent {\n handleSlackMessage(event: NormalizedSlackTriggerEvent, options?: HandleSlackMessageOptions): Promise<void>;\n}\n\ninterface AgentDeps {\n config: AppConfig;\n slack: SlackTransport;\n store: Store;\n}\n\nexport function createSlackComposioAgent({ config, slack, store }: AgentDeps): SlackComposioAgent {\n const composio = new Composio({ apiKey: config.composioApiKey });\n const composioRouting = createComposioRouting({ composio, config, store });\n\n const postSlackResponse = async (\n channel: string,\n threadTs: string | undefined,\n text: string,\n event: NormalizedSlackTriggerEvent,\n ): Promise<void> => {\n for (const chunk of splitForSlack(text)) {\n await slack.postMessage({ channel, threadTs, text: chunk }, event);\n }\n };\n\n const handleSlackMessage = async (\n event: NormalizedSlackTriggerEvent,\n options: HandleSlackMessageOptions = {},\n ): Promise<void> => {\n const threadKey = slackThreadKey(event);\n const userId = composioUserIdForSlack(event);\n const botUserId = store.getSlackbotConnection(event.teamId)?.botUserId ?? config.slackBotUserId;\n const prompt = cleanSlackPrompt(event.text, botUserId);\n const replyThreadTs = replyThreadTimestamp(event);\n\n if (!prompt) {\n if (options.autoAnalyze) {\n await slack.addReaction(event.channel, event.ts, config.ignoreReactionName, event);\n return;\n }\n\n await slack.postMessage(\n {\n channel: event.channel,\n threadTs: replyThreadTs,\n text: \"Hi! Ask me to do something across your connected apps, and I'll help.\",\n },\n event,\n );\n return;\n }\n\n const history = store.getHistory(threadKey);\n const [slackThreadMessages, slackUserContext] = await Promise.all([\n fetchSlackThreadContext(slack, event),\n fetchSlackUserContext(slack, event),\n ]);\n if (options.autoAnalyze) {\n const shouldRespond = await shouldRespondToMainUserMessage({ config, event, history, prompt, slackThreadMessages });\n if (!shouldRespond) {\n await slack.addReaction(event.channel, event.ts, config.ignoreReactionName, event);\n return;\n }\n }\n\n void slack.setThreadStatus(\n {\n channel: event.channel,\n threadTs: event.threadTs,\n status: claudeStyleStatus(`${threadKey}:${prompt}`),\n },\n event,\n );\n\n if (!event.isDirectMessage) {\n void slack.addReaction(event.channel, event.ts, 'eyes', event);\n }\n\n const composioSession = await composioRouting.getOrCreateUserSession(event, userId, threadKey);\n const threadOwnerUserId = store.getThreadSession(threadKey)?.userId ?? userId;\n const authCollector = createAuthLinkCollector({ store, threadKey });\n const tools = composioRouting.createPiComposioTools(event, composioSession, authCollector.handleAuthLinks);\n\n const assistantText = await runPiAgent({\n config,\n event,\n history,\n prompt,\n slackThreadMessages,\n systemPrompt: buildSystemPrompt(config, event, composioSession.sessionId, slackUserContext, threadOwnerUserId),\n tools,\n });\n\n const sentAuthDm = authCollector.pendingLinks.length > 0;\n if (sentAuthDm) {\n await slack.postDm(event.userId, formatConnectionDm(authCollector.pendingLinks, prompt), event);\n }\n\n const authLabels = sentAuthDm ? authLabelsForLinks(authCollector.pendingLinks) : [];\n const authLabelText = sentAuthDm ? formatAuthLabelList(authLabels) : '';\n const text = redactString(\n sentAuthDm\n ? `I sent you a DM to connect ${authLabelText}. After approving access, I\u2019ll continue automatically.`\n : assistantText || 'Done.',\n );\n\n if (sentAuthDm) {\n await store.setPendingAuthContinuation({\n authLabels,\n channel: event.channel,\n event: resumableEvent(event),\n prompt,\n teamId: event.teamId,\n threadKey,\n threadTs: event.threadTs,\n userId: event.userId,\n });\n const publicMessageTs = await slack.postMessage({ channel: event.channel, threadTs: replyThreadTs, text }, event);\n if (publicMessageTs) {\n await store.setPendingAuthPublicMessageTs(threadKey, publicMessageTs);\n }\n } else {\n await postSlackResponse(event.channel, replyThreadTs, text, event);\n }\n\n void slack.clearThreadStatus({ channel: event.channel, threadTs: event.threadTs }, event);\n await store.appendHistory(threadKey, [\n { role: 'user', content: prompt },\n { role: 'assistant', content: text },\n ]);\n };\n\n return { handleSlackMessage };\n}\n\nfunction resumableEvent(event: NormalizedSlackTriggerEvent) {\n return {\n botId: event.botId,\n channel: event.channel,\n channelType: event.channelType,\n connectedAccountId: event.connectedAccountId,\n eventKey: `auth-resume:${event.eventKey}`,\n isDirectMessage: event.isDirectMessage,\n subtype: event.subtype,\n teamId: event.teamId,\n text: event.text,\n threadTs: event.threadTs,\n triggerSlug: event.triggerSlug,\n ts: event.ts,\n userId: event.userId,\n };\n}\n\nfunction buildSystemPrompt(\n config: AppConfig,\n event: NormalizedSlackTriggerEvent,\n composioSessionId: string,\n slackUserContext: SlackUserContext,\n threadOwnerUserId: string,\n): string {\n return [\n 'You are Pi running as the brain of a Slack assistant. You are concise, practical, and action-oriented.',\n config.composioWorkbenchEnabled\n ? 'You have access to Composio remote workbench tools through the Composio session. Use composio_search_tools to find workbench tools, then composio_execute_tool to run them for scratch files, analysis, transformations, and code execution in Composio\u2019s remote sandbox.'\n : 'Composio remote workbench tools are disabled in this deployment.',\n config.piWorkbenchEnabled\n ? `Local Pi workbench tools are also enabled at ${config.piCwd}. Prefer Composio remote workbench for untrusted code or larger execution tasks.`\n : 'Local Pi filesystem/bash tools are disabled; use Composio remote workbench for code/scratch execution.',\n 'You have three Composio tools: search tools, manage connections, and execute tools. Use them to work across the Slack user\u2019s connected apps.',\n 'You are given the full Slack thread context fetched from Slack before the incoming message. Treat that thread context as the source of truth for conversation state, user instructions, prior decisions, and what has already been tried.',\n formatSlackUserContext(slackUserContext),\n 'Use the Slack requester timezone/local time when interpreting relative dates and times like today, tomorrow, next Friday, morning, EOD, or scheduling defaults.',\n 'composio_search_tools is global by default. Only pass a toolkits filter when intentionally narrowing the search.',\n 'For Slack workspace actions outside the current conversation, search with toolkits [\"slackbot\"] and execute SLACKBOT_* tools. Never use the user-scoped slack toolkit and never ask the user to connect Slack for Slack workspace actions.',\n 'For requests to say/reply/post something in the current Slack conversation, simply make that text your final response. Do not use Slack/Slackbot Composio tools or ask the user to connect Slack for current-conversation replies.',\n 'Always use the current user-scoped Composio session for non-Slackbot app actions. Never ask for API keys or OAuth secrets in Slack.',\n 'When a required non-Slack app is not connected, call composio_manage_connections. The system will DM auth links to the user, wait for approval when supported, and redact links from tool output.',\n 'Never reveal Composio connection links, OAuth URLs, or raw credentials in your final Slack response.',\n 'If a tool says a connection link was sent via Slack DM, tell the user to approve it and that you will continue automatically.',\n 'If the user says \u201cdone\u201d, \u201cconnected\u201d, or similar after an auth step, continue the previous task from the conversation context.',\n 'Ask before destructive or irreversible actions unless the user explicitly requested the action.',\n 'Use Slack mrkdwn in final responses.',\n `Composio session id: ${composioSessionId}`,\n `Thread owner Composio user id: ${threadOwnerUserId}. Incoming Slack requester: slack:${event.teamId}:${event.userId}. For user-scoped app actions, this thread uses the thread owner's Composio session unless a new thread is started.`,\n `Slack context: team=${event.teamId}, channel=${event.channel}, thread_ts=${event.threadTs}, user=${event.userId}.`,\n ].join('\\n');\n}\n\nfunction formatSlackUserContext(context: SlackUserContext): string {\n const fields = [\n `user=${context.userId}`,\n context.timeZone ? `timezone=${context.timeZone}` : undefined,\n context.timeZoneLabel ? `timezone_label=${context.timeZoneLabel}` : undefined,\n typeof context.timeZoneOffsetSeconds === 'number' ? `timezone_offset_seconds=${context.timeZoneOffsetSeconds}` : undefined,\n context.localTime ? `current_local_time=${context.localTime}` : undefined,\n context.locale ? `locale=${context.locale}` : undefined,\n ].filter(Boolean);\n return `Slack requester context: ${fields.join(', ')}.`;\n}\n\nasync function fetchSlackThreadContext(\n slack: SlackTransport,\n event: NormalizedSlackTriggerEvent,\n): Promise<SlackThreadMessage[]> {\n try {\n return ensureIncomingEventInThread(\n await slack.fetchThreadMessages({ channel: event.channel, threadTs: event.threadTs }, event),\n event,\n );\n } catch (error) {\n console.warn('Failed to fetch Slack thread context', error instanceof Error ? error.message : String(error));\n return [threadMessageFromEvent(event)];\n }\n}\n\nasync function fetchSlackUserContext(slack: SlackTransport, event: NormalizedSlackTriggerEvent): Promise<SlackUserContext> {\n try {\n return await slack.fetchUserContext(event.userId, event);\n } catch (error) {\n console.warn('Failed to fetch Slack user timezone context', error instanceof Error ? error.message : String(error));\n return { userId: event.userId };\n }\n}\n\nfunction ensureIncomingEventInThread(\n messages: SlackThreadMessage[],\n event: NormalizedSlackTriggerEvent,\n): SlackThreadMessage[] {\n if (messages.some((message) => message.ts === event.ts)) return messages;\n return [...messages, threadMessageFromEvent(event)].sort((left, right) => Number(left.ts) - Number(right.ts));\n}\n\nfunction threadMessageFromEvent(event: NormalizedSlackTriggerEvent): SlackThreadMessage {\n return {\n botId: event.botId,\n isBot: Boolean(event.botId),\n subtype: event.subtype,\n text: event.text,\n ts: event.ts,\n userId: event.userId,\n };\n}\n\nfunction replyThreadTimestamp(event: NormalizedSlackTriggerEvent): string | undefined {\n if (event.isDirectMessage && event.threadTs === event.ts) return undefined;\n return event.threadTs;\n}\n\nfunction splitForSlack(text: string, maxLength = 3600): string[] {\n if (text.length <= maxLength) return [text];\n\n const chunks: string[] = [];\n let remaining = text;\n while (remaining.length > maxLength) {\n const breakpoint = Math.max(remaining.lastIndexOf('\\n', maxLength), remaining.lastIndexOf(' ', maxLength));\n const index = breakpoint > maxLength * 0.5 ? breakpoint : maxLength;\n chunks.push(remaining.slice(0, index).trim());\n remaining = remaining.slice(index).trim();\n }\n if (remaining) chunks.push(remaining);\n return chunks;\n}\n"
26 +},
27 +{
28 +"path": "src/api/composio-webhook.ts",
29 +"composio": true,
30 +"contents": "import type { SlackComposioAgent } from '../agent/slack-composio-agent';\nimport type { AppConfig } from '../config/env';\nimport {\n composioUserIdForSlack,\n isProcessableSlackEvent,\n messageMentionsBot,\n normalizeComposioSlackEvent,\n slackMessageDedupeKey,\n slackThreadKey,\n} from '../slack/events';\nimport type { Store } from '../store/file-store';\n\ninterface ComposioWebhookHandlerDeps {\n agent: SlackComposioAgent;\n config: AppConfig;\n store: Store;\n}\n\nexport interface ComposioWebhookHandler {\n processPayload(body: unknown): Promise<Record<string, unknown>>;\n}\n\nexport function createComposioWebhookHandler({ agent, config, store }: ComposioWebhookHandlerDeps): ComposioWebhookHandler {\n const inFlightDedupeKeys = new Set<string>();\n\n const processPayload = async (body: unknown): Promise<Record<string, unknown>> => {\n const event = normalizeComposioSlackEvent(body);\n if (!event) {\n return { ok: true, ignored: 'not_a_slack_trigger_payload' };\n }\n\n const dedupeKeys = [event.eventKey, slackMessageDedupeKey(event)];\n if (dedupeKeys.some((key) => inFlightDedupeKeys.has(key) || store.hasProcessedEvent(key))) {\n return { ok: true, duplicate: true };\n }\n\n for (const key of dedupeKeys) inFlightDedupeKeys.add(key);\n try {\n await Promise.all(dedupeKeys.map((key) => store.markProcessedEvent(key)));\n } finally {\n for (const key of dedupeKeys) inFlightDedupeKeys.delete(key);\n }\n\n const botUserId = store.getSlackbotConnection(event.teamId)?.botUserId ?? config.slackBotUserId;\n if (!isProcessableSlackEvent(event, botUserId)) {\n return { ok: true, ignored: 'not_processable' };\n }\n\n const mentionedBot = messageMentionsBot(event, botUserId);\n const configuredMainUser = config.mainSlackUserIds.includes(event.userId);\n if (configuredMainUser) {\n await store.addMainSlackUser(event.teamId, event.userId);\n }\n\n if (\n config.autoPromoteFirstMainUser &&\n store.getMainSlackUsers(event.teamId).length === 0 &&\n (mentionedBot || event.isDirectMessage)\n ) {\n await store.addMainSlackUser(event.teamId, event.userId);\n }\n\n const isMainUser = store.isMainSlackUser(event.teamId, event.userId) || configuredMainUser;\n const threadSession = store.getThreadSession(slackThreadKey(event));\n const isThreadOwner = threadSession?.userId === composioUserIdForSlack(event);\n const shouldHandleNormally = event.isDirectMessage || mentionedBot;\n const shouldAutoAnalyze =\n !shouldHandleNormally &&\n ((config.autoAnalyzeMainUserMessages && isMainUser) || Boolean(threadSession && isThreadOwner));\n\n if (!shouldHandleNormally && !shouldAutoAnalyze) {\n return { ok: true, ignored: 'requires_mention' };\n }\n\n queueMicrotask(() => {\n agent.handleSlackMessage(event, { autoAnalyze: shouldAutoAnalyze }).catch((error) => {\n console.error('Failed to handle Slack event', error);\n });\n });\n\n return { ok: true, accepted: true, autoAnalyze: shouldAutoAnalyze };\n };\n\n return { processPayload };\n}\n\n"
31 +},
32 +{
33 +"path": "src/slack/transport.ts",
34 +"composio": true,
35 +"contents": "import { Composio } from '@composio/core';\n\nimport type { AppConfig } from '../config/env';\nimport type { Store } from '../store/file-store';\nimport { firstString, jsonObject } from '../utils/decode';\nimport type { JsonObject, JsonValue } from '../utils/json';\nimport type { NormalizedSlackTriggerEvent } from './events';\n\ntype ComposioSession = Awaited<ReturnType<Composio['create']>>;\n\ntype CachedSlackUserContext = {\n context: SlackUserContext;\n expiresAt: number;\n refresh?: Promise<SlackUserContext>;\n};\n\nconst USER_CONTEXT_CACHE_TTL_MS = 6 * 60 * 60 * 1000;\n\nexport interface SlackMessageOptions {\n channel: string;\n text: string;\n threadTs?: string;\n}\n\nexport interface SlackUpdateMessageOptions {\n channel: string;\n text: string;\n ts: string;\n}\n\nexport interface SlackThreadStatusOptions {\n channel: string;\n loadingMessages?: string[];\n status: string;\n threadTs: string;\n}\n\nexport interface SlackThreadMessage {\n botId?: string | null;\n isBot: boolean;\n subtype?: string | null;\n text: string;\n ts: string;\n userId?: string;\n username?: string;\n}\n\nexport interface SlackFetchThreadOptions {\n channel: string;\n maxMessages?: number;\n threadTs: string;\n}\n\nexport interface SlackUserContext {\n locale?: string;\n localTime?: string;\n timeZone?: string;\n timeZoneLabel?: string;\n timeZoneOffsetSeconds?: number;\n userId: string;\n}\n\nexport interface SlackTransport {\n addReaction(channel: string, timestamp: string, name: string, event?: NormalizedSlackTriggerEvent): Promise<void>;\n clearThreadStatus(options: Omit<SlackThreadStatusOptions, 'loadingMessages' | 'status'>, event?: NormalizedSlackTriggerEvent): Promise<void>;\n fetchThreadMessages(options: SlackFetchThreadOptions, event?: NormalizedSlackTriggerEvent): Promise<SlackThreadMessage[]>;\n fetchUserContext(userId: string, event?: NormalizedSlackTriggerEvent): Promise<SlackUserContext>;\n postDm(userId: string, text: string, event?: NormalizedSlackTriggerEvent): Promise<string | undefined>;\n postMessage(options: SlackMessageOptions, event?: NormalizedSlackTriggerEvent): Promise<string | undefined>;\n updateMessage(options: SlackUpdateMessageOptions, event?: NormalizedSlackTriggerEvent): Promise<void>;\n setThreadStatus(options: SlackThreadStatusOptions, event?: NormalizedSlackTriggerEvent): Promise<void>;\n}\n\ninterface SlackTransportDeps {\n config: AppConfig;\n store: Store;\n}\n\n/**\n * Slack transport backed by a Composio Slackbot connected account.\n * The Slack bot token stays in Composio; this app stores only ca_* ids.\n */\nexport function createSlackTransport({ config, store }: SlackTransportDeps): SlackTransport {\n const composio = new Composio({ apiKey: config.composioApiKey });\n const dmChannels = new Map<string, string>();\n const sessions = new Map<string, ComposioSession>();\n const userContexts = new Map<string, CachedSlackUserContext>();\n\n const sessionForEvent = async (event?: NormalizedSlackTriggerEvent): Promise<ComposioSession> => {\n const connectedAccountId = connectedAccountIdForEvent(config, store, event);\n const cached = sessions.get(connectedAccountId);\n if (cached) return cached;\n\n const session = await composio.create(transportUserIdForEvent(config, event), {\n toolkits: ['slackbot'],\n connectedAccounts: {\n slackbot: [connectedAccountId],\n },\n manageConnections: false,\n workbench: { enable: false },\n });\n\n sessions.set(connectedAccountId, session);\n return session;\n };\n\n const openDm = async (userId: string, event?: NormalizedSlackTriggerEvent): Promise<string> => {\n const cacheKey = `${connectedAccountIdForEvent(config, store, event)}:${userId}`;\n const cached = dmChannels.get(cacheKey);\n if (cached) return cached;\n\n const session = await sessionForEvent(event);\n const response = await proxySlack(session, 'conversations.open', { users: userId });\n const channelId = decodeOpenDmChannelId(response);\n if (!channelId) {\n throw new Error(`Slack conversations.open did not return a channel id for user ${userId}: ${JSON.stringify(response)}`);\n }\n\n dmChannels.set(cacheKey, channelId);\n return channelId;\n };\n\n const postMessage = async (\n { channel, text, threadTs }: SlackMessageOptions,\n event?: NormalizedSlackTriggerEvent,\n ): Promise<string | undefined> => {\n const session = await sessionForEvent(event);\n const response = await proxySlack(session, 'chat.postMessage', {\n channel,\n text,\n mrkdwn: true,\n thread_ts: threadTs,\n unfurl_links: false,\n unfurl_media: false,\n });\n\n return decodePostMessageTimestamp(response);\n };\n\n const updateMessage = async (\n { channel, text, ts }: SlackUpdateMessageOptions,\n event?: NormalizedSlackTriggerEvent,\n ): Promise<void> => {\n const session = await sessionForEvent(event);\n await proxySlack(session, 'chat.update', {\n channel,\n ts,\n text,\n mrkdwn: true,\n unfurl_links: false,\n unfurl_media: false,\n });\n };\n\n const setThreadStatus = async (\n { channel, threadTs, status, loadingMessages }: SlackThreadStatusOptions,\n event?: NormalizedSlackTriggerEvent,\n ): Promise<void> => {\n try {\n const session = await sessionForEvent(event);\n await proxySlack(session, 'assistant.threads.setStatus', {\n channel_id: channel,\n thread_ts: threadTs,\n status,\n loading_messages: loadingMessages,\n });\n } catch (error) {\n // Status indicators are optional polish. Missing Slack AI app capability should not break replies.\n console.warn('Failed to set Slack assistant thread status', summarizeError(error));\n }\n };\n\n const fetchThreadMessages = async (\n { channel, threadTs, maxMessages = Number.MAX_SAFE_INTEGER }: SlackFetchThreadOptions,\n event?: NormalizedSlackTriggerEvent,\n ): Promise<SlackThreadMessage[]> => {\n const session = await sessionForEvent(event);\n const messages: SlackThreadMessage[] = [];\n let cursor: string | undefined;\n\n do {\n const response = await proxySlackGet(session, 'conversations.replies', {\n channel,\n ts: threadTs,\n limit: Math.min(200, Math.max(1, maxMessages - messages.length)),\n cursor,\n });\n messages.push(...decodeThreadMessages(response));\n cursor = decodeNextCursor(response);\n } while (cursor && messages.length < maxMessages);\n\n return messages.slice(0, maxMessages);\n };\n\n const requestUserContext = async (userId: string, event?: NormalizedSlackTriggerEvent): Promise<SlackUserContext> => {\n const session = await sessionForEvent(event);\n const response = await proxySlackGet(session, 'users.info', {\n user: userId,\n include_locale: 'true',\n });\n return decodeUserContext(response, userId);\n };\n\n const refreshUserContext = (cacheKey: string, userId: string, event?: NormalizedSlackTriggerEvent): Promise<SlackUserContext> => {\n const refresh = requestUserContext(userId, event)\n .then((context) => {\n const cached = {\n context,\n expiresAt: Date.now() + USER_CONTEXT_CACHE_TTL_MS,\n };\n userContexts.set(cacheKey, cached);\n return withFreshLocalTime(context);\n })\n .catch((error) => {\n const existing = userContexts.get(cacheKey);\n if (existing) {\n userContexts.set(cacheKey, { context: existing.context, expiresAt: existing.expiresAt });\n }\n throw error;\n });\n\n const existing = userContexts.get(cacheKey);\n if (existing) {\n userContexts.set(cacheKey, { ...existing, refresh });\n }\n return refresh;\n };\n\n const fetchUserContext = async (userId: string, event?: NormalizedSlackTriggerEvent): Promise<SlackUserContext> => {\n const cacheKey = `${connectedAccountIdForEvent(config, store, event)}:${userId}`;\n const now = Date.now();\n const cached = userContexts.get(cacheKey);\n if (cached && cached.expiresAt > now) {\n return withFreshLocalTime(cached.context);\n }\n\n if (cached) {\n if (!cached.refresh) {\n const refresh = refreshUserContext(cacheKey, userId, event).catch((error) => {\n console.warn('Failed to refresh cached Slack user timezone context', summarizeError(error));\n return withFreshLocalTime(cached.context);\n });\n userContexts.set(cacheKey, { ...cached, refresh });\n }\n return withFreshLocalTime(cached.context);\n }\n\n const fallback = { userId };\n const refresh = refreshUserContext(cacheKey, userId, event).catch((error) => {\n console.warn('Failed to fetch Slack user timezone context', summarizeError(error));\n return fallback;\n });\n userContexts.set(cacheKey, {\n context: fallback,\n expiresAt: 0,\n refresh,\n });\n return fallback;\n };\n\n return {\n addReaction: async (channel, timestamp, name, event) => {\n try {\n const session = await sessionForEvent(event);\n await proxySlack(session, 'reactions.add', { channel, timestamp, name });\n } catch (error) {\n // Reactions are optional polish. Missing scopes or duplicate reactions should not break handling.\n console.warn('Failed to add Slack reaction', summarizeError(error));\n }\n },\n\n clearThreadStatus: async ({ channel, threadTs }, event) => {\n await setThreadStatus({ channel, threadTs, status: '' }, event);\n },\n\n fetchThreadMessages,\n fetchUserContext,\n\n postDm: async (userId, text, event) => {\n const channel = await openDm(userId, event);\n return postMessage({ channel, text }, event);\n },\n\n postMessage,\n setThreadStatus,\n updateMessage,\n };\n}\n\nexport async function proxySlack(\n session: ComposioSession,\n method: string,\n body: Record<string, JsonValue | undefined>,\n): Promise<JsonValue> {\n const response = await session.proxyExecute({\n toolkit: 'slackbot',\n endpoint: `https://slack.com/api/${method}`,\n method: 'POST',\n body: stripUndefined(body),\n });\n\n return decodeSlackApiResponse(method, response);\n}\n\nasync function proxySlackGet(\n session: ComposioSession,\n method: string,\n query: Record<string, string | number | undefined>,\n): Promise<JsonValue> {\n const response = await session.proxyExecute({\n toolkit: 'slackbot',\n endpoint: `https://slack.com/api/${method}`,\n method: 'GET',\n parameters: queryParameters(query),\n });\n\n return decodeSlackApiResponse(method, response);\n}\n\nfunction decodeSlackApiResponse(method: string, response: unknown): JsonValue {\n const responseObject = jsonObject(response) ?? {};\n const slackPayload = jsonObject(responseObject.data) ?? responseObject;\n\n if (slackPayload.ok === false) {\n throw new Error(`Slack API ${method} failed: ${firstString(slackPayload.error) ?? JSON.stringify(slackPayload)}`);\n }\n\n return slackPayload;\n}\n\nfunction decodeOpenDmChannelId(response: JsonValue): string | undefined {\n const payload = jsonObject(response) ?? {};\n const channel = jsonObject(payload.channel) ?? jsonObject(jsonObject(payload.data)?.channel);\n return firstString(channel?.id);\n}\n\nfunction decodePostMessageTimestamp(response: JsonValue): string | undefined {\n const payload = jsonObject(response) ?? {};\n const data = jsonObject(payload.data);\n const message = jsonObject(payload.message);\n return firstString(payload.ts, data?.ts, message?.ts);\n}\n\nfunction decodeThreadMessages(response: JsonValue): SlackThreadMessage[] {\n const payload = jsonObject(response) ?? {};\n const rawMessages = Array.isArray(payload.messages) ? payload.messages : [];\n\n return rawMessages.flatMap((rawMessage): SlackThreadMessage[] => {\n const message = jsonObject(rawMessage);\n const ts = firstString(message?.ts);\n if (!message || !ts) return [];\n\n return [\n {\n botId: firstString(message.bot_id, message.botId) ?? null,\n isBot: Boolean(firstString(message.bot_id, message.botId)) || typeof message.bot_profile === 'object',\n subtype: firstString(message.subtype) ?? null,\n text: messageTextWithFiles(message),\n ts,\n userId: firstString(message.user, message.user_id, message.userId),\n username: firstString(message.username, message.user_name, message.userName),\n },\n ];\n });\n}\n\nfunction decodeNextCursor(response: JsonValue): string | undefined {\n const payload = jsonObject(response) ?? {};\n const metadata = jsonObject(payload.response_metadata) ?? jsonObject(payload.responseMetadata);\n return firstString(metadata?.next_cursor, metadata?.nextCursor);\n}\n\nfunction decodeUserContext(response: JsonValue, fallbackUserId: string): SlackUserContext {\n const payload = jsonObject(response) ?? {};\n const data = jsonObject(payload.data);\n const user = jsonObject(payload.user) ?? jsonObject(data?.user) ?? {};\n const profile = jsonObject(user.profile) ?? {};\n const timeZone = firstString(user.tz, user.timezone, profile.tz, profile.timezone);\n\n return {\n locale: firstString(user.locale, profile.locale),\n localTime: timeZone ? formatLocalTime(timeZone) : undefined,\n timeZone,\n timeZoneLabel: firstString(user.tz_label, user.tzLabel),\n timeZoneOffsetSeconds: firstNumber(user.tz_offset, user.tzOffset),\n userId: firstString(user.id) ?? fallbackUserId,\n };\n}\n\nfunction messageTextWithFiles(message: JsonObject): string {\n const text = firstString(message.text) ?? '';\n const files = Array.isArray(message.files) ? message.files : [];\n const fileSummaries = files.flatMap((rawFile): string[] => {\n const file = jsonObject(rawFile);\n if (!file) return [];\n const title = firstString(file.title, file.name) ?? 'file';\n const url = firstString(file.permalink, file.url_private, file.urlPrivate);\n return [url ? `[file: ${title} ${url}]` : `[file: ${title}]`];\n });\n\n return [text, ...fileSummaries].filter(Boolean).join('\\n');\n}\n\nfunction firstNumber(...values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value !== 'string' || !value.trim()) continue;\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n}\n\nfunction withFreshLocalTime(context: SlackUserContext): SlackUserContext {\n return {\n ...context,\n localTime: context.timeZone ? formatLocalTime(context.timeZone) : undefined,\n };\n}\n\nfunction formatLocalTime(timeZone: string): string | undefined {\n try {\n return new Intl.DateTimeFormat('en-US', {\n dateStyle: 'full',\n timeStyle: 'long',\n timeZone,\n }).format(new Date());\n } catch {\n return undefined;\n }\n}\n\nfunction connectedAccountIdForEvent(config: AppConfig, store: Store, event?: NormalizedSlackTriggerEvent): string {\n const id =\n config.slackbotSharedConnectedAccountId ??\n event?.connectedAccountId ??\n (event?.teamId ? store.getSlackbotConnection(event.teamId)?.connectedAccountId : undefined);\n if (!id) {\n throw new Error(\n 'Missing Slackbot transport connected account. Open /setup/slackbot/start to install Slackbot or set SLACKBOT_SHARED_CONNECTED_ACCOUNT_ID.',\n );\n }\n return id;\n}\n\nfunction transportUserIdForEvent(config: AppConfig, event?: NormalizedSlackTriggerEvent): string {\n if (config.slackbotTransportUserId) return config.slackbotTransportUserId;\n if (!event?.teamId || event.teamId === 'unknown-team') {\n throw new Error('Missing Slack team id; cannot derive Slackbot transport user id service:${teamId}.');\n }\n return `service:${event.teamId}`;\n}\n\nfunction stripUndefined(value: Record<string, JsonValue | undefined>): JsonObject {\n return Object.fromEntries(Object.entries(value).filter(([, nested]) => nested !== undefined)) as JsonObject;\n}\n\nfunction queryParameters(value: Record<string, string | number | undefined>): Array<{ in: 'query'; name: string; value: string | number }> {\n return Object.entries(value).flatMap(([name, nested]) => (nested === undefined ? [] : [{ in: 'query' as const, name, value: nested }]));\n}\n\nfunction summarizeError(error: Error | unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n"
36 +},
37 +{
38 +"path": "src/slack/acl.ts",
39 +"composio": true,
40 +"contents": "import type { NormalizedSlackTriggerEvent } from './events';\n\nexport function assertSlackbotManualAcl(event: NormalizedSlackTriggerEvent, composioUserId: string): void {\n if (isAllowedSlackbotUserId(event.teamId, composioUserId)) return;\n\n throw new Error(\n `Refusing to pin Slackbot shared connection for ${composioUserId}. ` +\n `Allowed patterns: ${slackbotAllowedUserIdPatterns(event.teamId).join(', ')}`,\n );\n}\n\nexport function isAllowedSlackbotUserId(teamId: string, composioUserId: string): boolean {\n return composioUserId === `service:${teamId}` || composioUserId.startsWith(`slack:${teamId}:`);\n}\n\nexport function slackbotAllowedUserIdPatterns(teamId: string): string[] {\n return [`service:${teamId}`, `slack:${teamId}:*`];\n}\n"
41 +}
42 +]
\ No newline at end of file
docs/lib/source.ts
+49 -8
@@ -1,16 +1,38 @@
1 -import { docs, reference, cookbooks, toolkits, changelog } from 'fumadocs-mdx:collections/server';
1 +import { docs, reference, examples, toolkits, changelog } from 'fumadocs-mdx:collections/server';
2 import { type InferPageType, loader, multiple } from 'fumadocs-core/source';
3 import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons';
4 import { openapi, openapiV3 } from './openapi';
5 import { openapiSource, openapiPlugin } from 'fumadocs-openapi/server';
6 import { getGuardrails } from './llm-guardrails';
7 +import { HIDDEN_API_TAGS } from './filter-api-version';
8 +
9 +/**
10 + * True if a reference URL belongs to an intentionally-hidden API tag
11 + * (consumer, invite-codes) in either v3.1 or v3.0. These tags exist in the
12 + * upstream OpenAPI spec but are hidden on our side. The page tree is filtered
13 + * via `prepareTree` (lib/filter-api-version.ts); this mirror keeps the flat
14 + * `getPages()` list (consumed by validate-links, llms.mdx, sitemap) in sync.
15 + */
16 +function isHiddenReferenceUrl(url: string): boolean {
17 + for (const tag of HIDDEN_API_TAGS) {
18 + if (
19 + url.startsWith(`/reference/api-reference/${tag}/`) ||
20 + url === `/reference/api-reference/${tag}` ||
21 + url.startsWith(`/reference/v3/api-reference/${tag}/`) ||
22 + url === `/reference/v3/api-reference/${tag}`
23 + ) {
24 + return true;
25 + }
26 + }
27 + return false;
28 +}
29
30 /**
31 * Transformer to set defaultOpen: true for specific folders in the reference sidebar.
32 */
33 const defaultOpenTransformer = {
34 folder(node: { name: string; defaultOpen?: boolean }, folderPath: string) {
13 - if (folderPath === 'api-reference' || folderPath === 'sdk-reference' || folderPath === 'meta-tools' || folderPath === 'v3/api-reference') {
35 + if (folderPath === 'api-reference' || folderPath === 'sdk-reference' || folderPath === 'v3/api-reference') {
36 return { ...node, defaultOpen: true };
37 }
38 return node;
@@ -35,7 +57,13 @@ async function getOpenapiPages() {
57 _openapiPagesPromise = Promise.all([
58 openapiSource(openapi, { groupBy: 'tag', baseDir: 'api-reference' }),
59 openapiSource(openapiV3, { groupBy: 'tag', baseDir: 'v3/api-reference' }),
38 - ]);
60 + ]).catch((e) => {
61 + // Don't permanently cache a failed load (e.g. a transient OpenAPI spec
62 + // resolution error in a serverless instance). Clearing the memo lets the
63 + // next request retry instead of re-throwing the same cached rejection.
64 + _openapiPagesPromise = null;
65 + throw e;
66 + });
67 }
68 return _openapiPagesPromise;
69 }
@@ -43,7 +71,7 @@ async function getOpenapiPages() {
71 export async function getReferenceSource() {
72 if (!_referenceSource) {
73 const [openapiLatest, openapiV3Pages] = await getOpenapiPages();
46 - _referenceSource = loader({
74 + const loaded = loader({
75 baseUrl: '/reference',
76 source: multiple({
77 mdx: reference.toFumadocsSource(),
@@ -56,6 +84,19 @@ export async function getReferenceSource() {
84 transformers: [defaultOpenTransformer as any],
85 },
86 });
87 +
88 + // Exclude intentionally-hidden API tags (consumer, invite-codes) from the
89 + // flat page list so validate-links, llms.mdx, llms.txt, and sitemap skip
90 + // their fumadocs-openapi operation pages. The sidebar tree is filtered
91 + // separately via prepareTree (lib/filter-api-version.ts).
92 + const originalGetPages = loaded.getPages.bind(loaded);
93 + // eslint-disable-next-line @typescript-eslint/no-explicit-any
94 + (loaded as any).getPages = (...args: Parameters<typeof originalGetPages>) =>
95 + originalGetPages(...args).filter(
96 + (page: { url: string }) => !isHiddenReferenceUrl(page.url),
97 + );
98 +
99 + _referenceSource = loaded;
100 }
101 return _referenceSource;
102 }
@@ -67,9 +108,9 @@ export const referenceSource = loader({
108 plugins: [lucideIconsPlugin()],
109 });
110
70 -export const cookbooksSource = loader({
71 - baseUrl: '/cookbooks',
72 - source: cookbooks.toFumadocsSource(),
111 +export const examplesSource = loader({
112 + baseUrl: '/examples',
113 + source: examples.toFumadocsSource(),
114 plugins: [lucideIconsPlugin()],
115 });
116
@@ -357,7 +398,7 @@ ${page.data.description || ''}`;
398 }
399
400 const footer = includeFooter
360 - ? `\n\n---\n\n📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Glossary](https://docs.composio.dev/llms.mdx/docs/glossary) | [Cookbooks](https://docs.composio.dev/llms.mdx/cookbooks) | [API Reference](https://docs.composio.dev/llms.mdx/reference)`
401 + ? `\n\n---\n\n📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)`
402 : '';
403
404 const guardrails = includeGuardrails ? getGuardrails(page.data.llmGuardrails) : '';
docs/lib/standup-bot-build.ts new
+323
@@ -0,0 +1,323 @@
1 +/**
2 + * Cumulative stages of the standup-bot example's files, built up one piece at a
3 + * time. Each stage's `code` is the full file at that point; <FileBuildup> diffs
4 + * consecutive stages so the reader watches the file grow.
5 + *
6 + * These are teaching versions: tighter than the real repo (which factors helpers
7 + * into separate files), but the same Composio calls. <RepoBrowser> shows the
8 + * real split.
9 + */
10 +
11 +export interface BuildStage {
12 + title: string;
13 + description: string;
14 + /** Full file contents at this stage. */
15 + code: string;
16 +}
17 +
18 +// ── setup.ts: connect the bot's own Slack app ───────────────────────────────
19 +
20 +const setup1 = `import { Composio } from '@composio/core';
21 +
22 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
23 +const AUTH_CONFIG = process.env.COMPOSIO_SLACKBOT_AUTH_CONFIG_ID!;
24 +
25 +// Connect the bot's own Slack app once, so it can post and DM as the bot.
26 +async function main() {
27 + const session = await composio.create('default', {
28 + authConfigs: { slackbot: AUTH_CONFIG },
29 + });
30 +
31 + const toolkits = await session.toolkits({ toolkits: ['slackbot'] });
32 + const active = toolkits.items.find((t) => t.slug === 'slackbot')?.connection?.isActive;
33 + if (active) {
34 + console.log('Bot already connected.');
35 + return;
36 + }
37 +}
38 +
39 +main();
40 +`;
41 +
42 +const setup2 = `import { Composio } from '@composio/core';
43 +
44 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
45 +const AUTH_CONFIG = process.env.COMPOSIO_SLACKBOT_AUTH_CONFIG_ID!;
46 +
47 +// Connect the bot's own Slack app once, so it can post and DM as the bot.
48 +async function main() {
49 + const session = await composio.create('default', {
50 + authConfigs: { slackbot: AUTH_CONFIG },
51 + });
52 +
53 + const toolkits = await session.toolkits({ toolkits: ['slackbot'] });
54 + const active = toolkits.items.find((t) => t.slug === 'slackbot')?.connection?.isActive;
55 + if (active) {
56 + console.log('Bot already connected.');
57 + return;
58 + }
59 +
60 + // Not connected: print the Connect Link, then wait for the user to finish.
61 + const connectionRequest = await session.authorize('slackbot');
62 + console.log('Authorize the bot:', connectionRequest.redirectUrl);
63 +
64 + const account = await connectionRequest.waitForConnection();
65 + console.log('Bot connected:', account.id);
66 +}
67 +
68 +main();
69 +`;
70 +
71 +// ── slack.ts: send with tools, open the modal through the proxy ─────────────
72 +
73 +const proxy1 = `import { composio } from './composio';
74 +
75 +const BOT_USER = 'default';
76 +
77 +// Sending a message is a named tool, even when it carries interactive buttons:
78 +// SLACKBOT_SEND_MESSAGE takes markdown_text for prose, or Block Kit \`blocks\`.
79 +export async function postMessage(channel: string, text: string, blocks?: unknown[]) {
80 + const res = await composio.tools.execute('SLACKBOT_SEND_MESSAGE', {
81 + userId: BOT_USER,
82 + arguments: blocks ? { channel, blocks } : { channel, markdown_text: text },
83 + });
84 + return res.data as { ts?: string };
85 +}
86 +
87 +// Updating the draft after an edit is a tool too: SLACKBOT_UPDATES_A_MESSAGE.
88 +export async function updateMessage(channel: string, ts: string, blocks: unknown[]) {
89 + await composio.tools.execute('SLACKBOT_UPDATES_A_MESSAGE', {
90 + userId: BOT_USER,
91 + arguments: { channel, ts, blocks },
92 + });
93 +}
94 +`;
95 +
96 +const proxy2 = `import { composio } from './composio';
97 +
98 +const BOT_USER = 'default';
99 +
100 +// Sending a message is a named tool, even when it carries interactive buttons:
101 +// SLACKBOT_SEND_MESSAGE takes markdown_text for prose, or Block Kit \`blocks\`.
102 +export async function postMessage(channel: string, text: string, blocks?: unknown[]) {
103 + const res = await composio.tools.execute('SLACKBOT_SEND_MESSAGE', {
104 + userId: BOT_USER,
105 + arguments: blocks ? { channel, blocks } : { channel, markdown_text: text },
106 + });
107 + return res.data as { ts?: string };
108 +}
109 +
110 +// Updating the draft after an edit is a tool too: SLACKBOT_UPDATES_A_MESSAGE.
111 +export async function updateMessage(channel: string, ts: string, blocks: unknown[]) {
112 + await composio.tools.execute('SLACKBOT_UPDATES_A_MESSAGE', {
113 + userId: BOT_USER,
114 + arguments: { channel, ts, blocks },
115 + });
116 +}
117 +
118 +// Opening a modal (views.open) has no Composio tool, so it drops to the proxy.
119 +// proxyExecute hits the raw endpoint as the bot's connected account, the escape
120 +// hatch for anything the named tools don't cover.
121 +export async function openModal(triggerId: string, view: unknown) {
122 + const { items } = await composio.connectedAccounts.list({
123 + userIds: [BOT_USER],
124 + toolkitSlugs: ['slackbot'],
125 + statuses: ['ACTIVE'],
126 + });
127 + await composio.tools.proxyExecute({
128 + endpoint: '/views.open',
129 + method: 'POST',
130 + body: { trigger_id: triggerId, view },
131 + connectedAccountId: items[0]?.id,
132 + });
133 +}
134 +`;
135 +
136 +// ── agent.ts: research connected tools and write the draft ──────────────────
137 +
138 +const agent1 = `import { Composio } from '@composio/core';
139 +import { VercelProvider } from '@composio/vercel';
140 +import { generateText, stepCountIs } from 'ai';
141 +
142 +const composio = new Composio({
143 + apiKey: process.env.COMPOSIO_API_KEY,
144 + provider: new VercelProvider(),
145 +});
146 +
147 +// The toolkits the bot can draft from. A member only has some of these connected,
148 +// and that's fine: the session just uses whatever they've actually authorized.
149 +const TOOLKITS = ['github', 'linear', 'notion', 'googlecalendar', 'slack'];
150 +
151 +// Spin up a tool-router session for one member and let the agent research and
152 +// write their standup. session.tools() returns Composio's research meta-tools
153 +// (search / execute / workbench), scoped to those toolkits.
154 +export async function generateDraft(memberEmail: string) {
155 + const session = await composio.create(memberEmail, { toolkits: TOOLKITS });
156 + const tools = await session.tools();
157 +
158 + const { text } = await generateText({
159 + model: 'anthropic/claude-sonnet-4-5',
160 + system: "Write a concise daily standup from the member's recent activity.",
161 + prompt: 'Research and write the standup update.',
162 + tools,
163 + stopWhen: stepCountIs(40),
164 + });
165 + return text.trim();
166 +}
167 +`;
168 +
169 +const agent2 = `import { Composio } from '@composio/core';
170 +import { VercelProvider } from '@composio/vercel';
171 +import { generateText, stepCountIs } from 'ai';
172 +
173 +const composio = new Composio({
174 + apiKey: process.env.COMPOSIO_API_KEY,
175 + provider: new VercelProvider(),
176 +});
177 +
178 +// The toolkits the bot can draft from. A member only has some of these connected,
179 +// and that's fine: the session just uses whatever they've actually authorized.
180 +const TOOLKITS = ['github', 'linear', 'notion', 'googlecalendar', 'slack'];
181 +
182 +// Spin up a tool-router session for one member and let the agent research and
183 +// write their standup. session.tools() returns Composio's research meta-tools
184 +// (search / execute / workbench), scoped to those toolkits.
185 +export async function generateDraft(memberEmail: string) {
186 + // manageConnections:false strips the connection meta-tools. The agent drafts
187 + // from whatever the member already connected and never starts an OAuth flow
188 + // mid-draft: if a tool needs auth, it's simply not in the session.
189 + const session = await composio.create(memberEmail, {
190 + toolkits: TOOLKITS,
191 + manageConnections: false,
192 + });
193 + const tools = await session.tools();
194 +
195 + const { text } = await generateText({
196 + model: 'anthropic/claude-sonnet-4-5',
197 + system: "Write a concise daily standup from the member's recent activity.",
198 + prompt: 'Research and write the standup update.',
199 + tools,
200 + stopWhen: stepCountIs(40),
201 + });
202 + return text.trim();
203 +}
204 +`;
205 +
206 +// ── api/interactivity.ts: route button clicks ──────────────────────────────
207 +
208 +const buttons1 = `import { verifySlackSignature, readRawBody } from './_utils/slack';
209 +
210 +// Slack POSTs here every time someone clicks a button. Verify it really came
211 +// from Slack, then ack within 3 seconds (Slack retries if you're slow).
212 +export default async function handler(req: Request, res: Response) {
213 + const body = await readRawBody(req);
214 + if (!verifySlackSignature(body, req.headers)) return res.status(401).end();
215 +
216 + const payload = JSON.parse(new URLSearchParams(body).get('payload') ?? '{}');
217 + res.status(200).end(); // ack immediately
218 + await handleClick(payload); // then do the slow work
219 +}
220 +`;
221 +
222 +const buttons2 = `import { verifySlackSignature, readRawBody, updateMessage, postAsMember } from './_utils/slack';
223 +import { generateDraft } from './_utils/agent';
224 +import { draftMessage, connectMenu } from './_utils/blocks';
225 +
226 +// Slack POSTs here every time someone clicks a button. Verify it really came
227 +// from Slack, then ack within 3 seconds (Slack retries if you're slow).
228 +export default async function handler(req: Request, res: Response) {
229 + const body = await readRawBody(req);
230 + if (!verifySlackSignature(body, req.headers)) return res.status(401).end();
231 +
232 + const payload = JSON.parse(new URLSearchParams(body).get('payload') ?? '{}');
233 + res.status(200).end(); // ack immediately
234 + await handleClick(payload); // then do the slow work
235 +}
236 +
237 +// Each button carried its context in \`value\`, so the handler knows exactly what
238 +// to do. No model decides anything here: the flow is fixed.
239 +async function handleClick(payload: any) {
240 + const action = payload.actions?.[0];
241 + const ctx = JSON.parse(action?.value ?? '{}');
242 +
243 + if (action?.action_id === 'draft') {
244 + const draft = await generateDraft(ctx.memberEmail); // launch the subagent
245 + await updateMessage(ctx.dmChannel, ctx.dmTs, draftMessage(draft, ctx));
246 + } else if (action?.action_id === 'connect') {
247 + await updateMessage(ctx.dmChannel, ctx.dmTs, connectMenu(ctx));
248 + } else if (action?.action_id === 'confirm') {
249 + await postAsMember(ctx.memberEmail, ctx.channel, ctx.draft, ctx.threadTs);
250 + }
251 +}
252 +`;
253 +
254 +export const FILE_BUILDS: Record<string, { file: string; stages: BuildStage[] }> = {
255 + setup: {
256 + file: 'scripts/setup.ts',
257 + stages: [
258 + {
259 + title: 'Bind a session to your Slack auth config',
260 + description:
261 + "The bot authenticates as your own Slack app. Create a session against the slackbot auth config and check whether it's already connected.",
262 + code: setup1,
263 + },
264 + {
265 + title: 'Authorize and wait',
266 + description:
267 + 'If not connected, `session.authorize()` returns a Connect Link. Print it, then `waitForConnection()` resolves once the bot finishes OAuth. That connected account is the identity the bot posts as.',
268 + code: setup2,
269 + },
270 + ],
271 + },
272 + proxy: {
273 + file: 'api/_utils/slack.ts',
274 + stages: [
275 + {
276 + title: 'Send and update with named tools',
277 + description:
278 + 'Sending and updating are tools: SLACKBOT_SEND_MESSAGE and SLACKBOT_UPDATES_A_MESSAGE both take Block Kit `blocks`, so even the interactive button menus go through tools, not the proxy.',
279 + code: proxy1,
280 + },
281 + {
282 + title: 'The proxy for the one thing without a tool',
283 + description:
284 + "Opening a modal (views.open) has no Composio tool, so it drops to proxyExecute as the bot's connected account: the escape hatch for anything the named tools don't cover.",
285 + code: proxy2,
286 + },
287 + ],
288 + },
289 + buttons: {
290 + file: 'api/interactivity.ts',
291 + stages: [
292 + {
293 + title: 'Verify the request and ack fast',
294 + description:
295 + "Slack POSTs to this endpoint on every click. Verify the signature, then respond within 3 seconds so Slack doesn't retry, and handle the click after.",
296 + code: buttons1,
297 + },
298 + {
299 + title: 'Route on the action',
300 + description:
301 + 'The button carried its context in `value`. Switch on the `action_id` and call the right function. Draft launches the subagent; the rest post through the proxy. The flow is deterministic, no model in the loop.',
302 + code: buttons2,
303 + },
304 + ],
305 + },
306 + draft: {
307 + file: 'api/_utils/agent.ts',
308 + stages: [
309 + {
310 + title: 'A tool-router session writes the draft',
311 + description:
312 + "Create a session for the member, scoped to the toolkit catalogue, hand its research tools to the model, and let it investigate and write. You don't list what they connected: the session just uses whatever they've authorized.",
313 + code: agent1,
314 + },
315 + {
316 + title: 'Keep the agent from connecting mid-draft',
317 + description:
318 + 'manageConnections:false removes the connection meta-tools, so the agent drafts from what the member already connected and never starts an OAuth flow while drafting.',
319 + code: agent2,
320 + },
321 + ],
322 + },
323 +};
docs/lib/standup-bot-source.json new
+52
@@ -0,0 +1,52 @@
1 +[
2 + {
3 + "path": "standup.config.ts",
4 + "contents": "// ─────────────────────────────────────────────────────────────────────────────\n// Standup bot setup. Edit this file to configure your team and tools.\n// Secrets (API keys, IDs) live in .env.local, never here.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type Member = {\n slackEmail: string; // used to look up their Slack user + Composio connections\n githubUsername: string;\n standupTime?: string; // \"HH:MM\" 24h in THEIR timezone; defaults below\n standupTimezone?: string; // IANA tz, e.g. \"Europe/Rome\"; defaults below\n};\n\nexport type Toolkit = {\n slug: string; // Composio toolkit slug\n label: string; // shown on Connect buttons\n emoji: string; // leads the bullet in the draft\n draftInstruction: string; // injected into the draft prompt when connected\n};\n\n// Model used to write the draft, via the Vercel AI Gateway.\nexport const MODEL = \"anthropic/claude-sonnet-4-5\" as const;\n\n// ─── Schedule ────────────────────────────────────────────────────────────────\n// The cron runs every 30 min on weekdays; each member is reminded in the slot\n// containing their standupTime, evaluated in their own timezone.\nexport const DEFAULT_STANDUP_TIMEZONE = \"America/Los_Angeles\";\nexport const DEFAULT_STANDUP_TIME = \"10:00\";\nexport const CRON_SLOT_MINUTES = 30;\n// When true, every member is \"due\" on every cron run, ignoring standupTime.\n// Set false in production so per-person times are honored.\nexport const DEMO_MODE = false;\n\n// ─── Team ────────────────────────────────────────────────────────────────────\nexport const standupChannel = \"#standup\";\n\nexport const team: Member[] = [\n { slackEmail: \"you@example.com\", githubUsername: \"your-handle\" },\n { slackEmail: \"teammate@example.com\", githubUsername: \"teammate-handle\" },\n // A per-person time and timezone override the defaults below:\n { slackEmail: \"alberto@example.com\", githubUsername: \"alberto-handle\", standupTimezone: \"Europe/Rome\" },\n];\n\n// GitHub org that standup drafts are scoped to. Activity in other orgs and\n// personal repos is ignored. Change this to your org.\nexport const GITHUB_ORG = \"your-github-org\";\n\n// ─── Toolkit catalogue ───────────────────────────────────────────────────────\n// Every toolkit a member can connect. The draft agent gets a Composio tool-router\n// session scoped to whichever of these each member has connected. Delete what you\n// don't want; edit draftInstruction to change how each source is summarized.\nexport const TOOLKITS: Toolkit[] = [\n {\n slug: \"github\",\n label: \"GitHub\",\n emoji: \"🔧\",\n draftInstruction:\n `GitHub: find PRs they opened or merged in the time range, SCOPED TO THE ${GITHUB_ORG} ORG ONLY. Always include \\`org:${GITHUB_ORG}\\` in the search query. Ignore other orgs and personal repos. For each meaningful PR write a one-liner explaining its PURPOSE, prefixed with a status emoji: 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed. Include the *#number*.`,\n },\n {\n slug: \"linear\",\n label: \"Linear\",\n emoji: \"📋\",\n draftInstruction:\n \"Linear: find issues they created, updated, or completed in the time range. Summarize the meaningful ones (📋), focusing on what moved forward.\",\n },\n {\n slug: \"notion\",\n label: \"Notion\",\n emoji: \"📝\",\n draftInstruction:\n \"Notion: find pages/docs they created or edited in the time range. Summarize the doc work as a one-liner (📝) describing what the doc is for.\",\n },\n {\n slug: \"googlecalendar\",\n label: \"Google Calendar\",\n emoji: \"📅\",\n draftInstruction:\n \"Google Calendar: find their meetings/events in the time range. Only mention notable ones that reflect real work (📅), not routine blocks.\",\n },\n {\n slug: \"googlemeet\",\n label: \"Google Meet\",\n emoji: \"🎥\",\n draftInstruction:\n \"Google Meet (context only): optionally read meeting details/transcripts for context. Do not list meetings just for existing.\",\n },\n {\n slug: \"zoom\",\n label: \"Zoom\",\n emoji: \"🎥\",\n draftInstruction:\n \"Zoom (context only): optionally read meeting info/recordings in the time range for extra context.\",\n },\n {\n slug: \"granola_mcp\",\n label: \"Granola\",\n emoji: \"🎙️\",\n draftInstruction:\n \"Granola (context only): optionally read meeting transcripts in the time range for additional context.\",\n },\n {\n slug: \"slack\",\n label: \"Slack\",\n emoji: \"💬\",\n draftInstruction:\n \"Slack (context only): optionally look at messages they sent in public channels for context. Do not quote verbatim.\",\n },\n];\n\nexport const TOOLKIT_SLUGS = TOOLKITS.map((t) => t.slug);\n",
5 + "composio": false
6 + },
7 + {
8 + "path": "api/cron/standup.ts",
9 + "contents": "import type { VercelRequest, VercelResponse } from \"@vercel/node\";\nimport { team, standupChannel, TOOLKITS } from \"../../standup.config\";\nimport { formatToday, isMemberDue } from \"../_utils/schedule\";\nimport { getConnectedIntegrations } from \"../_utils/composio\";\nimport { buildReminderMenu } from \"../_utils/blocks\";\nimport {\n findChannelId,\n getRecentMessages,\n postMessage,\n getPermalink,\n findUserIdByEmail,\n sendDmBlocks,\n} from \"../_utils/slack\";\nimport { env } from \"../_utils/env\";\n\nexport const maxDuration = 300;\n\nexport default async function handler(req: VercelRequest, res: VercelResponse) {\n if (req.headers.authorization !== `Bearer ${env.CRON_SECRET}`) {\n return res.status(401).json({ error: \"Unauthorized\" });\n }\n\n const results: { member: string; status: string }[] = [];\n // One shared thread per calendar day, keyed to the team timezone on purpose:\n // everyone posts into the same thread even though reminders fire in each\n // member's local time. (Per-member timezone here would fork the thread.)\n const today = formatToday();\n\n // Only members whose configured time falls in this 30-minute slot.\n const dueMembers = team.filter(isMemberDue);\n if (dueMembers.length === 0) {\n return res.status(200).json({ status: \"no members due this slot\" });\n }\n\n try {\n // Resolve the channel and find or create today's thread.\n const channelId = await findChannelId(standupChannel);\n if (!channelId) {\n return res.status(500).json({\n error: `Channel ${standupChannel} not found. Is the bot a member?`,\n });\n }\n\n const parentText = `📅 *Daily Standup: ${today}*\\n_Standups are posted in this thread as folks confirm._`;\n // Scan a generous window for today's parent. A high-volume channel could push\n // it past this; a production bot would paginate or persist the thread ts.\n const recent = await getRecentMessages(channelId, 200);\n const threadTs =\n recent.find((m) => m.text.includes(\"Daily Standup\") && m.text.includes(today))\n ?.ts ?? (await postMessage(channelId, parentText))?.ts;\n if (!threadTs) {\n return res.status(500).json({ error: \"Failed to create daily thread\" });\n }\n // Narrowed const so the per-member closure below sees a plain string.\n const thread = threadTs;\n const threadUrl = (await getPermalink(channelId, thread)) ?? \"\";\n\n // DM each due member the reminder menu, in parallel.\n async function processMember(\n member: (typeof team)[number]\n ): Promise<{ member: string; status: string }> {\n try {\n const [connected, userId] = await Promise.all([\n getConnectedIntegrations(member.slackEmail),\n findUserIdByEmail(member.slackEmail),\n ]);\n const showConnect = connected.length < TOOLKITS.length;\n\n if (!userId) {\n return { member: member.slackEmail, status: \"error: no slack user\" };\n }\n\n const menu = buildReminderMenu(\n threadUrl,\n { memberEmail: member.slackEmail, threadTs: thread, channelId: channelId! },\n showConnect\n );\n const dm = await sendDmBlocks(userId, menu.text, menu.blocks);\n return {\n member: member.slackEmail,\n status: dm ? \"reminded\" : \"error: dm failed\",\n };\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n return { member: member.slackEmail, status: `error: ${errMsg}` };\n }\n }\n\n results.push(...(await Promise.all(dueMembers.map(processMember))));\n return res.status(200).json({ threadTs, threadUrl, results });\n } catch (err) {\n return res.status(500).json({\n error: \"Internal server error\",\n message: err instanceof Error ? err.message : String(err),\n results,\n });\n }\n}\n",
10 + "composio": true
11 + },
12 + {
13 + "path": "api/interactivity.ts",
14 + "contents": "import type { VercelRequest, VercelResponse } from \"@vercel/node\";\nimport { waitUntil } from \"@vercel/functions\";\nimport crypto from \"crypto\";\nimport { team, TOOLKITS } from \"../standup.config\";\nimport { memberName } from \"./_utils/schedule\";\nimport {\n ACTION_DRAFT,\n ACTION_CONNECT,\n ACTION_CONFIRM,\n ACTION_EDIT,\n MODAL_EDIT_SUBMIT,\n EDIT_INPUT_BLOCK,\n EDIT_INPUT_ACTION,\n buildLoadingMessage,\n buildDraftMessage,\n buildPostedMessage,\n buildCopyMessage,\n buildConnectMenu,\n buildEditModal,\n extractDraft,\n StandupContext,\n} from \"./_utils/blocks\";\nimport { getConnectedIntegrations, getConnectLink } from \"./_utils/composio\";\nimport { generateDraftText } from \"./_utils/agent\";\nimport {\n openModal,\n postMessage,\n updateMessage,\n postAsUser,\n getPermalink,\n} from \"./_utils/slack\";\nimport { env } from \"./_utils/env\";\n\nexport const maxDuration = 300;\n\n// Disable Vercel's body parsing: Slack signs the EXACT raw bytes.\nexport const config = { api: { bodyParser: false } };\n\n// The subset of a Slack interaction payload this handler reads.\ntype SlackAction = { action_id?: string; value?: string };\ntype SlackInteraction = {\n type?: string;\n trigger_id?: string;\n actions?: SlackAction[];\n message?: { ts?: string; blocks?: Array<{ block_id?: string; text?: { text?: string } }> };\n container?: { channel_id?: string };\n channel?: { id?: string };\n view?: {\n callback_id?: string;\n private_metadata?: string;\n state?: { values?: Record<string, Record<string, { value?: string }>> };\n };\n};\n// What buildEditModal stuffs into the modal's private_metadata.\ntype StoredMeta = StandupContext & { dmChannel?: string; dmTs?: string };\n\nfunction readRawBody(req: VercelRequest): Promise<string> {\n return new Promise((resolve) => {\n if (typeof req.body === \"string\") return resolve(req.body);\n if (req.body && Buffer.isBuffer(req.body)) return resolve(req.body.toString(\"utf8\"));\n let data = \"\";\n req.setEncoding?.(\"utf8\");\n req.on(\"data\", (c) => (data += c));\n req.on(\"end\", () => resolve(data));\n req.on(\"error\", () => resolve(data));\n });\n}\n\n// Implements Slack's documented request-verification algorithm (v0 basestring,\n// 5-minute replay window, constant-time HMAC-SHA256 compare):\n// https://docs.slack.dev/authentication/verifying-requests-from-slack\nfunction verifySlackSignature(\n rawBody: string,\n signature: string | undefined,\n timestamp: string | undefined,\n signingSecret: string\n): boolean {\n if (!signature || !timestamp) return false;\n const age = Math.abs(Date.now() / 1000 - Number(timestamp));\n if (!Number.isFinite(age) || age > 300) return false;\n const hmac =\n \"v0=\" +\n crypto\n .createHmac(\"sha256\", signingSecret)\n .update(`v0:${timestamp}:${rawBody}`)\n .digest(\"hex\");\n try {\n return crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(signature));\n } catch {\n return false;\n }\n}\n\nexport default async function handler(req: VercelRequest, res: VercelResponse) {\n if (req.method !== \"POST\") {\n return res.status(405).json({ error: \"Method not allowed\" });\n }\n\n const rawBody = await readRawBody(req);\n if (\n !verifySlackSignature(\n rawBody,\n req.headers[\"x-slack-signature\"] as string,\n req.headers[\"x-slack-request-timestamp\"] as string,\n env.SLACK_SIGNING_SECRET\n )\n ) {\n return res.status(401).json({ error: \"Invalid signature\" });\n }\n\n const payload: SlackInteraction = JSON.parse(\n new URLSearchParams(rawBody).get(\"payload\") || \"{}\"\n );\n\n // Modal submit (edits): fast, respond inline.\n if (payload.type === \"view_submission\") {\n if (payload.view?.callback_id === MODAL_EDIT_SUBMIT) {\n const meta: StoredMeta = JSON.parse(payload.view.private_metadata || \"{}\");\n const ctx: StandupContext = {\n memberEmail: meta.memberEmail,\n threadTs: meta.threadTs,\n channelId: meta.channelId,\n };\n const edited =\n payload.view.state?.values?.[EDIT_INPUT_BLOCK]?.[EDIT_INPUT_ACTION]\n ?.value ?? \"\";\n const msg = buildDraftMessage(edited, ctx);\n if (meta.dmChannel && meta.dmTs) {\n await updateMessage(meta.dmChannel, meta.dmTs, msg.text, msg.blocks);\n }\n }\n return res.status(200).send(\"\");\n }\n\n if (payload.type !== \"block_actions\") return res.status(200).send(\"\");\n\n const action = payload.actions?.[0];\n const ctx: StandupContext = JSON.parse(action?.value || \"{}\");\n const dmChannel = payload.container?.channel_id ?? payload.channel?.id;\n const dmTs = payload.message?.ts;\n if (!dmChannel || !dmTs) return res.status(200).send(\"\");\n\n // Edit opens a modal: must use trigger_id within ~3s, so handle inline.\n if (action?.action_id === ACTION_EDIT) {\n const draft = extractDraft(payload.message ?? {});\n await openModal(\n payload.trigger_id ?? \"\",\n buildEditModal(draft, ctx, { channel: dmChannel, ts: dmTs })\n );\n return res.status(200).send(\"\");\n }\n\n // Slow work (AI draft, OAuth links, posting): ack within Slack's 3s window,\n // then run via waitUntil, which keeps the function alive after the response is\n // sent. A plain post-send await would be frozen by Vercel.\n waitUntil(\n processSlowAction(action, ctx, dmChannel, dmTs, payload).catch(async (err) => {\n // Don't leave the member stuck on the loading message: log and tell them.\n console.error(\"standup interaction failed:\", err);\n await postMessage(\n dmChannel,\n \"⚠️ Something went wrong handling that. Please try again.\"\n ).catch(() => {});\n })\n );\n return res.status(200).send(\"\");\n}\n\nasync function processSlowAction(\n action: SlackAction | undefined,\n ctx: StandupContext,\n dmChannel: string,\n dmTs: string,\n payload: SlackInteraction\n) {\n const member = team.find((m) => m.slackEmail === ctx.memberEmail);\n\n if (action?.action_id === ACTION_DRAFT) {\n const loading = buildLoadingMessage();\n await updateMessage(dmChannel, dmTs, loading.text, loading.blocks);\n\n const connected = await getConnectedIntegrations(ctx.memberEmail);\n const draft =\n member && connected.length\n ? await generateDraftText(member, connected)\n : \"\";\n const msg = buildDraftMessage(draft, ctx);\n await updateMessage(dmChannel, dmTs, msg.text, msg.blocks);\n return;\n }\n\n if (action?.action_id === ACTION_CONNECT) {\n const connected = await getConnectedIntegrations(ctx.memberEmail);\n const unconnected = TOOLKITS.filter((t) => !connected.includes(t.slug));\n const links = (\n await Promise.all(\n unconnected.map(async (t) => {\n const url = await getConnectLink(ctx.memberEmail, t.slug);\n return url ? { label: t.label, url } : null;\n })\n )\n ).filter(Boolean) as { label: string; url: string }[];\n\n if (unconnected.length === 0) {\n await postMessage(dmChannel, \"You're already connected to everything! 🎉\");\n } else if (links.length === 0) {\n // Toolkits remain, but every connect link failed to generate.\n await postMessage(\n dmChannel,\n \"⚠️ Couldn't generate connect links right now. Please try again in a moment.\"\n );\n } else {\n const menu = buildConnectMenu(links);\n await postMessage(dmChannel, menu.text, { blocks: menu.blocks });\n }\n return;\n }\n\n if (action?.action_id === ACTION_CONFIRM) {\n const draft = extractDraft(payload.message ?? {});\n // Swap the buttons out immediately so a double-click can't post twice.\n const posting = buildLoadingMessage(\"Posting your standup…\");\n await updateMessage(dmChannel, dmTs, posting.text, posting.blocks);\n\n const name = member ? memberName(member) : ctx.memberEmail;\n const connected = await getConnectedIntegrations(ctx.memberEmail);\n\n let posted = false;\n if (connected.includes(\"slack\")) {\n posted = await postAsUser(\n ctx.memberEmail,\n ctx.channelId,\n `*${name}'s standup*\\n${draft}`,\n ctx.threadTs\n );\n }\n\n if (posted) {\n const m = buildPostedMessage(draft);\n await updateMessage(dmChannel, dmTs, m.text, m.blocks);\n } else {\n // No personal Slack (or post failed): give them copyable text.\n const url = (await getPermalink(ctx.channelId, ctx.threadTs)) ?? \"\";\n const m = buildCopyMessage(draft, url);\n await updateMessage(dmChannel, dmTs, m.text, m.blocks);\n }\n return;\n }\n}\n",
15 + "composio": true
16 + },
17 + {
18 + "path": "api/_utils/env.ts",
19 + "contents": "import { config } from \"dotenv\";\n\n// Load .env.local for local runs (scripts, `vercel dev`). Harmless on Vercel,\n// where the file is absent and real environment variables are already set.\nconfig({ path: \".env.local\" });\n\n// Validate every required var once at import time, so a misconfigured deploy\n// fails fast with a clear message instead of a vague error mid-request.\nconst REQUIRED = [\n \"COMPOSIO_API_KEY\",\n \"COMPOSIO_SLACKBOT_AUTH_CONFIG_ID\", // the \"slackbot\" auth config (ac_...)\n \"SLACK_SIGNING_SECRET\", // verifies Slack interactivity requests\n \"CRON_SECRET\", // shared secret the Vercel cron presents\n] as const;\n\ntype EnvKey = (typeof REQUIRED)[number];\n\nfunction loadEnv(): Record<EnvKey, string> {\n const missing = REQUIRED.filter((key) => !process.env[key]);\n if (missing.length > 0) {\n throw new Error(\n `Missing required environment variable(s): ${missing.join(\", \")}.\\n` +\n `Copy .env.local.example to .env.local and fill them in.`\n );\n }\n return Object.fromEntries(\n REQUIRED.map((key) => [key, process.env[key]!])\n ) as Record<EnvKey, string>;\n}\n\nexport const env = loadEnv();\n",
20 + "composio": false
21 + },
22 + {
23 + "path": "api/_utils/schedule.ts",
24 + "contents": "import dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\nimport timezone from \"dayjs/plugin/timezone\";\nimport {\n Member,\n DEFAULT_STANDUP_TIME,\n DEFAULT_STANDUP_TIMEZONE,\n CRON_SLOT_MINUTES,\n DEMO_MODE,\n} from \"../../standup.config\";\n\ndayjs.extend(utc);\ndayjs.extend(timezone);\n\n/** \"soham.basu@…\" → \"Soham Basu\". Keeps raw emails out of the public channel. */\nexport function memberName(member: Member): string {\n return member.slackEmail\n .split(\"@\")[0]\n .split(/[._]/)\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\" \");\n}\n\nexport function formatToday(): string {\n return dayjs().tz(DEFAULT_STANDUP_TIMEZONE).format(\"dddd, MMMM D, YYYY\");\n}\n\n/** Draft lookback: Monday reaches back to Friday, else the previous day.\n * Computed in the member's own timezone so the window matches their day. */\nexport function lookbackWindow(\n timezone: string = DEFAULT_STANDUP_TIMEZONE\n): { date: string; label: string } {\n const now = dayjs().tz(timezone);\n const days = now.day() === 1 ? 3 : 1;\n return {\n date: now.subtract(days, \"day\").format(\"YYYY-MM-DD\"),\n label: days === 1 ? \"since yesterday\" : \"since your last standup\",\n };\n}\n\nconst memberStandupTime = (m: Member) => m.standupTime ?? DEFAULT_STANDUP_TIME;\nconst memberTimezone = (m: Member) => m.standupTimezone ?? DEFAULT_STANDUP_TIMEZONE;\n\n/** Is this member due in the current cron slot, evaluated in their timezone? */\nexport function isMemberDue(member: Member): boolean {\n if (DEMO_MODE) return true;\n const now = dayjs().tz(memberTimezone(member));\n const nowMin = now.hour() * 60 + now.minute();\n const slotStart = Math.floor(nowMin / CRON_SLOT_MINUTES) * CRON_SLOT_MINUTES;\n const [h, m] = memberStandupTime(member).split(\":\").map(Number);\n const memberMin = h * 60 + m;\n return memberMin >= slotStart && memberMin < slotStart + CRON_SLOT_MINUTES;\n}\n",
25 + "composio": false
26 + },
27 + {
28 + "path": "api/_utils/composio.ts",
29 + "contents": "import { Composio } from \"@composio/core\";\nimport { VercelProvider } from \"@composio/vercel\";\nimport { TOOLKIT_SLUGS } from \"../../standup.config\";\nimport { env } from \"./env\";\n\nexport const composio = new Composio({\n apiKey: env.COMPOSIO_API_KEY,\n provider: new VercelProvider(),\n});\n\n// The bot's own Composio user. The slackbot OAuth connection lives here, so all\n// bot Slack actions (posting to the channel, DMing members) execute as the bot.\nexport const BOT_USER = \"default\";\n\n/** Active connected accounts for a user, optionally filtered to one toolkit.\n * Filters server-side via `statuses` so we never see stale/expired ones. */\nexport async function listActiveAccounts(userId: string, toolkitSlug?: string) {\n const res = await composio.connectedAccounts.list({\n userIds: [userId],\n statuses: [\"ACTIVE\"],\n ...(toolkitSlug ? { toolkitSlugs: [toolkitSlug] } : {}),\n });\n return res.items;\n}\n\n// The bot's slackbot connected-account ID. proxyExecute needs it so the call\n// authenticates as the bot (the project has several connections, so we can't\n// rely on a default-account fallback). Resolved once and memoized.\nlet botAccountIdPromise: Promise<string | undefined> | undefined;\nfunction getBotAccountId(): Promise<string | undefined> {\n botAccountIdPromise ??= listActiveAccounts(BOT_USER, \"slackbot\")\n .then((accounts) => accounts[0]?.id)\n .then((id) => {\n // Don't cache a miss: if the bot isn't connected yet, retry next call so a\n // later setup/OAuth is picked up without waiting for a cold start.\n if (!id) botAccountIdPromise = undefined;\n return id;\n });\n return botAccountIdPromise;\n}\n\n// Wraps Composio's proxyExecute to call any Slack Web API endpoint as the bot\n// (or a member, via accountId). Covers what the named SLACKBOT_* tools don't,\n// like views.open for modals.\nexport async function slackApi<T = unknown>(\n endpoint: string,\n method: \"GET\" | \"POST\",\n body?: Record<string, unknown>,\n accountId?: string // override the bot account (e.g. post as a member)\n): Promise<T> {\n const connectedAccountId = accountId ?? (await getBotAccountId());\n const res = await composio.tools.proxyExecute({\n endpoint,\n method,\n ...(body ? { body } : {}),\n ...(connectedAccountId ? { connectedAccountId } : {}),\n });\n // proxyExecute wraps Slack's JSON response in `data`.\n return ((res as { data?: unknown }).data ?? res) as T;\n}\n\n/** Run a named Composio tool as a user (the bot by default). This is the normal\n * path for actions a SLACKBOT or SLACK tool covers (sending a message, even\n * one with Block Kit buttons, updating one, posting as a member). Returns the\n * tool's `data`, which is the Slack API response. */\nexport async function slackTool<T = Record<string, unknown>>(\n slug: string,\n args: Record<string, unknown>,\n userId: string = BOT_USER\n): Promise<T> {\n const res = await composio.tools.execute(slug, { userId, arguments: args });\n return (res.data ?? {}) as T;\n}\n\n/** Which catalogue toolkits the member has actively connected. */\nexport async function getConnectedIntegrations(\n memberEmail: string\n): Promise<string[]> {\n const active = await listActiveAccounts(memberEmail);\n const slugs = new Set(active.map((a) => a.toolkit.slug));\n return TOOLKIT_SLUGS.filter((s) => slugs.has(s));\n}\n\n/** Generate an OAuth connect link for one toolkit, for one member. */\nexport async function getConnectLink(\n memberEmail: string,\n toolkitSlug: string\n): Promise<string | null> {\n try {\n const conn = await composio.toolkits.authorize(memberEmail, toolkitSlug);\n return conn.redirectUrl ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * A tool-router session scoped to the given toolkits. `session.tools()` returns\n * Composio's research meta-tools (search/execute/workbench) limited to these\n * toolkits. `manageConnections: false` strips the connection meta-tools so the\n * draft agent can research but never initiate an OAuth flow mid-draft.\n */\nexport async function createToolRouterSession(\n memberEmail: string,\n toolkitSlugs: string[]\n) {\n return composio.create(memberEmail, {\n toolkits: toolkitSlugs,\n manageConnections: false,\n });\n}\n",
30 + "composio": true
31 + },
32 + {
33 + "path": "api/_utils/slack.ts",
34 + "contents": "import { slackApi, slackTool, listActiveAccounts } from \"./composio\";\n\n// The subset of Slack Web API response fields this bot reads. proxyExecute\n// returns the raw Slack JSON, so one shared shape keeps call sites typed.\ntype SlackResponse = {\n ok?: boolean;\n error?: string;\n ts?: string;\n channel?: string;\n permalink?: string;\n user?: { id?: string };\n channels?: Array<{ id: string; name: string }>;\n messages?: Array<{ ts: string; text?: string }>;\n response_metadata?: { next_cursor?: string };\n};\n\nexport async function findUserIdByEmail(email: string): Promise<string | null> {\n const data = await slackApi<SlackResponse>(\n `/users.lookupByEmail?email=${encodeURIComponent(email)}`,\n \"GET\"\n );\n return data.user?.id ?? null;\n}\n\n/** Resolve a channel ID from a \"#channel-name\" (or bare name). */\nexport async function findChannelId(channelName: string): Promise<string | null> {\n const name = channelName.replace(/^#/, \"\");\n let cursor: string | undefined;\n for (let i = 0; i < 10; i++) {\n const qs = new URLSearchParams({\n types: \"public_channel,private_channel\",\n limit: \"200\",\n ...(cursor ? { cursor } : {}),\n });\n const data = await slackApi<SlackResponse>(`/conversations.list?${qs.toString()}`, \"GET\");\n const match = (data.channels ?? []).find((c) => c.name === name);\n if (match) return match.id;\n cursor = data.response_metadata?.next_cursor || undefined;\n if (!cursor) break;\n }\n return null;\n}\n\n/** Fetch recent top-level messages in a channel (newest first; threaded replies excluded). */\nexport async function getRecentMessages(\n channelId: string,\n limit = 50\n): Promise<Array<{ ts: string; text: string }>> {\n const data = await slackApi<SlackResponse>(\n `/conversations.history?channel=${encodeURIComponent(channelId)}&limit=${limit}`,\n \"GET\"\n );\n return (data.messages ?? []).map((m) => ({ ts: m.ts, text: m.text ?? \"\" }));\n}\n\nexport async function postMessage(\n channel: string,\n text: string,\n opts?: { thread_ts?: string; blocks?: unknown[] }\n): Promise<{ ts: string } | null> {\n // SLACKBOT_SEND_MESSAGE is the named tool: markdown_text for prose, or Block\n // Kit `blocks` (buttons included). channel must be a channel/DM id, not a user id.\n const data = await slackTool<SlackResponse>(\"SLACKBOT_SEND_MESSAGE\", {\n channel,\n ...(opts?.blocks ? { blocks: opts.blocks } : { markdown_text: text }),\n ...(opts?.thread_ts ? { thread_ts: opts.thread_ts } : {}),\n });\n return data.ts ? { ts: data.ts } : null;\n}\n\n// Stays on the proxy: this opens a DM by passing a user id as the channel, which\n// the raw chat.postMessage allows but SLACKBOT_SEND_MESSAGE rejects (it wants a\n// pre-opened D… channel id). The proxy lets us DM the member in one call.\nexport async function sendDmBlocks(\n userId: string,\n text: string,\n blocks: unknown[]\n): Promise<{ channel: string; ts: string } | null> {\n const data = await slackApi<SlackResponse>(\"/chat.postMessage\", \"POST\", {\n channel: userId,\n text,\n blocks,\n });\n if (!data.ok || !data.channel || !data.ts) return null;\n return { channel: data.channel, ts: data.ts };\n}\n\n/** Update an existing message (e.g. swap the draft after an edit). The named\n * tool SLACKBOT_UPDATES_A_MESSAGE takes Block Kit blocks just like sending. */\nexport async function updateMessage(\n channel: string,\n ts: string,\n _text: string,\n blocks: unknown[]\n): Promise<boolean> {\n const data = await slackTool<SlackResponse>(\"SLACKBOT_UPDATES_A_MESSAGE\", { channel, ts, blocks });\n return data.ok !== false;\n}\n\n/** Permalink to a message (used to link members to today's thread). */\nexport async function getPermalink(\n channel: string,\n ts: string\n): Promise<string | null> {\n const data = await slackApi<SlackResponse>(\n `/chat.getPermalink?channel=${encodeURIComponent(channel)}&message_ts=${ts}`,\n \"GET\"\n );\n return data.permalink ?? null;\n}\n\n/** The member's OWN active Slack connected-account id (for posting as them). */\nasync function getMemberSlackAccountId(\n memberEmail: string\n): Promise<string | undefined> {\n const [active] = await listActiveAccounts(memberEmail, \"slack\");\n return active?.id;\n}\n\n/**\n * Post into the thread AS the member, using their personal Slack connection.\n * SLACK_SEND_MESSAGE (the slack user toolkit) run under their email as the\n * userId, so it posts under their name. Returns false if they have no active\n * personal Slack account.\n */\nexport async function postAsUser(\n memberEmail: string,\n channel: string,\n text: string,\n threadTs: string\n): Promise<boolean> {\n const accountId = await getMemberSlackAccountId(memberEmail);\n if (!accountId) return false;\n const data = await slackTool<SlackResponse>(\n \"SLACK_SEND_MESSAGE\",\n { channel, markdown_text: text, thread_ts: threadTs },\n memberEmail\n );\n return data.ok !== false;\n}\n\n/** Open a modal in response to a button click (needs trigger_id, <3s). */\nexport async function openModal(triggerId: string, view: unknown): Promise<boolean> {\n const data = await slackApi<SlackResponse>(\"/views.open\", \"POST\", { trigger_id: triggerId, view });\n return !!data.ok;\n}\n",
35 + "composio": true
36 + },
37 + {
38 + "path": "api/_utils/agent.ts",
39 + "contents": "import { generateText, stepCountIs } from \"ai\";\nimport { Member, MODEL, TOOLKITS, GITHUB_ORG } from \"../../standup.config\";\nimport { lookbackWindow } from \"./schedule\";\nimport { createToolRouterSession } from \"./composio\";\n\n/** The standup draft prompt, adapted to whichever toolkits the member connected. */\nfunction buildDraftPrompt(\n member: Member,\n window: { date: string; label: string },\n connectedSlugs: string[]\n): string {\n const connected = TOOLKITS.filter((t) => connectedSlugs.includes(t.slug));\n const sources = connected.map((t) => ` - ${t.draftInstruction}`).join(\"\\n\");\n const emojiLegend = connected.map((t) => `${t.emoji} ${t.label}`).join(\", \");\n\n return `You are writing @${member.githubUsername}'s daily standup, covering\n${window.label} (everything since ${window.date}).\n\nYou have a Composio tool-router session with these tools connected:\n${connected.map((t) => t.label).join(\", \")}.\nUse the meta-tools to research yourself: search for the right tool per source,\nthen execute it. Do NOT guess activity. Investigate first, then write.\n\nIMPORTANT: All tools above are ALREADY connected. Do NOT attempt to connect,\nauthenticate, or generate OAuth links. If a tool call fails, skip that source.\nNever ask the user to connect anything.\n\nWhat to look at (ONLY these connected sources):\n${sources}\n\nKeep tool requests small (filter by date, ~10 items, no full transcripts).\n\nOutput rules:\n - 2 to 5 atomic, one-line updates. Prune noise.\n - Start each line with the right source emoji: ${emojiLegend}. GitHub PRs use\n 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed and include the *#number*.\n - State WHAT they did and WHY it matters, plainly. Facts only, no speculation.\n - NEVER use em dashes. Use colons, commas, or separate sentences.\n - LINKS: this is posted to Slack, which does NOT support Markdown links. NEVER\n write [text](url). Use Slack's link syntax <url|text> instead, e.g.\n <https://github.com/${GITHUB_ORG}/repo/pull/893|#893>. A bare URL is also fine.\n - CRITICAL: your reply is posted to Slack VERBATIM. It must contain ONLY the\n bullet lines, each starting with its source emoji. No preamble (\"Here's the\n standup\"), no narration (\"I found 3 PRs\"), no headings, no closing remarks,\n no sign-off. The very first character of your reply is the first bullet's emoji.\n - If no activity in range, your entire reply is exactly: \"📭 No tracked activity ${window.label}.\"`;\n}\n\n/**\n * Generate a member's standup draft by researching their CONNECTED tools. Spins\n * up a Composio tool-router session scoped to those toolkits and lets the agent\n * drive the meta-tools to gather activity. Returns the draft text only.\n */\nexport async function generateDraftText(\n member: Member,\n connectedSlugs: string[]\n): Promise<string> {\n if (connectedSlugs.length === 0) return \"\";\n\n const session = await createToolRouterSession(member.slackEmail, connectedSlugs);\n const tools = await session.tools();\n\n const { text } = await generateText({\n model: MODEL,\n system: buildDraftPrompt(member, lookbackWindow(member.standupTimezone), connectedSlugs),\n prompt: `Research and write @${member.githubUsername}'s standup update.`,\n tools,\n stopWhen: stepCountIs(40),\n });\n\n return text.trim();\n}\n",
40 + "composio": true
41 + },
42 + {
43 + "path": "api/_utils/blocks.ts",
44 + "contents": "// Block Kit builders for the standup menu / confirm / edit / connect flow.\n// Plain data (no agent involvement) keeps the interactive messages deterministic.\n\nexport const ACTION_DRAFT = \"standup_draft\";\nexport const ACTION_CONNECT = \"standup_connect\";\nexport const ACTION_CONFIRM = \"standup_confirm\";\nexport const ACTION_EDIT = \"standup_edit\";\nexport const MODAL_EDIT_SUBMIT = \"standup_edit_submit\";\nexport const EDIT_INPUT_BLOCK = \"standup_edit_block\";\nexport const EDIT_INPUT_ACTION = \"standup_edit_input\";\n// Stable id for the draft-body section, so the handler can recover the draft\n// text by block_id instead of a fragile positional index.\nexport const DRAFT_BODY_BLOCK = \"standup_draft_body\";\n\n// Context threaded through buttons/modals so the handler knows who/where without\n// re-deriving it. Kept small (button `value` is capped at 2000 chars).\nexport type StandupContext = {\n memberEmail: string;\n threadTs: string; // parent daily-thread message ts\n channelId: string; // the standup channel's ID\n};\n\n/** The daily reminder \"menu\": a nudge + Draft button (+ Connect if applicable). */\nexport function buildReminderMenu(\n threadUrl: string,\n ctx: StandupContext,\n showConnect: boolean\n) {\n const value = JSON.stringify(ctx);\n const buttons: Record<string, unknown>[] = [\n {\n type: \"button\",\n style: \"primary\",\n text: { type: \"plain_text\", text: \"📝 Draft\", emoji: true },\n action_id: ACTION_DRAFT,\n value,\n },\n ];\n if (showConnect) {\n buttons.push({\n type: \"button\",\n text: { type: \"plain_text\", text: \"🔌 Connect more tools\", emoji: true },\n action_id: ACTION_CONNECT,\n value,\n });\n }\n return {\n text: \"Daily standup reminder\",\n blocks: [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `📅 Time for your standup. Post your update in <${threadUrl}|today's thread>.\\nTap *Draft* and I'll put together a draft from your connected tools.`,\n },\n },\n { type: \"actions\", elements: buttons },\n ],\n };\n}\n\n/** \"Researching…\" placeholder shown while the draft is generated. */\nexport function buildLoadingMessage(label = \"Researching your activity and drafting your standup…\") {\n return {\n text: label,\n blocks: [{ type: \"section\", text: { type: \"mrkdwn\", text: `⏳ ${label}` } }],\n };\n}\n\n/** The draft DM: the draft text + Confirm/Edit buttons. */\nexport function buildDraftMessage(draft: string, ctx: StandupContext) {\n const value = JSON.stringify(ctx);\n const body = draft.trim()\n ? draft\n : \"_No draft yet. Tap ✏️ Edit to write your update._\";\n return {\n text: \"Your standup draft is ready for review.\",\n blocks: [\n {\n type: \"section\",\n text: { type: \"mrkdwn\", text: \"*Your standup draft.* Review and post 👇\" },\n },\n { type: \"section\", block_id: DRAFT_BODY_BLOCK, text: { type: \"mrkdwn\", text: body } },\n { type: \"divider\" },\n {\n type: \"actions\",\n elements: [\n {\n type: \"button\",\n style: \"primary\",\n text: { type: \"plain_text\", text: \"✅ Confirm & Post\", emoji: true },\n action_id: ACTION_CONFIRM,\n value,\n },\n {\n type: \"button\",\n text: { type: \"plain_text\", text: \"✏️ Edit\", emoji: true },\n action_id: ACTION_EDIT,\n value,\n },\n ],\n },\n ],\n };\n}\n\ntype DraftMessage = {\n blocks?: Array<{ block_id?: string; text?: { text?: string } }>;\n};\n\n/** Recover the draft text from a posted draft message, by stable block_id. */\nexport function extractDraft(message: DraftMessage): string {\n const block = (message.blocks ?? []).find(\n (b) => b.block_id === DRAFT_BODY_BLOCK\n );\n return block?.text?.text ?? \"\";\n}\n\n/** Shown after posting from the user's own Slack account. */\nexport function buildPostedMessage(draft: string) {\n return {\n text: \"Standup posted.\",\n blocks: [\n { type: \"section\", text: { type: \"mrkdwn\", text: \"✅ *Posted to the standup thread.*\" } },\n { type: \"section\", text: { type: \"mrkdwn\", text: draft } },\n ],\n };\n}\n\n/** Fallback when the member has no personal Slack: copyable text + thread link. */\nexport function buildCopyMessage(draft: string, threadUrl: string) {\n return {\n text: \"Copy your standup into the thread.\",\n blocks: [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: `Here's your standup. Copy it and paste it into <${threadUrl}|today's thread>:`,\n },\n },\n { type: \"section\", text: { type: \"mrkdwn\", text: \"```\" + draft + \"```\" } },\n {\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: \"_Connect your Slack (tap Connect on the reminder) to have me post it for you next time._\",\n },\n ],\n },\n ],\n };\n}\n\n/** Connect menu: one URL button per unconnected tool (opens its OAuth link). */\nexport function buildConnectMenu(links: { label: string; url: string }[]) {\n // Slack actions blocks allow max 5 elements; chunk into rows of 5.\n const rows: Record<string, unknown>[] = [];\n for (let i = 0; i < links.length; i += 5) {\n rows.push({\n type: \"actions\",\n elements: links.slice(i, i + 5).map((l) => ({\n type: \"button\",\n text: { type: \"plain_text\", text: `Connect ${l.label}`, emoji: true },\n url: l.url,\n })),\n });\n }\n return {\n text: \"Connect tools to enrich your standup drafts.\",\n blocks: [\n {\n type: \"section\",\n text: {\n type: \"mrkdwn\",\n text: \"*Connect your tools* so I can draft from your real activity. All optional:\",\n },\n },\n ...rows,\n ],\n };\n}\n\n/** Edit modal: multiline input prefilled with the current draft. */\nexport function buildEditModal(\n draft: string,\n ctx: StandupContext,\n dm: { channel: string; ts: string }\n) {\n return {\n type: \"modal\",\n callback_id: MODAL_EDIT_SUBMIT,\n private_metadata: JSON.stringify({ ...ctx, dmChannel: dm.channel, dmTs: dm.ts }),\n title: { type: \"plain_text\", text: \"Edit standup\" },\n submit: { type: \"plain_text\", text: \"Save\" },\n close: { type: \"plain_text\", text: \"Cancel\" },\n blocks: [\n {\n type: \"input\",\n block_id: EDIT_INPUT_BLOCK,\n label: { type: \"plain_text\", text: \"Your standup update\" },\n element: {\n type: \"plain_text_input\",\n action_id: EDIT_INPUT_ACTION,\n multiline: true,\n initial_value: draft,\n },\n },\n ],\n };\n}\n",
45 + "composio": false
46 + },
47 + {
48 + "path": "scripts/setup.ts",
49 + "contents": "import { Composio } from \"@composio/core\";\nimport { env } from \"../api/_utils/env\";\n\n// One-time setup: connect the bot's Slack (\"slackbot\") account so it can post to\n// the channel and DM members. Run with `npx tsx scripts/setup.ts`, or\n// `--reconnect` to clear and re-do the OAuth (needed after changing Slack scopes).\nconst COMPOSIO_BASE_URL = \"https://backend.composio.dev\";\nconst TOOLKIT_SLUG = \"slackbot\";\n\n// Scopes the bot's OAuth *user* token must carry. Composio freezes the scopes at\n// connect time, so we check them before connecting and tell the user what to add.\nconst REQUIRED_USER_SCOPES = [\"team:read\"];\n\nconst log = {\n ok: (msg: string) => console.log(` ✅ ${msg}`),\n info: (msg: string) => console.log(` · ${msg}`),\n warn: (msg: string) => console.log(` ⚠️ ${msg}`),\n};\n\nfunction errMessage(err: unknown): string {\n if (err && typeof err === \"object\") {\n const e = err as {\n error?: { error?: { message?: string }; message?: string };\n message?: string;\n };\n return e.error?.error?.message ?? e.error?.message ?? e.message ?? String(err);\n }\n return String(err);\n}\n\nasync function main() {\n const RECONNECT = process.argv.includes(\"--reconnect\");\n\n console.log(\"\\n╭─────────────────────────────────────────────────────────╮\");\n console.log(\"│ Daily Standup Bot: One-Time Setup │\");\n console.log(\"╰─────────────────────────────────────────────────────────╯\");\n if (RECONNECT) {\n console.log(\" (--reconnect: will clear and re-do the bot's Slack auth)\");\n }\n\n const composio = new Composio({ apiKey: env.COMPOSIO_API_KEY });\n const authConfigId = env.COMPOSIO_SLACKBOT_AUTH_CONFIG_ID;\n\n // Check the auth config requests the scopes the bot needs.\n // READ-ONLY on purpose. GET returns secrets MASKED, and a PATCH that echoes\n // those masked values back overwrites the real client_secret with the mask.\n // So we never write credentials here; we only check and warn.\n const cfgRes = await fetch(`${COMPOSIO_BASE_URL}/api/v3/auth_configs/${authConfigId}`, {\n headers: { \"x-api-key\": env.COMPOSIO_API_KEY },\n });\n if (cfgRes.ok) {\n const cfg = (await cfgRes.json().catch(() => ({}))) as {\n credentials?: { user_scopes?: string[] };\n };\n const userScopes = cfg.credentials?.user_scopes ?? [];\n const missing = REQUIRED_USER_SCOPES.filter((s) => !userScopes.includes(s));\n if (missing.length > 0) {\n log.warn(`Auth config is missing required user scope(s): ${missing.join(\", \")}`);\n console.log(\n \" Add them under the auth config's User Token Scopes in the Composio\\n\" +\n \" dashboard (Auth Configs → slackbot), then re-run with --reconnect.\"\n );\n } else {\n log.ok(\"Auth config has the required user scopes.\");\n }\n }\n\n // Ensure the bot's Slack connection is active.\n const session = await composio.create(\"default\", {\n authConfigs: { slackbot: authConfigId },\n });\n\n async function listSlackbotAccounts() {\n try {\n const res = await composio.connectedAccounts.list({\n userIds: [\"default\"],\n toolkitSlugs: [TOOLKIT_SLUG],\n });\n return res.items;\n } catch {\n return [];\n }\n }\n\n if (RECONNECT) {\n const accounts = await listSlackbotAccounts();\n if (accounts.length === 0) {\n log.info(\"No existing connections to clear.\");\n } else {\n for (const acc of accounts) {\n try {\n await composio.connectedAccounts.delete(acc.id);\n log.ok(`Removed old connection ${acc.id}.`);\n } catch (err) {\n log.warn(`Could not remove ${acc.id}: ${errMessage(err)}`);\n }\n }\n }\n }\n\n let connected = false;\n if (!RECONNECT) {\n const toolkits = await session.toolkits({ toolkits: [TOOLKIT_SLUG] });\n connected = !!toolkits.items.find((t) => t.slug === TOOLKIT_SLUG)?.connection\n ?.isActive;\n }\n\n if (connected) {\n log.ok(\"Bot is already connected to Slack.\");\n } else {\n log.info(\"Bot is not connected yet. Generating an authorization link…\");\n // Manual authentication: authorize() returns a Connect Link, then\n // waitForConnection() resolves once the bot finishes OAuth in the browser.\n // https://docs.composio.dev/docs/manually-authenticating\n const connectionRequest = await session.authorize(TOOLKIT_SLUG);\n if (!connectionRequest.redirectUrl) {\n throw new Error(\"Composio did not return an authorization link.\");\n }\n\n console.log(\"\\n Open this URL in your browser to authorize the bot:\\n\");\n console.log(` ${connectionRequest.redirectUrl}\\n`);\n console.log(\" Waiting for you to complete the OAuth flow (Ctrl+C to abort)…\");\n\n const TIMEOUT_MS = 5 * 60 * 1000;\n const account = await connectionRequest.waitForConnection(TIMEOUT_MS);\n log.ok(`Bot connected to Slack (${account.id}).`);\n }\n\n console.log(`\\n${\"─\".repeat(70)}`);\n console.log(\" 🎉 Setup complete. Invite the bot to your standup channel and\");\n console.log(\" point your Slack app's Interactivity Request URL at\");\n console.log(\" https://<your-deployment>/api/interactivity\");\n console.log(`${\"─\".repeat(70)}\\n`);\n}\n\nmain().catch((err) => {\n console.error(`\\n ❌ ${errMessage(err)}\\n`);\n process.exit(1);\n});\n",
50 + "composio": true
51 + }
52 +]
docs/lib/terminal-layout.ts new
+10
@@ -0,0 +1,10 @@
1 +import type { TerminalTheme } from "@/lib/terminal-themes"
2 +
3 +/** Per-theme structural layout — distinct from palette tokens alone. */
4 +export type TerminalLayoutMode = "bubble" | "compact" | "claude"
5 +
6 +export function terminalLayoutMode(theme: TerminalTheme): TerminalLayoutMode {
7 + if (theme === "claude") return "claude"
8 + if (theme === "default") return "bubble"
9 + return "compact"
10 +}
docs/lib/terminal-themes.ts new
+28
@@ -0,0 +1,28 @@
1 +export const TERMINAL_THEMES = ["default", "grok", "claude"] as const
2 +
3 +export type TerminalTheme = (typeof TERMINAL_THEMES)[number]
4 +
5 +export const TERMINAL_THEME_LABELS: Record<TerminalTheme, string> = {
6 + default: "Default",
7 + grok: "Grok",
8 + claude: "Claude",
9 +}
10 +
11 +export function terminalThemeClass(theme: TerminalTheme = "default") {
12 + return theme === "default" ? "terminal-theme-default" : `terminal-theme-${theme}`
13 +}
14 +
15 +export function terminalThemeLightClass(theme: TerminalTheme = "default") {
16 + return theme === "default" ? "terminal-theme-light" : `terminal-theme-${theme}-light`
17 +}
18 +
19 +export function terminalThemeClasses(
20 + theme: TerminalTheme = "default",
21 + variant: "dark" | "light" = "dark"
22 +) {
23 + return [
24 + "terminal-theme",
25 + terminalThemeClass(theme),
26 + variant === "light" ? terminalThemeLightClass(theme) : null,
27 + ].filter(Boolean) as string[]
28 +}
docs/mdx-components.tsx
+32
@@ -25,12 +25,28 @@ import { Mermaid } from '@/components/mermaid';
25 import { AIToolsBanner } from '@/components/ai-tools-banner';
26 import { DocsHero } from '@/components/docs-hero';
27 import { HomeFeatures } from '@/components/home-features';
28 +import { SessionFlow } from '@/components/session-flow';
29 +import { TriggersFlow } from '@/components/triggers-flow';
30 +import { SlackBotFlow } from '@/components/slack-bot-flow';
31 +import { LocalWorkbenchFlow } from '@/components/local-workbench-flow';
32 +import { LocalSandboxBoundary } from '@/components/local-sandbox-boundary';
33 +import { FileBuildup } from '@/components/file-buildup';
34 +import { RepoBrowser } from '@/components/repo-browser';
35 +import { AppLogo } from '@/components/standup-example';
36 +import { WorkbenchFlow } from '@/components/workbench-flow';
37 +import { AuthConfigFlow } from '@/components/auth-config-flow';
38 +import { WhiteLabelFlow } from '@/components/white-label-flow';
39 +import { ImportConnectionFlow } from '@/components/import-connection-flow';
40 import { HomeSurfaces } from '@/components/home-surfaces';
41 import { HomeResources } from '@/components/home-resources';
42 import { Glossary, GlossaryTerm } from '@/components/glossary';
43 import { ApiBaseUrl } from '@/components/api-base-url';
44 import { ApiEndpointsTable } from '@/components/api-endpoints-table';
45 import { ClaudeMockUI } from '@/components/claude-mock-ui';
46 +import { InChatAuthTerminal } from '@/components/in-chat-auth-terminal';
47 +import { MediaSplit } from '@/components/media-split';
48 +import { ManageConnectionsVisual } from '@/components/manage-connections-visual';
49 +import { ConnectionRefreshVisual } from '@/components/connection-refresh-visual';
50 import {
51 ShieldCheck,
52 Route as RouteIcon,
@@ -105,6 +121,18 @@ export function getMDXComponents(components?: MDXComponents): MDXComponents {
121 AIToolsBanner,
122 DocsHero,
123 HomeFeatures,
124 + SessionFlow,
125 + TriggersFlow,
126 + SlackBotFlow,
127 + LocalWorkbenchFlow,
128 + LocalSandboxBoundary,
129 + FileBuildup,
130 + RepoBrowser,
131 + AppLogo,
132 + WorkbenchFlow,
133 + AuthConfigFlow,
134 + WhiteLabelFlow,
135 + ImportConnectionFlow,
136 HomeSurfaces,
137 HomeResources,
138 StepTitle,
@@ -113,6 +141,10 @@ export function getMDXComponents(components?: MDXComponents): MDXComponents {
141 ApiBaseUrl,
142 ApiEndpointsTable,
143 ClaudeMockUI,
144 + InChatAuthTerminal,
145 + MediaSplit,
146 + ManageConnectionsVisual,
147 + ConnectionRefreshVisual,
148 // Lucide icons
149 ShieldCheck,
150 RouteIcon,
docs/next.config.mjs
+234 -41
@@ -1,6 +1,7 @@
1 import { dirname } from 'path';
2 import { fileURLToPath } from 'url';
3 import { createMDX } from 'fumadocs-mdx/next';
4 +import { withEve } from 'eve/next';
5
6 const __dirname = dirname(fileURLToPath(import.meta.url));
7 const withMDX = createMDX();
@@ -10,6 +11,28 @@ const config = {
11 reactStrictMode: true,
12 turbopack: {
13 root: __dirname,
14 + resolveAlias: {
15 + // eve/react pulls in a bundled rolldown helper with a bare, unused
16 + // `import "node:module"`. Turbopack can't keep that as an external in a
17 + // browser chunk, so stub it to an empty module on the browser.
18 + 'node:module': { browser: './lib/eve-empty-module.js' },
19 + },
20 + },
21 + // The OpenAPI specs are loaded at request time via
22 + // `join(process.cwd(), 'public/openapi.json')` (see lib/openapi.ts). Because
23 + // that path is computed, Next.js' file tracer can't statically detect it, so
24 + // the JSON files are NOT bundled into the serverless functions that render
25 + // reference pages and their `/llms.mdx/reference/...` (.md) endpoints. Without
26 + // them present on disk, fumadocs-openapi throws
27 + // `[OpenAPI] Failed to resolve input` and the route 500s in production
28 + // (it works at build time only because `public/` exists at the project root).
29 + // Explicitly trace the specs into every route that may resolve them at runtime.
30 + outputFileTracingIncludes: {
31 + '/reference/**': ['./public/openapi.json', './public/openapi-v3.json'],
32 + '/reference/v3/**': ['./public/openapi.json', './public/openapi-v3.json'],
33 + '/llms.mdx/**': ['./public/openapi.json', './public/openapi-v3.json'],
34 + '/llms-full.txt/**': ['./public/openapi.json', './public/openapi-v3.json'],
35 + '/llms.txt/**': ['./public/openapi.json', './public/openapi-v3.json'],
36 },
37 images: {
38 // Enable modern image formats for better compression
@@ -27,30 +50,151 @@ const config = {
50 },
51 async redirects() {
52 return [
53 + // === Docs v3 reorganization redirects (auto-generated: route moves vs pre-reorg) ===
54 + // Renamed/moved pages -> new location
55 + {
56 + source: '/docs/observability/logs',
57 + destination: '/reference/api-reference/logs',
58 + permanent: true,
59 + },
60 + {
61 + source: '/reference/sdk-reference/python/tool-router-session',
62 + destination: '/reference/sdk-reference/python/session',
63 + permanent: true,
64 + },
65 + {
66 + source: '/reference/sdk-reference/typescript/tool-router-session-files-mount',
67 + destination: '/reference/sdk-reference/typescript/session-files',
68 + permanent: true,
69 + },
70 + {
71 + source: '/reference/sdk-reference/typescript/tool-router-session',
72 + destination: '/reference/sdk-reference/typescript/session',
73 + permanent: true,
74 + },
75 + {
76 + source: '/toolkits/premium-tools',
77 + destination: '/toolkits/pro-tools',
78 + permanent: true,
79 + },
80 + // Deleted/merged pages -> closest surviving page (semantically resolved + verified)
81 + {
82 + source: '/docs/authenticating-users/in-chat-authentication',
83 + destination: '/docs/authentication',
84 + permanent: true,
85 + },
86 + {
87 + source: '/docs/common-faq',
88 + destination: '/docs',
89 + permanent: true,
90 + },
91 + {
92 + source: '/docs/debugging-info',
93 + destination: '/reference/errors',
94 + permanent: true,
95 + },
96 + {
97 + source: '/docs/glossary',
98 + destination: '/reference/glossary',
99 + permanent: true,
100 + },
101 + {
102 + source: '/docs/native-tools-vs-mcp',
103 + destination: '/docs/sessions-via-mcp',
104 + permanent: true,
105 + },
106 + {
107 + source: '/docs/observability',
108 + destination: '/reference/api-reference/logs',
109 + permanent: true,
110 + },
111 + {
112 + source: '/docs/observability/usage',
113 + destination: '/reference/api-reference/organization',
114 + permanent: true,
115 + },
116 + {
117 + source: '/docs/projects',
118 + destination: '/reference/api-reference/projects',
119 + permanent: true,
120 + },
121 + {
122 + source: '/docs/signing-up-as-an-agent',
123 + destination: '/docs/cli',
124 + permanent: true,
125 + },
126 + {
127 + source: '/docs/subscribing-to-connection-expiry-events',
128 + destination: '/docs/setting-up-triggers/subscribing-to-events',
129 + permanent: true,
130 + },
131 + {
132 + source: '/docs/toolkits/enable-and-disable-toolkits',
133 + destination: '/docs/configuring-sessions',
134 + permanent: true,
135 + },
136 + {
137 + source: '/docs/toolkits/fetching-tools-and-toolkits',
138 + destination: '/docs/configuring-sessions',
139 + permanent: true,
140 + },
141 + {
142 + source: '/docs/tools-and-toolkits',
143 + destination: '/docs/how-composio-works',
144 + permanent: true,
145 + },
146 + {
147 + source: '/docs/webhook-verification',
148 + destination: '/docs/setting-up-triggers/subscribing-to-events',
149 + permanent: true,
150 + },
151 + {
152 + source: '/reference/api-reference/authentication',
153 + destination: '/reference/authenticating-to-composio',
154 + permanent: true,
155 + },
156 + {
157 + source: '/reference/sdk-reference/python/session-context-impl',
158 + destination: '/reference/sdk-reference/python/session',
159 + permanent: true,
160 + },
161 + {
162 + source: '/reference/sdk-reference/typescript/session-context-impl',
163 + destination: '/reference/sdk-reference/typescript/session',
164 + permanent: true,
165 + },
166 + {
167 + source: '/reference/v3/api-reference/authentication',
168 + destination: '/reference/v3/authentication',
169 + permanent: true,
170 + },
171 + // === end docs v3 reorganization redirects ===
172 {
173 source: '/',
174 destination: '/docs',
175 permanent: false,
176 },
177 + // Meta Tools moved from the Reference tab to the Toolkits tab.
178 {
36 - source: '/examples',
37 - destination: '/cookbooks',
179 + source: '/reference/meta-tools',
180 + destination: '/toolkits/meta-tools',
181 permanent: true,
182 },
183 {
41 - source: '/cookbooks/vercel-chat',
42 - destination: '/cookbooks/chat-app',
184 + source: '/reference/meta-tools/:path*',
185 + destination: '/toolkits/meta-tools/:path*',
186 permanent: true,
187 },
45 - // Specific /examples/ subroutes before the catch-all
188 + // Cookbooks were renamed to Examples; the old articles were removed,
189 + // so send every old /cookbooks URL to the Examples index.
190 {
47 - source: '/examples/combined/:path*',
48 - destination: '/cookbooks',
191 + source: '/cookbooks',
192 + destination: '/examples',
193 permanent: true,
194 },
195 {
52 - source: '/examples/:path*',
53 - destination: '/cookbooks/:path*',
196 + source: '/cookbooks/:path*',
197 + destination: '/examples',
198 permanent: true,
199 },
200 {
@@ -58,6 +202,18 @@ const config = {
202 destination: '/docs',
203 permanent: true,
204 },
205 + // The workbench was renamed to the sandbox; keep old links working.
206 + {
207 + source: '/docs/workbench',
208 + destination: '/docs/sandbox/remote',
209 + permanent: true,
210 + },
211 + // The sandbox page became a section (remote + local); keep the old URL working.
212 + {
213 + source: '/docs/sandbox',
214 + destination: '/docs/sandbox/remote',
215 + permanent: true,
216 + },
217 {
218 source: '/docs/changelog',
219 destination: '/reference/changelog',
@@ -126,18 +282,18 @@ const config = {
282 },
283 {
284 source: '/tool-router/tools-and-toolkits',
129 - destination: '/docs/tools-and-toolkits',
285 + destination: '/docs/how-composio-works',
286 permanent: true,
287 },
288 // Authentication pages moved from tool-router to docs
289 {
290 source: '/tool-router/using-in-chat-authentication',
135 - destination: '/docs/authenticating-users/in-chat-authentication',
291 + destination: '/docs/authentication#in-chat-authentication',
292 permanent: true,
293 },
294 {
295 source: '/tool-router/manually-authenticating-users',
140 - destination: '/docs/authenticating-users/manually-authenticating',
296 + destination: '/docs/manually-authenticating',
297 permanent: true,
298 },
299 {
@@ -275,6 +431,39 @@ const config = {
431 destination: '/reference/api-reference/:path*',
432 permanent: true,
433 },
434 + // Programmatic auth configs consolidated into the Customizing auth section
435 + {
436 + source: '/docs/auth-configuration/programmatic-auth-configs',
437 + destination: '/docs/programmatic-auth-configs',
438 + permanent: true,
439 + },
440 + // Authenticating users folder flattened into the Authenticate users section
441 + {
442 + source: '/docs/authenticating-users/manually-authenticating',
443 + destination: '/docs/manually-authenticating',
444 + permanent: true,
445 + },
446 + {
447 + source: '/docs/authenticating-users/managing-multiple-connected-accounts',
448 + destination: '/docs/managing-multiple-connected-accounts',
449 + permanent: true,
450 + },
451 + {
452 + source: '/docs/authenticating-users/shared-connections',
453 + destination: '/docs/shared-connections',
454 + permanent: true,
455 + },
456 + // Authentication reference renamed to "Authenticating to Composio"
457 + {
458 + source: '/reference/authentication',
459 + destination: '/reference/authenticating-to-composio',
460 + permanent: true,
461 + },
462 + {
463 + source: '/reference/authentication/:path*',
464 + destination: '/reference/authenticating-to-composio/:path*',
465 + permanent: true,
466 + },
467 // Features section redirects
468 {
469 source: '/docs/users-and-sessions',
@@ -291,11 +480,6 @@ const config = {
480 destination: '/docs/setting-up-triggers/creating-triggers',
481 permanent: true,
482 },
294 - {
295 - source: '/docs/setting-up-triggers/webhook-verification',
296 - destination: '/docs/webhook-verification',
297 - permanent: true,
298 - },
483 {
484 source: '/triggers',
485 destination: '/docs/triggers',
@@ -303,7 +487,7 @@ const config = {
487 },
488 {
489 source: '/docs/how-tools-work',
306 - destination: '/docs/tools-and-toolkits',
490 + destination: '/docs/how-composio-works',
491 permanent: true,
492 },
493 {
@@ -352,19 +536,35 @@ const config = {
536 destination: '/docs/tools-direct/modify-tool-behavior/:path*',
537 permanent: true,
538 },
539 + // Custom tools and proxy execute moved under the Extending sessions section.
540 + {
541 + source: '/docs/custom-tools-and-toolkits',
542 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
543 + permanent: true,
544 + },
545 + {
546 + source: '/docs/toolkits/custom-tools-and-toolkits',
547 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
548 + permanent: true,
549 + },
550 + {
551 + source: '/docs/proxy-execute',
552 + destination: '/docs/extending-sessions/proxy-execute',
553 + permanent: true,
554 + },
555 {
556 source: '/docs/custom-tools',
357 - destination: '/docs/toolkits/custom-tools-and-toolkits',
557 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
558 permanent: true,
559 },
560 {
561 source: '/docs/tools-direct/custom-tools',
362 - destination: '/docs/toolkits/custom-tools-and-toolkits',
562 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
563 permanent: true,
564 },
565 {
566 source: '/docs/tools-direct/custom-tools/:path*',
367 - destination: '/docs/toolkits/custom-tools-and-toolkits',
567 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
568 permanent: true,
569 },
570 {
@@ -378,11 +578,6 @@ const config = {
578 destination: '/docs/auth-configuration/custom-auth-configs',
579 permanent: true,
580 },
381 - {
382 - source: '/docs/programmatic-auth-configs',
383 - destination: '/docs/auth-configuration/programmatic-auth-configs',
384 - permanent: true,
385 - },
581 {
582 source: '/docs/custom-auth-params',
583 destination: '/docs/auth-configuration/custom-auth-params',
@@ -413,7 +608,7 @@ const config = {
608 },
609 {
610 source: '/toolkits/introduction',
416 - destination: '/docs/tools-and-toolkits',
611 + destination: '/docs/how-composio-works',
612 permanent: true,
613 },
614 {
@@ -433,12 +628,12 @@ const config = {
628 },
629 {
630 source: '/guides/examples/:path*',
436 - destination: '/cookbooks',
631 + destination: '/examples',
632 permanent: true,
633 },
634 {
635 source: '/custom-tools/:path*',
441 - destination: '/docs/toolkits/custom-tools-and-toolkits',
636 + destination: '/docs/extending-sessions/custom-tools-and-toolkits',
637 permanent: true,
638 },
639 // Error handling redirect (old fern URL)
@@ -471,12 +666,12 @@ const config = {
666 },
667 {
668 source: '/tool-calling/introduction',
474 - destination: '/docs/tools-and-toolkits',
669 + destination: '/docs/how-composio-works',
670 permanent: true,
671 },
672 {
673 source: '/tool-calling/:path*',
479 - destination: '/docs/tools-and-toolkits',
674 + destination: '/docs/how-composio-works',
675 permanent: true,
676 },
677 // Old framework pages
@@ -563,7 +758,7 @@ const config = {
758 // Guides case studies
759 {
760 source: '/guides/casestudy/:path*',
566 - destination: '/cookbooks',
761 + destination: '/examples',
762 permanent: true,
763 },
764 // Docs pages that moved or don't exist
@@ -579,7 +774,7 @@ const config = {
774 },
775 {
776 source: '/docs/tools',
582 - destination: '/docs/tools-and-toolkits',
777 + destination: '/docs/how-composio-works',
778 permanent: true,
779 },
780 {
@@ -666,7 +861,7 @@ const config = {
861 },
862 {
863 source: '/apps/usecases/:path*',
669 - destination: '/cookbooks',
864 + destination: '/examples',
865 permanent: true,
866 },
867 {
@@ -711,11 +906,6 @@ const config = {
906 destination: '/docs/tools-direct/modify-tool-behavior',
907 permanent: true,
908 },
714 - {
715 - source: '/docs/troubleshooting/overview',
716 - destination: '/docs/troubleshooting',
717 - permanent: true,
718 - },
909 {
910 source: '/docs/mcp-overview',
911 destination: '/docs/single-toolkit-mcp',
@@ -804,7 +994,7 @@ const config = {
994 },
995 {
996 source: '/cryptokit/:path*',
807 - destination: '/cookbooks',
997 + destination: '/examples',
998 permanent: true,
999 },
1000 {
@@ -859,4 +1049,7 @@ const config = {
1049 },
1050 };
1051
862 -export default withMDX(config);
1052 +// `withEve` mounts the Eve docs assistant (agent/) on same-origin /eve/v1/*
1053 +// routes and runs the agent alongside the Next.js app in one Vercel deploy.
1054 +// Requires Node 24+ (see package.json engines / .node-version).
1055 +export default withEve(withMDX(config));
docs/package.json
+22 -3
@@ -2,11 +2,17 @@
2 "name": "@composio/docs",
3 "version": "0.0.0",
4 "private": true,
5 + "engines": {
6 + "node": ">=24"
7 + },
8 "scripts": {
9 + "build:agent-index": "bun scripts/build-agent-index.ts",
10 + "prebuild": "bun scripts/build-agent-index.ts",
11 "build": "next build",
12 + "predev": "bun scripts/build-agent-index.ts",
13 "dev": "next dev",
14 "start": "next start",
9 - "types:check": "fumadocs-mdx && next typegen && tsc --noEmit",
15 + "types:check": "bun scripts/build-agent-index.ts && fumadocs-mdx && next typegen && tsc --noEmit",
16 "postinstall": "fumadocs-mdx",
17 "lint": "eslint",
18 "lint:links": "bun scripts/validate-links.ts",
@@ -19,26 +25,38 @@
25 "test:integration": "bun test tests/integration/ --timeout 30000"
26 },
27 "dependencies": {
28 + "@pierre/diffs": "^1.2.11",
29 + "@pierre/trees": "^1.0.0-beta.4",
30 "@radix-ui/react-tabs": "^1.1.13",
31 + "@shikijs/langs": "^4.2.0",
32 + "@shikijs/themes": "^4.2.0",
33 "@shikijs/twoslash": "^3.21.0",
34 "@vercel/analytics": "^1.6.1",
35 "algoliasearch": "^5",
36 "class-variance-authority": "^0.7.1",
37 "clsx": "^2.1.1",
38 + "diff": "^9.0.0",
39 + "eve": "^0.13.3",
40 "framer-motion": "^12.39.0",
41 "fumadocs-core": "^16.4.2",
42 "fumadocs-mdx": "^14.2.4",
43 "fumadocs-openapi": "^10.2.2",
44 "fumadocs-ui": "^16.4.2",
45 + "highlight.js": "^11.11.1",
46 "lucide-react": "^0.562.0",
47 "mermaid": "^11.12.3",
48 + "motion": "^12.34.3",
49 "next": "16.2.6",
50 + "nucleo-pixel": "^1.3.0",
51 "posthog-js": "^1.319.0",
52 "react": "^19.2.3",
53 "react-dom": "^19.2.3",
54 + "react-markdown": "^10.1.0",
55 + "remark-gfm": "^4.0.1",
56 "search-insights": "^2",
57 "shiki": "^3.20.0",
41 - "tailwind-merge": "^3.4.0"
58 + "tailwind-merge": "^3.4.0",
59 + "zod": "^4.4.3"
60 },
61 "devDependencies": {
62 "@ai-sdk/anthropic": "^3.0.11",
@@ -71,12 +89,13 @@
89 "@types/node": "^24.10.2",
90 "@types/react": "^19.2.7",
91 "@types/react-dom": "^19.2.3",
74 - "ai": "^6.0.30",
92 + "ai": "7.0.0-beta.178",
93 "ajv": "^8.17.1",
94 "ajv-draft-04": "^1.0.0",
95 "eslint": "^9.39.2",
96 "eslint-config-next": "16.2.9",
97 "github-slugger": "^2.0.0",
98 + "microsandbox": "^0.5.7",
99 "next-validate-link": "^1.6.4",
100 "openai": "^6.16.0",
101 "postcss": "^8.5.6",
docs/public/images/providers/pi-logo-dark.svg new
+20
@@ -0,0 +1,20 @@
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">
3 + <path fill="#fff" fill-rule="evenodd" d="
4 + M165.29 165.29
5 + H517.36
6 + V400
7 + H400
8 + V517.36
9 + H282.65
10 + V634.72
11 + H165.29
12 + Z
13 + M282.65 282.65
14 + V400
15 + H400
16 + V282.65
17 + Z
18 + "/>
19 + <path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/>
20 +</svg>
docs/public/images/providers/pi-logo.svg new
+20
@@ -0,0 +1,20 @@
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">
3 + <path fill="#000" fill-rule="evenodd" d="
4 + M165.29 165.29
5 + H517.36
6 + V400
7 + H400
8 + V517.36
9 + H282.65
10 + V634.72
11 + H165.29
12 + Z
13 + M282.65 282.65
14 + V400
15 + H400
16 + V282.65
17 + Z
18 + "/>
19 + <path fill="#000" d="M517.36 400 H634.72 V634.72 H517.36 Z"/>
20 +</svg>
docs/public/images/standup-slackbot/README.md new
+26
@@ -0,0 +1,26 @@
1 +# Standup bot screenshots
2 +
3 +Drop the "bring your own Slack bot" screenshots here. The example page references
4 +these exact filenames (PNG, ~1200px wide; redact any secrets):
5 +
6 +Bot identity:
7 +- `bot-avatar.png` — the bot's profile picture (shown in the intro)
8 +
9 +What a teammate sees (runtime Slack UI, shown in the intro):
10 +- `slack-reminder.png` — the daily reminder DM with Draft / Connect more tools
11 +- `slack-draft.png` — a generated draft with Confirm & Post / Edit
12 +- `slack-connect.png` — the connect-more-tools menu of per-member OAuth buttons
13 +
14 +Slack side:
15 +- `create-app.png` — Slack "Name app & choose workspace" modal (From scratch)
16 +- `bot-scopes.png` — OAuth & Permissions, Bot Token Scopes being added
17 +- `app-credentials.png` — Basic Information, App Credentials (Client ID/Secret; redact the Secret)
18 +
19 +Composio auth config (Slackbot toolkit):
20 +- `auth-config-slackbot.png` — Create Auth Config search, choosing Slackbot (not Slack)
21 +- `auth-config-credentials.png` — OAuth 2.0 + Your Own Credentials + Client ID/Secret (redact the Secret)
22 +- `auth-config-created.png` — the created slackbot auth config row with its ac_ id
23 +
24 +Connect:
25 +- `oauth-approve.png` — the Slack OAuth approval screen the setup script links to
26 +- `connected.png` — Composio's "Successfully connected to Slackbot" confirmation
docs/public/images/standup-slackbot/app-credentials.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/app-credentials.png differ
docs/public/images/standup-slackbot/auth-config-created.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/auth-config-created.png differ
docs/public/images/standup-slackbot/auth-config-credentials.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/auth-config-credentials.png differ
docs/public/images/standup-slackbot/auth-config-slackbot.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/auth-config-slackbot.png differ
docs/public/images/standup-slackbot/bot-avatar.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/bot-avatar.png differ
docs/public/images/standup-slackbot/bot-scopes.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/bot-scopes.png differ
docs/public/images/standup-slackbot/connected.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/connected.png differ
docs/public/images/standup-slackbot/create-app.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/create-app.png differ
docs/public/images/standup-slackbot/oauth-approve.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/oauth-approve.png differ
docs/public/images/standup-slackbot/slack-connect.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/slack-connect.png differ
docs/public/images/standup-slackbot/slack-draft.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/slack-draft.png differ
docs/public/images/standup-slackbot/slack-reminder.png
Binary files /dev/null and b/docs/public/images/standup-slackbot/slack-reminder.png differ
docs/scripts/build-agent-index.ts new
+145
@@ -0,0 +1,145 @@
1 +/**
2 + * Build the docs snapshot the Ask AI agent imports (`agent/lib/docs-index.ts`).
3 + *
4 + * The deployed eve service bundles the `agent/` directory but NOT `content/` or
5 + * `public/data/`, so the agent can't read the docs from disk at runtime. This
6 + * script snapshots every content page (cleaned Markdown + metadata) and the
7 + * toolkit catalog into a generated module the agent imports, so eve bundles it
8 + * into the deployed service. In dev the agent still reads `content/` live; the
9 + * bundle is only used when the content tree isn't on disk.
10 + *
11 + * Self-contained on purpose: it does NOT import `agent/lib/docs.ts` (which
12 + * imports the generated file), so it can run from a clean checkout where
13 + * `docs-index.ts` doesn't exist yet. The generated file is gitignored and
14 + * regenerated before `dev`, `build`, and `types:check`.
15 + *
16 + * Run manually with `bun scripts/build-agent-index.ts`.
17 + */
18 +import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
19 +import { join, relative } from 'node:path';
20 +
21 +const ROOT = process.cwd();
22 +const CONTENT = join(ROOT, 'content');
23 +const COLLECTIONS = ['docs', 'reference', 'examples', 'toolkits'] as const;
24 +const LEGACY_URL_PATTERNS = [
25 + '/docs/tools-direct',
26 + '/docs/auth-configuration',
27 + '/docs/sessions-vs-direct-execution',
28 +];
29 +
30 +// The helpers below mirror agent/lib/docs.ts so generated URLs and cleaned
31 +// Markdown match what the live (filesystem) path produces. Keep them in sync.
32 +function isLegacyUrl(url: string): boolean {
33 + return LEGACY_URL_PATTERNS.some((p) => url === p || url.startsWith(`${p}/`));
34 +}
35 +
36 +function urlFromContentPath(absPath: string): string | undefined {
37 + const rel = relative(CONTENT, absPath).replace(/\\/g, '/');
38 + const withoutExt = rel.replace(/\.mdx?$/, '');
39 + const parts = withoutExt.split('/');
40 + const collection = parts.shift();
41 + if (!collection) return undefined;
42 + if (collection === 'docs') return `/docs/${parts.join('/')}`.replace(/\/index$/, '');
43 + if (collection === 'examples') return `/examples/${parts.join('/')}`.replace(/\/index$/, '');
44 + if (collection === 'reference') return `/reference/${parts.join('/')}`.replace(/\/index$/, '');
45 + if (collection === 'toolkits') {
46 + if (parts[0] === 'faq') return undefined;
47 + return `/toolkits/${parts.join('/')}`.replace(/\/index$/, '');
48 + }
49 + return undefined;
50 +}
51 +
52 +function parseFrontmatter(raw: string): { title: string; description: string; legacy: boolean; body: string } {
53 + const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
54 + if (!match) return { title: '', description: '', legacy: false, body: raw };
55 + const [, fm, body] = match;
56 + const get = (key: string) => {
57 + const m = fm.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'));
58 + return m ? m[1].trim().replace(/^["']|["']$/g, '') : '';
59 + };
60 + return { title: get('title'), description: get('description'), legacy: get('legacy') === 'true', body };
61 +}
62 +
63 +function toCleanMarkdown(raw: string): string {
64 + const { body } = parseFrontmatter(raw);
65 + return body
66 + .replace(/<\/?[A-Za-z][A-Za-z0-9.]*(\s[^>]*)?\/?>/g, '')
67 + .replace(/\n{3,}/g, '\n\n')
68 + .trim();
69 +}
70 +
71 +interface BundlePage {
72 + collection: string;
73 + url: string;
74 + title: string;
75 + description: string;
76 + legacy: boolean;
77 + markdown: string;
78 +}
79 +
80 +const pages: BundlePage[] = [];
81 +for (const collection of COLLECTIONS) {
82 + const dir = join(CONTENT, collection);
83 + let entries: string[];
84 + try {
85 + entries = readdirSync(dir, { recursive: true }) as string[];
86 + } catch {
87 + continue;
88 + }
89 + for (const entry of entries) {
90 + if (!/\.mdx?$/.test(entry)) continue;
91 + const absPath = join(dir, entry);
92 + const url = urlFromContentPath(absPath);
93 + if (!url) continue;
94 + const raw = readFileSync(absPath, 'utf8');
95 + const { title, description, legacy } = parseFrontmatter(raw);
96 + pages.push({
97 + collection,
98 + url,
99 + title: title || url,
100 + description,
101 + legacy: legacy || isLegacyUrl(url),
102 + markdown: toCleanMarkdown(raw),
103 + });
104 + }
105 +}
106 +
107 +interface BundleToolkit {
108 + slug: string;
109 + name?: string;
110 + description?: string;
111 + category?: string;
112 + authSchemes?: string[];
113 +}
114 +
115 +let toolkits: BundleToolkit[] = [];
116 +try {
117 + const parsed = JSON.parse(readFileSync(join(ROOT, 'public', 'data', 'toolkits.json'), 'utf8'));
118 + const list = Array.isArray(parsed) ? parsed : (parsed.toolkits ?? parsed.items ?? []);
119 + toolkits = list
120 + .filter((tk: { slug?: string }) => Boolean(tk?.slug))
121 + .map((tk: BundleToolkit) => ({
122 + slug: tk.slug,
123 + name: tk.name,
124 + description: tk.description,
125 + category: tk.category,
126 + authSchemes: tk.authSchemes,
127 + }));
128 +} catch {
129 + // no catalog available
130 +}
131 +
132 +// Emit a .ts module (not .json): eve's discovery scans agent/lib/ and only
133 +// accepts authored modules there, so a raw .json fails `eve build`. We embed the
134 +// snapshot as a JSON string parsed at runtime — a plain string literal keeps the
135 +// source fast for tsc and free of escaping pitfalls, and lets eve bundle it.
136 +const json = JSON.stringify({ pages, toolkits });
137 +const ts =
138 + `/* eslint-disable */\n` +
139 + `// Auto-generated by scripts/build-agent-index.ts — do not edit by hand.\n` +
140 + `// Gitignored snapshot of content/ + the toolkit catalog, imported by\n` +
141 + `// lib/docs.ts so eve bundles it into the deployed service (agent/ but not content/).\n` +
142 + `export default JSON.parse(\n ${JSON.stringify(json)},\n) as unknown;\n`;
143 +const out = join(ROOT, 'agent', 'lib', 'docs-index.ts');
144 +writeFileSync(out, ts);
145 +console.log(`[build-agent-index] wrote ${pages.length} pages + ${toolkits.length} toolkits (${Math.round(json.length / 1024)} KB) -> ${out}`);
docs/scripts/docs-graph.ts new
+413
@@ -0,0 +1,413 @@
1 +/**
2 + * docs-graph.ts — content link-graph generator + connectivity checker.
3 + *
4 + * Builds a directed graph of the docs where nodes are pages and edges are
5 + * internal `/docs/...` links in page bodies (markdown links + `href=`).
6 + *
7 + * It then checks the *topology* (not broken links — that's validate-links.ts):
8 + * 1. Weakly-connected components. The biggest is "the main graph". Anything
9 + * else is an island — a page (or a little 2-/3-loop) that doesn't mainline
10 + * back into the main graph through content links.
11 + * 2. Reachability from `index` — pages you can't click your way to starting
12 + * from the homepage.
13 + * 3. Short directed cycles (A->B->A, A->B->C->A) that are *isolated* (their
14 + * own tiny component). Cycles embedded in the main graph are fine.
15 + *
16 + * Usage (from docs/):
17 + * bun run scripts/docs-graph.ts # report for content/docs
18 + * bun run scripts/docs-graph.ts --html # also write docs-graph.html
19 + * bun run scripts/docs-graph.ts --dot # also write docs-graph.dot
20 + * bun run scripts/docs-graph.ts --root content/docs --json
21 + */
22 +
23 +import { readFile, writeFile } from 'node:fs/promises';
24 +import { glob } from 'node:fs/promises';
25 +import { relative, resolve } from 'node:path';
26 +
27 +// ---------------------------------------------------------------------------
28 +// Config / args
29 +// ---------------------------------------------------------------------------
30 +
31 +const args = process.argv.slice(2);
32 +const flag = (name: string) => args.includes(`--${name}`);
33 +const opt = (name: string, fallback: string) => {
34 + const i = args.indexOf(`--${name}`);
35 + return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
36 +};
37 +
38 +const ROOT = opt('root', 'content/docs'); // dir to scan, relative to cwd
39 +const URL_PREFIX = opt('prefix', '/docs'); // route prefix these files serve at
40 +const MAX_ISLAND = Number(opt('max-island', '4')); // components <= this are "small"
41 +
42 +// ---------------------------------------------------------------------------
43 +// Types
44 +// ---------------------------------------------------------------------------
45 +
46 +interface Node {
47 + /** route relative to URL_PREFIX, e.g. "providers/openai" ("" for index) */
48 + id: string;
49 + /** display label */
50 + label: string;
51 + file: string;
52 + out: Set<string>; // internal doc targets (node ids)
53 + in: Set<string>;
54 + /** links to other sections (/toolkits, /reference, ...) — keeps a page from
55 + * looking orphaned when its only links point outside docs */
56 + crossOut: string[];
57 + /** links to /docs/<x> that resolve to no known page (dangling) */
58 + dangling: string[];
59 +}
60 +
61 +// ---------------------------------------------------------------------------
62 +// Build nodes
63 +// ---------------------------------------------------------------------------
64 +
65 +function routeFromFile(file: string): string {
66 + // file is relative to ROOT, e.g. "providers/openai.mdx" or "providers/index.mdx"
67 + let r = file.replace(/\.mdx$/, '');
68 + r = r.replace(/\/index$/, '');
69 + if (r === 'index') r = '';
70 + return r;
71 +}
72 +
73 +const cwd = process.cwd();
74 +const rootAbs = resolve(cwd, ROOT);
75 +
76 +const nodes = new Map<string, Node>();
77 +const filesByRoute = new Map<string, string>();
78 +
79 +for await (const abs of glob(`${rootAbs}/**/*.mdx`)) {
80 + const rel = relative(rootAbs, abs);
81 + const id = routeFromFile(rel);
82 + nodes.set(id, {
83 + id,
84 + label: id === '' ? 'index' : id,
85 + file: `${ROOT}/${rel}`,
86 + out: new Set(),
87 + in: new Set(),
88 + crossOut: [],
89 + dangling: [],
90 + });
91 + filesByRoute.set(id, abs);
92 +}
93 +
94 +// ---------------------------------------------------------------------------
95 +// Extract edges
96 +// ---------------------------------------------------------------------------
97 +
98 +// Matches markdown links `](/path...)`, href="/path", href={'/path'} etc.
99 +const LINK_RE = /(?:\]\(|href\s*=\s*["'{]?)(\/[A-Za-z0-9/_\-.#?=&]+)/g;
100 +
101 +function normalizeDocTarget(raw: string): string | null {
102 + // strip anchor + query, trailing slash
103 + let t = raw.split('#')[0].split('?')[0].replace(/\/+$/, '');
104 + if (!t.startsWith(`${URL_PREFIX}`)) return null;
105 + t = t.slice(URL_PREFIX.length).replace(/^\//, ''); // -> route id
106 + return t;
107 +}
108 +
109 +for (const node of nodes.values()) {
110 + const content = await readFile(filesByRoute.get(node.id)!, 'utf8');
111 + // strip fenced code blocks so code samples don't create edges
112 + const body = content.replace(/```[\s\S]*?```/g, '');
113 + for (const m of body.matchAll(LINK_RE)) {
114 + const href = m[1];
115 + if (href.startsWith(`${URL_PREFIX}/`) || href === URL_PREFIX) {
116 + const target = normalizeDocTarget(href);
117 + if (target === null) continue;
118 + if (target === node.id) continue; // self-anchor link
119 + if (nodes.has(target)) {
120 + node.out.add(target);
121 + nodes.get(target)!.in.add(node.id);
122 + } else {
123 + node.dangling.push(href);
124 + }
125 + } else {
126 + // cross-section internal link (/toolkits, /reference, /examples, ...)
127 + node.crossOut.push(href.split('#')[0]);
128 + }
129 + }
130 +}
131 +
132 +// ---------------------------------------------------------------------------
133 +// Graph algorithms
134 +// ---------------------------------------------------------------------------
135 +
136 +const ids = [...nodes.keys()];
137 +
138 +// Weakly-connected components (treat edges as undirected)
139 +function weaklyConnectedComponents(): string[][] {
140 + const seen = new Set<string>();
141 + const comps: string[][] = [];
142 + for (const start of ids) {
143 + if (seen.has(start)) continue;
144 + const stack = [start];
145 + const comp: string[] = [];
146 + seen.add(start);
147 + while (stack.length) {
148 + const n = stack.pop()!;
149 + comp.push(n);
150 + const node = nodes.get(n)!;
151 + for (const nb of [...node.out, ...node.in]) {
152 + if (!seen.has(nb)) {
153 + seen.add(nb);
154 + stack.push(nb);
155 + }
156 + }
157 + }
158 + comps.push(comp);
159 + }
160 + return comps.sort((a, b) => b.length - a.length);
161 +}
162 +
163 +// Reachability from a root over directed out-edges
164 +function reachableFrom(root: string): Set<string> {
165 + const seen = new Set<string>([root]);
166 + const stack = [root];
167 + while (stack.length) {
168 + const n = stack.pop()!;
169 + for (const nb of nodes.get(n)!.out) {
170 + if (!seen.has(nb)) {
171 + seen.add(nb);
172 + stack.push(nb);
173 + }
174 + }
175 + }
176 + return seen;
177 +}
178 +
179 +// Directed cycles up to length `maxLen` (deduped by canonical rotation)
180 +function shortCycles(maxLen: number): string[][] {
181 + const found = new Map<string, string[]>();
182 + const key = (cyc: string[]) => {
183 + const rots = cyc.map((_, i) => [...cyc.slice(i), ...cyc.slice(0, i)].join('>'));
184 + return rots.sort()[0];
185 + };
186 + const dfs = (start: string, path: string[]) => {
187 + const last = path[path.length - 1];
188 + for (const nb of nodes.get(last)!.out) {
189 + if (nb === start && path.length >= 2) {
190 + const cyc = [...path];
191 + found.set(key(cyc), cyc);
192 + } else if (path.length < maxLen && !path.includes(nb) && nb > start) {
193 + // nb > start keeps each cycle anchored at its smallest node
194 + dfs(start, [...path, nb]);
195 + }
196 + }
197 + };
198 + for (const id of ids) dfs(id, [id]);
199 + return [...found.values()];
200 +}
201 +
202 +const components = weaklyConnectedComponents();
203 +const main = new Set(components[0] ?? []);
204 +const islands = components.slice(1);
205 +const reachFromIndex = nodes.has('') ? reachableFrom('') : new Set<string>();
206 +const cycles = shortCycles(3);
207 +
208 +// A short cycle is "concerning" only if its nodes are NOT part of the main
209 +// component (i.e. the loop is itself an island) — embedded loops are fine.
210 +const isolatedCycles = cycles.filter((c) => c.some((n) => !main.has(n)));
211 +
212 +// Degree + hubs. A "hub" is a high-degree page (lots of things link to/from it).
213 +const degree = (id: string) => nodes.get(id)!.in.size + nodes.get(id)!.out.size;
214 +const degrees = ids.map(degree).sort((a, b) => a - b);
215 +// top ~15% by degree, with a floor so tiny graphs don't flag everything
216 +const HUB_DEGREE = Math.max(
217 + Number(opt('hub-degree', '0')) || 0,
218 + degrees[Math.floor(degrees.length * 0.85)] ?? 0,
219 + 6,
220 +);
221 +const isHub = (id: string) => degree(id) >= HUB_DEGREE;
222 +
223 +// Mutual 2-cycles (A->B and B->A) — an immediate circle-back. Benign between
224 +// sibling leaf pages, but a smell between two hubs: flow ping-pongs at the top
225 +// of the graph instead of moving forward. We flag only the hub<->hub ones.
226 +const mutual2: Array<[string, string]> = [];
227 +const seenPair = new Set<string>();
228 +for (const id of ids) {
229 + for (const t of nodes.get(id)!.out) {
230 + if (nodes.get(t)!.out.has(id)) {
231 + const key = [id, t].sort().join('|');
232 + if (!seenPair.has(key)) {
233 + seenPair.add(key);
234 + mutual2.push([id, t].sort() as [string, string]);
235 + }
236 + }
237 + }
238 +}
239 +const hubLoops = mutual2
240 + .filter(([a, b]) => isHub(a) && isHub(b))
241 + .sort((x, y) => degree(y[0]) + degree(y[1]) - degree(x[0]) - degree(x[1]));
242 +
243 +// ---------------------------------------------------------------------------
244 +// Report
245 +// ---------------------------------------------------------------------------
246 +
247 +const totalEdges = ids.reduce((a, id) => a + nodes.get(id)!.out.size, 0);
248 +const orphans = ids.filter(
249 + (id) => nodes.get(id)!.in.size === 0 && nodes.get(id)!.out.size === 0,
250 +);
251 +const noInbound = ids.filter(
252 + (id) => id !== '' && nodes.get(id)!.in.size === 0,
253 +);
254 +const unreachable = ids.filter((id) => !reachFromIndex.has(id));
255 +
256 +const C = {
257 + red: (s: string) => `\x1b[31m${s}\x1b[0m`,
258 + yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
259 + green: (s: string) => `\x1b[32m${s}\x1b[0m`,
260 + dim: (s: string) => `\x1b[2m${s}\x1b[0m`,
261 + bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
262 +};
263 +
264 +console.log(C.bold(`\nDocs link graph — ${ROOT}`));
265 +console.log(
266 + `${nodes.size} pages · ${totalEdges} internal links · ${components.length} component(s)\n`,
267 +);
268 +
269 +console.log(C.bold('Main graph'));
270 +console.log(` ${main.size}/${nodes.size} pages connected into the main component\n`);
271 +
272 +if (islands.length) {
273 + console.log(C.red(C.bold(`Islands (${islands.length}) — not connected to the main graph`)));
274 + for (const comp of islands) {
275 + const kind =
276 + comp.length === 1 ? 'orphan page' : `${comp.length}-page loop/cluster`;
277 + console.log(` ${C.red('●')} ${kind}`);
278 + for (const n of comp) {
279 + const node = nodes.get(n)!;
280 + const outNote = node.crossOut.length
281 + ? C.dim(` (links out to ${[...new Set(node.crossOut)].slice(0, 3).join(', ')})`)
282 + : node.out.size || node.in.size
283 + ? ''
284 + : C.dim(' (no links at all)');
285 + console.log(` ${node.label || 'index'}${outNote}`);
286 + }
287 + }
288 + console.log();
289 +} else {
290 + console.log(C.green('No islands — every page connects into the main graph.\n'));
291 +}
292 +
293 +if (hubLoops.length) {
294 + console.log(C.red(C.bold(`Hub ping-pong loops (${hubLoops.length})`)));
295 + console.log(C.dim(' (two high-traffic pages that only circle back to each other — flow should move forward)'));
296 + for (const [a, b] of hubLoops) {
297 + console.log(` ${C.red('⇄')} ${a || 'index'} ⇄ ${b || 'index'} ${C.dim(`(deg ${degree(a)} / ${degree(b)})`)}`);
298 + }
299 + console.log();
300 +} else {
301 + console.log(C.green('No hub ping-pong loops.\n'));
302 +}
303 +
304 +if (isolatedCycles.length) {
305 + console.log(C.yellow(C.bold(`Isolated short cycles (${isolatedCycles.length})`)));
306 + console.log(C.dim(' (pages that circle straight back without joining the main graph)'));
307 + for (const c of isolatedCycles) {
308 + console.log(` ${C.yellow('↻')} ${c.map((n) => n || 'index').join(' → ')} → ${c[0] || 'index'}`);
309 + }
310 + console.log();
311 +}
312 +
313 +// Click-reachability from index is only meaningful if index actually links out.
314 +// (Docs here navigate by sidebar, so an index with no body links makes every
315 +// page "unreachable" — that's noise, and index already shows up as an island.)
316 +if (nodes.has('') && nodes.get('')!.out.size === 0) {
317 + console.log(C.dim('Click-reachability from index: N/A (index has no outbound content links)\n'));
318 +} else if (unreachable.length && nodes.has('')) {
319 + console.log(C.yellow(C.bold(`Not reachable from index by clicking (${unreachable.length})`)));
320 + console.log(C.dim(' (in the sidebar, but no content link path from the homepage)'));
321 + for (const id of unreachable.slice(0, 40)) {
322 + console.log(` ${C.yellow('·')} ${id || 'index'}`);
323 + }
324 + if (unreachable.length > 40) console.log(C.dim(` … +${unreachable.length - 40} more`));
325 + console.log();
326 +}
327 +
328 +if (noInbound.length) {
329 + console.log(C.dim(`Pages with no inbound content links (${noInbound.length}): ${noInbound.slice(0, 12).join(', ')}${noInbound.length > 12 ? ', …' : ''}\n`));
330 +}
331 +
332 +// ---------------------------------------------------------------------------
333 +// Optional outputs
334 +// ---------------------------------------------------------------------------
335 +
336 +if (flag('json')) {
337 + const out = {
338 + nodes: ids.map((id) => ({
339 + id,
340 + out: [...nodes.get(id)!.out],
341 + in: [...nodes.get(id)!.in],
342 + crossOut: nodes.get(id)!.crossOut,
343 + dangling: nodes.get(id)!.dangling,
344 + })),
345 + components,
346 + islands,
347 + isolatedCycles,
348 + unreachable,
349 + };
350 + await writeFile('docs-graph.json', JSON.stringify(out, null, 2));
351 + console.log(C.dim('Wrote docs-graph.json'));
352 +}
353 +
354 +if (flag('dot')) {
355 + const compIndex = new Map<string, number>();
356 + components.forEach((c, i) => c.forEach((n) => compIndex.set(n, i)));
357 + const palette = ['#2563eb', '#dc2626', '#d97706', '#7c3aed', '#059669', '#db2777'];
358 + const lines = ['digraph docs {', ' rankdir=LR;', ' node [shape=box, style=rounded, fontname="Helvetica"];'];
359 + for (const id of ids) {
360 + const ci = compIndex.get(id)!;
361 + const color = ci === 0 ? '#94a3b8' : palette[(ci - 1) % palette.length];
362 + const isIsland = ci !== 0;
363 + lines.push(` "${id || 'index'}" [color="${color}"${isIsland ? ', penwidth=2, fontcolor="' + color + '"' : ''}];`);
364 + }
365 + for (const id of ids) {
366 + for (const t of nodes.get(id)!.out) {
367 + lines.push(` "${id || 'index'}" -> "${t || 'index'}";`);
368 + }
369 + }
370 + lines.push('}');
371 + await writeFile('docs-graph.dot', lines.join('\n'));
372 + console.log(C.dim('Wrote docs-graph.dot (render: dot -Tsvg docs-graph.dot -o docs-graph.svg)'));
373 +}
374 +
375 +if (flag('html')) {
376 + const compIndex = new Map<string, number>();
377 + components.forEach((c, i) => c.forEach((n) => compIndex.set(n, i)));
378 + const data = {
379 + nodes: ids.map((id) => ({
380 + id: id || 'index',
381 + comp: compIndex.get(id)!,
382 + island: compIndex.get(id)! !== 0,
383 + degree: nodes.get(id)!.in.size + nodes.get(id)!.out.size,
384 + })),
385 + edges: ids.flatMap((id) =>
386 + [...nodes.get(id)!.out].map((t) => ({ from: id || 'index', to: t || 'index' })),
387 + ),
388 + };
389 + const html = `<!doctype html><meta charset=utf8><title>Docs link graph</title>
390 +<style>html,body{margin:0;height:100%;background:#0b0f17;color:#e5e7eb;font-family:system-ui}
391 +#net{height:100vh}#legend{position:fixed;top:12px;left:12px;background:#111827cc;padding:10px 14px;border-radius:8px;font-size:13px;line-height:1.6}</style>
392 +<div id=legend><b>Docs link graph</b><br><span style=color:#94a3b8>●</span> main graph &nbsp; <span style=color:#dc2626>●</span> island (disconnected)<br>node size = link count</div>
393 +<div id=net></div>
394 +<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
395 +<script>
396 +const D=${JSON.stringify(data)};
397 +const palette=['#94a3b8','#dc2626','#d97706','#7c3aed','#059669','#db2777','#2563eb'];
398 +const nodes=new vis.DataSet(D.nodes.map(n=>({id:n.id,label:n.id,value:n.degree+1,
399 + color:{background:n.island?palette[1+(n.comp-1)%6]:'#334155',border:n.island?palette[1+(n.comp-1)%6]:'#64748b'},
400 + font:{color:n.island?'#fca5a5':'#cbd5e1'}})));
401 +const edges=new vis.DataSet(D.edges.map(e=>({from:e.from,to:e.to,arrows:'to',color:{color:'#33415588'}})));
402 +new vis.Network(document.getElementById('net'),{nodes,edges},{
403 + physics:{stabilization:true,barnesHut:{gravitationalConstant:-8000,springLength:120}},
404 + nodes:{shape:'dot',scaling:{min:6,max:40}},interaction:{hover:true}});
405 +</script>`;
406 + await writeFile('docs-graph.html', html);
407 + console.log(C.dim('Wrote docs-graph.html (open in a browser)'));
408 +}
409 +
410 +// exit non-zero if there are islands, so this can gate CI
411 +if (flag('check') && (islands.length || isolatedCycles.length || hubLoops.length)) {
412 + process.exit(1);
413 +}
docs/scripts/generate-api-index.ts
+64 -6
@@ -8,6 +8,23 @@
8
9 import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync } from 'fs';
10 import { join } from 'path';
11 +import { HIDDEN_API_TAGS } from '../lib/filter-api-version';
12 +
13 +/**
14 + * API-reference tags hidden on our side even though the upstream OpenAPI spec
15 + * (from hermes) includes them. Matched by slug. We neither generate their
16 + * `index.mdx` overview pages nor leave stale ones behind. Shared with the
17 + * reference page-tree filter so both stay in sync.
18 + */
19 +const HIDDEN_TAGS: ReadonlySet<string> = HIDDEN_API_TAGS;
20 +
21 +/**
22 + * Display-title overrides for API-reference tags whose upstream OpenAPI tag
23 + * name is stale or off-brand. Keyed by tag slug.
24 + */
25 +const TITLE_OVERRIDES: Record<string, string> = {
26 + 'tool-router': 'Sessions (prev Tool Router)',
27 +};
28
29 interface OpenAPIOperation {
30 summary?: string;
@@ -36,6 +53,21 @@ function slugify(text: string): string {
53 .replace(/^-|-$/g, '');
54 }
55
56 +/**
57 + * Optional hand-written overview for a tag, merged above the generated
58 + * endpoints table. Lives in `api-overviews/<tagSlug>.mdx` (outside `content/`,
59 + * so Fumadocs never renders it as its own page). Use this to fold a conceptual
60 + * guide into the API reference page instead of keeping a separate docs page.
61 + * Frontmatter, if present, is stripped — the generator owns the frontmatter.
62 + */
63 +function readOverview(tagSlug: string): string | null {
64 + const overviewPath = join(process.cwd(), 'api-overviews', `${tagSlug}.mdx`);
65 + if (!existsSync(overviewPath)) return null;
66 + const raw = readFileSync(overviewPath, 'utf-8');
67 + const stripped = raw.replace(/^---\n[\s\S]*?\n---\n/, '').trim();
68 + return stripped.length > 0 ? stripped : null;
69 +}
70 +
71 function getOperationsByTag(spec: OpenAPISpec): Record<string, OperationEntry[]> {
72 const tagOps: Record<string, OperationEntry[]> = {};
73
@@ -91,6 +123,22 @@ function generateIndexPages() {
123 const ops3 = v3Ops[tagName] || [];
124 const tagSlug = slugify(tagName);
125
126 + // Intentionally-hidden tag — skip generation and delete any existing index.mdx
127 + // (v3.1 and v3.0) so neither overview page lingers in the sidebar.
128 + if (HIDDEN_TAGS.has(tagSlug)) {
129 + for (const baseDir of [
130 + join(process.cwd(), 'content/reference/api-reference'),
131 + join(process.cwd(), 'content/reference/v3/api-reference'),
132 + ]) {
133 + const hidden = join(baseDir, tagSlug, 'index.mdx');
134 + if (existsSync(hidden)) {
135 + rmSync(hidden);
136 + console.log(`Removed hidden tag: ${hidden}`);
137 + }
138 + }
139 + continue;
140 + }
141 +
142 // Tag declared in spec.tags but no operations reference it — clean up any stale index.mdx from a prior run.
143 if (ops31.length === 0 && ops3.length === 0) {
144 for (const baseDir of [
@@ -107,6 +155,16 @@ function generateIndexPages() {
155 }
156
157 const tagDescription = tagDescriptions[tagName] || `${tagName} API endpoints`;
158 + // Display-title overrides for tags whose OpenAPI name is stale (e.g. the
159 + // tool router is now Sessions). Keyed by slug.
160 + const displayTitle = TITLE_OVERRIDES[tagSlug] ?? tagName;
161 + const overview = readOverview(tagSlug);
162 + // Body above the endpoints table: hand-written overview when present,
163 + // otherwise the thin OpenAPI tag description.
164 + const body = overview ?? tagDescription;
165 + const genComment = overview
166 + ? `{/* Auto-generated from OpenAPI spec. Edit the overview at api-overviews/${tagSlug}.mdx, not this file. */}`
167 + : '{/* Auto-generated from OpenAPI spec. Do not edit directly. */}';
168
169 // Only generate v3.1 index page if the tag has v3.1 operations
170 if (ops31.length > 0) {
@@ -127,13 +185,13 @@ function generateIndexPages() {
185 });
186
187 const content = `---
130 -title: ${tagName}
188 +title: ${displayTitle}
189 description: "${tagDescription}"
190 ---
191
134 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
192 +${genComment}
193
136 -${tagDescription}
194 +${body}
195
196 ## Endpoints
197
@@ -157,13 +215,13 @@ ${tagDescription}
215 }));
216
217 const v3Content = `---
160 -title: ${tagName}
218 +title: ${displayTitle}
219 description: "${tagDescription}"
220 ---
221
164 -{/* Auto-generated from OpenAPI spec. Do not edit directly. */}
222 +${genComment}
223
166 -${tagDescription}
224 +${body}
225
226 ## Endpoints
227
docs/scripts/generate-meta-tools.ts
+35 -17
@@ -3,9 +3,9 @@
3 *
4 * Fetches meta tool definitions from the Composio Tool Router API and generates:
5 * - /public/data/meta-tools.json (complete meta tool schemas from API)
6 - * - /content/reference/meta-tools/meta.json (sidebar navigation)
7 - * - /content/reference/meta-tools/index.mdx (overview page)
8 - * - /content/reference/meta-tools/{name}.mdx (individual tool pages)
6 + * - /content/toolkits/meta-tools/meta.json (sidebar navigation)
7 + * - /content/toolkits/meta-tools/index.mdx (overview page)
8 + * - /content/toolkits/meta-tools/{name}.mdx (individual tool pages)
9 *
10 * All output is derived from the API response — no hardcoded tool definitions.
11 *
@@ -19,6 +19,7 @@
19 import { writeFile, mkdir, readdir, unlink } from 'fs/promises';
20 import { join } from 'path';
21 import { fetchWithRetry } from './fetch-with-retry';
22 +import { META_TOOL_OVERRIDES } from '../lib/meta-tool-overrides';
23
24 const API_BASE = process.env.COMPOSIO_API_BASE || 'https://backend.composio.dev/api/v3';
25 const API_KEY = process.env.COMPOSIO_API_KEY;
@@ -29,7 +30,7 @@ if (!API_KEY) {
30 }
31
32 const DATA_DIR = join(process.cwd(), 'public/data');
32 -const CONTENT_DIR = join(process.cwd(), 'content/reference/meta-tools');
33 +const CONTENT_DIR = join(process.cwd(), 'content/toolkits/meta-tools');
34
35 async function createSession(): Promise<string> {
36 console.log('Creating session...');
@@ -123,32 +124,49 @@ function briefDescription(description: string): string {
124 return firstSentence;
125 }
126
126 -/** Generate the index.mdx overview page — flat table of all tools */
127 +/** One-line summary for the index table. Prefer hand-written override copy, fall back to the API description. */
128 +function indexLine(tool: any): string {
129 + const override = META_TOOL_OVERRIDES[tool.slug];
130 + if (override) {
131 + // First sentence of the hand-written summary keeps the table tight.
132 + const firstSentence = override.summary.split(/\.(\s|$)/)[0].trim();
133 + return firstSentence.replace(/\|/g, '\\|');
134 + }
135 + return briefDescription(tool.description).replace(/\|/g, '\\|');
136 +}
137 +
138 +/** Generate the index.mdx overview page — Modal-voice intro plus a one-line-per-tool table */
139 function generateIndexMdx(tools: any[]): string {
140 let content = `---
141 title: Meta Tools
130 -description: Complete reference for all Composio meta tools available in sessions.
142 +description: The system tools every Composio session gives your agent to discover, authenticate, execute, and process tools at runtime.
143 keywords: [meta tools, session]
144 ---
145
134 -{/* Auto-generated by scripts/generate-meta-tools.ts — do not edit manually */}
146 +{/* Auto-generated by scripts/generate-meta-tools.ts — do not edit manually. To change the intro prose or a tool's one-line summary, edit the template and the override map in lib/meta-tool-overrides.ts. */}
147
148 import { Callout } from 'fumadocs-ui/components/callout';
149
138 -<Callout type="warn">
139 -Meta tool schemas are for reference only. We do not guarantee backward compatibility for parameter names or response shapes. Do not rely on them for structured type definitions in your code.
140 -</Callout>
150 +Every Composio [session](/docs/how-composio-works) hands your agent a small set of meta tools instead of hundreds of raw tool definitions. The agent uses them to find the right tools for a task, connect the accounts those tools need, execute them, and process the results, all at runtime and all sharing one \`session_id\`.
151
142 -Meta tools are system-level tools available in [sessions](/docs/tools-and-toolkits). They handle tool discovery, execution, authentication, and sandboxing.
152 +This keeps your context window small: you load a handful of meta tools, not a catalog of 500+ apps. The agent searches for what it needs when it needs it.
153
144 -| Tool | Description |
145 -|------|-------------|
154 +A typical workflow runs in order: call \`COMPOSIO_SEARCH_TOOLS\` to discover tools and open a session, call \`COMPOSIO_MANAGE_CONNECTIONS\` if a toolkit is not yet connected, then run the tools with \`COMPOSIO_MULTI_EXECUTE_TOOL\`. Reach for the workbench and bash tools when responses are large enough to process out of context.
155 +
156 +| Tool | What it does |
157 +|------|--------------|
158 `;
159
160 for (const tool of tools) {
149 - content += `| [\`${tool.slug}\`](/reference/meta-tools/${pageSlug(tool.slug)}) | ${briefDescription(tool.description)} |\n`;
161 + content += `| [\`${tool.slug}\`](/toolkits/meta-tools/${pageSlug(tool.slug)}) | ${indexLine(tool)} |\n`;
162 }
163
164 + content += `
165 +<Callout type="warn">
166 +These schemas are for reference only. We do not guarantee backward compatibility for parameter names or response shapes, so do not rely on them as structured type definitions in your code.
167 +</Callout>
168 +`;
169 +
170 return content;
171 }
172
@@ -211,17 +229,17 @@ async function main() {
229
230 // 3. Write meta.json
231 await writeFile(join(CONTENT_DIR, 'meta.json'), generateMetaJson(metaTools));
214 - console.log('Wrote content/reference/meta-tools/meta.json');
232 + console.log('Wrote content/toolkits/meta-tools/meta.json');
233
234 // 4. Write index.mdx
235 await writeFile(join(CONTENT_DIR, 'index.mdx'), generateIndexMdx(metaTools));
218 - console.log('Wrote content/reference/meta-tools/index.mdx');
236 + console.log('Wrote content/toolkits/meta-tools/index.mdx');
237
238 // 5. Write individual tool pages
239 for (const tool of metaTools) {
240 const filename = `${pageSlug(tool.slug)}.mdx`;
241 await writeFile(join(CONTENT_DIR, filename), generateToolMdx(tool));
224 - console.log(`Wrote content/reference/meta-tools/${filename}`);
242 + console.log(`Wrote content/toolkits/meta-tools/${filename}`);
243 }
244
245 console.log(`\nGeneration complete! ${metaTools.length} meta tools.`);
docs/scripts/validate-links.ts
+6 -6
@@ -11,14 +11,14 @@ import GithubSlugger from 'github-slugger';
11 import {
12 source,
13 getReferenceSource,
14 - cookbooksSource,
14 + examplesSource,
15 toolkitsSource,
16 } from '../lib/source';
17
18 type AnySource =
19 | typeof source
20 | Awaited<ReturnType<typeof getReferenceSource>>
21 - | typeof cookbooksSource
21 + | typeof examplesSource
22 | typeof toolkitsSource;
23
24 type PageOf = ReturnType<AnySource['getPages']>[number];
@@ -92,10 +92,10 @@ async function getDynamicToolkitEntries() {
92
93 async function checkLinks() {
94 const referenceSource = await getReferenceSource();
95 - const [docsEntries, refEntries, cookbookEntries, toolkitEntries, dynamicToolkitEntries] = await Promise.all([
95 + const [docsEntries, refEntries, exampleEntries, toolkitEntries, dynamicToolkitEntries] = await Promise.all([
96 buildPopulateEntries(source),
97 buildPopulateEntries(referenceSource),
98 - buildPopulateEntries(cookbooksSource),
98 + buildPopulateEntries(examplesSource),
99 buildPopulateEntries(toolkitsSource),
100 getDynamicToolkitEntries(),
101 ]);
@@ -106,7 +106,7 @@ async function checkLinks() {
106 // Keys must include (home) route group to match app directory structure
107 '(home)/docs/[[...slug]]': docsEntries,
108 '(home)/reference/[[...slug]]': refEntries,
109 - '(home)/cookbooks/[[...slug]]': cookbookEntries,
109 + '(home)/examples/[[...slug]]': exampleEntries,
110 '(home)/toolkits/[[...slug]]': [...toolkitEntries, ...dynamicToolkitEntries],
111 },
112 });
@@ -139,7 +139,7 @@ async function checkLinks() {
139
140 async function getFiles(): Promise<FileObject[]> {
141 const referenceSource = await getReferenceSource();
142 - const sources = [source, referenceSource, cookbooksSource, toolkitsSource];
142 + const sources = [source, referenceSource, examplesSource, toolkitsSource];
143 const allFiles: FileObject[] = [];
144
145 for (const src of sources) {
docs/source.config.ts
+21 -2
@@ -17,11 +17,27 @@ import { z } from 'zod';
17 // Extended schema with keywords for search
18 const docsSchema = frontmatterSchema.extend({
19 keywords: z.array(z.string()).optional(),
20 + /** When true, the page shows an "Experimental" badge in the sidebar. */
21 + experimental: z.boolean().optional(),
22 + /** When true, the page shows a "New" badge in the sidebar. */
23 + isNew: z.boolean().optional(),
24 + /** When true, the page shows a "Legacy" badge at the top of the page. */
25 + legacy: z.boolean().optional(),
26 /** Controls which LLM guardrail set is appended to the .md output.
27 * - undefined / omitted → default session-based guardrails
28 * - "direct-execution" → softer guardrails acknowledging this is the low-level API
29 * - "none" → no guardrails appended */
30 llmGuardrails: z.enum(['direct-execution', 'none']).optional(),
31 + /** Links rendered in the right-hand "Related" rail under the table of contents. */
32 + related: z
33 + .array(
34 + z.object({
35 + title: z.string(),
36 + href: z.string(),
37 + description: z.string().optional(),
38 + }),
39 + )
40 + .optional(),
41 });
42
43 export const docs = defineDocs({
@@ -47,6 +63,9 @@ export const reference = defineDocs({
63 includeProcessedMarkdown: true,
64 },
65 mdxOptions: applyMdxPreset({
66 + // Match the global remark plugins so mermaid diagrams in merged
67 + // api-overviews render (applyMdxPreset replaces, not merges).
68 + remarkPlugins: [remarkMdxMermaid],
69 rehypeCodeOptions: {
70 themes: {
71 light: 'github-light',
@@ -61,8 +80,8 @@ export const reference = defineDocs({
80 },
81 });
82
64 -export const cookbooks = defineDocs({
65 - dir: 'content/cookbooks',
83 +export const examples = defineDocs({
84 + dir: 'content/examples',
85 docs: {
86 schema: docsSchema,
87 postprocess: {
docs/tests/integration/llm-endpoints.test.ts
+1 -1
@@ -23,7 +23,7 @@ describe("LLM endpoints - .md pages", () => {
23 const MD_PAGES = [
24 { path: "/docs/quickstart.md", name: "Quickstart" },
25 { path: "/docs/authentication.md", name: "Authentication" },
26 - { path: "/docs/tools-and-toolkits.md", name: "Tools & Toolkits" },
26 + { path: "/docs/how-composio-works.md", name: "How Composio works" },
27 ];
28
29 for (const { path, name } of MD_PAGES) {
docs/tests/integration/redirects.test.ts
+10 -6
@@ -10,7 +10,7 @@ import { fetchPage, fetchNoRedirect, BASE_URL } from "./helpers";
10 /** Sample of important redirects to test (from next.config.mjs) */
11 const REDIRECTS = [
12 { from: "/", to: "/docs" },
13 - { from: "/examples", to: "/cookbooks" },
13 + { from: "/cookbooks", to: "/examples" },
14 { from: "/api-reference", to: "/reference" },
15 { from: "/providers/openai", to: "/docs/providers/openai" },
16 { from: "/providers/anthropic", to: "/docs/providers/anthropic" },
@@ -23,16 +23,20 @@ const REDIRECTS = [
23 { from: "/docs/providers/langgraph", to: "/docs/providers/langchain" },
24 { from: "/tools", to: "/toolkits" },
25 { from: "/docs/fetching-tools", to: "/docs/tools-direct/fetching-tools" },
26 - { from: "/docs/custom-tools", to: "/docs/toolkits/custom-tools-and-toolkits" },
27 - { from: "/docs/tools-direct/custom-tools", to: "/docs/toolkits/custom-tools-and-toolkits" },
28 - { from: "/docs/tools-direct/custom-tools/github", to: "/docs/toolkits/custom-tools-and-toolkits" },
29 - { from: "/custom-tools/github", to: "/docs/toolkits/custom-tools-and-toolkits" },
30 - { from: "/docs/how-tools-work", to: "/docs/tools-and-toolkits" },
26 + { from: "/docs/custom-tools", to: "/docs/extending-sessions/custom-tools-and-toolkits" },
27 + { from: "/docs/tools-direct/custom-tools", to: "/docs/extending-sessions/custom-tools-and-toolkits" },
28 + { from: "/docs/tools-direct/custom-tools/github", to: "/docs/extending-sessions/custom-tools-and-toolkits" },
29 + { from: "/custom-tools/github", to: "/docs/extending-sessions/custom-tools-and-toolkits" },
30 + { from: "/docs/how-tools-work", to: "/docs/how-composio-works" },
31 { from: "/authentication", to: "/docs/authentication" },
32 { from: "/changelog", to: "/docs/changelog" },
33 { from: "/docs/mcp-quickstart", to: "/docs/single-toolkit-mcp" },
34 { from: "/docs/welcome", to: "/docs" },
35 { from: "/docs/managed-authentication", to: "/docs/authentication" },
36 + { from: "/docs/workbench", to: "/docs/sandbox/remote" },
37 + { from: "/docs/sandbox", to: "/docs/sandbox/remote" },
38 + { from: "/docs/custom-tools-and-toolkits", to: "/docs/extending-sessions/custom-tools-and-toolkits" },
39 + { from: "/docs/proxy-execute", to: "/docs/extending-sessions/proxy-execute" },
40 ];
41
42 describe("Redirects - key patterns", () => {
docs/tests/integration/rendering.test.ts
+2 -2
@@ -12,9 +12,9 @@ const CRITICAL_PAGES = [
12 { path: "/docs", name: "Docs home" },
13 { path: "/docs/quickstart", name: "Quickstart" },
14 { path: "/docs/authentication", name: "Authentication" },
15 - { path: "/docs/tools-and-toolkits", name: "Tools & Toolkits" },
15 + { path: "/docs/how-composio-works", name: "How Composio works" },
16 { path: "/docs/users-and-sessions", name: "Users & Sessions" },
17 - { path: "/cookbooks", name: "Cookbooks index" },
17 + { path: "/examples", name: "Examples index" },
18 { path: "/toolkits", name: "Toolkits index" },
19 { path: "/reference", name: "Reference index" },
20 ];
docs/tests/static/content.test.ts
+4 -4
@@ -9,7 +9,7 @@ import { readdir, readFile, stat } from "fs/promises";
9 import { join, relative } from "path";
10
11 const DOCS_DIR = join(import.meta.dir, "../../content/docs");
12 -const COOKBOOKS_DIR = join(import.meta.dir, "../../content/cookbooks");
12 +const EXAMPLES_DIR = join(import.meta.dir, "../../content/examples");
13 const CHANGELOG_DIR = join(import.meta.dir, "../../content/changelog");
14
15 /** Recursively find all .mdx files */
@@ -66,15 +66,15 @@ describe("Content - frontmatter validation", () => {
66 expect(missingTitle).toEqual([]);
67 });
68
69 - test("all cookbooks pages have a title", async () => {
70 - const files = await findMdxFiles(COOKBOOKS_DIR);
69 + test("all examples pages have a title", async () => {
70 + const files = await findMdxFiles(EXAMPLES_DIR);
71 const missingTitle: string[] = [];
72
73 for (const file of files) {
74 const content = await readFile(file, "utf-8");
75 const fm = parseFrontmatter(content);
76 if (!fm || !fm.title) {
77 - missingTitle.push(relative(COOKBOOKS_DIR, file));
77 + missingTitle.push(relative(EXAMPLES_DIR, file));
78 }
79 }
80
pnpm-lock.yaml
+998 -88
@@ -151,7 +151,7 @@ importers:
151 version: 4.1.9(vitest@4.1.9)
152 eslint:
153 specifier: ^9.25.1
154 - version: 9.39.2(supports-color@10.2.2)
154 + version: 9.39.2(jiti@2.7.0)
155 globals:
156 specifier: ^16.0.0
157 version: 16.5.0
@@ -160,7 +160,7 @@ importers:
160 version: 9.1.7
161 lint-staged:
162 specifier: ^15.5.1
163 - version: 15.5.2(supports-color@10.2.2)
163 + version: 15.5.2
164 prettier:
165 specifier: ^3.8.4
166 version: 3.8.4
@@ -184,10 +184,10 @@ importers:
184 version: 6.0.3
185 typescript-eslint:
186 specifier: ^8.61.1
187 - version: 8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
187 + version: 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
188 vitest:
189 specifier: 'catalog:'
190 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0))
190 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
191 zod:
192 specifier: 'catalog:'
193 version: 4.4.3
@@ -254,7 +254,7 @@ importers:
254 version: 6.0.3
255 vitest:
256 specifier: 'catalog:'
257 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
257 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
258 wrangler:
259 specifier: 'catalog:'
260 version: 4.101.0(@cloudflare/workers-types@4.20260617.1)
@@ -282,7 +282,7 @@ importers:
282 version: 6.0.3
283 vitest:
284 specifier: 'catalog:'
285 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
285 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
286 wrangler:
287 specifier: 'catalog:'
288 version: 4.101.0(@cloudflare/workers-types@4.20260617.1)
@@ -322,7 +322,7 @@ importers:
322 version: 6.0.3
323 vitest:
324 specifier: 'catalog:'
325 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
325 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
326 wrangler:
327 specifier: 'catalog:'
328 version: 4.101.0(@cloudflare/workers-types@4.20260617.1)
@@ -578,7 +578,7 @@ importers:
578 version: 6.0.3
579 vitest:
580 specifier: 'catalog:'
581 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
581 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
582 wrangler:
583 specifier: 'catalog:'
584 version: 4.101.0(@cloudflare/workers-types@4.20260617.1)
@@ -753,7 +753,7 @@ importers:
753 version: link:../../packages/providers/mastra
754 '@mastra/core':
755 specifier: ^1.0.4
756 - version: 1.4.0(@cfworker/json-schema@4.1.1)(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3))(@types/json-schema@7.0.15)(openapi-types@12.1.3)(zod@4.4.3)
756 + version: 1.4.0(@cfworker/json-schema@4.1.1)(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3))(@types/json-schema@7.0.15)(openapi-types@12.1.3)(zod@4.4.3)
757 dotenv:
758 specifier: 'catalog:'
759 version: 17.4.2
@@ -834,7 +834,7 @@ importers:
834 version: 1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
835 '@openai/agents':
836 specifier: ^0.1.4
837 - version: 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
837 + version: 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
838 dotenv:
839 specifier: 'catalog:'
840 version: 17.4.2
@@ -899,13 +899,13 @@ importers:
899 version: 1.3.18(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))
900 '@langchain/mcp-adapters':
901 specifier: ^1.0.1
902 - version: 1.1.3(@cfworker/json-schema@4.1.1)(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(@langchain/langgraph@1.1.4(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(supports-color@10.2.2)
902 + version: 1.1.3(@cfworker/json-schema@4.1.1)(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(@langchain/langgraph@1.1.4(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))
903 '@langchain/openai':
904 specifier: ^1.1.3
905 version: 1.2.8(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(ws@8.20.1)
906 '@openai/agents':
907 specifier: ^0.1.3
908 - version: 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
908 + version: 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
909 ai:
910 specifier: 'catalog:'
911 version: 6.0.207(zod@4.4.3)
@@ -1209,7 +1209,7 @@ importers:
1209 version: 6.0.3
1210 vitest:
1211 specifier: 'catalog:'
1212 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1212 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1213
1214 ts/packages/cli-keyring:
1215 devDependencies:
@@ -1230,7 +1230,7 @@ importers:
1230 version: 6.0.3
1231 vitest:
1232 specifier: 'catalog:'
1233 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1233 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1234
1235 ts/packages/cli-local-tools:
1236 dependencies:
@@ -1264,7 +1264,7 @@ importers:
1264 version: 6.0.3
1265 vitest:
1266 specifier: 'catalog:'
1267 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1267 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1268
1269 ts/packages/core:
1270 dependencies:
@@ -1313,11 +1313,36 @@ importers:
1313 version: 6.0.3
1314 vitest:
1315 specifier: 'catalog:'
1316 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1316 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1317 zod:
1318 specifier: 'catalog:'
1319 version: 4.4.3
1320
1321 + ts/packages/experimental:
1322 + dependencies:
1323 + typebox:
1324 + specifier: 1.1.38
1325 + version: 1.1.38
1326 + devDependencies:
1327 + '@composio/core':
1328 + specifier: workspace:*
1329 + version: link:../core
1330 + '@earendil-works/pi-coding-agent':
1331 + specifier: 0.79.8
1332 + version: 0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)
1333 + tsdown:
1334 + specifier: 'catalog:'
1335 + version: 0.22.3(@arethetypeswrong/core@0.18.3)(@typescript/native-preview@7.0.0-dev.20260615.1)(publint@0.3.21)(tsx@4.22.4)(typescript@6.0.3)(unrun@0.2.27(@emnapi/core@1.11.0)(@emnapi/runtime@1.11.0))
1336 + tsx:
1337 + specifier: 'catalog:'
1338 + version: 4.22.4
1339 + typescript:
1340 + specifier: 'catalog:'
1341 + version: 6.0.3
1342 + vitest:
1343 + specifier: 'catalog:'
1344 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1345 +
1346 ts/packages/json-schema-to-zod:
1347 devDependencies:
1348 '@types/json-schema':
@@ -1334,7 +1359,7 @@ importers:
1359 version: 6.0.3
1360 vitest:
1361 specifier: 'catalog:'
1337 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1362 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1363 zod:
1364 specifier: 'catalog:'
1365 version: 4.4.3
@@ -1359,7 +1384,7 @@ importers:
1384 version: 6.0.3
1385 vitest:
1386 specifier: 'catalog:'
1362 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1387 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1388
1389 ts/packages/providers/claude-agent-sdk:
1390 dependencies:
@@ -1381,7 +1406,7 @@ importers:
1406 version: 6.0.3
1407 vitest:
1408 specifier: 'catalog:'
1384 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1409 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1410
1411 ts/packages/providers/cloudflare:
1412 dependencies:
@@ -1400,7 +1425,7 @@ importers:
1425 version: 6.0.3
1426 vitest:
1427 specifier: 'catalog:'
1403 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1428 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1429
1430 ts/packages/providers/google:
1431 dependencies:
@@ -1434,7 +1459,7 @@ importers:
1459 version: 6.0.3
1460 vitest:
1461 specifier: 'catalog:'
1437 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1462 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1463 zod:
1464 specifier: 'catalog:'
1465 version: 4.4.3
@@ -1475,7 +1500,7 @@ importers:
1500 version: 6.0.3
1501 vitest:
1502 specifier: 'catalog:'
1478 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1503 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1504 zod:
1505 specifier: 'catalog:'
1506 version: 4.4.3
@@ -1497,7 +1522,7 @@ importers:
1522 version: 6.0.3
1523 vitest:
1524 specifier: 'catalog:'
1500 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1525 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1526
1527 ts/packages/providers/openai-agents:
1528 devDependencies:
@@ -1506,7 +1531,7 @@ importers:
1531 version: link:../../core
1532 '@openai/agents':
1533 specifier: ^0.1.3
1509 - version: 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
1534 + version: 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
1535 tsdown:
1536 specifier: 'catalog:'
1537 version: 0.22.3(@arethetypeswrong/core@0.18.3)(@typescript/native-preview@7.0.0-dev.20260615.1)(publint@0.3.21)(tsx@4.22.4)(typescript@6.0.3)(unrun@0.2.27(@emnapi/core@1.11.0)(@emnapi/runtime@1.11.0))
@@ -1515,7 +1540,7 @@ importers:
1540 version: 6.0.3
1541 vitest:
1542 specifier: 'catalog:'
1518 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1543 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1544 zod:
1545 specifier: 'catalog:'
1546 version: 4.4.3
@@ -1536,11 +1561,41 @@ importers:
1561 version: 6.0.3
1562 vitest:
1563 specifier: 'catalog:'
1539 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1564 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1565 zod:
1566 specifier: 'catalog:'
1567 version: 4.4.3
1568
1569 + ts/packages/slim:
1570 + dependencies:
1571 + '@composio/client':
1572 + specifier: 'catalog:'
1573 + version: 0.1.0-alpha.74
1574 + '@composio/json-schema-to-zod':
1575 + specifier: workspace:*
1576 + version: link:../json-schema-to-zod
1577 + '@types/json-schema':
1578 + specifier: ^7.0.15
1579 + version: 7.0.15
1580 + openai:
1581 + specifier: 'catalog:'
1582 + version: 6.43.0(ws@8.20.1)(zod@3.25.76)
1583 + picocolors:
1584 + specifier: 'catalog:'
1585 + version: 1.1.1
1586 + pusher-js:
1587 + specifier: ^8.5.0
1588 + version: 8.5.0
1589 + semver:
1590 + specifier: ^7.8.4
1591 + version: 7.8.4
1592 + zod:
1593 + specifier: ^3.25 || ^4
1594 + version: 3.25.76
1595 + zod-to-json-schema:
1596 + specifier: 'catalog:'
1597 + version: 3.25.2(zod@3.25.76)
1598 +
1599 ts/packages/ts-builders:
1600 dependencies:
1601 '@babel/helper-validator-identifier':
@@ -1558,7 +1613,7 @@ importers:
1613 version: 0.22.3(@arethetypeswrong/core@0.18.3)(@typescript/native-preview@7.0.0-dev.20260615.1)(publint@0.3.21)(tsx@4.22.4)(typescript@6.0.3)(unrun@0.2.27(@emnapi/core@1.11.0)(@emnapi/runtime@1.11.0))
1614 vitest:
1615 specifier: 'catalog:'
1561 - version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
1616 + version: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
1617
1618 packages:
1619
@@ -1758,6 +1813,15 @@ packages:
1813 zod:
1814 optional: true
1815
1816 + '@anthropic-ai/sdk@0.91.1':
1817 + resolution: {integrity: sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw==}
1818 + hasBin: true
1819 + peerDependencies:
1820 + zod: ^3.25.0 || ^4.0.0
1821 + peerDependenciesMeta:
1822 + zod:
1823 + optional: true
1824 +
1825 '@apidevtools/json-schema-ref-parser@14.2.1':
1826 resolution: {integrity: sha512-HmdFw9CDYqM6B25pqGBpNeLCKvGPlIx1EbLrVL0zPvj50CJQUHyBNBw45Muk0kEIkogo1VZvOKHajdMuAzSxRg==}
1827 engines: {node: '>= 20'}
@@ -1773,17 +1837,111 @@ packages:
1837 resolution: {integrity: sha512-sWBB/tdIktaT5xMq0Dz6CJyqcf6oMNdmiKiuPU1lWoJLTL6gjRSsksBuSgqot21hylkklBQY1wiSu+PkZhW7sw==}
1838 engines: {node: '>=20'}
1839
1840 + '@aws-crypto/crc32@5.2.0':
1841 + resolution: {integrity: sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==}
1842 + engines: {node: '>=16.0.0'}
1843 +
1844 + '@aws-crypto/sha256-browser@5.2.0':
1845 + resolution: {integrity: sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==}
1846 +
1847 '@aws-crypto/sha256-js@5.2.0':
1848 resolution: {integrity: sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==}
1849 engines: {node: '>=16.0.0'}
1850
1851 + '@aws-crypto/supports-web-crypto@5.2.0':
1852 + resolution: {integrity: sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==}
1853 +
1854 '@aws-crypto/util@5.2.0':
1855 resolution: {integrity: sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==}
1856
1857 + '@aws-sdk/client-bedrock-runtime@3.1048.0':
1858 + resolution: {integrity: sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ==}
1859 + engines: {node: '>=20.0.0'}
1860 +
1861 + '@aws-sdk/core@3.974.22':
1862 + resolution: {integrity: sha512-YofH63shc6YRdXjz80BJkpJW+Bkn0Cuu2dn4Rv7s9G2Idt58tgtzQEWxrR2xVljlVfIBeUjPuULnSVYLke3sUQ==}
1863 + engines: {node: '>=20.0.0'}
1864 +
1865 + '@aws-sdk/credential-provider-env@3.972.48':
1866 + resolution: {integrity: sha512-h6FEC95fbexUd6zxm4PdgS82bTcI2PRtUb2ZwMipb/Xr8bPwtf0G8rBo2jp7NA24Mbx2JA8/WingiYpA9RCCyw==}
1867 + engines: {node: '>=20.0.0'}
1868 +
1869 + '@aws-sdk/credential-provider-http@3.972.50':
1870 + resolution: {integrity: sha512-lJO3OLpjvz5m/RSBQmsG/CEUGsvCy5ruxKwPQaOCqxqCMuyYT2BZwQUTDZVVwqQ9LrZKuK24JSa6r31hL/tvkg==}
1871 + engines: {node: '>=20.0.0'}
1872 +
1873 + '@aws-sdk/credential-provider-ini@3.972.55':
1874 + resolution: {integrity: sha512-TBoF4buBGYhXjdZAryayY2TrkQj2B2KfE/msG4V53XCt+w0EhEwM2JRjx8p2grJ2C6gtH5++SAwEvGMRdi0yyw==}
1875 + engines: {node: '>=20.0.0'}
1876 +
1877 + '@aws-sdk/credential-provider-login@3.972.54':
1878 + resolution: {integrity: sha512-hBWI3wZTdTGiuMfmPts6AWbAjFfRniOQnqx68tc2cQvRKWawFbN9wkLOVPWM1FAOyowZU73mC6Fi+rHSHNyLFw==}
1879 + engines: {node: '>=20.0.0'}
1880 +
1881 + '@aws-sdk/credential-provider-node@3.972.57':
1882 + resolution: {integrity: sha512-u6dClpzNdWf1HGWz4wwhdXi1wiOofCLniM9S4BQQGlLAN9TW7VB+ld5V533GdKrYMaFeBGFqKnj0JCYvynLqwQ==}
1883 + engines: {node: '>=20.0.0'}
1884 +
1885 + '@aws-sdk/credential-provider-process@3.972.48':
1886 + resolution: {integrity: sha512-w6VZwojPt12WnEkAUy6Nu4K6sWCbBmR7QX390b0nE6vRvkXbrYr9Lq9VySGkfjiMjpUA87op+J4EgvRmtWIDoQ==}
1887 + engines: {node: '>=20.0.0'}
1888 +
1889 + '@aws-sdk/credential-provider-sso@3.972.54':
1890 + resolution: {integrity: sha512-23uZpIpF2SIFDCa1fcWa202tK4gGeyvX6GIIAjiB8WBsvsVRBMnJ/7dCxHzxf7eZT7GToJg837LDIBnZsl/VUg==}
1891 + engines: {node: '>=20.0.0'}
1892 +
1893 + '@aws-sdk/credential-provider-web-identity@3.972.54':
1894 + resolution: {integrity: sha512-0Iv5QttS6wcATlodYKgvQj6B9Db51rx7NU9fqu0PoLeS4BIgdYMc/QK4smwLwpm5RFrs02V/eLyEFp3FklvlNQ==}
1895 + engines: {node: '>=20.0.0'}
1896 +
1897 + '@aws-sdk/eventstream-handler-node@3.972.22':
1898 + resolution: {integrity: sha512-tqPJv0dz4+O0hWGm1a6YekcMZyPhDFs/zH73Von7icaVT5n0Jqvm86typ3jRrG+qoUdPhALOnboRLTmnWQTlYQ==}
1899 + engines: {node: '>=20.0.0'}
1900 +
1901 + '@aws-sdk/middleware-eventstream@3.972.18':
1902 + resolution: {integrity: sha512-OHpk8YoZi3yexPq8aFt1vN1IxA2zLKvsIR5GpWYylX/ve6kQmY7wxHNSFy/D3t2apMZ16rs76Co4dJWcDyIk3A==}
1903 + engines: {node: '>=20.0.0'}
1904 +
1905 + '@aws-sdk/middleware-websocket@3.972.30':
1906 + resolution: {integrity: sha512-kH6N4f/Fzi9r/dYap8EQ+Zk4NOz8pl4AtWKhzAoG2C1/4YkIHok9APp/e+75woreWQq264n+LkrJsJVZ0Q+M1Q==}
1907 + engines: {node: '>= 14.0.0'}
1908 +
1909 + '@aws-sdk/nested-clients@3.997.22':
1910 + resolution: {integrity: sha512-4IwtcYSxEIVw5hcp8ogq0CMbFNZFw7jJUetpfFUhFFeqsa1K8j2Ihg2hnxLyOp3stMZnXda6VzOmPi1AFZQXcg==}
1911 + engines: {node: '>=20.0.0'}
1912 +
1913 + '@aws-sdk/signature-v4-multi-region@3.996.35':
1914 + resolution: {integrity: sha512-6L/VWs+Wch2stHemCGTmUNqKLMzURxQDK5boNG3Jn3kAOp71meDUuS5sbObpEvFxHDq0uWeSLFDNSYsjNt+Dlg==}
1915 + engines: {node: '>=20.0.0'}
1916 +
1917 + '@aws-sdk/token-providers@3.1048.0':
1918 + resolution: {integrity: sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA==}
1919 + engines: {node: '>=20.0.0'}
1920 +
1921 + '@aws-sdk/token-providers@3.1071.0':
1922 + resolution: {integrity: sha512-4LDW2Qob6LoLFuqYSYZq2AyTE9koSE9+i+n5UZcm10GpmQOK0zRD9L4uYlzItiTKksIWgC/qMFChAi3RvKYtMg==}
1923 + engines: {node: '>=20.0.0'}
1924 +
1925 '@aws-sdk/types@3.973.1':
1926 resolution: {integrity: sha512-DwHBiMNOB468JiX6+i34c+THsKHErYUdNQ3HexeXZvVn4zouLjgaS4FejiGSi2HyBuzuyHg7SuOPmjSvoU9NRg==}
1927 engines: {node: '>=20.0.0'}
1928
1929 + '@aws-sdk/types@3.973.13':
1930 + resolution: {integrity: sha512-pEHZqRkAlHfnfAU9tK+WpKv/gBNjGJrHMgA3A0iYRGyswBS2t0pfez+lWlwktb3Bqa0ovh7w/QJTFwp3fDxLNg==}
1931 + engines: {node: '>=20.0.0'}
1932 +
1933 + '@aws-sdk/util-locate-window@3.965.8':
1934 + resolution: {integrity: sha512-uUbMs1cBZPafD0ohUj6EwNf0fPZ534NvBxHox4hjX+0Rxq5paSYUem7+hi833pYrzrcnBATKIYpR02MDXT5M9g==}
1935 + engines: {node: '>=20.0.0'}
1936 +
1937 + '@aws-sdk/xml-builder@3.972.30':
1938 + resolution: {integrity: sha512-StElZPEoBquWwNqw1AcfpzEyZqJvFxouG+mpDNYlcH6ZOrqd2CuIryv+8LV8gNHZUOyKyJF3Dq9vxaXEmDR9TQ==}
1939 + engines: {node: '>=20.0.0'}
1940 +
1941 + '@aws/lambda-invoke-store@0.2.4':
1942 + resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}
1943 + engines: {node: '>=18.0.0'}
1944 +
1945 '@babel/code-frame@7.29.0':
1946 resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
1947 engines: {node: '>=6.9.0'}
@@ -1986,6 +2144,24 @@ packages:
2144 '@dprint/typescript@0.91.8':
2145 resolution: {integrity: sha512-tuKn4leCPItox1O4uunHcQF0QllDCvPWklnNQIh2PiWWVtRAGltJJnM4Cwj5AciplosD1Hiz7vAY3ew3crLb3A==}
2146
2147 + '@earendil-works/pi-agent-core@0.79.8':
2148 + resolution: {integrity: sha512-8m5fcqRpoGpq3QY0I/tFXROSTmPwBb1dAuzYZO3XYgjsdCokkRMAGRjA9P8s/UD6Jy9yy69lyE4H6sz/5A1TmQ==}
2149 + engines: {node: '>=22.19.0'}
2150 +
2151 + '@earendil-works/pi-ai@0.79.8':
2152 + resolution: {integrity: sha512-ZpSwaD7oNpsjn9vtEatZQNT9PSdDJXi6rFeY5Qv+OHQGFDKlmcrfJE4ypm4SAc/fBECPs4Rdi3l+YjVtXYrkKw==}
2153 + engines: {node: '>=22.19.0'}
2154 + hasBin: true
2155 +
2156 + '@earendil-works/pi-coding-agent@0.79.8':
2157 + resolution: {integrity: sha512-wr9oTS/yrwURDXnYrONQgFgV7QDlwslXL/rvKU5X7TRtrGxIhippsRApXqYlRwSeMjb2YzgHMfZ/kAhOqrzoFQ==}
2158 + engines: {node: '>=22.19.0'}
2159 + hasBin: true
2160 +
2161 + '@earendil-works/pi-tui@0.79.8':
2162 + resolution: {integrity: sha512-QerB+0wUc6eEO8MwvzOQGtzcsbwo6y8VvdxYU6vGcakz6ofJZWhrmwrknp1dCGx3bEtCf+siUIxEzkqvFCzIsg==}
2163 + engines: {node: '>=22.19.0'}
2164 +
2165 '@effect/cli@0.75.2':
2166 resolution: {integrity: sha512-+cMn/ZtFB+jEvgB6phrTT6XyPkIUnmX4G0nUSln7yj3lwyiHQ578Iwr8nHeU1CKEtlh4Xt+mYc0yiT912xu7YA==}
2167 peerDependencies:
@@ -2626,6 +2802,15 @@ packages:
2802 '@modelcontextprotocol/sdk':
2803 optional: true
2804
2805 + '@google/genai@1.52.0':
2806 + resolution: {integrity: sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==}
2807 + engines: {node: '>=20.0.0'}
2808 + peerDependencies:
2809 + '@modelcontextprotocol/sdk': ^1.25.2
2810 + peerDependenciesMeta:
2811 + '@modelcontextprotocol/sdk':
2812 + optional: true
2813 +
2814 '@hono/node-server@1.19.9':
2815 resolution: {integrity: sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==}
2816 engines: {node: '>=18.14.1'}
@@ -3059,6 +3244,74 @@ packages:
3244 '@manypkg/get-packages@1.1.3':
3245 resolution: {integrity: sha512-fo+QhuU3qE/2TQMQmbVMqaQ6EWbMhi4ABWP+O4AM1NqPBuy0OrApV5LO6BrrgnhtAHS2NH6RrVk9OL181tTi8A==}
3246
3247 + '@mariozechner/clipboard-darwin-arm64@0.3.9':
3248 + resolution: {integrity: sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ==}
3249 + engines: {node: '>= 10'}
3250 + cpu: [arm64]
3251 + os: [darwin]
3252 +
3253 + '@mariozechner/clipboard-darwin-universal@0.3.9':
3254 + resolution: {integrity: sha512-BGGR4iA9Z2shAjI65eI5xtyb3LYNlDW9X3gxKxDbqtbnREohsrqznov6zpKoIrsRWpzlYVEdKphS7ksJ0/ndSQ==}
3255 + engines: {node: '>= 10'}
3256 + os: [darwin]
3257 +
3258 + '@mariozechner/clipboard-darwin-x64@0.3.9':
3259 + resolution: {integrity: sha512-4kURmCbS6nt8uYhtmWpUcJWyPHfmAr5dTpXD1nO3pIfa+TSQ9DbrGOYCKH+aEFW47XhQ4Vp8ZTszie+wfFvDKg==}
3260 + engines: {node: '>= 10'}
3261 + cpu: [x64]
3262 + os: [darwin]
3263 +
3264 + '@mariozechner/clipboard-linux-arm64-gnu@0.3.9':
3265 + resolution: {integrity: sha512-g59OkUGP2DDfCOIKypHeYgv2M55u/cKvXa5dSxFbEJ34XvIQMdcVmpKCkGUro3ZgefXiGVdwguvTMQGpHWzIXw==}
3266 + engines: {node: '>= 10'}
3267 + cpu: [arm64]
3268 + os: [linux]
3269 + libc: [glibc]
3270 +
3271 + '@mariozechner/clipboard-linux-arm64-musl@0.3.9':
3272 + resolution: {integrity: sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ==}
3273 + engines: {node: '>= 10'}
3274 + cpu: [arm64]
3275 + os: [linux]
3276 + libc: [musl]
3277 +
3278 + '@mariozechner/clipboard-linux-riscv64-gnu@0.3.9':
3279 + resolution: {integrity: sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw==}
3280 + engines: {node: '>= 10'}
3281 + cpu: [riscv64]
3282 + os: [linux]
3283 + libc: [glibc]
3284 +
3285 + '@mariozechner/clipboard-linux-x64-gnu@0.3.9':
3286 + resolution: {integrity: sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw==}
3287 + engines: {node: '>= 10'}
3288 + cpu: [x64]
3289 + os: [linux]
3290 + libc: [glibc]
3291 +
3292 + '@mariozechner/clipboard-linux-x64-musl@0.3.9':
3293 + resolution: {integrity: sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ==}
3294 + engines: {node: '>= 10'}
3295 + cpu: [x64]
3296 + os: [linux]
3297 + libc: [musl]
3298 +
3299 + '@mariozechner/clipboard-win32-arm64-msvc@0.3.9':
3300 + resolution: {integrity: sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ==}
3301 + engines: {node: '>= 10'}
3302 + cpu: [arm64]
3303 + os: [win32]
3304 +
3305 + '@mariozechner/clipboard-win32-x64-msvc@0.3.9':
3306 + resolution: {integrity: sha512-ihQC3EufqEY81vhXBgVBtK4prL+wc62zJsSvxrgz7K1hsdt6OObz6v9p3Rn1OG3GJksTTKMJF0u/guMISHPhSA==}
3307 + engines: {node: '>= 10'}
3308 + cpu: [x64]
3309 + os: [win32]
3310 +
3311 + '@mariozechner/clipboard@0.3.9':
3312 + resolution: {integrity: sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA==}
3313 + engines: {node: '>= 10'}
3314 +
3315 '@mastra/core@1.4.0':
3316 resolution: {integrity: sha512-dyCUFozUGXwyNLl5zRZbKFKemp4gfk+vTsrfgv9M08OlXl2AuLgc+J6Yyj9gFwBVCTgxPaKUtu3QaDOiproXrg==}
3317 engines: {node: '>=22.13.0'}
@@ -3108,6 +3361,14 @@ packages:
3361 peerDependencies:
3362 zod: ^3.25.0 || ^4.0.0
3363
3364 + '@mistralai/mistralai@2.2.6':
3365 + resolution: {integrity: sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ==}
3366 + peerDependencies:
3367 + '@opentelemetry/api': ^1.9.0
3368 + peerDependenciesMeta:
3369 + '@opentelemetry/api':
3370 + optional: true
3371 +
3372 '@modelcontextprotocol/sdk@1.26.0':
3373 resolution: {integrity: sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==}
3374 engines: {node: '>=18'}
@@ -3164,6 +3425,9 @@ packages:
3425 '@emnapi/core': ^1.7.1
3426 '@emnapi/runtime': ^1.7.1
3427
3428 + '@nodable/entities@2.2.0':
3429 + resolution: {integrity: sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg==}
3430 +
3431 '@nodelib/fs.scandir@2.1.5':
3432 resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
3433 engines: {node: '>= 8'}
@@ -3203,6 +3467,10 @@ packages:
3467 resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}
3468 engines: {node: '>=8.0.0'}
3469
3470 + '@opentelemetry/semantic-conventions@1.41.1':
3471 + resolution: {integrity: sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==}
3472 + engines: {node: '>=14'}
3473 +
3474 '@oxc-project/types@0.112.0':
3475 resolution: {integrity: sha512-m6RebKHIRsax2iCwVpYW2ErQwa4ywHJrE4sCK3/8JK8ZZAWOKXaRJFl/uP51gaVyyXlaS4+chU1nSCdzYf6QqQ==}
3476
@@ -3707,6 +3975,9 @@ packages:
3975 '@shikijs/vscode-textmate@10.0.2':
3976 resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
3977
3978 + '@silvia-odwyer/photon-node@0.3.4':
3979 + resolution: {integrity: sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==}
3980 +
3981 '@sindresorhus/is@4.6.0':
3982 resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
3983 engines: {node: '>=10'}
@@ -3727,14 +3998,42 @@ packages:
3998 resolution: {integrity: sha512-doH1gimEu3A46VX6aVxpHTeHrytJAG6HgdxntYnCFiIFHEM/ZGpG8KiZGBChchjQmG0XFIBL552kBTjVcMZXwQ==}
3999 engines: {node: '>=12'}
4000
4001 + '@smithy/core@3.25.1':
4002 + resolution: {integrity: sha512-zpDbpXBCBsxfLtG2GEUyfgvHvSFrw5CwDZSNzL0v52gx/c3oPlPbm+7W7num8xs6vyiUBn+bvYPHcQDOXZynCQ==}
4003 + engines: {node: '>=18.0.0'}
4004 +
4005 + '@smithy/credential-provider-imds@4.4.1':
4006 + resolution: {integrity: sha512-TSAF5NHgxEsllbErYWbK8aLnl5L601NGc5VYJlSPsKnf3YlkhdoBN+geGcaU00oiw2OK3QO5LA3QNXiiWhCidQ==}
4007 + engines: {node: '>=18.0.0'}
4008 +
4009 + '@smithy/fetch-http-handler@5.5.1':
4010 + resolution: {integrity: sha512-96JrD1q71anokymx9Iblb+zKmNQYNstlV/25A9ZYIJ2A0rp1r7/GZAIm0bDWSmVvz3DpNOCZuabzsiL+w0UHhw==}
4011 + engines: {node: '>=18.0.0'}
4012 +
4013 '@smithy/is-array-buffer@2.2.0':
4014 resolution: {integrity: sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==}
4015 engines: {node: '>=14.0.0'}
4016
4017 + '@smithy/node-http-handler@4.7.3':
4018 + resolution: {integrity: sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==}
4019 + engines: {node: '>=18.0.0'}
4020 +
4021 + '@smithy/node-http-handler@4.8.1':
4022 + resolution: {integrity: sha512-emtXvoky671puri18ETf64AFIQUGIEA093F2drXpBgB0OGnBLjcwNR3CA2mYu62IAqNsS56xa5lnTxAgPq7cjw==}
4023 + engines: {node: '>=18.0.0'}
4024 +
4025 + '@smithy/signature-v4@5.5.1':
4026 + resolution: {integrity: sha512-X9rVls3En0z3NtrmguTmpRM0/NqtWUxBjal6fcAkwtsub+gOdLZ6kD+V7xhUgFMGdG14bHbZ7M5QjaRI1+DatQ==}
4027 + engines: {node: '>=18.0.0'}
4028 +
4029 '@smithy/types@4.12.0':
4030 resolution: {integrity: sha512-9YcuJVTOBDjg9LWo23Qp0lTQ3D7fQsQtwle0jVfpbUHy9qBwCEgKuVH4FqFB3VYu0nwdHKiEMA+oXz7oV8X1kw==}
4031 engines: {node: '>=18.0.0'}
4032
4033 + '@smithy/types@4.15.0':
4034 + resolution: {integrity: sha512-Z5TAOxygoFvybJV3igo5SloFflSokHx2hu1eFA+DxDTcn+FtKxUSui+rbTRG1pAafMA888Z3MVvCWUuvCrTXjg==}
4035 + engines: {node: '>=18.0.0'}
4036 +
4037 '@smithy/util-buffer-from@2.2.0':
4038 resolution: {integrity: sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==}
4039 engines: {node: '>=14.0.0'}
@@ -3927,6 +4226,9 @@ packages:
4226 '@types/range-parser@1.2.7':
4227 resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}
4228
4229 + '@types/retry@0.12.0':
4230 + resolution: {integrity: sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==}
4231 +
4232 '@types/semver@7.7.1':
4233 resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==}
4234
@@ -4223,6 +4525,9 @@ packages:
4525 any-promise@1.3.0:
4526 resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}
4527
4528 + anynum@1.0.1:
4529 + resolution: {integrity: sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==}
4530 +
4531 argparse@1.0.10:
4532 resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==}
4533
@@ -4288,6 +4593,9 @@ packages:
4593 resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==}
4594 engines: {node: '>=18'}
4595
4596 + bowser@2.14.1:
4597 + resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
4598 +
4599 brace-expansion@1.1.12:
4600 resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
4601
@@ -4631,6 +4939,10 @@ packages:
4939 resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}
4940 engines: {node: '>=0.3.1'}
4941
4942 + diff@8.0.4:
4943 + resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
4944 + engines: {node: '>=0.3.1'}
4945 +
4946 dir-glob@3.0.1:
4947 resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
4948 engines: {node: '>=8'}
@@ -4919,6 +5231,13 @@ packages:
5231 fast-wrap-ansi@0.2.2:
5232 resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}
5233
5234 + fast-xml-builder@1.2.0:
5235 + resolution: {integrity: sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==}
5236 +
5237 + fast-xml-parser@5.7.3:
5238 + resolution: {integrity: sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==}
5239 + hasBin: true
5240 +
5241 fastq@1.20.1:
5242 resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}
5243
@@ -5056,6 +5375,10 @@ packages:
5375 resolution: {integrity: sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==}
5376 engines: {node: '>=18'}
5377
5378 + get-east-asian-width@1.6.0:
5379 + resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}
5380 + engines: {node: '>=18'}
5381 +
5382 get-intrinsic@1.3.0:
5383 resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
5384 engines: {node: '>= 0.4'}
@@ -5093,6 +5416,10 @@ packages:
5416 deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
5417 hasBin: true
5418
5419 + glob@13.0.6:
5420 + resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
5421 + engines: {node: 18 || 20 || >=22}
5422 +
5423 globals@14.0.0:
5424 resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==}
5425 engines: {node: '>=18'}
@@ -5176,6 +5503,10 @@ packages:
5503 hookable@6.1.1:
5504 resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==}
5505
5506 + hosted-git-info@9.0.3:
5507 + resolution: {integrity: sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==}
5508 + engines: {node: ^20.17.0 || >=22.9.0}
5509 +
5510 html-to-text@9.0.5:
5511 resolution: {integrity: sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==}
5512 engines: {node: '>=14'}
@@ -5187,6 +5518,10 @@ packages:
5518 resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
5519 engines: {node: '>= 0.8'}
5520
5521 + http-proxy-agent@7.0.2:
5522 + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
5523 + engines: {node: '>= 14'}
5524 +
5525 https-proxy-agent@7.0.6:
5526 resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
5527 engines: {node: '>= 14'}
@@ -5374,6 +5709,10 @@ packages:
5709 resolution: {integrity: sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==}
5710 engines: {node: 20 || >=22}
5711
5712 + jiti@2.7.0:
5713 + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
5714 + hasBin: true
5715 +
5716 jose@6.1.3:
5717 resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==}
5718
@@ -5573,6 +5912,11 @@ packages:
5912 peerDependencies:
5913 marked: '>=1 <16'
5914
5915 + marked@18.0.5:
5916 + resolution: {integrity: sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==}
5917 + engines: {node: '>= 20'}
5918 + hasBin: true
5919 +
5920 marked@9.1.6:
5921 resolution: {integrity: sha512-jcByLnIFkd5gSXZmjNvS1TlmRhCXZjIzHYlaGkPlLIekG55JDR2Z4va9tZwCiP+/RDERiNhMOFu01xd6O5ct1Q==}
5922 engines: {node: '>= 16'}
@@ -5794,6 +6138,10 @@ packages:
6138 resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}
6139 engines: {node: '>=16 || 14 >=14.17'}
6140
6141 + minipass@7.1.3:
6142 + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
6143 + engines: {node: '>=16 || 14 >=14.17'}
6144 +
6145 mri@1.2.0:
6146 resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
6147 engines: {node: '>=4'}
@@ -5937,6 +6285,18 @@ packages:
6285 zod:
6286 optional: true
6287
6288 + openai@6.26.0:
6289 + resolution: {integrity: sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA==}
6290 + hasBin: true
6291 + peerDependencies:
6292 + ws: ^8.18.0
6293 + zod: ^3.25 || ^4.0
6294 + peerDependenciesMeta:
6295 + ws:
6296 + optional: true
6297 + zod:
6298 + optional: true
6299 +
6300 openai@6.43.0:
6301 resolution: {integrity: sha512-wVjioGjbnAZycj5mmkFVxbBxLEp+NkKpdMscCYP9LTbq+nbf1WTMVp+ovmD35jgyco4tldWZJkcqdmlh3O9yHQ==}
6302 peerDependencies:
@@ -6008,6 +6368,10 @@ packages:
6368 resolution: {integrity: sha512-O/ZPaXuQV29uSLbxWBGGZO1mCQXV2BLIwUr59JUU9SoH76mnYvtms7aafH/isNSNGwuEfP6W/4xD0/TJXxrizw==}
6369 engines: {node: '>=20'}
6370
6371 + p-retry@4.6.2:
6372 + resolution: {integrity: sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==}
6373 + engines: {node: '>=8'}
6374 +
6375 p-retry@7.1.1:
6376 resolution: {integrity: sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w==}
6377 engines: {node: '>=20'}
@@ -6061,6 +6425,9 @@ packages:
6425 resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
6426 engines: {node: '>= 0.8'}
6427
6428 + partial-json@0.1.7:
6429 + resolution: {integrity: sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==}
6430 +
6431 path-browserify@1.0.1:
6432 resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
6433
@@ -6068,6 +6435,10 @@ packages:
6435 resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
6436 engines: {node: '>=8'}
6437
6438 + path-expression-matcher@1.5.0:
6439 + resolution: {integrity: sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==}
6440 + engines: {node: '>=14.0.0'}
6441 +
6442 path-key@3.1.1:
6443 resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
6444 engines: {node: '>=8'}
@@ -6080,6 +6451,10 @@ packages:
6451 resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
6452 engines: {node: '>=16 || 14 >=14.18'}
6453
6454 + path-scurry@2.0.2:
6455 + resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
6456 + engines: {node: 18 || 20 || >=22}
6457 +
6458 path-to-regexp@0.1.13:
6459 resolution: {integrity: sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==}
6460
@@ -6196,6 +6571,9 @@ packages:
6571 process-nextick-args@2.0.1:
6572 resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}
6573
6574 + proper-lockfile@4.1.2:
6575 + resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
6576 +
6577 protobufjs@7.5.9:
6578 resolution: {integrity: sha512-Od4muIm3HW1AouyHF5lONOf1FWo3hY1NbFDoy191X9GzhpgW1clCoaFjfVs2rKJNFYpTNJbje4cbAIDBZJ63ZA==}
6579 engines: {node: '>=12.0.0'}
@@ -6294,6 +6672,14 @@ packages:
6672 resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
6673 engines: {node: '>=18'}
6674
6675 + retry@0.12.0:
6676 + resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==}
6677 + engines: {node: '>= 4'}
6678 +
6679 + retry@0.13.1:
6680 + resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
6681 + engines: {node: '>= 4'}
6682 +
6683 reusify@1.1.0:
6684 resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
6685 engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
@@ -6377,6 +6763,11 @@ packages:
6763 selderee@0.11.0:
6764 resolution: {integrity: sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==}
6765
6766 + semver@7.8.0:
6767 + resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==}
6768 + engines: {node: '>=10'}
6769 + hasBin: true
6770 +
6771 semver@7.8.4:
6772 resolution: {integrity: sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==}
6773 engines: {node: '>=10'}
@@ -6436,6 +6827,9 @@ packages:
6827 siginfo@2.0.0:
6828 resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
6829
6830 + signal-exit@3.0.7:
6831 + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
6832 +
6833 signal-exit@4.1.0:
6834 resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
6835 engines: {node: '>=14'}
@@ -6544,6 +6938,9 @@ packages:
6938 resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
6939 engines: {node: '>=8'}
6940
6941 + strnum@2.4.1:
6942 + resolution: {integrity: sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg==}
6943 +
6944 superjson@2.2.6:
6945 resolution: {integrity: sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==}
6946 engines: {node: '>=16'}
@@ -6718,6 +7115,12 @@ packages:
7115 resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==}
7116 engines: {node: '>= 0.6'}
7117
7118 + typebox@1.1.38:
7119 + resolution: {integrity: sha512-pZ0aQPmMmXoUvSbeuWf/Hzsc+avNw/Zd6VeE8CFgkVGWyuHPJvqeJJDeJqLve+K70LvjYIoleGcoJHPT17cWoA==}
7120 +
7121 + typebox@1.2.17:
7122 + resolution: {integrity: sha512-FHB10V5OI+MBKQ9N4CS4FTpdTiPwjAwkS9cjXt4uBULFE2zNOYu4A6iAR4GZVPcujSD6uCQjY1fqnOsjn/SLPQ==}
7123 +
7124 typed-array-buffer@1.0.3:
7125 resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==}
7126 engines: {node: '>= 0.4'}
@@ -6765,6 +7168,10 @@ packages:
7168 resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==}
7169 engines: {node: '>=20.18.1'}
7170
7171 + undici@8.5.0:
7172 + resolution: {integrity: sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==}
7173 + engines: {node: '>=22.19.0'}
7174 +
7175 unenv@2.0.0-rc.24:
7176 resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
7177
@@ -7033,6 +7440,10 @@ packages:
7440 resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
7441 engines: {node: '>=18'}
7442
7443 + xml-naming@0.1.0:
7444 + resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==}
7445 + engines: {node: '>=16.0.0'}
7446 +
7447 xtend@4.0.2:
7448 resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
7449 engines: {node: '>=0.4'}
@@ -7401,6 +7812,12 @@ snapshots:
7812 optionalDependencies:
7813 zod: 3.25.76
7814
7815 + '@anthropic-ai/sdk@0.91.1(zod@3.25.76)':
7816 + dependencies:
7817 + json-schema-to-ts: 3.1.1
7818 + optionalDependencies:
7819 + zod: 3.25.76
7820 +
7821 '@apidevtools/json-schema-ref-parser@14.2.1(@types/json-schema@7.0.15)':
7822 dependencies:
7823 '@types/json-schema': 7.0.15
@@ -7427,23 +7844,234 @@ snapshots:
7844 typescript: 5.6.1-rc
7845 validate-npm-package-name: 5.0.1
7846
7847 + '@aws-crypto/crc32@5.2.0':
7848 + dependencies:
7849 + '@aws-crypto/util': 5.2.0
7850 + '@aws-sdk/types': 3.973.1
7851 + tslib: 2.8.1
7852 +
7853 + '@aws-crypto/sha256-browser@5.2.0':
7854 + dependencies:
7855 + '@aws-crypto/sha256-js': 5.2.0
7856 + '@aws-crypto/supports-web-crypto': 5.2.0
7857 + '@aws-crypto/util': 5.2.0
7858 + '@aws-sdk/types': 3.973.13
7859 + '@aws-sdk/util-locate-window': 3.965.8
7860 + '@smithy/util-utf8': 2.3.0
7861 + tslib: 2.8.1
7862 +
7863 '@aws-crypto/sha256-js@5.2.0':
7864 dependencies:
7865 '@aws-crypto/util': 5.2.0
7866 '@aws-sdk/types': 3.973.1
7867 tslib: 2.8.1
7868
7869 + '@aws-crypto/supports-web-crypto@5.2.0':
7870 + dependencies:
7871 + tslib: 2.8.1
7872 +
7873 '@aws-crypto/util@5.2.0':
7874 dependencies:
7875 '@aws-sdk/types': 3.973.1
7876 '@smithy/util-utf8': 2.3.0
7877 tslib: 2.8.1
7878
7879 + '@aws-sdk/client-bedrock-runtime@3.1048.0':
7880 + dependencies:
7881 + '@aws-crypto/sha256-browser': 5.2.0
7882 + '@aws-crypto/sha256-js': 5.2.0
7883 + '@aws-sdk/core': 3.974.22
7884 + '@aws-sdk/credential-provider-node': 3.972.57
7885 + '@aws-sdk/eventstream-handler-node': 3.972.22
7886 + '@aws-sdk/middleware-eventstream': 3.972.18
7887 + '@aws-sdk/middleware-websocket': 3.972.30
7888 + '@aws-sdk/token-providers': 3.1048.0
7889 + '@aws-sdk/types': 3.973.13
7890 + '@smithy/core': 3.25.1
7891 + '@smithy/fetch-http-handler': 5.5.1
7892 + '@smithy/node-http-handler': 4.7.3
7893 + '@smithy/types': 4.15.0
7894 + tslib: 2.8.1
7895 +
7896 + '@aws-sdk/core@3.974.22':
7897 + dependencies:
7898 + '@aws-sdk/types': 3.973.13
7899 + '@aws-sdk/xml-builder': 3.972.30
7900 + '@aws/lambda-invoke-store': 0.2.4
7901 + '@smithy/core': 3.25.1
7902 + '@smithy/signature-v4': 5.5.1
7903 + '@smithy/types': 4.15.0
7904 + bowser: 2.14.1
7905 + tslib: 2.8.1
7906 +
7907 + '@aws-sdk/credential-provider-env@3.972.48':
7908 + dependencies:
7909 + '@aws-sdk/core': 3.974.22
7910 + '@aws-sdk/types': 3.973.13
7911 + '@smithy/core': 3.25.1
7912 + '@smithy/types': 4.15.0
7913 + tslib: 2.8.1
7914 +
7915 + '@aws-sdk/credential-provider-http@3.972.50':
7916 + dependencies:
7917 + '@aws-sdk/core': 3.974.22
7918 + '@aws-sdk/types': 3.973.13
7919 + '@smithy/core': 3.25.1
7920 + '@smithy/fetch-http-handler': 5.5.1
7921 + '@smithy/node-http-handler': 4.8.1
7922 + '@smithy/types': 4.15.0
7923 + tslib: 2.8.1
7924 +
7925 + '@aws-sdk/credential-provider-ini@3.972.55':
7926 + dependencies:
7927 + '@aws-sdk/core': 3.974.22
7928 + '@aws-sdk/credential-provider-env': 3.972.48
7929 + '@aws-sdk/credential-provider-http': 3.972.50
7930 + '@aws-sdk/credential-provider-login': 3.972.54
7931 + '@aws-sdk/credential-provider-process': 3.972.48
7932 + '@aws-sdk/credential-provider-sso': 3.972.54
7933 + '@aws-sdk/credential-provider-web-identity': 3.972.54
7934 + '@aws-sdk/nested-clients': 3.997.22
7935 + '@aws-sdk/types': 3.973.13
7936 + '@smithy/core': 3.25.1
7937 + '@smithy/credential-provider-imds': 4.4.1
7938 + '@smithy/types': 4.15.0
7939 + tslib: 2.8.1
7940 +
7941 + '@aws-sdk/credential-provider-login@3.972.54':
7942 + dependencies:
7943 + '@aws-sdk/core': 3.974.22
7944 + '@aws-sdk/nested-clients': 3.997.22
7945 + '@aws-sdk/types': 3.973.13
7946 + '@smithy/core': 3.25.1
7947 + '@smithy/types': 4.15.0
7948 + tslib: 2.8.1
7949 +
7950 + '@aws-sdk/credential-provider-node@3.972.57':
7951 + dependencies:
7952 + '@aws-sdk/credential-provider-env': 3.972.48
7953 + '@aws-sdk/credential-provider-http': 3.972.50
7954 + '@aws-sdk/credential-provider-ini': 3.972.55
7955 + '@aws-sdk/credential-provider-process': 3.972.48
7956 + '@aws-sdk/credential-provider-sso': 3.972.54
7957 + '@aws-sdk/credential-provider-web-identity': 3.972.54
7958 + '@aws-sdk/types': 3.973.13
7959 + '@smithy/core': 3.25.1
7960 + '@smithy/credential-provider-imds': 4.4.1
7961 + '@smithy/types': 4.15.0
7962 + tslib: 2.8.1
7963 +
7964 + '@aws-sdk/credential-provider-process@3.972.48':
7965 + dependencies:
7966 + '@aws-sdk/core': 3.974.22
7967 + '@aws-sdk/types': 3.973.13
7968 + '@smithy/core': 3.25.1
7969 + '@smithy/types': 4.15.0
7970 + tslib: 2.8.1
7971 +
7972 + '@aws-sdk/credential-provider-sso@3.972.54':
7973 + dependencies:
7974 + '@aws-sdk/core': 3.974.22
7975 + '@aws-sdk/nested-clients': 3.997.22
7976 + '@aws-sdk/token-providers': 3.1071.0
7977 + '@aws-sdk/types': 3.973.13
7978 + '@smithy/core': 3.25.1
7979 + '@smithy/types': 4.15.0
7980 + tslib: 2.8.1
7981 +
7982 + '@aws-sdk/credential-provider-web-identity@3.972.54':
7983 + dependencies:
7984 + '@aws-sdk/core': 3.974.22
7985 + '@aws-sdk/nested-clients': 3.997.22
7986 + '@aws-sdk/types': 3.973.13
7987 + '@smithy/core': 3.25.1
7988 + '@smithy/types': 4.15.0
7989 + tslib: 2.8.1
7990 +
7991 + '@aws-sdk/eventstream-handler-node@3.972.22':
7992 + dependencies:
7993 + '@aws-sdk/types': 3.973.13
7994 + '@smithy/core': 3.25.1
7995 + '@smithy/types': 4.15.0
7996 + tslib: 2.8.1
7997 +
7998 + '@aws-sdk/middleware-eventstream@3.972.18':
7999 + dependencies:
8000 + '@aws-sdk/types': 3.973.13
8001 + '@smithy/core': 3.25.1
8002 + '@smithy/types': 4.15.0
8003 + tslib: 2.8.1
8004 +
8005 + '@aws-sdk/middleware-websocket@3.972.30':
8006 + dependencies:
8007 + '@aws-sdk/core': 3.974.22
8008 + '@aws-sdk/types': 3.973.13
8009 + '@smithy/core': 3.25.1
8010 + '@smithy/fetch-http-handler': 5.5.1
8011 + '@smithy/signature-v4': 5.5.1
8012 + '@smithy/types': 4.15.0
8013 + tslib: 2.8.1
8014 +
8015 + '@aws-sdk/nested-clients@3.997.22':
8016 + dependencies:
8017 + '@aws-crypto/sha256-browser': 5.2.0
8018 + '@aws-crypto/sha256-js': 5.2.0
8019 + '@aws-sdk/core': 3.974.22
8020 + '@aws-sdk/signature-v4-multi-region': 3.996.35
8021 + '@aws-sdk/types': 3.973.13
8022 + '@smithy/core': 3.25.1
8023 + '@smithy/fetch-http-handler': 5.5.1
8024 + '@smithy/node-http-handler': 4.8.1
8025 + '@smithy/types': 4.15.0
8026 + tslib: 2.8.1
8027 +
8028 + '@aws-sdk/signature-v4-multi-region@3.996.35':
8029 + dependencies:
8030 + '@aws-sdk/types': 3.973.13
8031 + '@smithy/signature-v4': 5.5.1
8032 + '@smithy/types': 4.15.0
8033 + tslib: 2.8.1
8034 +
8035 + '@aws-sdk/token-providers@3.1048.0':
8036 + dependencies:
8037 + '@aws-sdk/core': 3.974.22
8038 + '@aws-sdk/nested-clients': 3.997.22
8039 + '@aws-sdk/types': 3.973.13
8040 + '@smithy/core': 3.25.1
8041 + '@smithy/types': 4.15.0
8042 + tslib: 2.8.1
8043 +
8044 + '@aws-sdk/token-providers@3.1071.0':
8045 + dependencies:
8046 + '@aws-sdk/core': 3.974.22
8047 + '@aws-sdk/nested-clients': 3.997.22
8048 + '@aws-sdk/types': 3.973.13
8049 + '@smithy/core': 3.25.1
8050 + '@smithy/types': 4.15.0
8051 + tslib: 2.8.1
8052 +
8053 '@aws-sdk/types@3.973.1':
8054 dependencies:
8055 '@smithy/types': 4.12.0
8056 tslib: 2.8.1
8057
8058 + '@aws-sdk/types@3.973.13':
8059 + dependencies:
8060 + '@smithy/types': 4.15.0
8061 + tslib: 2.8.1
8062 +
8063 + '@aws-sdk/util-locate-window@3.965.8':
8064 + dependencies:
8065 + tslib: 2.8.1
8066 +
8067 + '@aws-sdk/xml-builder@3.972.30':
8068 + dependencies:
8069 + '@smithy/types': 4.15.0
8070 + fast-xml-parser: 5.7.3
8071 + tslib: 2.8.1
8072 +
8073 + '@aws/lambda-invoke-store@0.2.4': {}
8074 +
8075 '@babel/code-frame@7.29.0':
8076 dependencies:
8077 '@babel/helper-validator-identifier': 7.28.5
@@ -7656,7 +8284,7 @@ snapshots:
8284 cjs-module-lexer: 1.2.3
8285 esbuild: 0.27.3
8286 miniflare: 4.20260611.0
7659 - vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
8287 + vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
8288 wrangler: 4.100.0(@cloudflare/workers-types@4.20260617.1)
8289 zod: 3.25.76
8290 transitivePeerDependencies:
@@ -7709,6 +8337,76 @@ snapshots:
8337
8338 '@dprint/typescript@0.91.8': {}
8339
8340 + '@earendil-works/pi-agent-core@0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)':
8341 + dependencies:
8342 + '@earendil-works/pi-ai': 0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)
8343 + ignore: 7.0.5
8344 + typebox: 1.1.38
8345 + yaml: 2.9.0
8346 + transitivePeerDependencies:
8347 + - '@modelcontextprotocol/sdk'
8348 + - bufferutil
8349 + - supports-color
8350 + - utf-8-validate
8351 + - ws
8352 + - zod
8353 +
8354 + '@earendil-works/pi-ai@0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)':
8355 + dependencies:
8356 + '@anthropic-ai/sdk': 0.91.1(zod@3.25.76)
8357 + '@aws-sdk/client-bedrock-runtime': 3.1048.0
8358 + '@google/genai': 1.52.0(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))
8359 + '@mistralai/mistralai': 2.2.6(@opentelemetry/api@1.9.0)
8360 + '@opentelemetry/api': 1.9.0
8361 + '@smithy/node-http-handler': 4.7.3
8362 + http-proxy-agent: 7.0.2
8363 + https-proxy-agent: 7.0.6(supports-color@10.2.2)
8364 + openai: 6.26.0(ws@8.20.1)(zod@3.25.76)
8365 + partial-json: 0.1.7
8366 + typebox: 1.1.38
8367 + transitivePeerDependencies:
8368 + - '@modelcontextprotocol/sdk'
8369 + - bufferutil
8370 + - supports-color
8371 + - utf-8-validate
8372 + - ws
8373 + - zod
8374 +
8375 + '@earendil-works/pi-coding-agent@0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)':
8376 + dependencies:
8377 + '@earendil-works/pi-agent-core': 0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)
8378 + '@earendil-works/pi-ai': 0.79.8(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(ws@8.20.1)(zod@3.25.76)
8379 + '@earendil-works/pi-tui': 0.79.8
8380 + '@silvia-odwyer/photon-node': 0.3.4
8381 + chalk: 5.6.2
8382 + cross-spawn: 7.0.6
8383 + diff: 8.0.4
8384 + glob: 13.0.6
8385 + highlight.js: 10.7.3
8386 + hosted-git-info: 9.0.3
8387 + ignore: 7.0.5
8388 + jiti: 2.7.0
8389 + minimatch: 10.2.5
8390 + proper-lockfile: 4.1.2
8391 + semver: 7.8.0
8392 + typebox: 1.1.38
8393 + undici: 8.5.0
8394 + yaml: 2.9.0
8395 + optionalDependencies:
8396 + '@mariozechner/clipboard': 0.3.9
8397 + transitivePeerDependencies:
8398 + - '@modelcontextprotocol/sdk'
8399 + - bufferutil
8400 + - supports-color
8401 + - utf-8-validate
8402 + - ws
8403 + - zod
8404 +
8405 + '@earendil-works/pi-tui@0.79.8':
8406 + dependencies:
8407 + get-east-asian-width: 1.6.0
8408 + marked: 18.0.5
8409 +
8410 '@effect/cli@0.75.2(@effect/platform@0.96.1(effect@3.21.3))(@effect/printer-ansi@0.49.0(@effect/typeclass@0.40.0(effect@3.21.3))(effect@3.21.3))(@effect/printer@0.49.0(@effect/typeclass@0.40.0(effect@3.21.3))(effect@3.21.3))(effect@3.21.3)':
8411 dependencies:
8412 '@effect/platform': 0.96.1(effect@3.21.3)
@@ -7807,7 +8505,7 @@ snapshots:
8505 '@effect/vitest@0.29.0(effect@3.21.3)(vitest@4.1.9)':
8506 dependencies:
8507 effect: 3.21.3
7810 - vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
8508 + vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
8509
8510 '@effect/workflow@0.18.2(@effect/experimental@0.60.0(@effect/platform@0.96.1(effect@3.21.3))(effect@3.21.3))(@effect/platform@0.96.1(effect@3.21.3))(@effect/rpc@0.75.1(@effect/platform@0.96.1(effect@3.21.3))(effect@3.21.3))(effect@3.21.3)':
8511 dependencies:
@@ -8071,14 +8769,14 @@ snapshots:
8769 '@esbuild/win32-x64@0.28.1':
8770 optional: true
8771
8074 - '@eslint-community/eslint-utils@4.9.1(eslint@9.39.2(supports-color@10.2.2))':
8772 + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.2(jiti@2.7.0))':
8773 dependencies:
8076 - eslint: 9.39.2(supports-color@10.2.2)
8774 + eslint: 9.39.2(jiti@2.7.0)
8775 eslint-visitor-keys: 3.4.3
8776
8777 '@eslint-community/regexpp@4.12.2': {}
8778
8081 - '@eslint/config-array@0.21.1(supports-color@10.2.2)':
8779 + '@eslint/config-array@0.21.1':
8780 dependencies:
8781 '@eslint/object-schema': 2.1.7
8782 debug: 4.4.3(supports-color@10.2.2)
@@ -8094,7 +8792,7 @@ snapshots:
8792 dependencies:
8793 '@types/json-schema': 7.0.15
8794
8097 - '@eslint/eslintrc@3.3.3(supports-color@10.2.2)':
8795 + '@eslint/eslintrc@3.3.3':
8796 dependencies:
8797 ajv: 6.12.6
8798 debug: 4.4.3(supports-color@10.2.2)
@@ -8142,6 +8840,19 @@ snapshots:
8840 - supports-color
8841 - utf-8-validate
8842
8843 + '@google/genai@1.52.0(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))':
8844 + dependencies:
8845 + google-auth-library: 10.5.0
8846 + p-retry: 4.6.2
8847 + protobufjs: 7.5.9
8848 + ws: 8.20.1
8849 + optionalDependencies:
8850 + '@modelcontextprotocol/sdk': 1.29.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
8851 + transitivePeerDependencies:
8852 + - bufferutil
8853 + - supports-color
8854 + - utf-8-validate
8855 +
8856 '@hono/node-server@1.19.9(hono@4.11.9)':
8857 dependencies:
8858 hono: 4.11.9
@@ -8481,7 +9192,7 @@ snapshots:
9192 - react
9193 - react-dom
9194
8484 - '@langchain/mcp-adapters@1.1.3(@cfworker/json-schema@4.1.1)(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(@langchain/langgraph@1.1.4(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(supports-color@10.2.2)':
9195 + '@langchain/mcp-adapters@1.1.3(@cfworker/json-schema@4.1.1)(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(@langchain/langgraph@1.1.4(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))':
9196 dependencies:
9197 '@langchain/core': 1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3))
9198 '@langchain/langgraph': 1.1.4(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.20.1)(zod@4.4.3)))(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)
@@ -8591,7 +9302,51 @@ snapshots:
9302 globby: 11.1.0
9303 read-yaml-file: 1.1.0
9304
8594 - '@mastra/core@1.4.0(@cfworker/json-schema@4.1.1)(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3))(@types/json-schema@7.0.15)(openapi-types@12.1.3)(zod@4.4.3)':
9305 + '@mariozechner/clipboard-darwin-arm64@0.3.9':
9306 + optional: true
9307 +
9308 + '@mariozechner/clipboard-darwin-universal@0.3.9':
9309 + optional: true
9310 +
9311 + '@mariozechner/clipboard-darwin-x64@0.3.9':
9312 + optional: true
9313 +
9314 + '@mariozechner/clipboard-linux-arm64-gnu@0.3.9':
9315 + optional: true
9316 +
9317 + '@mariozechner/clipboard-linux-arm64-musl@0.3.9':
9318 + optional: true
9319 +
9320 + '@mariozechner/clipboard-linux-riscv64-gnu@0.3.9':
9321 + optional: true
9322 +
9323 + '@mariozechner/clipboard-linux-x64-gnu@0.3.9':
9324 + optional: true
9325 +
9326 + '@mariozechner/clipboard-linux-x64-musl@0.3.9':
9327 + optional: true
9328 +
9329 + '@mariozechner/clipboard-win32-arm64-msvc@0.3.9':
9330 + optional: true
9331 +
9332 + '@mariozechner/clipboard-win32-x64-msvc@0.3.9':
9333 + optional: true
9334 +
9335 + '@mariozechner/clipboard@0.3.9':
9336 + optionalDependencies:
9337 + '@mariozechner/clipboard-darwin-arm64': 0.3.9
9338 + '@mariozechner/clipboard-darwin-universal': 0.3.9
9339 + '@mariozechner/clipboard-darwin-x64': 0.3.9
9340 + '@mariozechner/clipboard-linux-arm64-gnu': 0.3.9
9341 + '@mariozechner/clipboard-linux-arm64-musl': 0.3.9
9342 + '@mariozechner/clipboard-linux-riscv64-gnu': 0.3.9
9343 + '@mariozechner/clipboard-linux-x64-gnu': 0.3.9
9344 + '@mariozechner/clipboard-linux-x64-musl': 0.3.9
9345 + '@mariozechner/clipboard-win32-arm64-msvc': 0.3.9
9346 + '@mariozechner/clipboard-win32-x64-msvc': 0.3.9
9347 + optional: true
9348 +
9349 + '@mastra/core@1.4.0(@cfworker/json-schema@4.1.1)(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3))(@types/json-schema@7.0.15)(openapi-types@12.1.3)(zod@4.4.3)':
9350 dependencies:
9351 '@a2a-js/sdk': 0.2.5
9352 '@ai-sdk/provider-utils-v5': '@ai-sdk/provider-utils@3.0.20(zod@4.4.3)'
@@ -8607,7 +9362,7 @@ snapshots:
9362 dotenv: 17.3.1
9363 gray-matter: 4.0.3
9364 hono: 4.11.9
8610 - hono-openapi: 1.2.0(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3))(@types/json-schema@7.0.15)(hono@4.11.9)(openapi-types@12.1.3)
9365 + hono-openapi: 1.2.0(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3))(@types/json-schema@7.0.15)(hono@4.11.9)(openapi-types@12.1.3)
9366 js-tiktoken: 1.0.21
9367 json-schema: 0.4.0
9368 lru-cache: 11.2.6
@@ -8860,6 +9615,18 @@ snapshots:
9615 zod-from-json-schema-v3: zod-from-json-schema@0.0.5
9616 zod-to-json-schema: 3.25.2(zod@4.4.3)
9617
9618 + '@mistralai/mistralai@2.2.6(@opentelemetry/api@1.9.0)':
9619 + dependencies:
9620 + '@opentelemetry/semantic-conventions': 1.41.1
9621 + ws: 8.20.1
9622 + zod: 3.25.76
9623 + zod-to-json-schema: 3.25.2(zod@3.25.76)
9624 + optionalDependencies:
9625 + '@opentelemetry/api': 1.9.0
9626 + transitivePeerDependencies:
9627 + - bufferutil
9628 + - utf-8-validate
9629 +
9630 '@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
9631 dependencies:
9632 '@hono/node-server': 1.19.9(hono@4.11.9)
@@ -9029,6 +9796,8 @@ snapshots:
9796 '@tybys/wasm-util': 0.10.2
9797 optional: true
9798
9799 + '@nodable/entities@2.2.0': {}
9800 +
9801 '@nodelib/fs.scandir@2.1.5':
9802 dependencies:
9803 '@nodelib/fs.stat': 2.0.5
@@ -9041,7 +9810,7 @@ snapshots:
9810 '@nodelib/fs.scandir': 2.1.5
9811 fastq: 1.20.1
9812
9044 - '@openai/agents-core@0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)':
9813 + '@openai/agents-core@0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)':
9814 dependencies:
9815 debug: 4.4.3(supports-color@10.2.2)
9816 openai: 5.23.2(ws@8.20.1)(zod@4.4.3)
@@ -9053,9 +9822,9 @@ snapshots:
9822 - supports-color
9823 - ws
9824
9056 - '@openai/agents-openai@0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)':
9825 + '@openai/agents-openai@0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)':
9826 dependencies:
9058 - '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
9827 + '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
9828 debug: 4.4.3(supports-color@10.2.2)
9829 openai: 5.23.2(ws@8.20.1)(zod@4.4.3)
9830 zod: 4.4.3
@@ -9064,9 +9833,9 @@ snapshots:
9833 - supports-color
9834 - ws
9835
9067 - '@openai/agents-realtime@0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)':
9836 + '@openai/agents-realtime@0.1.11(@cfworker/json-schema@4.1.1)(zod@4.4.3)':
9837 dependencies:
9069 - '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
9838 + '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
9839 '@types/ws': 8.18.1
9840 debug: 4.4.3(supports-color@10.2.2)
9841 ws: 8.20.1
@@ -9077,11 +9846,11 @@ snapshots:
9846 - supports-color
9847 - utf-8-validate
9848
9080 - '@openai/agents@0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)':
9849 + '@openai/agents@0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)':
9850 dependencies:
9082 - '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
9083 - '@openai/agents-openai': 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(ws@8.20.1)(zod@4.4.3)
9084 - '@openai/agents-realtime': 0.1.11(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
9851 + '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
9852 + '@openai/agents-openai': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.20.1)(zod@4.4.3)
9853 + '@openai/agents-realtime': 0.1.11(@cfworker/json-schema@4.1.1)(zod@4.4.3)
9854 debug: 4.4.3(supports-color@10.2.2)
9855 openai: 5.23.2(ws@8.20.1)(zod@4.4.3)
9856 zod: 4.4.3
@@ -9094,6 +9863,8 @@ snapshots:
9863
9864 '@opentelemetry/api@1.9.0': {}
9865
9866 + '@opentelemetry/semantic-conventions@1.41.1': {}
9867 +
9868 '@oxc-project/types@0.112.0':
9869 optional: true
9870
@@ -9433,6 +10204,8 @@ snapshots:
10204
10205 '@shikijs/vscode-textmate@10.0.2': {}
10206
10207 + '@silvia-odwyer/photon-node@0.3.4': {}
10208 +
10209 '@sindresorhus/is@4.6.0': {}
10210
10211 '@sindresorhus/is@7.2.0': {}
@@ -9448,14 +10221,54 @@ snapshots:
10221 dependencies:
10222 escape-string-regexp: 5.0.0
10223
10224 + '@smithy/core@3.25.1':
10225 + dependencies:
10226 + '@aws-crypto/crc32': 5.2.0
10227 + '@smithy/types': 4.15.0
10228 + tslib: 2.8.1
10229 +
10230 + '@smithy/credential-provider-imds@4.4.1':
10231 + dependencies:
10232 + '@smithy/core': 3.25.1
10233 + '@smithy/types': 4.15.0
10234 + tslib: 2.8.1
10235 +
10236 + '@smithy/fetch-http-handler@5.5.1':
10237 + dependencies:
10238 + '@smithy/core': 3.25.1
10239 + '@smithy/types': 4.15.0
10240 + tslib: 2.8.1
10241 +
10242 '@smithy/is-array-buffer@2.2.0':
10243 dependencies:
10244 tslib: 2.8.1
10245
10246 + '@smithy/node-http-handler@4.7.3':
10247 + dependencies:
10248 + '@smithy/core': 3.25.1
10249 + '@smithy/types': 4.15.0
10250 + tslib: 2.8.1
10251 +
10252 + '@smithy/node-http-handler@4.8.1':
10253 + dependencies:
10254 + '@smithy/core': 3.25.1
10255 + '@smithy/types': 4.15.0
10256 + tslib: 2.8.1
10257 +
10258 + '@smithy/signature-v4@5.5.1':
10259 + dependencies:
10260 + '@smithy/core': 3.25.1
10261 + '@smithy/types': 4.15.0
10262 + tslib: 2.8.1
10263 +
10264 '@smithy/types@4.12.0':
10265 dependencies:
10266 tslib: 2.8.1
10267
10268 + '@smithy/types@4.15.0':
10269 + dependencies:
10270 + tslib: 2.8.1
10271 +
10272 '@smithy/util-buffer-from@2.2.0':
10273 dependencies:
10274 '@smithy/is-array-buffer': 2.2.0
@@ -9468,23 +10281,25 @@ snapshots:
10281
10282 '@speed-highlight/core@1.2.15': {}
10283
9471 - '@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)':
10284 + '@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)':
10285 dependencies:
10286 '@standard-schema/spec': 1.1.0
10287 '@types/json-schema': 7.0.15
10288 quansync: 1.0.0
10289 optionalDependencies:
10290 effect: 3.21.3
10291 + typebox: 1.2.17
10292 zod: 4.4.3
10293 zod-to-json-schema: 3.25.2(zod@4.4.3)
10294
9481 - '@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3)':
10295 + '@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3)':
10296 dependencies:
9483 - '@standard-community/standard-json': 0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)
10297 + '@standard-community/standard-json': 0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)
10298 '@standard-schema/spec': 1.1.0
10299 openapi-types: 12.1.3
10300 optionalDependencies:
10301 effect: 3.21.3
10302 + typebox: 1.2.17
10303 zod: 4.4.3
10304
10305 '@standard-schema/spec@1.1.0': {}
@@ -9606,6 +10421,8 @@ snapshots:
10421
10422 '@types/range-parser@1.2.7': {}
10423
10424 + '@types/retry@0.12.0': {}
10425 +
10426 '@types/semver@7.7.1': {}
10427
10428 '@types/send@0.17.6':
@@ -9631,15 +10448,15 @@ snapshots:
10448 dependencies:
10449 '@types/node': 24.10.13
10450
9634 - '@typescript-eslint/eslint-plugin@8.61.1(@typescript-eslint/parser@8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)':
10451 + '@typescript-eslint/eslint-plugin@8.61.1(@typescript-eslint/parser@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3))(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)':
10452 dependencies:
10453 '@eslint-community/regexpp': 4.12.2
9637 - '@typescript-eslint/parser': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
10454 + '@typescript-eslint/parser': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
10455 '@typescript-eslint/scope-manager': 8.61.1
9639 - '@typescript-eslint/type-utils': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
9640 - '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(typescript@6.0.3)
10456 + '@typescript-eslint/type-utils': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
10457 + '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
10458 '@typescript-eslint/visitor-keys': 8.61.1
9642 - eslint: 9.39.2(supports-color@10.2.2)
10459 + eslint: 9.39.2(jiti@2.7.0)
10460 ignore: 7.0.5
10461 natural-compare: 1.4.0
10462 ts-api-utils: 2.5.0(typescript@6.0.3)
@@ -9647,14 +10464,14 @@ snapshots:
10464 transitivePeerDependencies:
10465 - supports-color
10466
9650 - '@typescript-eslint/parser@8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)':
10467 + '@typescript-eslint/parser@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)':
10468 dependencies:
10469 '@typescript-eslint/scope-manager': 8.61.1
10470 '@typescript-eslint/types': 8.61.1
10471 '@typescript-eslint/typescript-estree': 8.61.1(typescript@6.0.3)
10472 '@typescript-eslint/visitor-keys': 8.61.1
10473 debug: 4.4.3(supports-color@10.2.2)
9657 - eslint: 9.39.2(supports-color@10.2.2)
10474 + eslint: 9.39.2(jiti@2.7.0)
10475 typescript: 6.0.3
10476 transitivePeerDependencies:
10477 - supports-color
@@ -9677,13 +10494,13 @@ snapshots:
10494 dependencies:
10495 typescript: 6.0.3
10496
9680 - '@typescript-eslint/type-utils@8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)':
10497 + '@typescript-eslint/type-utils@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)':
10498 dependencies:
10499 '@typescript-eslint/types': 8.61.1
10500 '@typescript-eslint/typescript-estree': 8.61.1(typescript@6.0.3)
9684 - '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(typescript@6.0.3)
10501 + '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
10502 debug: 4.4.3(supports-color@10.2.2)
9686 - eslint: 9.39.2(supports-color@10.2.2)
10503 + eslint: 9.39.2(jiti@2.7.0)
10504 ts-api-utils: 2.5.0(typescript@6.0.3)
10505 typescript: 6.0.3
10506 transitivePeerDependencies:
@@ -9706,13 +10523,13 @@ snapshots:
10523 transitivePeerDependencies:
10524 - supports-color
10525
9709 - '@typescript-eslint/utils@8.61.1(eslint@9.39.2(supports-color@10.2.2))(typescript@6.0.3)':
10526 + '@typescript-eslint/utils@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)':
10527 dependencies:
9711 - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2))
10528 + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(jiti@2.7.0))
10529 '@typescript-eslint/scope-manager': 8.61.1
10530 '@typescript-eslint/types': 8.61.1
10531 '@typescript-eslint/typescript-estree': 8.61.1(typescript@6.0.3)
9715 - eslint: 9.39.2(supports-color@10.2.2)
10532 + eslint: 9.39.2(jiti@2.7.0)
10533 typescript: 6.0.3
10534 transitivePeerDependencies:
10535 - supports-color
@@ -9764,21 +10581,21 @@ snapshots:
10581 chai: 6.2.2
10582 tinyrainbow: 3.1.0
10583
9767 - '@vitest/mocker@4.1.9(vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0))':
10584 + '@vitest/mocker@4.1.9(vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))':
10585 dependencies:
10586 '@vitest/spy': 4.1.9
10587 estree-walker: 3.0.3
10588 magic-string: 0.30.21
10589 optionalDependencies:
9773 - vite: 7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0)
10590 + vite: 7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)
10591
9775 - '@vitest/mocker@4.1.9(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))':
10592 + '@vitest/mocker@4.1.9(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))':
10593 dependencies:
10594 '@vitest/spy': 4.1.9
10595 estree-walker: 3.0.3
10596 magic-string: 0.30.21
10597 optionalDependencies:
9781 - vite: 7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0)
10598 + vite: 7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)
10599
10600 '@vitest/pretty-format@4.1.9':
10601 dependencies:
@@ -9807,7 +10624,7 @@ snapshots:
10624 sirv: 3.0.2
10625 tinyglobby: 0.2.17
10626 tinyrainbow: 3.1.0
9810 - vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0))
10627 + vitest: 4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
10628
10629 '@vitest/utils@4.1.9':
10630 dependencies:
@@ -9943,6 +10760,8 @@ snapshots:
10760
10761 any-promise@1.3.0: {}
10762
10763 + anynum@1.0.1: {}
10764 +
10765 argparse@1.0.10:
10766 dependencies:
10767 sprintf-js: 1.0.3
@@ -10023,6 +10842,8 @@ snapshots:
10842 transitivePeerDependencies:
10843 - supports-color
10844
10845 + bowser@2.14.1: {}
10846 +
10847 brace-expansion@1.1.12:
10848 dependencies:
10849 balanced-match: 1.0.2
@@ -10367,6 +11188,8 @@ snapshots:
11188
11189 diff@8.0.3: {}
11190
11191 + diff@8.0.4: {}
11192 +
11193 dir-glob@3.0.1:
11194 dependencies:
11195 path-type: 4.0.0
@@ -10557,14 +11380,14 @@ snapshots:
11380
11381 eslint-visitor-keys@5.0.0: {}
11382
10560 - eslint@9.39.2(supports-color@10.2.2):
11383 + eslint@9.39.2(jiti@2.7.0):
11384 dependencies:
10562 - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2))
11385 + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(jiti@2.7.0))
11386 '@eslint-community/regexpp': 4.12.2
10564 - '@eslint/config-array': 0.21.1(supports-color@10.2.2)
11387 + '@eslint/config-array': 0.21.1
11388 '@eslint/config-helpers': 0.4.2
11389 '@eslint/core': 0.17.0
10567 - '@eslint/eslintrc': 3.3.3(supports-color@10.2.2)
11390 + '@eslint/eslintrc': 3.3.3
11391 '@eslint/js': 9.39.2
11392 '@eslint/plugin-kit': 0.4.1
11393 '@humanfs/node': 0.16.7
@@ -10593,6 +11416,8 @@ snapshots:
11416 minimatch: 3.1.2
11417 natural-compare: 1.4.0
11418 optionator: 0.9.4
11419 + optionalDependencies:
11420 + jiti: 2.7.0
11421 transitivePeerDependencies:
11422 - supports-color
11423
@@ -10784,6 +11609,18 @@ snapshots:
11609 dependencies:
11610 fast-string-width: 3.0.2
11611
11612 + fast-xml-builder@1.2.0:
11613 + dependencies:
11614 + path-expression-matcher: 1.5.0
11615 + xml-naming: 0.1.0
11616 +
11617 + fast-xml-parser@5.7.3:
11618 + dependencies:
11619 + '@nodable/entities': 2.2.0
11620 + fast-xml-builder: 1.2.0
11621 + path-expression-matcher: 1.5.0
11622 + strnum: 2.4.1
11623 +
11624 fastq@1.20.1:
11625 dependencies:
11626 reusify: 1.1.0
@@ -10926,6 +11763,8 @@ snapshots:
11763
11764 get-east-asian-width@1.4.0: {}
11765
11766 + get-east-asian-width@1.6.0: {}
11767 +
11768 get-intrinsic@1.3.0:
11769 dependencies:
11770 call-bind-apply-helpers: 1.0.2
@@ -10977,6 +11816,12 @@ snapshots:
11816 package-json-from-dist: 1.0.1
11817 path-scurry: 1.11.1
11818
11819 + glob@13.0.6:
11820 + dependencies:
11821 + minimatch: 10.2.5
11822 + minipass: 7.1.3
11823 + path-scurry: 2.0.2
11824 +
11825 globals@14.0.0: {}
11826
11827 globals@16.5.0: {}
@@ -11040,10 +11885,10 @@ snapshots:
11885
11886 highlight.js@10.7.3: {}
11887
11043 - hono-openapi@1.2.0(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3))(@types/json-schema@7.0.15)(hono@4.11.9)(openapi-types@12.1.3):
11888 + hono-openapi@1.2.0(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-community/standard-openapi@0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3))(@types/json-schema@7.0.15)(hono@4.11.9)(openapi-types@12.1.3):
11889 dependencies:
11045 - '@standard-community/standard-json': 0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)
11046 - '@standard-community/standard-openapi': 0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(zod@4.4.3)
11890 + '@standard-community/standard-json': 0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3)
11891 + '@standard-community/standard-openapi': 0.2.9(@standard-community/standard-json@0.3.5(@standard-schema/spec@1.1.0)(@types/json-schema@7.0.15)(effect@3.21.3)(quansync@1.0.0)(typebox@1.2.17)(zod-to-json-schema@3.25.2(zod@4.4.3))(zod@4.4.3))(@standard-schema/spec@1.1.0)(effect@3.21.3)(openapi-types@12.1.3)(typebox@1.2.17)(zod@4.4.3)
11892 '@types/json-schema': 7.0.15
11893 openapi-types: 12.1.3
11894 optionalDependencies:
@@ -11055,6 +11900,10 @@ snapshots:
11900
11901 hookable@6.1.1: {}
11902
11903 + hosted-git-info@9.0.3:
11904 + dependencies:
11905 + lru-cache: 11.5.1
11906 +
11907 html-to-text@9.0.5:
11908 dependencies:
11909 '@selderee/plugin-htmlparser2': 0.11.0
@@ -11078,6 +11927,13 @@ snapshots:
11927 statuses: 2.0.2
11928 toidentifier: 1.0.1
11929
11930 + http-proxy-agent@7.0.2:
11931 + dependencies:
11932 + agent-base: 7.1.4
11933 + debug: 4.4.3(supports-color@10.2.2)
11934 + transitivePeerDependencies:
11935 + - supports-color
11936 +
11937 https-proxy-agent@7.0.6(supports-color@10.2.2):
11938 dependencies:
11939 agent-base: 7.1.4
@@ -11204,6 +12060,8 @@ snapshots:
12060 dependencies:
12061 '@isaacs/cliui': 9.0.0
12062
12063 + jiti@2.7.0: {}
12064 +
12065 jose@6.1.3: {}
12066
12067 jpeg-js@0.4.4: {}
@@ -11346,7 +12204,7 @@ snapshots:
12204 dependencies:
12205 uc.micro: 2.1.0
12206
11349 - lint-staged@15.5.2(supports-color@10.2.2):
12207 + lint-staged@15.5.2:
12208 dependencies:
12209 chalk: 5.6.2
12210 commander: 13.1.0
@@ -11463,6 +12321,8 @@ snapshots:
12321 node-emoji: 2.2.0
12322 supports-hyperlinks: 3.2.0
12323
12324 + marked@18.0.5: {}
12325 +
12326 marked@9.1.6: {}
12327
12328 math-intrinsics@1.1.0: {}
@@ -11845,6 +12705,8 @@ snapshots:
12705
12706 minipass@7.1.2: {}
12707
12708 + minipass@7.1.3: {}
12709 +
12710 mri@1.2.0: {}
12711
12712 mrmime@2.0.1: {}
@@ -11963,6 +12825,11 @@ snapshots:
12825 ws: 8.20.1
12826 zod: 4.4.3
12827
12828 + openai@6.26.0(ws@8.20.1)(zod@3.25.76):
12829 + optionalDependencies:
12830 + ws: 8.20.1
12831 + zod: 3.25.76
12832 +
12833 openai@6.43.0(ws@8.20.1)(zod@3.25.76):
12834 optionalDependencies:
12835 ws: 8.20.1
@@ -12043,6 +12910,11 @@ snapshots:
12910 eventemitter3: 5.0.4
12911 p-timeout: 7.0.1
12912
12913 + p-retry@4.6.2:
12914 + dependencies:
12915 + '@types/retry': 0.12.0
12916 + retry: 0.13.1
12917 +
12918 p-retry@7.1.1:
12919 dependencies:
12920 is-network-error: 1.3.0
@@ -12090,10 +12962,14 @@ snapshots:
12962
12963 parseurl@1.3.3: {}
12964
12965 + partial-json@0.1.7: {}
12966 +
12967 path-browserify@1.0.1: {}
12968
12969 path-exists@4.0.0: {}
12970
12971 + path-expression-matcher@1.5.0: {}
12972 +
12973 path-key@3.1.1: {}
12974
12975 path-key@4.0.0: {}
@@ -12103,6 +12979,11 @@ snapshots:
12979 lru-cache: 10.4.3
12980 minipass: 7.1.2
12981
12982 + path-scurry@2.0.2:
12983 + dependencies:
12984 + lru-cache: 11.5.1
12985 + minipass: 7.1.3
12986 +
12987 path-to-regexp@0.1.13: {}
12988
12989 path-to-regexp@6.3.0: {}
@@ -12173,6 +13054,12 @@ snapshots:
13054
13055 process-nextick-args@2.0.1: {}
13056
13057 + proper-lockfile@4.1.2:
13058 + dependencies:
13059 + graceful-fs: 4.2.11
13060 + retry: 0.12.0
13061 + signal-exit: 3.0.7
13062 +
13063 protobufjs@7.5.9:
13064 dependencies:
13065 '@protobufjs/aspromise': 1.1.2
@@ -12298,6 +13185,10 @@ snapshots:
13185 onetime: 7.0.0
13186 signal-exit: 4.1.0
13187
13188 + retry@0.12.0: {}
13189 +
13190 + retry@0.13.1: {}
13191 +
13192 reusify@1.1.0: {}
13193
13194 rfdc@1.4.1: {}
@@ -12439,6 +13330,8 @@ snapshots:
13330 dependencies:
13331 parseley: 0.12.1
13332
13333 + semver@7.8.0: {}
13334 +
13335 semver@7.8.4: {}
13336
13337 send@0.19.2:
@@ -12571,6 +13464,8 @@ snapshots:
13464
13465 siginfo@2.0.0: {}
13466
13467 + signal-exit@3.0.7: {}
13468 +
13469 signal-exit@4.1.0: {}
13470
13471 simple-wcswidth@1.1.2: {}
@@ -12667,6 +13562,10 @@ snapshots:
13562
13563 strip-json-comments@3.1.1: {}
13564
13565 + strnum@2.4.1:
13566 + dependencies:
13567 + anynum: 1.0.1
13568 +
13569 superjson@2.2.6:
13570 dependencies:
13571 copy-anything: 4.0.5
@@ -12831,6 +13730,11 @@ snapshots:
13730 media-typer: 1.1.0
13731 mime-types: 3.0.2
13732
13733 + typebox@1.1.38: {}
13734 +
13735 + typebox@1.2.17:
13736 + optional: true
13737 +
13738 typed-array-buffer@1.0.3:
13739 dependencies:
13740 call-bound: 1.0.4
@@ -12846,13 +13750,13 @@ snapshots:
13750 typescript: 6.0.3
13751 yaml: 2.9.0
13752
12849 - typescript-eslint@8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3):
13753 + typescript-eslint@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3):
13754 dependencies:
12851 - '@typescript-eslint/eslint-plugin': 8.61.1(@typescript-eslint/parser@8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
12852 - '@typescript-eslint/parser': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)
13755 + '@typescript-eslint/eslint-plugin': 8.61.1(@typescript-eslint/parser@8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3))(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
13756 + '@typescript-eslint/parser': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
13757 '@typescript-eslint/typescript-estree': 8.61.1(typescript@6.0.3)
12854 - '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(supports-color@10.2.2))(typescript@6.0.3)
12855 - eslint: 9.39.2(supports-color@10.2.2)
13758 + '@typescript-eslint/utils': 8.61.1(eslint@9.39.2(jiti@2.7.0))(typescript@6.0.3)
13759 + eslint: 9.39.2(jiti@2.7.0)
13760 typescript: 6.0.3
13761 transitivePeerDependencies:
13762 - supports-color
@@ -12879,6 +13783,8 @@ snapshots:
13783
13784 undici@7.24.8: {}
13785
13786 + undici@8.5.0: {}
13787 +
13788 unenv@2.0.0-rc.24:
13789 dependencies:
13790 pathe: 2.0.3
@@ -12962,7 +13868,7 @@ snapshots:
13868 '@types/unist': 3.0.3
13869 vfile-message: 4.0.3
13870
12965 - vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0):
13871 + vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0):
13872 dependencies:
13873 esbuild: 0.27.7
13874 fdir: 6.5.0(picomatch@4.0.4)
@@ -12973,10 +13879,11 @@ snapshots:
13879 optionalDependencies:
13880 '@types/node': 22.19.11
13881 fsevents: 2.3.3
13882 + jiti: 2.7.0
13883 tsx: 4.22.4
13884 yaml: 2.9.0
13885
12979 - vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0):
13886 + vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0):
13887 dependencies:
13888 esbuild: 0.27.7
13889 fdir: 6.5.0(picomatch@4.0.4)
@@ -12987,13 +13894,14 @@ snapshots:
13894 optionalDependencies:
13895 '@types/node': 24.10.13
13896 fsevents: 2.3.3
13897 + jiti: 2.7.0
13898 tsx: 4.22.4
13899 yaml: 2.9.0
13900
12993 - vitest@4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0)):
13901 + vitest@4.1.9(@opentelemetry/api@1.9.0)(@types/node@22.19.11)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)):
13902 dependencies:
13903 '@vitest/expect': 4.1.9
12996 - '@vitest/mocker': 4.1.9(vite@7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0))
13904 + '@vitest/mocker': 4.1.9(vite@7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
13905 '@vitest/pretty-format': 4.1.9
13906 '@vitest/runner': 4.1.9
13907 '@vitest/snapshot': 4.1.9
@@ -13010,7 +13918,7 @@ snapshots:
13918 tinyexec: 1.2.4
13919 tinyglobby: 0.2.17
13920 tinyrainbow: 3.1.0
13013 - vite: 7.3.1(@types/node@22.19.11)(tsx@4.22.4)(yaml@2.9.0)
13921 + vite: 7.3.1(@types/node@22.19.11)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)
13922 why-is-node-running: 2.3.0
13923 optionalDependencies:
13924 '@opentelemetry/api': 1.9.0
@@ -13019,10 +13927,10 @@ snapshots:
13927 transitivePeerDependencies:
13928 - msw
13929
13022 - vitest@4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0)):
13930 + vitest@4.1.9(@opentelemetry/api@1.9.0)(@types/node@24.10.13)(@vitest/ui@4.1.9)(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)):
13931 dependencies:
13932 '@vitest/expect': 4.1.9
13025 - '@vitest/mocker': 4.1.9(vite@7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0))
13933 + '@vitest/mocker': 4.1.9(vite@7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
13934 '@vitest/pretty-format': 4.1.9
13935 '@vitest/runner': 4.1.9
13936 '@vitest/snapshot': 4.1.9
@@ -13039,7 +13947,7 @@ snapshots:
13947 tinyexec: 1.2.4
13948 tinyglobby: 0.2.17
13949 tinyrainbow: 3.1.0
13042 - vite: 7.3.1(@types/node@24.10.13)(tsx@4.22.4)(yaml@2.9.0)
13950 + vite: 7.3.1(@types/node@24.10.13)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)
13951 why-is-node-running: 2.3.0
13952 optionalDependencies:
13953 '@opentelemetry/api': 1.9.0
@@ -13151,6 +14059,8 @@ snapshots:
14059 dependencies:
14060 is-wsl: 3.1.1
14061
14062 + xml-naming@0.1.0: {}
14063 +
14064 xtend@4.0.2: {}
14065
14066 xxhash-wasm@1.1.0: {}
@@ -13205,7 +14115,7 @@ snapshots:
14115
14116 zod-from-json-schema@0.5.2:
14117 dependencies:
13208 - zod: 4.3.6
14118 + zod: 4.4.3
14119
14120 zod-to-json-schema@3.25.1(zod@3.25.76):
14121 dependencies:
pnpm-workspace.yaml
+3
@@ -10,12 +10,15 @@ packages:
10 - ts/packages/cli-keyring
11 - ts/packages/cli-local-tools
12 - ts/packages/core
13 + - ts/packages/experimental
14 - ts/packages/json-schema-to-zod
15 + - ts/packages/slim
16 - ts/packages/providers/*
17 - ts/packages/ts-builders
18 - ts/packages/wrappers/*
19
20 allowBuilds:
21 + '@google/genai': false
22 '@parcel/watcher': true
23 esbuild: true
24 msgpackr-extract: true
python/composio/core/models/connected_accounts.py
+68
@@ -407,6 +407,74 @@ class ConnectedAccounts:
407 connection=connection if connection is not None else omit,
408 )
409
410 + def update_acl(
411 + self,
412 + nanoid: str,
413 + *,
414 + allow_all_users: t.Optional[bool] = None,
415 + allowed_user_ids: t.Optional[t.List[str]] = None,
416 + not_allowed_user_ids: t.Optional[t.List[str]] = None,
417 + ) -> connected_account_patch_response.ConnectedAccountPatchResponse:
418 + """
419 + Update the per-user ACL on a SHARED connected account. Experimental —
420 + shape may change in future releases.
421 +
422 + Only valid on SHARED connections; raises
423 + ``ComposioAclOnlyForSharedError`` on a PRIVATE connection. Omit a
424 + parameter to leave it unchanged; pass an empty list to clear an
425 + allow/deny list. At least one parameter must be provided.
426 +
427 + :param nanoid: The connected account ID (``ca_xxx``).
428 + :param allow_all_users: When True, any ``user_id`` may use this
429 + SHARED connection (subject to the deny list).
430 + :param allowed_user_ids: Explicit list of allowed ``user_id`` strings.
431 + Pass ``[]`` to clear.
432 + :param not_allowed_user_ids: Explicit deny list (wins over allow on
433 + conflict). Pass ``[]`` to clear — note that clearing the deny
434 + list silently re-grants access to previously-blocked users.
435 + :return: Response with ``id``, ``status``, and ``success``.
436 +
437 + Example:
438 + composio.connected_accounts.update_acl(
439 + 'ca_abc',
440 + allow_all_users=True,
441 + not_allowed_user_ids=['user_bob'],
442 + )
443 + """
444 + if (
445 + allow_all_users is None
446 + and allowed_user_ids is None
447 + and not_allowed_user_ids is None
448 + ):
449 + raise exceptions.ValidationError(
450 + "update_acl requires at least one of allow_all_users, "
451 + "allowed_user_ids, or not_allowed_user_ids"
452 + )
453 +
454 + acl: t.Dict[str, t.Any] = {}
455 + if allow_all_users is not None:
456 + acl["allow_all_users"] = allow_all_users
457 + if allowed_user_ids is not None:
458 + acl["allowed_user_ids"] = allowed_user_ids
459 + if not_allowed_user_ids is not None:
460 + acl["not_allowed_user_ids"] = not_allowed_user_ids
461 +
462 + try:
463 + return self._client.connected_accounts.patch(
464 + nanoid,
465 + experimental={
466 + "acl_config_for_shared": t.cast(
467 + connected_account_patch_params.ExperimentalACLConfigForShared,
468 + acl,
469 + ),
470 + },
471 + )
472 + except BadRequestError as error:
473 + message = str(error)
474 + if ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT in message:
475 + raise exceptions.ComposioAclOnlyForSharedError(message) from error
476 + raise
477 +
478 def initiate(
479 self,
480 user_id: str,
python/composio/core/models/experimental.py
+18 -40
@@ -21,10 +21,7 @@ import typing as t
21 from pydantic import BaseModel
22
23 from composio.client import HttpClient
24 -from composio.client.types import (
25 - connected_account_patch_params,
26 - connected_account_patch_response,
27 -)
24 +from composio.client.types import connected_account_patch_response
25
26 from .custom_tool import (
27 CustomTool,
@@ -80,55 +77,36 @@ class ExperimentalAPI:
77 list silently re-grants access to previously-blocked users.
78 :return: Response with ``id``, ``status``, and ``success``.
79
80 + .. deprecated::
81 + Use :meth:`composio.connected_accounts.update_acl` instead — ACL
82 + updates graduated onto the ``connected_accounts`` model. This
83 + experimental alias is kept only for backwards compatibility and
84 + delegates to it. Prefer the ``connected_accounts`` model; do not
85 + generate new code against this alias.
86 +
87 Example:
84 - composio.experimental.update_acl(
88 + composio.connected_accounts.update_acl(
89 'ca_abc',
90 allow_all_users=True,
91 not_allowed_user_ids=['user_bob'],
92 )
93 """
90 - from composio_client import BadRequestError
91 -
94 from composio import exceptions
95
96 + from .connected_accounts import ConnectedAccounts
97 +
98 if self._client is None:
99 raise exceptions.ValidationError(
100 "update_acl requires a Composio client. Access it via "
97 - "composio.experimental.update_acl(...)."
98 - )
99 - if (
100 - allow_all_users is None
101 - and allowed_user_ids is None
102 - and not_allowed_user_ids is None
103 - ):
104 - raise exceptions.ValidationError(
105 - "update_acl requires at least one of allow_all_users, "
106 - "allowed_user_ids, or not_allowed_user_ids"
101 + "composio.connected_accounts.update_acl(...)."
102 )
103
109 - acl: t.Dict[str, t.Any] = {}
110 - if allow_all_users is not None:
111 - acl["allow_all_users"] = allow_all_users
112 - if allowed_user_ids is not None:
113 - acl["allowed_user_ids"] = allowed_user_ids
114 - if not_allowed_user_ids is not None:
115 - acl["not_allowed_user_ids"] = not_allowed_user_ids
116 -
117 - try:
118 - return self._client.connected_accounts.patch(
119 - nanoid,
120 - experimental={
121 - "acl_config_for_shared": t.cast(
122 - connected_account_patch_params.ExperimentalACLConfigForShared,
123 - acl,
124 - ),
125 - },
126 - )
127 - except BadRequestError as error:
128 - message = str(error)
129 - if ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT in message:
130 - raise exceptions.ComposioAclOnlyForSharedError(message) from error
131 - raise
104 + return ConnectedAccounts(client=self._client).update_acl(
105 + nanoid,
106 + allow_all_users=allow_all_users,
107 + allowed_user_ids=allowed_user_ids,
108 + not_allowed_user_ids=not_allowed_user_ids,
109 + )
110
111 @t.overload
112 def tool(self, fn: t.Callable[..., t.Any], /) -> CustomTool: ...
python/composio/core/models/mcp.py
+9
@@ -107,6 +107,15 @@ class MCP(Resource):
107 Provides enhanced MCP server operations
108
109 This matches the TypeScript ExperimentalMCP class functionality.
110 +
111 + .. deprecated::
112 + Use a session's MCP endpoint instead:
113 + ``composio.create(user_id, mcp=True)`` returns a session that exposes
114 + ``session.mcp.url`` / ``session.mcp.headers``. MCP is now opt-in per
115 + session; this standalone ``composio.mcp`` server-management API is kept
116 + only for backwards compatibility. Prefer the session MCP endpoint; do
117 + not generate new code against ``composio.mcp``.
118 + See https://docs.composio.dev/docs/sessions-via-mcp
119 """
120
121 def __init__(self, client: HttpClient):
python/composio/core/models/tool_router.py
+166 -42
@@ -22,6 +22,7 @@ from composio_client.types.tool_router.session_retrieve_response import (
22 )
23
24 from composio.client import HttpClient
25 +from composio.exceptions import InvalidParams
26 from composio.core.models.base import Resource
27 from composio.core.models.custom_tool import (
28 ExperimentalToolkit,
@@ -40,6 +41,7 @@ from composio.core.models.custom_tool_types import (
41 from composio.core.models.tool_router_session import (
42 ToolRouterSession,
43 ToolRouterSessionPreloadConfig,
44 + ToolRouterSessionWithMcp,
45 )
46 from composio.core.models.tool_router_session_files import ToolRouterSessionFilesMount
47 from composio.core.models.tool_router_constants import (
@@ -57,7 +59,7 @@ ToolRouterTag = t.Literal[
59 "readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"
60 ]
61
60 -# Type alias for sandbox compute tier on the workbench
62 +# Type alias for sandbox compute tier on the session sandbox
63 # +----------+------+------+
64 # | Tier | vCPU | RAM |
65 # +----------+------+------+
@@ -166,18 +168,18 @@ def _is_tools_tags_config(
168 return isinstance(config, dict) and "tags" in config
169
170
169 -class ToolRouterWorkbenchConfig(te.TypedDict, total=False):
170 - """Configuration for workbench settings in tool router session.
171 +class ToolRouterSandboxConfig(te.TypedDict, total=False):
172 + """Configuration for session sandbox settings.
173
174 Attributes:
173 - enable: Whether to enable the workbench entirely. Defaults to True.
175 + enable: Whether to enable the sandbox entirely. Defaults to True.
176 When set to False, no code execution tools
177 (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are
176 - available in the session, workbench-related prompt lines are
177 - stripped, and direct workbench calls are rejected.
178 - enable_proxy_execution: Whether to allow proxy execute calls in the workbench.
178 + available in the session, sandbox-related prompt lines are
179 + stripped, and direct sandbox calls are rejected.
180 + enable_proxy_execution: Whether to allow proxy execute calls in the sandbox.
181 If False, prevents arbitrary HTTP requests.
180 - auto_offload_threshold: Maximum execution payload size to offload to workbench.
182 + auto_offload_threshold: Maximum execution payload size to offload to the sandbox.
183 sandbox_size: Sandbox compute tier. One of ``"standard"`` (1 vCPU / 1 GB),
184 ``"medium"`` (2 vCPU / 2 GB), ``"large"`` (4 vCPU / 4 GB), or
185 ``"xlarge"`` (8 vCPU / 8 GB). Defaults to ``"standard"``
@@ -192,6 +194,14 @@ class ToolRouterWorkbenchConfig(te.TypedDict, total=False):
194 sandbox_size: SandboxSize
195
196
197 +class ToolRouterWorkbenchConfig(ToolRouterSandboxConfig, total=False):
198 + """Deprecated alias for :class:`ToolRouterSandboxConfig`.
199 +
200 + ``workbench`` is still accepted for backwards compatibility; prefer
201 + ``sandbox`` in new code.
202 + """
203 +
204 +
205 class ToolRouterManageConnectionsConfig(te.TypedDict, total=False):
206 """Configuration for connection management in tool router session.
207
@@ -270,11 +280,11 @@ def _preloads_all_custom_tools(
280 def _apply_session_preset_defaults(
281 session_preset: t.Optional[SessionPreset],
282 manage_connections: t.Optional[t.Union[bool, ToolRouterManageConnectionsConfig]],
273 - workbench: t.Optional[ToolRouterWorkbenchConfig],
283 + workbench: t.Optional[ToolRouterSandboxConfig],
284 preload: t.Optional[ToolRouterPreloadConfig],
285 ) -> t.Tuple[
286 t.Optional[t.Union[bool, ToolRouterManageConnectionsConfig]],
277 - t.Optional[ToolRouterWorkbenchConfig],
287 + t.Optional[ToolRouterSandboxConfig],
288 t.Optional[ToolRouterPreloadConfig],
289 ]:
290 if session_preset != SESSION_PRESET_DIRECT_TOOLS:
@@ -579,6 +589,65 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
589 else:
590 return None
591
592 + # Overloads: pass ``mcp=True`` to surface ``session.mcp`` in the returned
593 + # type (ToolRouterSessionWithMcp). The MCP endpoint exists at runtime on
594 + # every session regardless. See https://docs.composio.dev/docs/sessions-via-mcp
595 + @t.overload
596 + def create(
597 + self,
598 + *,
599 + user_id: str,
600 + toolkits: t.Optional[
601 + t.Union[
602 + t.List[str],
603 + ToolRouterToolkitsEnableConfig,
604 + ToolRouterToolkitsDisableConfig,
605 + ]
606 + ] = None,
607 + tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None,
608 + tags: t.Optional[ToolRouterConfigTags] = None,
609 + manage_connections: t.Optional[
610 + t.Union[bool, ToolRouterManageConnectionsConfig]
611 + ] = None,
612 + auth_configs: t.Optional[t.Dict[str, str]] = None,
613 + connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None,
614 + sandbox: t.Optional[ToolRouterSandboxConfig] = None,
615 + workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
616 + multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
617 + preload: t.Optional[ToolRouterPreloadConfig] = None,
618 + session_preset: t.Optional[SessionPreset] = None,
619 + experimental: t.Optional[ToolRouterExperimentalConfig] = None,
620 + mcp: t.Literal[True],
621 + ) -> ToolRouterSessionWithMcp[TTool, TToolCollection]: ...
622 +
623 + @t.overload
624 + def create(
625 + self,
626 + *,
627 + user_id: str,
628 + toolkits: t.Optional[
629 + t.Union[
630 + t.List[str],
631 + ToolRouterToolkitsEnableConfig,
632 + ToolRouterToolkitsDisableConfig,
633 + ]
634 + ] = None,
635 + tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None,
636 + tags: t.Optional[ToolRouterConfigTags] = None,
637 + manage_connections: t.Optional[
638 + t.Union[bool, ToolRouterManageConnectionsConfig]
639 + ] = None,
640 + auth_configs: t.Optional[t.Dict[str, str]] = None,
641 + connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None,
642 + sandbox: t.Optional[ToolRouterSandboxConfig] = None,
643 + workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
644 + multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
645 + preload: t.Optional[ToolRouterPreloadConfig] = None,
646 + session_preset: t.Optional[SessionPreset] = None,
647 + experimental: t.Optional[ToolRouterExperimentalConfig] = None,
648 + mcp: t.Literal[False] = False,
649 + ) -> ToolRouterSession[TTool, TToolCollection]: ...
650 +
651 def create(
652 self,
653 *,
@@ -597,11 +666,13 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
666 ] = None,
667 auth_configs: t.Optional[t.Dict[str, str]] = None,
668 connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None,
669 + sandbox: t.Optional[ToolRouterSandboxConfig] = None,
670 workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
671 multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
672 preload: t.Optional[ToolRouterPreloadConfig] = None,
673 session_preset: t.Optional[SessionPreset] = None,
674 experimental: t.Optional[ToolRouterExperimentalConfig] = None,
675 + mcp: bool = False,
676 ) -> ToolRouterSession[TTool, TToolCollection]:
677 """
678 Create a new tool router session for a user.
@@ -660,21 +731,22 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
731 Only one account per toolkit is allowed when multi-account
732 mode is disabled.
733 Example: {'github': 'ca_xxx', 'slack': ['ca_yyy']}
663 - :param workbench: Optional workbench configuration. Dict with:
664 - - 'enable' (bool): Whether to enable the workbench entirely.
665 - Defaults to True. When set to False, no code execution tools
666 - (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are
667 - available in the session.
668 - - 'enable_proxy_execution' (bool): Whether to allow proxy execute
669 - calls in the workbench. If False, prevents arbitrary HTTP requests.
670 - - 'auto_offload_threshold' (int): Maximum execution payload size to
671 - offload to workbench.
672 - - 'sandbox_size' (SandboxSize): Sandbox compute tier. One of
673 - 'standard' (1 vCPU / 1 GB, default), 'medium' (2 vCPU / 2 GB),
674 - 'large' (4 vCPU / 4 GB), or 'xlarge' (8 vCPU / 8 GB).
675 - Example: {'enable': False}
676 - Example: {'enable_proxy_execution': False, 'auto_offload_threshold': 300}
677 - Example: {'sandbox_size': 'large'}
734 + :param sandbox: Optional sandbox configuration. Dict with:
735 + - 'enable' (bool): Whether to enable the sandbox entirely.
736 + Defaults to True. When set to False, no code execution tools
737 + (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are
738 + available in the session.
739 + - 'enable_proxy_execution' (bool): Whether to allow proxy execute
740 + calls in the sandbox. If False, prevents arbitrary HTTP requests.
741 + - 'auto_offload_threshold' (int): Maximum execution payload size to
742 + offload to the sandbox.
743 + - 'sandbox_size' (SandboxSize): Sandbox compute tier. One of
744 + 'standard' (1 vCPU / 1 GB, default), 'medium' (2 vCPU / 2 GB),
745 + 'large' (4 vCPU / 4 GB), or 'xlarge' (8 vCPU / 8 GB).
746 + Example: {'enable': False}
747 + Example: {'enable_proxy_execution': False, 'auto_offload_threshold': 300}
748 + Example: {'sandbox_size': 'large'}
749 + :param workbench: Deprecated alias for sandbox. Accepted for backwards compatibility.
750 :param multi_account: Optional multi-account configuration (ToolRouterMultiAccountConfig).
751 Dict with:
752 - 'enable' (bool): When True, enables multi-account mode.
@@ -707,6 +779,12 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
779 it directly from session.tools(); otherwise custom tools
780 remain search-only.
781 Example: {'assistive_prompt': {'user_timezone': 'America/New_York'}}
782 + :param mcp: When True, the returned session surfaces its hosted MCP
783 + endpoint (``session.mcp.url`` / ``session.mcp.headers``) in
784 + the type (returns ToolRouterSessionWithMcp). The endpoint
785 + exists on every session at runtime regardless of this flag;
786 + native tools (``session.tools()``) are unaffected.
787 + See https://docs.composio.dev/docs/sessions-via-mcp
788 :return: Tool router session object
789
790 Example:
@@ -771,18 +849,18 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
849 }
850 )
851
774 - # Create a session with workbench disabled
852 + # Create a session with sandbox disabled
853 session = tool_router.create(
854 user_id='user_123',
777 - workbench={
855 + sandbox={
856 'enable': False
857 }
858 )
859
782 - # Create a session with workbench config
860 + # Create a session with sandbox config
861 session = tool_router.create(
862 user_id='user_123',
785 - workbench={
863 + sandbox={
864 'enable_proxy_execution': False,
865 'auto_offload_threshold': 300
866 }
@@ -795,11 +873,21 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
873 ```
874 """
875
876 + if sandbox is not None and workbench is not None:
877 + raise InvalidParams(
878 + "Pass either `sandbox` or `workbench`, not both. "
879 + "`workbench` is a backwards-compatible alias for `sandbox`."
880 + )
881 +
882 + sandbox_config: t.Optional[ToolRouterSandboxConfig] = (
883 + sandbox if sandbox is not None else workbench
884 + )
885 +
886 direct_tools_preset = session_preset == SESSION_PRESET_DIRECT_TOOLS
799 - manage_connections, workbench, preload = _apply_session_preset_defaults(
887 + manage_connections, sandbox_config, preload = _apply_session_preset_defaults(
888 session_preset=session_preset,
889 manage_connections=manage_connections,
802 - workbench=workbench,
890 + workbench=sandbox_config,
891 preload=preload,
892 )
893 default_custom_preload = _preloads_all_custom_tools(preload)
@@ -908,20 +996,20 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
996 if tags_payload is not None:
997 create_params["tags"] = tags_payload
998
911 - if workbench is not None:
999 + if sandbox_config is not None:
1000 execution_payload: t.Dict[str, t.Any] = {
913 - "enable": workbench.get("enable", True),
1001 + "enable": sandbox_config.get("enable", True),
1002 }
915 - if "enable_proxy_execution" in workbench:
916 - execution_payload["enable_proxy_execution"] = workbench[
1003 + if "enable_proxy_execution" in sandbox_config:
1004 + execution_payload["enable_proxy_execution"] = sandbox_config[
1005 "enable_proxy_execution"
1006 ]
919 - if "auto_offload_threshold" in workbench:
1007 + if "auto_offload_threshold" in sandbox_config:
1008 execution_payload["auto_offload_threshold"] = int(
921 - workbench["auto_offload_threshold"]
1009 + sandbox_config["auto_offload_threshold"]
1010 )
923 - if "sandbox_size" in workbench:
924 - execution_payload["sandbox_size"] = workbench["sandbox_size"]
1011 + if "sandbox_size" in sandbox_config:
1012 + execution_payload["sandbox_size"] = sandbox_config["sandbox_size"]
1013
1014 if execution_payload:
1015 create_params["workbench"] = execution_payload
@@ -1012,8 +1100,13 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1100 ),
1101 )
1102
1015 - # Create and return the session
1016 - return ToolRouterSession(
1103 + # Create and return the session. `mcp=True` returns the subclass that
1104 + # surfaces `session.mcp` in the type; the runtime object is otherwise
1105 + # identical (the base always stores the MCP endpoint).
1106 + session_cls: t.Type[ToolRouterSession[TTool, TToolCollection]] = (
1107 + ToolRouterSessionWithMcp if mcp else ToolRouterSession
1108 + )
1109 + return session_cls(
1110 client=self._client,
1111 provider=self._provider,
1112 dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
@@ -1033,12 +1126,35 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1126 inline_custom_tools_payload=inline_custom_tools_payload,
1127 )
1128
1129 + # Overloads mirror create(): pass ``mcp=True`` to surface ``session.mcp`` in
1130 + # the returned type. See https://docs.composio.dev/docs/sessions-via-mcp
1131 + @t.overload
1132 + def use(
1133 + self,
1134 + session_id: str,
1135 + *,
1136 + custom_tools: t.Optional[t.List[CustomTool]] = None,
1137 + custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None,
1138 + mcp: t.Literal[True],
1139 + ) -> ToolRouterSessionWithMcp[TTool, TToolCollection]: ...
1140 +
1141 + @t.overload
1142 def use(
1143 self,
1144 session_id: str,
1145 *,
1146 custom_tools: t.Optional[t.List[CustomTool]] = None,
1147 custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None,
1148 + mcp: t.Literal[False] = False,
1149 + ) -> ToolRouterSession[TTool, TToolCollection]: ...
1150 +
1151 + def use(
1152 + self,
1153 + session_id: str,
1154 + *,
1155 + custom_tools: t.Optional[t.List[CustomTool]] = None,
1156 + custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None,
1157 + mcp: bool = False,
1158 ) -> ToolRouterSession[TTool, TToolCollection]:
1159 """
1160 Use an existing tool router session.
@@ -1054,6 +1170,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1170 :param session_id: The session ID to use.
1171 :param custom_tools: Optional custom tools to bind to the session.
1172 :param custom_toolkits: Optional custom toolkits to bind to the session.
1173 + :param mcp: When True, the returned session surfaces its hosted MCP
1174 + endpoint in the type (returns ToolRouterSessionWithMcp).
1175 + See https://docs.composio.dev/docs/sessions-via-mcp
1176 :return: Tool router session object
1177
1178 Example:
@@ -1132,7 +1251,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1251 assistive_prompt=None,
1252 )
1253
1135 - return ToolRouterSession(
1254 + session_cls: t.Type[ToolRouterSession[TTool, TToolCollection]] = (
1255 + ToolRouterSessionWithMcp if mcp else ToolRouterSession
1256 + )
1257 + return session_cls(
1258 client=self._client,
1259 provider=self._provider,
1260 dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
@@ -1156,6 +1278,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1278 __all__ = [
1279 "ToolRouter",
1280 "ToolRouterSession",
1281 + "ToolRouterSessionWithMcp",
1282 "ToolRouterSessionExperimental",
1283 "ToolRouterToolkitsEnableConfig",
1284 "ToolRouterToolkitsDisableConfig",
@@ -1167,6 +1290,7 @@ __all__ = [
1290 "ToolRouterTagsEnableDisableConfig",
1291 "ToolRouterConfigTags",
1292 "ToolRouterManageConnectionsConfig",
1293 + "ToolRouterSandboxConfig",
1294 "ToolRouterWorkbenchConfig",
1295 "SandboxSize",
1296 "SessionPreset",
python/composio/core/models/tool_router_session.py
+44 -7
@@ -60,6 +60,7 @@ from composio.core.provider.base import BaseProvider
60 if t.TYPE_CHECKING:
61 from composio.core.models.tool_router import (
62 ToolkitConnectionsDetails,
63 + ToolRouterMCPServerConfig,
64 ToolRouterSessionExperimental,
65 )
66
@@ -79,22 +80,27 @@ class ToolRouterSessionPreloadConfig:
80
81 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
82 """
82 - Tool router session containing session information and methods.
83 + A Composio session — the object returned by ``composio.create(...)`` /
84 + ``composio.use(...)``. Use it to fetch session-scoped tools, authorize
85 + toolkits, search, and execute tools.
86
87 Generic Parameters:
88 TTool: The individual tool type returned by the provider.
89 TToolCollection: The collection type returned by tools().
90
91 + The hosted MCP endpoint (``session.mcp``) exists at runtime on every
92 + session, but is only surfaced in the type when you opt in with
93 + ``create(..., mcp=True)`` / ``use(..., mcp=True)``, which returns a
94 + :class:`ToolRouterSessionWithMcp`. By default agents use native tools via
95 + :meth:`tools`. See https://docs.composio.dev/docs/sessions-via-mcp
96 +
97 Attributes:
98 session_id: Unique session identifier
90 - mcp: MCP server configuration
99 experimental: Experimental features (files, assistive prompt, etc.)
100 """
101
102 #: Unique session identifier.
103 session_id: str
96 - #: MCP server configuration for this session.
97 - mcp: t.Any
104 #: Experimental capabilities available on this session.
105 experimental: "ToolRouterSessionExperimental"
106
@@ -123,7 +129,11 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
129 self._file_upload_path_deny_segments = file_upload_path_deny_segments
130 self._file_upload_dirs = file_upload_dirs
131 self.session_id = session_id
126 - self.mcp = mcp
132 + # The MCP endpoint exists on every session at runtime (kept for
133 + # backwards compatibility), but is only typed via
134 + # ToolRouterSessionWithMcp. Assign through setattr so type checkers do
135 + # not surface `mcp` on the base class — MCP is an explicit opt-in.
136 + setattr(self, "mcp", mcp)
137 self.experimental = experimental
138 self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
139 self._custom_tools_map = custom_tools_map
@@ -831,6 +841,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
841 manage_connections: t.Union[
842 t.Optional[session_patch_params.ManageConnections], "Omit"
843 ] = omit,
844 + sandbox: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
845 workbench: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
846 multi_account: t.Union[
847 t.Optional[session_patch_params.MultiAccount], "Omit"
@@ -842,14 +853,25 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
853 Only the fields provided will be changed; omitted fields are preserved.
854 Mutates this session's ``preload`` in-place.
855
845 - Pass ``None`` for ``manage_connections``, ``workbench``, or
856 + Pass ``None`` for ``manage_connections``, ``sandbox``/``workbench``, or
857 ``multi_account`` to clear the stored value.
858
859 + ``workbench`` is a backwards-compatible alias for ``sandbox``. Prefer
860 + ``sandbox`` in new code.
861 +
862 All parameters use the same types as the Stainless-generated
863 ``client.tool_router.session.patch()`` method.
864 """
865 from composio.core.models.tool_router import _session_preload_config
866
867 + if sandbox is not omit and workbench is not omit:
868 + raise exceptions.InvalidParams(
869 + "Pass either `sandbox` or `workbench`, not both. "
870 + "`workbench` is a backwards-compatible alias for `sandbox`."
871 + )
872 +
873 + workbench_payload = sandbox if sandbox is not omit else workbench
874 +
875 response = self._client.tool_router.session.patch(
876 session_id=self.session_id,
877 toolkits=toolkits,
@@ -858,8 +880,23 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
880 auth_configs=auth_configs,
881 connected_accounts=connected_accounts,
882 manage_connections=manage_connections,
861 - workbench=workbench,
883 + workbench=workbench_payload,
884 multi_account=multi_account,
885 preload=preload,
886 )
887 self.preload = _session_preload_config(response.config.preload)
888 +
889 +
890 +class ToolRouterSessionWithMcp(ToolRouterSession[TTool, TToolCollection]):
891 + """A :class:`ToolRouterSession` whose hosted MCP endpoint is exposed.
892 +
893 + Returned by ``create(..., mcp=True)`` / ``use(..., mcp=True)``. The ``mcp``
894 + attribute is populated by the base ``__init__`` at runtime; this subclass
895 + only surfaces it in the type. See
896 + https://docs.composio.dev/docs/sessions-via-mcp
897 + """
898 +
899 + #: Hosted MCP server configuration (url + auth headers) for this session.
900 + #: This is the recommended MCP path, gated behind ``mcp=True``.
901 + #: See https://docs.composio.dev/docs/sessions-via-mcp
902 + mcp: "ToolRouterMCPServerConfig"
python/composio/core/models/triggers.py
+330 -1
@@ -14,7 +14,7 @@ from enum import Enum
14 from unittest import mock
15
16 import typing_extensions as te
17 -from composio_client import omit
17 +from composio_client import Omit, omit
18 from composio_client.types import TriggersTypeRetrieveResponse
19 from pysher import Pusher
20 from pysher.channel import Channel as PusherChannel
@@ -187,6 +187,22 @@ class VerifyWebhookResult(t.TypedDict):
187 raw_payload: WebhookPayload # The original parsed payload
188
189
190 +class WebhookSubscription(t.TypedDict, total=False):
191 + """Webhook subscription returned by the Composio API."""
192 +
193 + id: str
194 + webhook_url: str
195 + version: str
196 + enabled_events: t.List[str]
197 + secret: str
198 + created_at: str
199 + updated_at: str
200 +
201 +
202 +DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS = ("composio.trigger.message",)
203 +WEBHOOK_SUBSCRIPTIONS_PATH = "/api/v3.1/webhook_subscriptions"
204 +
205 +
206 _ = {
207 "appName": "github",
208 "payload": {
@@ -895,6 +911,129 @@ class Triggers(Resource):
911 status="disable",
912 )
913
914 + def set_webhook_subscription(
915 + self,
916 + *,
917 + webhook_url: str,
918 + enabled_events: t.Optional[t.Sequence[str]] = None,
919 + version: t.Union[WebhookVersion, str] = WebhookVersion.V3,
920 + ) -> WebhookSubscription:
921 + """
922 + Create or update the project webhook subscription used for webhook delivery.
923 +
924 + If a subscription already exists, the first subscription is updated. Otherwise a
925 + new subscription is created. By default this subscribes to V3 trigger message
926 + events.
927 +
928 + Example:
929 + composio.triggers.set_webhook_subscription(
930 + webhook_url=f"{APP_URL}/webhooks/composio",
931 + )
932 + """
933 + if not webhook_url:
934 + raise exceptions.ValidationError("please provide a valid `webhook_url`")
935 +
936 + events = list(
937 + DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS
938 + if enabled_events is None
939 + else enabled_events
940 + )
941 + if len(events) == 0:
942 + raise exceptions.ValidationError(
943 + "please provide at least one enabled event"
944 + )
945 +
946 + version_value = (
947 + version.value if isinstance(version, WebhookVersion) else version
948 + )
949 + body = {
950 + "webhook_url": webhook_url,
951 + "enabled_events": events,
952 + "version": version_value,
953 + }
954 +
955 + existing = self._client.get(
956 + WEBHOOK_SUBSCRIPTIONS_PATH,
957 + cast_to=object,
958 + options={"params": {"limit": 1}},
959 + )
960 + subscription_id = self._first_webhook_subscription_id(existing)
961 +
962 + if subscription_id:
963 + return self._normalize_webhook_subscription(
964 + self._client.patch(
965 + f"{WEBHOOK_SUBSCRIPTIONS_PATH}/{subscription_id}",
966 + cast_to=object,
967 + body=body,
968 + )
969 + )
970 +
971 + return self._normalize_webhook_subscription(
972 + self._client.post(
973 + WEBHOOK_SUBSCRIPTIONS_PATH,
974 + cast_to=object,
975 + body=body,
976 + ),
977 + )
978 +
979 + @staticmethod
980 + def _normalize_webhook_subscription(raw: object) -> WebhookSubscription:
981 + """Build a typed :class:`WebhookSubscription` from the raw API response.
982 +
983 + Maps explicitly (accepting either snake_case or camelCase wire keys)
984 + instead of ``cast``-ing the raw object, so the returned dict always
985 + matches the declared shape and a shift in the wire format surfaces as a
986 + normalized field rather than a ``KeyError`` at the call site.
987 + """
988 + data = raw if isinstance(raw, dict) else {}
989 +
990 + def _first_str(*keys: str) -> t.Optional[str]:
991 + for key in keys:
992 + value = data.get(key)
993 + if isinstance(value, str) and value:
994 + return value
995 + return None
996 +
997 + def _str_list(*keys: str) -> t.List[str]:
998 + for key in keys:
999 + value = data.get(key)
1000 + if isinstance(value, list):
1001 + return [item for item in value if isinstance(item, str)]
1002 + return []
1003 +
1004 + result: WebhookSubscription = {
1005 + "id": _first_str("id") or "",
1006 + "webhook_url": _first_str("webhook_url", "webhookUrl") or "",
1007 + "version": _first_str("version") or WebhookVersion.V3.value,
1008 + "enabled_events": _str_list("enabled_events", "enabledEvents"),
1009 + }
1010 + secret = _first_str("secret")
1011 + if secret is not None:
1012 + result["secret"] = secret
1013 + created_at = _first_str("created_at", "createdAt")
1014 + if created_at is not None:
1015 + result["created_at"] = created_at
1016 + updated_at = _first_str("updated_at", "updatedAt")
1017 + if updated_at is not None:
1018 + result["updated_at"] = updated_at
1019 + return result
1020 +
1021 + @staticmethod
1022 + def _first_webhook_subscription_id(response: object) -> t.Optional[str]:
1023 + if not isinstance(response, dict):
1024 + return None
1025 +
1026 + items = response.get("items")
1027 + if not isinstance(items, list) or len(items) == 0:
1028 + return None
1029 +
1030 + first = items[0]
1031 + if not isinstance(first, dict):
1032 + return None
1033 +
1034 + subscription_id = first.get("id")
1035 + return subscription_id if isinstance(subscription_id, str) else None
1036 +
1037 def get_type(self, slug: str) -> TriggersTypeRetrieveResponse:
1038 """
1039 Get a trigger type by its slug
@@ -1119,6 +1258,196 @@ class Triggers(Resource):
1258 "raw_payload": raw_payload,
1259 }
1260
1261 + def parse(
1262 + self,
1263 + request: t.Any = None,
1264 + *,
1265 + body: t.Union[str, bytes, t.Mapping[str, t.Any], None] = None,
1266 + headers: t.Union[t.Mapping[str, t.Any], None] = None,
1267 + verify_secret: t.Union[str, None, Omit] = omit,
1268 + tolerance: int = 300,
1269 + ) -> VerifyWebhookResult:
1270 + """
1271 + Parse an incoming webhook request into a typed, normalized trigger payload.
1272 +
1273 + Dump the incoming request in and get back the parsed Composio trigger
1274 + event. When ``verify_secret`` is provided, the request signature is
1275 + verified before the payload is returned (delegating to
1276 + :meth:`verify_webhook`); without it, the body is parsed without
1277 + verification.
1278 +
1279 + ``request`` may be any object exposing the request body and headers, such
1280 + as a Flask/Django/FastAPI request. The body is read from ``.body`` (or
1281 + ``.data`` / ``.get_data()``) and the headers from ``.headers``. Because
1282 + this SDK is synchronous, the caller must pass an already-read raw body for
1283 + async frameworks (e.g. FastAPI ``await request.body()``) — either via the
1284 + ``body`` keyword or by reading it first.
1285 +
1286 + Alternatively, pass ``body=`` and ``headers=`` explicitly instead of a
1287 + ``request`` object.
1288 +
1289 + :param request: The incoming webhook request object (Flask/Django/FastAPI)
1290 + :param body: The raw request body (str/bytes/parsed mapping); overrides ``request``
1291 + :param headers: The request headers as a mapping; overrides ``request``
1292 + :param verify_secret: Webhook secret; when set, the signature is verified.
1293 + Omit it entirely to parse without verification. Passing a present-but-empty
1294 + value (e.g. an unset ``COMPOSIO_WEBHOOK_SECRET``) raises rather than
1295 + silently skipping verification.
1296 + :param tolerance: Max webhook age in seconds (only used when verifying)
1297 + :return: VerifyWebhookResult containing version, normalized payload, and raw payload
1298 + :raises ValidationError: If ``verify_secret`` is empty, or is set but signature headers are missing
1299 + :raises WebhookSignatureVerificationError: If signature verification fails
1300 + :raises WebhookPayloadError: If the payload cannot be parsed
1301 +
1302 + Example:
1303 + # Flask — verify the signature
1304 + @app.route('/webhooks/composio', methods=['POST'])
1305 + def webhook():
1306 + try:
1307 + result = composio.triggers.parse(
1308 + request,
1309 + verify_secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
1310 + )
1311 + print(f"Trigger: {result['payload']['trigger_slug']}")
1312 + print(f"Event data: {result['payload']['payload']}")
1313 + return 'OK', 200
1314 + except exceptions.WebhookSignatureVerificationError:
1315 + return 'Unauthorized', 401
1316 +
1317 + # FastAPI — parse without verifying (read the async body first)
1318 + @app.post('/webhooks/composio')
1319 + async def webhook(request: Request):
1320 + raw = await request.body()
1321 + result = composio.triggers.parse(body=raw, headers=request.headers)
1322 + return {'trigger': result['payload']['trigger_slug']}
1323 + """
1324 + raw_body = body if body is not None else self._extract_request_body(request)
1325 + raw_headers = (
1326 + headers if headers is not None else getattr(request, "headers", None)
1327 + )
1328 +
1329 + payload = self._body_to_str(raw_body)
1330 +
1331 + # Distinguish "caller omitted verify_secret" (explicit opt-out) from
1332 + # "caller passed verify_secret but it resolved to empty" (almost always
1333 + # an unset COMPOSIO_WEBHOOK_SECRET). The latter must fail loudly rather
1334 + # than silently skip verification and accept forged events.
1335 + if isinstance(verify_secret, Omit):
1336 + version, raw_payload, normalized_payload = self._parse_webhook_payload(
1337 + payload
1338 + )
1339 + return {
1340 + "version": version,
1341 + "payload": normalized_payload,
1342 + "raw_payload": raw_payload,
1343 + }
1344 +
1345 + if not verify_secret:
1346 + raise exceptions.ValidationError(
1347 + "Cannot verify webhook: `verify_secret` was provided but is empty — "
1348 + "your COMPOSIO_WEBHOOK_SECRET is likely unset. Set the secret, or omit "
1349 + "`verify_secret` entirely to parse without verification."
1350 + )
1351 +
1352 + # Secret provided: signature headers are required to verify.
1353 + webhook_id = self._get_header(raw_headers, "webhook-id")
1354 + timestamp = self._get_header(raw_headers, "webhook-timestamp")
1355 + signature = self._get_header(raw_headers, "webhook-signature")
1356 +
1357 + missing = [
1358 + name
1359 + for name, value in (
1360 + ("webhook-id", webhook_id),
1361 + ("webhook-timestamp", timestamp),
1362 + ("webhook-signature", signature),
1363 + )
1364 + if not value
1365 + ]
1366 + if missing:
1367 + raise exceptions.ValidationError(
1368 + "Cannot verify webhook: missing signature header(s) "
1369 + f"{', '.join(repr(name) for name in missing)}. "
1370 + "Pass the raw, unparsed request body and ensure the Composio "
1371 + "signature headers (webhook-id, webhook-timestamp, "
1372 + "webhook-signature) are forwarded to triggers.parse(). "
1373 + "To parse without verifying, omit `verify_secret`."
1374 + )
1375 +
1376 + return self.verify_webhook(
1377 + id=t.cast(str, webhook_id),
1378 + payload=payload,
1379 + secret=verify_secret,
1380 + signature=t.cast(str, signature),
1381 + timestamp=t.cast(str, timestamp),
1382 + tolerance=tolerance,
1383 + )
1384 +
1385 + @staticmethod
1386 + def _extract_request_body(request: t.Any) -> t.Union[str, bytes, None]:
1387 + """Read the raw body from a framework request object.
1388 +
1389 + Tries the common attributes used by Flask (``get_data``/``data``),
1390 + Django (``body``) and similar. Returns ``None`` when nothing usable is
1391 + found so the caller surfaces a clear parse error.
1392 + """
1393 + if request is None:
1394 + return None
1395 +
1396 + # Flask: request.get_data() returns the raw body bytes.
1397 + get_data = getattr(request, "get_data", None)
1398 + if callable(get_data):
1399 + return get_data()
1400 +
1401 + for attr in ("body", "data"):
1402 + value = getattr(request, attr, None)
1403 + if value is not None and not callable(value):
1404 + return value
1405 +
1406 + return None
1407 +
1408 + @staticmethod
1409 + def _body_to_str(body: t.Union[str, bytes, t.Mapping[str, t.Any], None]) -> str:
1410 + """Coerce a body (str, bytes, parsed mapping, or None) into a raw string."""
1411 + if body is None:
1412 + return ""
1413 + if isinstance(body, str):
1414 + return body
1415 + if isinstance(body, (bytes, bytearray)):
1416 + return bytes(body).decode("utf-8")
1417 + # Already-parsed mapping (e.g. a framework that pre-parsed JSON). Note:
1418 + # re-serializing cannot reproduce the exact signed bytes, so signature
1419 + # verification on a pre-parsed body is best-effort only.
1420 + return json.dumps(body)
1421 +
1422 + @staticmethod
1423 + def _get_header(headers: t.Any, name: str) -> t.Optional[str]:
1424 + """Read a header value case-insensitively from a headers mapping.
1425 +
1426 + Supports both plain ``dict`` headers and framework header objects
1427 + (Werkzeug/Django ``HttpHeaders``) that expose a ``get`` method, which is
1428 + already case-insensitive.
1429 + """
1430 + if headers is None:
1431 + return None
1432 +
1433 + get = getattr(headers, "get", None)
1434 + if callable(get):
1435 + value = get(name)
1436 + if value is not None:
1437 + return str(value)
1438 +
1439 + # Fall back to a manual case-insensitive scan for plain mappings.
1440 + try:
1441 + items = headers.items()
1442 + except AttributeError:
1443 + return None
1444 +
1445 + target = name.lower()
1446 + for key, value in items:
1447 + if isinstance(key, str) and key.lower() == target:
1448 + return str(value) if value is not None else None
1449 + return None
1450 +
1451 def _verify_webhook_signature(
1452 self,
1453 *,
python/composio/sdk.py
+42 -5
@@ -68,7 +68,6 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
68 """
69
70 tools: "Tools[TTool, TToolCollection]"
71 - tool_router: "ToolRouter[TTool, TToolCollection]"
71
72 @t.overload
73 def __init__(
@@ -185,8 +184,10 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
184
185 self.experimental = ExperimentalAPI(client=self._client)
186
188 - # initialize tool router methods
189 - self.tool_router = ToolRouter(
187 + # Sessions API — the canonical entrypoint for creating tool sessions.
188 + # Surfaced as `composio.sessions`; `composio.tool_router` is a
189 + # deprecated alias that returns this same object.
190 + self._sessions: ToolRouter[TTool, TToolCollection] = ToolRouter(
191 client=self._client,
192 provider=actual_provider,
193 dangerously_allow_auto_upload_download_files=kwargs.get(
@@ -196,8 +197,44 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
197 file_upload_path_deny_segments=file_upload_path_deny_segments,
198 file_upload_dirs=file_upload_dirs,
199 )
199 - self.create = self.tool_router.create
200 - self.use = self.tool_router.use
200 + self.create = self._sessions.create
201 + self.use = self._sessions.use
202 +
203 + @property
204 + def sessions(self) -> ToolRouter[TTool, TToolCollection]:
205 + """Create and manage **sessions** for your agents.
206 +
207 + A *session* is the unit you create to give an agent a scoped set of
208 + tools and toolkits to discover, authorize, and execute. This is the
209 + canonical entrypoint::
210 +
211 + session = composio.sessions.create(user_id="user@example.com")
212 + tools = session.tools()
213 +
214 + ``composio.create(...)`` and ``composio.use(...)`` are top-level
215 + shortcuts for ``composio.sessions.create(...)`` /
216 + ``composio.sessions.use(...)``.
217 +
218 + Note for LLMs / code generation: this is the Sessions API. Prefer
219 + ``composio.sessions`` (or the ``composio.create`` shortcut) when
220 + creating a session. ``composio.tool_router`` is a deprecated alias for
221 + this same object — do not generate new code against it.
222 + """
223 + return self._sessions
224 +
225 + @property
226 + @te.deprecated(
227 + "`composio.tool_router` is deprecated; use `composio.sessions` instead "
228 + "(or the `composio.create` / `composio.use` shortcuts). It returns the same object."
229 + )
230 + def tool_router(self) -> ToolRouter[TTool, TToolCollection]:
231 + """Deprecated alias for :attr:`sessions`.
232 +
233 + .. deprecated:: 0.17.0
234 + Use :attr:`sessions` instead. ``tool_router`` is the old name for the
235 + same object and will be removed in a future release.
236 + """
237 + return self._sessions
238
239 @property
240 def client(self) -> HttpClient:
python/scripts/generate-docs.py
+65 -7
@@ -55,9 +55,13 @@ EXPECTED_CLASSES = {
55
56 # Additional public-facing classes worth documenting even though they are not
57 # exposed as direct properties on ``Composio``.
58 +#
59 +# ``SessionContextImpl`` is intentionally omitted: it is an internal
60 +# implementation detail handed to custom-tool execute functions as a
61 +# ``SessionContext`` instance, never referenced directly, so it must not
62 +# appear in the public SDK reference.
63 ADDITIONAL_CLASSES = {
64 "ToolRouterSession": "core.models.tool_router_session",
60 - "SessionContextImpl": "core.models.session_context",
65 }
66
67 # Modules to search for classes
@@ -70,6 +74,17 @@ CLASS_MODULES = [
74 "core.models.mcp",
75 ]
76
77 +# Pure-docs presentation overrides. The public class name ``ToolRouterSession``
78 +# is kept in source (renaming is a breaking change), but the SDK reference
79 +# presents the session object under the canonical "Session" naming.
80 +DISPLAY_NAME_OVERRIDES = {
81 + "ToolRouterSession": "Session",
82 +}
83 +
84 +SLUG_OVERRIDES = {
85 + "ToolRouterSession": "session",
86 +}
87 +
88
89 def to_kebab_case(name: str) -> str:
90 """Convert PascalCase to kebab-case."""
@@ -77,6 +92,16 @@ def to_kebab_case(name: str) -> str:
92 return re.sub("([a-z0-9])([A-Z])", r"\1-\2", s1).lower()
93
94
95 +def display_name_for(class_name: str) -> str:
96 + """Resolve the display title for a class (falls back to the class name)."""
97 + return DISPLAY_NAME_OVERRIDES.get(class_name, class_name)
98 +
99 +
100 +def slug_for(class_name: str) -> str:
101 + """Resolve the URL slug / filename stem (falls back to kebab-case)."""
102 + return SLUG_OVERRIDES.get(class_name, to_kebab_case(class_name))
103 +
104 +
105 def escape_yaml_string(s: str) -> str:
106 """Escape a string for YAML frontmatter."""
107 return json.dumps(s)
@@ -126,13 +151,20 @@ def format_type(annotation: Any) -> str:
151 def parse_docstring(docstring: str | None) -> dict[str, Any]:
152 """Parse docstring into components."""
153 if not docstring:
129 - return {"description": "", "params": {}, "returns": None, "examples": []}
154 + return {
155 + "description": "",
156 + "params": {},
157 + "returns": None,
158 + "examples": [],
159 + "deprecated": None,
160 + }
161
162 lines = docstring.strip().split("\n")
163 description_lines = []
164 params: dict[str, str] = {}
165 returns = None
166 examples: list[str] = []
167 + deprecated_lines: list[str] = []
168
169 section = "description"
170 current_param = None
@@ -141,6 +173,14 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
173 for line in lines:
174 stripped = line.strip()
175
176 + # Check for a ``.. deprecated::`` directive (reStructuredText).
177 + if re.match(r"\.\.\s+deprecated::", stripped):
178 + section = "deprecated"
179 + rest = re.sub(r"\.\.\s+deprecated::\s*", "", stripped).strip()
180 + if rest:
181 + deprecated_lines.append(rest)
182 + continue
183 +
184 # Check for :param name: description
185 param_match = re.match(r":param\s+(\w+):\s*(.*)", stripped)
186 if param_match:
@@ -170,6 +210,8 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
210 returns += " " + stripped
211 elif section == "examples":
212 example_lines.append(line)
213 + elif section == "deprecated" and stripped:
214 + deprecated_lines.append(stripped)
215
216 if example_lines:
217 examples.append("\n".join(example_lines).strip())
@@ -179,6 +221,7 @@ def parse_docstring(docstring: str | None) -> dict[str, Any]:
221 "params": params,
222 "returns": returns,
223 "examples": examples,
224 + "deprecated": " ".join(deprecated_lines).strip() if deprecated_lines else None,
225 }
226
227
@@ -193,6 +236,7 @@ def extract_class_info(
236 "access": config.get("access"),
237 "source_link": get_source_link(cls),
238 "description": doc["description"],
239 + "deprecated": doc.get("deprecated"),
240 "properties": [],
241 "methods": [],
242 }
@@ -260,15 +304,29 @@ def generate_class_mdx(
304 if info["description"]
305 else f"{info['name']} class"
306 )
307 + # Normalize reStructuredText ``double backticks`` to single backticks so the
308 + # frontmatter description reads cleanly.
309 + desc = re.sub(r"``([^`]+)``", r"`\1`", desc)
310 if len(desc) > 150:
311 desc = desc[:147] + "..."
312
313 lines.append("---")
267 - lines.append(f"title: {escape_yaml_string(info['name'])}")
314 + lines.append(f"title: {escape_yaml_string(display_name_for(info['name']))}")
315 lines.append(f"description: {escape_yaml_string(desc)}")
316 lines.append("---")
317 lines.append("")
318
319 + # Class-level deprecation callout (rendered as a fumadocs warning callout).
320 + deprecated_note = info.get("deprecated")
321 + if deprecated_note:
322 + # Normalize reStructuredText ``double backticks`` to MDX `single` so
323 + # inline code renders correctly.
324 + deprecated_note = re.sub(r"``([^`]+)``", r"`\1`", deprecated_note)
325 + lines.append('<Callout type="warn" title="Deprecated">')
326 + lines.append(deprecated_note)
327 + lines.append("</Callout>")
328 + lines.append("")
329 +
330 source_link = info.get("source_link", "")
331
332 # Properties
@@ -395,13 +453,13 @@ def generate_index_mdx(classes: list[dict], decorators: list[dict]) -> str:
453 # Classes table
454 class_rows = []
455 for c in classes:
398 - link = f"/reference/sdk-reference/python/{to_kebab_case(c['name'])}"
456 + link = f"/reference/sdk-reference/python/{slug_for(c['name'])}"
457 desc = (
458 c["description"][:80] + "..."
459 if len(c["description"]) > 80
460 else c["description"]
461 )
404 - class_rows.append(f"| [`{c['name']}`]({link}) | {desc} |")
462 + class_rows.append(f"| [`{display_name_for(c['name'])}`]({link}) | {desc} |")
463
464 # Decorators section
465 dec_section = ""
@@ -561,7 +619,7 @@ def main():
619 else:
620 mdx = generate_class_mdx(info, None)
621
564 - file_path = OUTPUT_DIR / f"{to_kebab_case(class_name)}.mdx"
622 + file_path = OUTPUT_DIR / f"{slug_for(class_name)}.mdx"
623 file_path.write_text(mdx)
624
625 documented_classes.append(
@@ -616,7 +674,7 @@ def main():
674 # Generate meta.json
675 meta = {
676 "title": "Python SDK",
619 - "pages": [to_kebab_case(c["name"]) for c in documented_classes],
677 + "pages": [slug_for(c["name"]) for c in documented_classes],
678 }
679 (OUTPUT_DIR / "meta.json").write_text(json.dumps(meta, indent=2))
680
python/tests/test_no_retry_writes.py
+4 -1
@@ -116,7 +116,10 @@ class TestStainlessCopyContract:
116 def test_with_options_is_aliased_to_our_copy_override(self) -> None:
117 # The base binds `with_options = copy` at class-definition time, so the
118 # subclass must re-alias it to the override that re-injects `provider`.
119 - assert HttpClient.with_options is HttpClient.copy
119 + # (Accessing these bound methods via the generic class trips mypy's
120 + # "generic instance variable via class" check; the identity assert is
121 + # intentional.)
122 + assert HttpClient.with_options is HttpClient.copy # type: ignore[misc]
123
124
125 class TestWritePathDoesNotRetry:
python/tests/test_tool_router.py
+73 -2
@@ -22,8 +22,10 @@ from composio.core.models.tool_router import (
22 )
23 from composio.core.models.tool_router_session import (
24 DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX,
25 + ToolRouterSession,
26 + ToolRouterSessionWithMcp,
27 )
26 -from composio.exceptions import ValidationError
28 +from composio.exceptions import InvalidParams, ValidationError
29
30 experimental_api = ExperimentalAPI()
31
@@ -135,6 +137,39 @@ class TestToolRouter:
137 # Verify API was called
138 mock_client.tool_router.session.create.assert_called_once()
139
140 + def test_create_session_default_returns_base_session(self, tool_router):
141 + """Default create() (mcp omitted) returns the base ToolRouterSession.
142 +
143 + MCP is opt-in: the type must NOT be the mcp-surfacing subclass.
144 + """
145 + session = tool_router.create(user_id="user_123")
146 +
147 + assert type(session) is ToolRouterSession
148 + assert not isinstance(session, ToolRouterSessionWithMcp)
149 +
150 + def test_create_session_with_mcp_true_returns_with_mcp(self, tool_router):
151 + """create(..., mcp=True) returns ToolRouterSessionWithMcp with mcp surfaced."""
152 + session = tool_router.create(user_id="user_123", mcp=True)
153 +
154 + assert isinstance(session, ToolRouterSessionWithMcp)
155 + # The MCP endpoint is populated on the runtime object either way.
156 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
157 + assert session.mcp.url == "https://mcp.example.com/session_123"
158 +
159 + def test_use_session_default_returns_base_session(self, tool_router):
160 + """Default use() (mcp omitted) returns the base ToolRouterSession."""
161 + session = tool_router.use("session_123")
162 +
163 + assert type(session) is ToolRouterSession
164 + assert not isinstance(session, ToolRouterSessionWithMcp)
165 +
166 + def test_use_session_with_mcp_true_returns_with_mcp(self, tool_router):
167 + """use(..., mcp=True) returns ToolRouterSessionWithMcp."""
168 + session = tool_router.use("session_123", mcp=True)
169 +
170 + assert isinstance(session, ToolRouterSessionWithMcp)
171 + assert session.mcp.url == "https://mcp.example.com/session_123"
172 +
173 def test_create_session_with_toolkits_list(self, tool_router, mock_client):
174 """Test creating a session with toolkits as a list."""
175 session = tool_router.create(user_id="user_123", toolkits=["github", "slack"])
@@ -516,8 +551,44 @@ class TestToolRouter:
551 "slack": ["ca_yyy"],
552 }
553
554 + def test_create_session_with_sandbox_config(self, tool_router, mock_client):
555 + """Test creating a session with preferred sandbox configuration."""
556 + session = tool_router.create(
557 + user_id="user_123",
558 + sandbox={
559 + "enable_proxy_execution": False,
560 + "auto_offload_threshold": 300,
561 + "sandbox_size": "large",
562 + },
563 + )
564 +
565 + assert session.session_id == "session_123"
566 +
567 + call_args = mock_client.tool_router.session.create.call_args
568 + kwargs = call_args.kwargs
569 + assert "workbench" in kwargs
570 + assert kwargs["workbench"] == {
571 + "enable": True,
572 + "enable_proxy_execution": False,
573 + "auto_offload_threshold": 300,
574 + "sandbox_size": "large",
575 + }
576 +
577 + def test_create_session_rejects_sandbox_and_workbench(
578 + self, tool_router, mock_client
579 + ):
580 + """Test creating a session rejects both sandbox and workbench."""
581 + with pytest.raises(InvalidParams):
582 + tool_router.create(
583 + user_id="user_123",
584 + sandbox={"enable": True},
585 + workbench={"enable": True},
586 + )
587 +
588 + mock_client.tool_router.session.create.assert_not_called()
589 +
590 def test_create_session_with_workbench_config(self, tool_router, mock_client):
520 - """Test creating a session with workbench configuration."""
591 + """Test creating a session with backwards-compatible workbench configuration."""
592 session = tool_router.create(
593 user_id="user_123",
594 workbench={"enable_proxy_execution": False, "auto_offload_threshold": 300},
python/tests/test_triggers.py
+217
@@ -97,6 +97,88 @@ class TestTriggers:
97
98 assert triggers._toolkit_versions == custom_versions
99
100 + def test_set_webhook_subscription_creates_when_none_exists(
101 + self, triggers, mock_client
102 + ):
103 + """Test set_webhook_subscription creates a subscription when none exists."""
104 + webhook_url = "https://example.com/webhooks/composio"
105 + raw_subscription = {
106 + "id": "sub_123",
107 + "webhook_url": webhook_url,
108 + "version": "V3",
109 + "enabled_events": ["composio.trigger.message"],
110 + }
111 + mock_client.get.return_value = {"items": []}
112 + mock_client.post.return_value = raw_subscription
113 +
114 + result = triggers.set_webhook_subscription(webhook_url=webhook_url)
115 +
116 + mock_client.get.assert_called_once_with(
117 + "/api/v3.1/webhook_subscriptions",
118 + cast_to=object,
119 + options={"params": {"limit": 1}},
120 + )
121 + mock_client.post.assert_called_once_with(
122 + "/api/v3.1/webhook_subscriptions",
123 + cast_to=object,
124 + body={
125 + "webhook_url": webhook_url,
126 + "enabled_events": ["composio.trigger.message"],
127 + "version": "V3",
128 + },
129 + )
130 + mock_client.patch.assert_not_called()
131 + assert result == raw_subscription
132 +
133 + def test_set_webhook_subscription_updates_first_existing(
134 + self, triggers, mock_client
135 + ):
136 + """Test set_webhook_subscription updates the first subscription when one exists."""
137 + webhook_url = "https://example.com/webhooks/composio"
138 + raw_subscription = {
139 + "id": "sub_123",
140 + "webhook_url": webhook_url,
141 + "version": "V3",
142 + "enabled_events": [
143 + "composio.trigger.message",
144 + "composio.connected_account.expired",
145 + ],
146 + }
147 + mock_client.get.return_value = {"items": [{"id": "sub_123"}]}
148 + mock_client.patch.return_value = raw_subscription
149 +
150 + result = triggers.set_webhook_subscription(
151 + webhook_url=webhook_url,
152 + enabled_events=[
153 + "composio.trigger.message",
154 + "composio.connected_account.expired",
155 + ],
156 + version="V3",
157 + )
158 +
159 + mock_client.patch.assert_called_once_with(
160 + "/api/v3.1/webhook_subscriptions/sub_123",
161 + cast_to=object,
162 + body={
163 + "webhook_url": webhook_url,
164 + "enabled_events": [
165 + "composio.trigger.message",
166 + "composio.connected_account.expired",
167 + ],
168 + "version": "V3",
169 + },
170 + )
171 + mock_client.post.assert_not_called()
172 + assert result == raw_subscription
173 +
174 + def test_set_webhook_subscription_rejects_empty_events(self, triggers):
175 + """Test set_webhook_subscription rejects empty enabled_events."""
176 + with pytest.raises(exceptions.ValidationError):
177 + triggers.set_webhook_subscription(
178 + webhook_url="https://example.com/webhooks/composio",
179 + enabled_events=[],
180 + )
181 +
182 def test_get_type_with_default_versions(
183 self, triggers, mock_client, mock_trigger_type
184 ):
@@ -1132,6 +1214,141 @@ class TestVerifyWebhook:
1214 assert isinstance(error, exceptions.TriggerError)
1215
1216
1217 +class TestParseWebhook:
1218 + """Test cases for the parse() webhook helper."""
1219 +
1220 + @pytest.fixture
1221 + def mock_client(self):
1222 + """Create a mock HTTP client."""
1223 + client = Mock()
1224 + client.triggers_types = Mock()
1225 + client.trigger_instances = Mock()
1226 + client.trigger_instances.manage = Mock()
1227 + client.connected_accounts = Mock()
1228 + return client
1229 +
1230 + @pytest.fixture
1231 + def triggers(self, mock_client):
1232 + """Create a Triggers instance."""
1233 + return Triggers(client=mock_client)
1234 +
1235 + @pytest.fixture
1236 + def test_secret(self):
1237 + """Test webhook secret."""
1238 + return "test-webhook-secret-12345"
1239 +
1240 + @pytest.fixture
1241 + def test_webhook_id(self):
1242 + """Test webhook ID."""
1243 + return "msg_test123"
1244 +
1245 + @pytest.fixture
1246 + def test_timestamp(self):
1247 + """Test webhook timestamp (current time in Unix seconds)."""
1248 + return str(int(time.time()))
1249 +
1250 + @pytest.fixture
1251 + def mock_v3_payload(self):
1252 + """Create mock V3 webhook payload."""
1253 + return {
1254 + "id": "evt-123",
1255 + "timestamp": datetime.now(timezone.utc).isoformat(),
1256 + "type": "composio.trigger.message",
1257 + "metadata": {
1258 + "log_id": "log-123",
1259 + "trigger_slug": "GITHUB_PUSH_EVENT",
1260 + "trigger_id": "trigger-nano-123",
1261 + "connected_account_id": "conn-nano-123",
1262 + "auth_config_id": "auth-nano-123",
1263 + "user_id": "user-456",
1264 + },
1265 + "data": {"action": "push", "repository": "test-repo"},
1266 + }
1267 +
1268 + def create_signature(
1269 + self, webhook_id: str, timestamp: str, payload: str, secret: str
1270 + ) -> str:
1271 + """Helper to create a valid v1,base64 signature."""
1272 + to_sign = f"{webhook_id}.{timestamp}.{payload}"
1273 + signature_bytes = hmac.new(
1274 + key=secret.encode("utf-8"),
1275 + msg=to_sign.encode("utf-8"),
1276 + digestmod=hashlib.sha256,
1277 + ).digest()
1278 + return f"v1,{base64.b64encode(signature_bytes).decode('utf-8')}"
1279 +
1280 + def test_parse_with_request_object_and_verify(
1281 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
1282 + ):
1283 + """Parse and verify from a framework-style request object."""
1284 + payload = json.dumps(mock_v3_payload)
1285 + signature = self.create_signature(
1286 + test_webhook_id, test_timestamp, payload, test_secret
1287 + )
1288 +
1289 + request = Mock()
1290 + request.body = payload.encode("utf-8")
1291 + request.headers = {
1292 + "webhook-id": test_webhook_id,
1293 + "webhook-timestamp": test_timestamp,
1294 + "webhook-signature": signature,
1295 + }
1296 + # Avoid Mock auto-creating a callable get_data attribute.
1297 + del request.get_data
1298 +
1299 + result = triggers.parse(request, verify_secret=test_secret)
1300 +
1301 + assert result["version"] == WebhookVersion.V3
1302 + assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
1303 + assert result["payload"]["payload"] == {
1304 + "action": "push",
1305 + "repository": "test-repo",
1306 + }
1307 +
1308 + def test_parse_with_explicit_body_and_headers_no_verify(
1309 + self, triggers, mock_v3_payload
1310 + ):
1311 + """Parse without verifying using explicit body/headers kwargs."""
1312 + payload = json.dumps(mock_v3_payload)
1313 +
1314 + result = triggers.parse(body=payload, headers={})
1315 +
1316 + assert result["version"] == WebhookVersion.V3
1317 + assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT"
1318 + assert result["payload"]["payload"] == {
1319 + "action": "push",
1320 + "repository": "test-repo",
1321 + }
1322 +
1323 + def test_parse_bad_signature_raises(
1324 + self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload
1325 + ):
1326 + """A bad signature with verify_secret raises a verification error."""
1327 + payload = json.dumps(mock_v3_payload)
1328 +
1329 + with pytest.raises(exceptions.WebhookSignatureVerificationError):
1330 + triggers.parse(
1331 + body=payload,
1332 + headers={
1333 + "webhook-id": test_webhook_id,
1334 + "webhook-timestamp": test_timestamp,
1335 + "webhook-signature": "v1,not-a-valid-signature",
1336 + },
1337 + verify_secret=test_secret,
1338 + )
1339 +
1340 + def test_parse_missing_headers_with_verify_raises(
1341 + self, triggers, test_secret, mock_v3_payload
1342 + ):
1343 + """verify_secret set but missing signature headers raises ValidationError."""
1344 + payload = json.dumps(mock_v3_payload)
1345 +
1346 + with pytest.raises(exceptions.ValidationError) as exc_info:
1347 + triggers.parse(body=payload, headers={}, verify_secret=test_secret)
1348 +
1349 + assert "missing signature header" in str(exc_info.value)
1350 +
1351 +
1352 class TestTriggerSubscriptionParsing:
1353 """Tests for realtime (Pusher) payload parsing in TriggerSubscription."""
1354
skills-lock.json new
+11
@@ -0,0 +1,11 @@
1 +{
2 + "version": 1,
3 + "skills": {
4 + "eve": {
5 + "source": "vercel/eve",
6 + "sourceType": "github",
7 + "skillPath": "SKILL.md",
8 + "computedHash": "79a1e606ecf33eed33c1f3adc1cc266de391e19aa9237ca37e4f3aa3fba6b228"
9 + }
10 + }
11 +}
ts/packages/core/CHANGELOG.md
+2 -2
@@ -128,7 +128,7 @@
128
129 - 42ebff3: feat(connected-accounts): namespace SHARED-connection surface under `experimental`
130
131 - Aligns the TypeScript SDK with the experimental wire shape used by Shared Connections. The flat `accountType` / `aclConfigForShared` options on `connectedAccounts.link()` and `session.authorize()` have moved under a single `experimental` block, and `connectedAccounts.updateAcl()` has moved off the class onto a top-level `experimental_updateAcl(composio, id, opts)` export — same precedent as `experimental_createTool` / `experimental_createToolkit`.
131 + Aligns the TypeScript SDK with the experimental wire shape used by Shared Connections. The flat `accountType` / `aclConfigForShared` options on `connectedAccounts.link()` and `session.authorize()` have moved under a single `experimental` block. ACL updates remain on the domain-specific `connectedAccounts.updateAcl()` mount, with `experimental.updateAcl()` kept as an experimental compatibility alias.
132
133 The `experimental` namespace is the signal that the shape may change in future releases. Pinning a SHARED connection in a session config (`connectedAccounts: { gmail: [...] }`) and direct execute by `connectedAccountId` are unchanged — only the connection-create / patch / authorize surfaces are namespaced.
134
@@ -157,7 +157,7 @@
157 aclConfigForShared: { allowAllUsers: true },
158 },
159 });
160 - await experimental_updateAcl(composio, 'ca_abc', { allowAllUsers: true });
160 + await composio.connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true });
161 await session.authorize('github', {
162 experimental: {
163 accountType: 'SHARED',
ts/packages/core/package.json
+3 -2
@@ -73,13 +73,14 @@
73 },
74 "files": [
75 "README.md",
76 + "docs",
77 "dist",
78 "generated",
78 - "src/platform"
79 + "src"
80 ],
81 "scripts": {
82 "clean": "git clean -xdf node_modules",
82 - "build": "tsdown",
83 + "build": "pnpm exec tsdown",
84 "test": "vitest run",
85 "typecheck": "pnpm exec tsgo --noEmit --skipLibCheck && pnpm exec tsgo --noEmit --skipLibCheck -p tsconfig.type-tests.json",
86 "typecheck:tsc": "tsc --noEmit --skipLibCheck && tsc --noEmit --skipLibCheck -p tsconfig.type-tests.json",
ts/packages/core/scripts/generate-docs.ts
+65 -7
@@ -31,6 +31,30 @@ const INTERNAL_CLASSES = new Set([
31 // Classes that users instantiate directly (show constructor)
32 const USER_INSTANTIATED_CLASSES = new Set(['Composio']);
33
34 +// Pure-docs presentation overrides. The public class names retain their
35 +// legacy "ToolRouter*" names in source (renaming them is a breaking change),
36 +// but the SDK reference presents them under the canonical "Session" naming.
37 +// Keys are the source class names.
38 +const DISPLAY_NAME_OVERRIDES: Record<string, string> = {
39 + ToolRouterSession: 'Session',
40 + ToolRouterSessionFilesMount: 'Session files',
41 +};
42 +
43 +const SLUG_OVERRIDES: Record<string, string> = {
44 + ToolRouterSession: 'session',
45 + ToolRouterSessionFilesMount: 'session-files',
46 +};
47 +
48 +// Resolve the display title for a class (falls back to the class name).
49 +function displayNameFor(className: string): string {
50 + return DISPLAY_NAME_OVERRIDES[className] ?? className;
51 +}
52 +
53 +// Resolve the URL slug / filename stem for a class (falls back to kebab-case).
54 +function slugFor(className: string): string {
55 + return SLUG_OVERRIDES[className] ?? toKebabCase(className);
56 +}
57 +
58 // Discover model files automatically
59 async function discoverModelFiles(): Promise<string[]> {
60 const files = await readdir(MODELS_DIR);
@@ -197,6 +221,9 @@ interface MethodDoc {
221 }[];
222 examples: string[];
223 isAsync: boolean;
224 + /** Present when the symbol carries an `@deprecated` JSDoc tag. The string is
225 + * the (possibly empty) tag body, e.g. the recommended replacement. */
226 + deprecated?: string;
227 source?: { file: string; line: number };
228 }
229
@@ -214,6 +241,8 @@ interface ClassDoc {
241 methods: MethodDoc[];
242 properties: PropertyDoc[];
243 source?: { file: string; line: number };
244 + /** Present when the class carries a class-level `@deprecated` JSDoc tag. */
245 + deprecated?: string;
246 }
247
248 interface SourceSignatureTypes {
@@ -681,6 +710,10 @@ function extractMethod(reflection: TypeDocReflection): MethodDoc | null {
710 const primarySig = reflection.signatures[0];
711 const description = extractDescription(primarySig.comment);
712 const examples = extractTag(primarySig.comment, '@example');
713 + // `@deprecated` may live on the signature comment or the reflection comment.
714 + const deprecated =
715 + extractTag(primarySig.comment, '@deprecated')[0] ??
716 + extractTag(reflection.comment, '@deprecated')[0];
717
718 return {
719 name: reflection.name,
@@ -690,6 +723,7 @@ function extractMethod(reflection: TypeDocReflection): MethodDoc | null {
723 isAsync:
724 signatures[0]?.returnType.startsWith('Promise') ??
725 formatType(primarySig.type).startsWith('Promise'),
726 + deprecated,
727 source: reflection.sources?.[0]
728 ? { file: reflection.sources[0].fileName, line: reflection.sources[0].line }
729 : undefined,
@@ -705,6 +739,7 @@ function extractClass(reflection: TypeDocReflection): ClassDoc {
739 source: reflection.sources?.[0]
740 ? { file: reflection.sources[0].fileName, line: reflection.sources[0].line }
741 : undefined,
742 + deprecated: extractTag(reflection.comment, '@deprecated')[0],
743 };
744
745 if (!reflection.children) return classDoc;
@@ -748,10 +783,21 @@ function extractClass(reflection: TypeDocReflection): ClassDoc {
783 function generateMethodMdx(method: MethodDoc): string {
784 const lines: string[] = [];
785
751 - // Method header
752 - lines.push(`### ${method.name}()`);
786 + // Method header. Flag deprecated methods in the heading so they read clearly
787 + // in the sidebar/anchor and at a glance.
788 + const deprecatedSuffix = method.deprecated !== undefined ? ' (deprecated)' : '';
789 + lines.push(`### ${method.name}()${deprecatedSuffix}`);
790 lines.push('');
791
792 + // Deprecation callout (rendered as a fumadocs warning callout).
793 + if (method.deprecated !== undefined) {
794 + const note = method.deprecated.trim();
795 + lines.push('<Callout type="warn" title="Deprecated">');
796 + lines.push(note.length > 0 ? escapeTextForMdx(note) : 'This method is deprecated.');
797 + lines.push('</Callout>');
798 + lines.push('');
799 + }
800 +
801 // Description
802 if (method.description) {
803 lines.push(method.description);
@@ -867,11 +913,20 @@ function generateClassMdx(classDoc: ClassDoc): string {
913
914 // Frontmatter - fumadocs renders title and description automatically
915 lines.push('---');
870 - lines.push(`title: ${formatYamlFrontmatterString(classDoc.name)}`);
916 + lines.push(`title: ${formatYamlFrontmatterString(displayNameFor(classDoc.name))}`);
917 lines.push(`description: ${formatYamlFrontmatterString(fullDescription)}`);
918 lines.push('---');
919 lines.push('');
920
921 + // Class-level deprecation callout (rendered as a fumadocs warning callout).
922 + if (classDoc.deprecated !== undefined) {
923 + const note = classDoc.deprecated.trim();
924 + lines.push('<Callout type="warn" title="Deprecated">');
925 + lines.push(note.length > 0 ? escapeTextForMdx(note) : 'This class is deprecated.');
926 + lines.push('</Callout>');
927 + lines.push('');
928 + }
929 +
930 // Content starts directly with Constructor or Usage (no duplicate title/description)
931
932 // Constructor - only show for user-instantiated classes
@@ -879,7 +934,10 @@ function generateClassMdx(classDoc: ClassDoc): string {
934 lines.push('## Constructor');
935 lines.push('');
936 lines.push(generateMethodMdx(classDoc.constructor));
882 - } else if (!USER_INSTANTIATED_CLASSES.has(classDoc.name)) {
937 + } else if (!USER_INSTANTIATED_CLASSES.has(classDoc.name) && !(classDoc.name in SLUG_OVERRIDES)) {
938 + // Skip the `composio.<accessor>` Usage block for session-object classes —
939 + // they are not accessed as a `composio` sub-client property; the class
940 + // description explains how to obtain them (via `composio.sessions`).
941 lines.push('## Usage');
942 lines.push('');
943
@@ -1137,7 +1195,7 @@ async function main() {
1195
1196 const classDoc = extractClass(reflection);
1197 const mdx = generateClassMdx(classDoc);
1140 - const fileName = toKebabCase(className) + '.mdx';
1198 + const fileName = slugFor(className) + '.mdx';
1199 const filePath = join(OUTPUT_DIR, fileName);
1200
1201 await writeFile(filePath, mdx);
@@ -1151,7 +1209,7 @@ async function main() {
1209 const classesTable = documented
1210 .map(
1211 ({ name, description }) =>
1154 - `| [\`${name}\`](/reference/sdk-reference/typescript/${toKebabCase(name)}) | ${escapeTextForMdx(description)} |`
1212 + `| [\`${displayNameFor(name)}\`](/reference/sdk-reference/typescript/${slugFor(name)}) | ${escapeTextForMdx(description)} |`
1213 )
1214 .join('\n');
1215
@@ -1218,7 +1276,7 @@ const result = await composio.tools.execute('GITHUB_GET_REPOS', {
1276 // Generate meta.json for sidebar
1277 const meta = {
1278 title: 'TypeScript SDK',
1221 - pages: documented.map(({ name }) => toKebabCase(name)),
1279 + pages: documented.map(({ name }) => slugFor(name)),
1280 };
1281 await writeFile(join(OUTPUT_DIR, 'meta.json'), JSON.stringify(meta, null, 2));
1282
ts/packages/core/src/composio.ts
+43 -25
@@ -20,8 +20,7 @@ import { Files } from '#files';
20 import { getDefaultHeaders } from './utils/session';
21 import { ToolkitVersionParam } from './types/tool.types';
22 import { ToolRouter } from './models/ToolRouter';
23 -import { ToolRouterCreateSessionConfig, Session } from './types/toolRouter.types';
24 -import type { CustomTool, CustomToolkit } from './types/customTool.types';
23 +import { Sessions } from './models/Sessions';
24 import { CONFIG_DEFAULTS } from './utils/config-defaults';
25 import { expandHomeAndResolve, expandHomeAndResolveMany } from './utils/fileDirs';
26 export type ComposioConfig<
@@ -198,17 +197,33 @@ export class Composio<
197 connectedAccounts: ConnectedAccounts;
198 /**
199 * Experimental SDK methods whose shape may change in future releases.
201 - * Houses stateful operations like {@link Experimental.updateAcl} that
202 - * take a client and perform I/O. Stateless experimental factories
203 - * (e.g. `experimental_createTool`) stay at the top level.
200 + * Prefer domain-specific mounts (for example
201 + * `composio.connectedAccounts.updateAcl(...)`) when available; this
202 + * namespace keeps compatibility aliases while APIs are experimental.
203 + * Stateless experimental factories (e.g. `experimental_createTool`) stay
204 + * at the top level.
205 * @experimental
206 */
207 experimental: Experimental;
207 - /** Model Context Protocol server management */
208 + /**
209 + * Model Context Protocol server management.
210 + * @deprecated Use a session's MCP endpoint instead: `composio.create(userId, { mcp: true })`
211 + * returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now opt-in
212 + * per session; this standalone server-management API is kept only for backwards compatibility.
213 + * Prefer the session MCP endpoint; do not generate new code against `composio.mcp`.
214 + * See https://docs.composio.dev/docs/sessions-via-mcp
215 + */
216 mcp: MCP;
217 /**
210 - * Experimental feature, use with caution
211 - * @experimental
218 + * Create and reuse Composio sessions.
219 + *
220 + * Prefer `composio.sessions.create(...)` for new code. The top-level
221 + * `composio.create(...)` method is kept as an alias.
222 + */
223 + sessions: Sessions<unknown, unknown, TProvider>;
224 + /**
225 + * Legacy alias for `composio.sessions`.
226 + * @deprecated Use `composio.sessions` instead — `toolRouter` was renamed to `sessions` and is kept only for backwards compatibility. Prefer `composio.sessions`; do not generate new code against `composio.toolRouter`.
227 */
228 toolRouter: ToolRouter<unknown, unknown, TProvider>;
229 /**
@@ -227,7 +242,12 @@ export class Composio<
242 * const composio = new Composio();
243 * const userId = 'user_123';
244 *
230 - * const session = await composio.create(userId, {
245 + * const session = await composio.sessions.create(userId, {
246 + * manageConnections: true,
247 + * });
248 + *
249 + * // Backwards-compatible alias:
250 + * const same = await composio.create(userId, {
251 * manageConnections: true,
252 * });
253 *
@@ -236,11 +256,7 @@ export class Composio<
256 * console.log(session.tools());
257 * ```
258 */
239 - create: (
240 - userId: string,
241 - routerConfig?: ToolRouterCreateSessionConfig,
242 - requestOptions?: ComposioRequestOptions
243 - ) => Promise<Session<unknown, unknown, TProvider>>;
259 + create: Sessions<unknown, unknown, TProvider>['create'];
260
261 /**
262 * Use an existing tool router session
@@ -253,11 +269,7 @@ export class Composio<
269 * their own per-call requestOptions.
270 * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
271 */
256 - use: (
257 - id: string,
258 - options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] },
259 - requestOptions?: ComposioRequestOptions
260 - ) => Promise<Session<unknown, unknown, TProvider>>;
272 + use: Sessions<unknown, unknown, TProvider>['use'];
273
274 /**
275 * Creates a new instance of the Composio SDK.
@@ -349,14 +361,18 @@ export class Composio<
361 });
362 this.connectedAccounts = new ConnectedAccounts(this.client);
363 this.experimental = new Experimental(this.client);
352 - this.toolRouter = new ToolRouter(this.client, this.config);
364 + this.sessions = new Sessions(this.client, this.config);
365 + this.toolRouter = this.sessions;
366
367 /**
355 - * Initialize tool router methods
356 - * Properly bind the methods to maintain the correct 'this' context
368 + * Initialize session aliases.
369 + * Properly bind the methods to maintain the correct 'this' context.
370 */
358 - this.create = this.toolRouter.create.bind(this.toolRouter);
359 - this.use = this.toolRouter.use.bind(this.toolRouter);
371 + // Cast: Function.prototype.bind collapses the create/use overloads to a
372 + // single signature; re-assert the overloaded type. Runtime behaviour is
373 + // unchanged — bind only rebinds `this`.
374 + this.create = this.sessions.create.bind(this.sessions) as Composio<TProvider>['create'];
375 + this.use = this.sessions.use.bind(this.sessions) as Composio<TProvider>['use'];
376
377 /**
378 * Initialize the client telemetry.
@@ -424,7 +440,9 @@ export class Composio<
440 * The new instance inherits all configuration from the parent instance (apiKey, baseURL, provider, etc.)
441 * but allows you to specify custom request options that will be used for all API calls made through this session.
442 *
427 - * @deprecated DEPRECATED: This method will be removed in a future version of the SDK.
443 + * @deprecated Will be removed in a future version of the SDK. Instead, construct a new
444 + * instance directly with the headers you need: `new Composio({ ...existingConfig, defaultHeaders })`.
445 + * For one-off overrides, pass per-call `requestOptions` where supported.
446 *
447 * @param {MergedRequestInit} fetchOptions - Custom request options to be used for all API calls in this session.
448 * This follows the Fetch API RequestInit interface with additional options.
ts/packages/core/src/errors/ConnectedAccountsErrors.ts
+2 -2
@@ -74,7 +74,7 @@ export class ComposioSharedAccessDeniedError extends ComposioError {
74 code: ConnectedAccountErrorCodes.SHARED_ACCESS_DENIED,
75 statusCode: 403,
76 possibleFixes: options.possibleFixes || [
77 - "Ask the connection's creator to grant access via composio.experimental.updateAcl() — set allowAllUsers, add the userId to allowedUserIds, or remove it from notAllowedUserIds.",
77 + "Ask the connection's creator to grant access via composio.connectedAccounts.updateAcl() — set allowAllUsers, add the userId to allowedUserIds, or remove it from notAllowedUserIds.",
78 ],
79 });
80 this.name = 'ComposioSharedAccessDeniedError';
@@ -119,7 +119,7 @@ export class ComposioSharedConnectionNotAccessibleError extends ComposioError {
119 code: ConnectedAccountErrorCodes.SHARED_CONNECTION_NOT_ACCESSIBLE,
120 statusCode: 400,
121 possibleFixes: options.possibleFixes || [
122 - 'Grant the session user access via composio.experimental.updateAcl() on the pinned connection, or pin a different connection the user can use.',
122 + 'Grant the session user access via composio.connectedAccounts.updateAcl() on the pinned connection, or pin a different connection the user can use.',
123 ],
124 });
125 this.name = 'ComposioSharedConnectionNotAccessibleError';
ts/packages/core/src/experimental/index.ts
+15 -4
@@ -1,12 +1,23 @@
1 /**
2 - * Experimental APIs for @composio/core.
2 + * Experimental APIs for `@composio/core`, exposed on the
3 + * `@composio/core/experimental` subpath. **Experimental — shape may change in
4 + * future releases.**
5 *
4 - * @deprecated Import from '@composio/core' instead:
5 - * import { experimental_createTool, experimental_createToolkit } from '@composio/core';
6 + * The stateless tool/toolkit factories (`experimental_createTool`,
7 + * `experimental_createToolkit`) are ALSO re-exported from the package root, so
8 + * for those prefer the shorter import:
9 + * `import { experimental_createTool, experimental_createToolkit } from '@composio/core';`
10 + *
11 + * The experimental local workbench helpers now live in the standalone
12 + * `@composio/experimental` package, on the `@composio/experimental/workbench`
13 + * subpath — they are no longer part of `@composio/core`.
14 */
15
16 // Re-export for backward compatibility with existing code
9 -export { createCustomTool as experimental_createTool, createCustomToolkit as experimental_createToolkit } from '../models/CustomTool';
17 +export {
18 + createCustomTool as experimental_createTool,
19 + createCustomToolkit as experimental_createToolkit,
20 +} from '../models/CustomTool';
21 export type {
22 CustomTool,
23 CreateCustomToolParams,
ts/packages/core/src/index.ts
+5 -4
@@ -27,6 +27,7 @@ export { MCP } from './models/MCP';
27 export { RemoteFile } from './models/RemoteFile';
28 export { createConnectionRequest } from './models/ConnectionRequest';
29 export { ToolRouterSession } from './models/ToolRouterSession';
30 +export { Sessions } from './models/Sessions';
31 export * from './types/provider.types';
32 export * from './types/customTool.types';
33 export * from './types/tool.types';
@@ -53,10 +54,10 @@ export { createCustomTool as experimental_createTool } from './models/CustomTool
54 export { createCustomToolkit as experimental_createToolkit } from './models/CustomTool';
55
56 // Experimental shared connected accounts — shape may change in future releases.
56 -// `updateAcl` is mounted as a method on `composio.experimental.updateAcl(...)`
57 -// because it takes a client and performs I/O. The `Experimental` class
58 -// itself is re-exported so callers can type their own composio handles
59 -// (e.g. in test helpers).
57 +// Prefer `composio.connectedAccounts.updateAcl(...)`; the experimental
58 +// namespace keeps `composio.experimental.updateAcl(...)` as an alias while
59 +// the API is experimental. The `Experimental` class itself is re-exported
60 +// so callers can type their own composio handles (e.g. in test helpers).
61 export { Experimental } from './models/Experimental';
62
63 // Error handling exports
ts/packages/core/src/lib/toolRouterParams.ts
+36 -17
@@ -13,6 +13,7 @@ import {
13 ToolRouterToolkitsDisabledConfigSchema,
14 ToolRouterToolkitsEnabledConfigSchema,
15 ToolRouterUpdateSessionConfig,
16 + ToolRouterSandboxConfig,
17 } from '../types/toolRouter.types';
18 import { ValidationError } from '../errors';
19 import { z } from 'zod';
@@ -115,8 +116,19 @@ export const transformToolRouterManageConnectionsParams = (
116 };
117 };
118
118 -export const transformToolRouterWorkbenchParams = (
119 - params?: ToolRouterCreateSessionConfig['workbench']
119 +export const resolveToolRouterSandboxConfig = (
120 + config: Pick<ToolRouterCreateSessionConfig, 'sandbox' | 'workbench'>
121 +): ToolRouterCreateSessionConfig['sandbox'] | ToolRouterCreateSessionConfig['workbench'] => {
122 + if (config.sandbox !== undefined && config.workbench !== undefined) {
123 + throw new ValidationError(
124 + 'Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.'
125 + );
126 + }
127 + return config.sandbox ?? config.workbench;
128 +};
129 +
130 +export const transformToolRouterSandboxParams = (
131 + params?: ToolRouterCreateSessionConfig['sandbox'] | ToolRouterCreateSessionConfig['workbench']
132 ): SessionCreateParams.Workbench | undefined => {
133 if (!params) {
134 return undefined;
@@ -130,6 +142,9 @@ export const transformToolRouterWorkbenchParams = (
142 };
143 };
144
145 +/** @deprecated Renamed — use `transformToolRouterSandboxParams` instead. `workbench` is a backwards-compatible alias for `sandbox`. */
146 +export const transformToolRouterWorkbenchParams = transformToolRouterSandboxParams;
147 +
148 /**
149 * PATCH-safe variant of transformToolRouterManageConnectionsParams.
150 * Does NOT apply defaults — only includes fields explicitly present in the input.
@@ -163,16 +178,11 @@ export const transformToolRouterUpdateManageConnectionsParams = (
178 };
179
180 /**
166 - * PATCH-safe variant of transformToolRouterWorkbenchParams.
181 + * PATCH-safe variant of transformToolRouterSandboxParams.
182 * Does NOT apply `enable ?? true` default — only includes fields explicitly present.
183 */
169 -export const transformToolRouterUpdateWorkbenchParams = (
170 - params: {
171 - enable?: boolean;
172 - enableProxyExecution?: boolean;
173 - autoOffloadThreshold?: number;
174 - sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge';
175 - }
184 +export const transformToolRouterUpdateSandboxParams = (
185 + params: Partial<ToolRouterSandboxConfig>
186 ): SessionPatchParams.Workbench => {
187 const result: Record<string, unknown> = {};
188 if (params.enable !== undefined) {
@@ -190,6 +200,9 @@ export const transformToolRouterUpdateWorkbenchParams = (
200 return result as SessionPatchParams.Workbench;
201 };
202
203 +/** @deprecated Renamed — use `transformToolRouterUpdateSandboxParams` instead. `workbench` is a backwards-compatible alias for `sandbox`. */
204 +export const transformToolRouterUpdateWorkbenchParams = transformToolRouterUpdateSandboxParams;
205 +
206 export const transformToolRouterMultiAccountParams = (
207 params?: ToolRouterCreateSessionConfig['multiAccount']
208 ): SessionCreateParams.MultiAccount | undefined => {
@@ -200,7 +213,8 @@ export const transformToolRouterMultiAccountParams = (
213 const transformedParams = {
214 enable: params.enable,
215 max_accounts_per_toolkit: params.maxAccountsPerToolkit,
203 - require_explicit_selection: params.requireExplicitSelection ?? (params.enable ? true : undefined),
216 + require_explicit_selection:
217 + params.requireExplicitSelection ?? (params.enable ? true : undefined),
218 };
219
220 if (
@@ -258,14 +272,17 @@ export const transformToolRouterUpdateParams = (
272 if (config.manageConnections === null) {
273 params.manage_connections = null;
274 } else {
261 - params.manage_connections = transformToolRouterUpdateManageConnectionsParams(config.manageConnections);
275 + params.manage_connections = transformToolRouterUpdateManageConnectionsParams(
276 + config.manageConnections
277 + );
278 }
279 }
264 - if (config.workbench !== undefined) {
265 - if (config.workbench === null) {
280 + const sandboxConfig = config.sandbox !== undefined ? config.sandbox : config.workbench;
281 + if (sandboxConfig !== undefined) {
282 + if (sandboxConfig === null) {
283 params.workbench = null;
284 } else {
268 - params.workbench = transformToolRouterUpdateWorkbenchParams(config.workbench);
285 + params.workbench = transformToolRouterUpdateSandboxParams(sandboxConfig);
286 }
287 }
288 if (config.multiAccount !== undefined) {
@@ -274,8 +291,10 @@ export const transformToolRouterUpdateParams = (
291 } else {
292 const ma: Record<string, unknown> = {};
293 if (config.multiAccount.enable !== undefined) ma.enable = config.multiAccount.enable;
277 - if (config.multiAccount.maxAccountsPerToolkit !== undefined) ma.max_accounts_per_toolkit = config.multiAccount.maxAccountsPerToolkit;
278 - if (config.multiAccount.requireExplicitSelection !== undefined) ma.require_explicit_selection = config.multiAccount.requireExplicitSelection;
294 + if (config.multiAccount.maxAccountsPerToolkit !== undefined)
295 + ma.max_accounts_per_toolkit = config.multiAccount.maxAccountsPerToolkit;
296 + if (config.multiAccount.requireExplicitSelection !== undefined)
297 + ma.require_explicit_selection = config.multiAccount.requireExplicitSelection;
298 params.multi_account = ma as SessionPatchParams.MultiAccount;
299 }
300 }
ts/packages/core/src/models/ConnectedAccounts.ts
+49 -6
@@ -13,6 +13,7 @@ import {
13 ConnectedAccountRefreshResponse,
14 ConnectedAccountUpdateStatusParams,
15 ConnectedAccountUpdateStatusResponse,
16 + ConnectedAccountPatchResponse,
17 ConnectedAccountListParams as ConnectedAccountListParamsRaw,
18 ConnectedAccountCreateParams as ConnectedAccountCreateParamsRaw,
19 } from '@composio/client/resources/connected-accounts';
@@ -28,12 +29,17 @@ import {
29 ConnectedAccountStatuses,
30 ConnectedAccountRefreshOptions,
31 ConnectedAccountRefreshOptionsSchema,
32 + UpdateConnectedAccountAclParams,
33 UpdateConnectedAccountParams,
34 UpdateConnectedAccountParamsSchema,
35 } from '../types/connectedAccounts.types';
36 import { ConnectionRequest } from '../types/connectionRequest.types';
37 import { createConnectionRequest } from './ConnectionRequest';
36 -import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from './Experimental';
38 +import {
39 + ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT,
40 + serializeExperimentalForWire,
41 + updateConnectedAccountAcl,
42 +} from './Experimental';
43 import { ValidationError } from '../errors/ValidationErrors';
44 import { telemetry } from '../telemetry/Telemetry';
45 import {
@@ -337,7 +343,7 @@ export class ConnectedAccounts {
343 *
344 * @param userId {string} - The external user ID to create the connected account for.
345 * @param authConfigId {string} - The auth config ID to create the connected account for.
340 - * @param options {CreateConnectedAccountOptions} - Options for creating a new connected account.
346 + * @param options {CreateConnectedAccountLinkOptions} - Options for creating a new connected account link.
347 * @param options.callbackUrl {string} - The url to redirect the user to post connecting their account.
348 * @returns {ConnectionRequest} Connection request object
349 *
@@ -378,6 +384,8 @@ export class ConnectedAccounts {
384 });
385 }
386
387 + const opts = parsedLinkOptions.data;
388 +
389 // Mirror initiate(): guard against silently creating extra connections on
390 // the same auth config unless the caller explicitly opts in. The preflight
391 // list call honors the caller's signal too — the whole composite is
@@ -390,7 +398,7 @@ export class ConnectedAccounts {
398 },
399 requestOptions
400 );
393 - if (existing.items.length > 0 && !parsedLinkOptions.data.allowMultiple) {
401 + if (existing.items.length > 0 && !opts.allowMultiple) {
402 throw new ComposioMultipleConnectedAccountsError(
403 `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`
404 );
@@ -400,7 +408,6 @@ export class ConnectedAccounts {
408 );
409 }
410
403 - const opts = parsedLinkOptions.data;
411 const experimentalWire = serializeExperimentalForWire(opts.experimental);
412 const body: LinkCreateParams = {
413 auth_config_id: authConfigId,
@@ -656,11 +663,47 @@ export class ConnectedAccounts {
663 );
664 }
665
666 + /**
667 + * Update the per-user ACL on a SHARED connected account.
668 + * **Experimental — shape may change in future releases.**
669 + *
670 + * Only meaningful for SHARED connections — calling this on a PRIVATE
671 + * connection raises `ComposioAclOnlyForSharedError` (400). ACL writes
672 + * require the connection's creator or an API key.
673 + *
674 + * PATCH semantics: omit a field to leave it unchanged; pass an empty
675 + * array to clear an allow/deny list. At least one field must be
676 + * provided.
677 + *
678 + * @param {string} nanoid - The unique identifier of the connected account
679 + * @param {UpdateConnectedAccountAclParams} params - The ACL fields to patch
680 + * @returns {Promise<ConnectedAccountPatchResponse>} The PATCH response
681 + *
682 + * @example
683 + * ```typescript
684 + * // Allow every userId to use this SHARED connection
685 + * await composio.connectedAccounts.updateAcl('ca_abc123', { allowAllUsers: true });
686 + *
687 + * // Targeted allow list
688 + * await composio.connectedAccounts.updateAcl('ca_abc123', {
689 + * allowedUserIds: ['user_alice', 'user_bob'],
690 + * });
691 + *
692 + * // Clear the allow list (back to deny-by-default unless allowAllUsers is true)
693 + * await composio.connectedAccounts.updateAcl('ca_abc123', { allowedUserIds: [] });
694 + * ```
695 + */
696 + async updateAcl(
697 + nanoid: string,
698 + params: UpdateConnectedAccountAclParams
699 + ): Promise<ConnectedAccountPatchResponse> {
700 + return updateConnectedAccountAcl(this.client, nanoid, params);
701 + }
702 +
703 /**
704 * Enable or disable a connected account. Accepts `{ enabled: boolean }`.
705 *
662 - * For ACL writes on SHARED connections, see
663 - * `composio.experimental.updateAcl()`.
706 + * Use `updateAcl()` for ACL writes on SHARED connections.
707 *
708 * @param {string} nanoid - The unique identifier of the connected account
709 * @param {UpdateConnectedAccountParams} params - The update parameters
ts/packages/core/src/models/Experimental.ts
+51 -39
@@ -2,9 +2,11 @@
2 * @fileoverview The `composio.experimental` namespace. Houses experimental
3 * SDK methods whose shape may change in future releases.
4 *
5 - * For experimental stateless factories (e.g. `experimental_createTool`),
6 - * see the top-level `experimental_*` exports from `@composio/core`.
7 - * Anything that takes a Composio client and performs I/O belongs here.
5 + * Domain-specific mounts remain preferred when they exist (for example
6 + * `composio.connectedAccounts.updateAcl(...)`). This namespace keeps
7 + * compatibility aliases while those APIs are experimental. For experimental
8 + * stateless factories (e.g. `experimental_createTool`), see the top-level
9 + * `experimental_*` exports from `@composio/core`.
10 */
11 import ComposioClient, { BadRequestError } from '@composio/client';
12 import {
@@ -22,10 +24,9 @@ import { telemetry } from '../telemetry/Telemetry';
24
25 /**
26 * Server-side 400 message the API uses to reject ACL writes against a
25 - * PRIVATE connection. Substring-matched in `updateAcl` here, and in the
26 - * sibling `connectedAccounts.link()` / `session.authorize()` call sites
27 - * — kept as a single constant so a server-side message tweak only
28 - * requires one edit.
27 + * PRIVATE connection. Substring-matched in `updateAcl` and in the sibling
28 + * `connectedAccounts.link()` / `session.authorize()` call sites — kept as
29 + * a single constant so a server-side message tweak only requires one edit.
30 */
31 export const ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT = 'acl_config_for_shared is only valid on SHARED';
32
@@ -89,10 +90,42 @@ export function serializeExperimentalForWire(
90 }
91
92 /**
92 - * `composio.experimental` namespace. Mirrors the Python SDK's
93 - * `composio.experimental` mount, with one method per experimental
94 - * surface. **Shape may change in future releases.**
93 + * `composio.experimental` namespace. Keeps compatibility aliases for
94 + * experimental surfaces while domain-specific mounts graduate. **Shape may
95 + * change in future releases.**
96 */
97 +export async function updateConnectedAccountAcl(
98 + client: ComposioClient,
99 + nanoid: string,
100 + params: UpdateConnectedAccountAclParams
101 +): Promise<ConnectedAccountPatchResponse> {
102 + const parsedParams = UpdateConnectedAccountAclParamsSchema.safeParse(params);
103 + if (!parsedParams.success) {
104 + throw new ValidationError('Failed to parse connected account ACL update params', {
105 + cause: parsedParams.error,
106 + });
107 + }
108 +
109 + const body: ConnectedAccountPatchParams = {
110 + experimental: {
111 + acl_config_for_shared: serializeAclConfigForWire(parsedParams.data),
112 + },
113 + };
114 +
115 + try {
116 + return await client.connectedAccounts.patch(nanoid, body);
117 + } catch (error) {
118 + if (
119 + error instanceof BadRequestError &&
120 + typeof error.message === 'string' &&
121 + error.message.includes(ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT)
122 + ) {
123 + throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
124 + }
125 + throw error;
126 + }
127 +}
128 +
129 export class Experimental {
130 private client: ComposioClient;
131
@@ -102,6 +135,7 @@ export class Experimental {
135 }
136
137 /**
138 + * Compatibility alias for `composio.connectedAccounts.updateAcl(...)`.
139 * Update the per-user ACL on a SHARED connected account.
140 * **Experimental — shape may change in future releases.**
141 *
@@ -126,21 +160,21 @@ export class Experimental {
160 * const composio = new Composio({ apiKey: '...' });
161 *
162 * // Allow every userId to use this connection
129 - * await composio.experimental.updateAcl('ca_abc', { allowAllUsers: true });
163 + * await composio.connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true });
164 *
165 * // Everyone except a specific user
132 - * await composio.experimental.updateAcl('ca_abc', {
166 + * await composio.connectedAccounts.updateAcl('ca_abc', {
167 * allowAllUsers: true,
168 * notAllowedUserIds: ['user_bob'],
169 * });
170 *
171 * // Targeted allow
138 - * await composio.experimental.updateAcl('ca_abc', {
172 + * await composio.connectedAccounts.updateAcl('ca_abc', {
173 * allowedUserIds: ['user_alice', 'user_bob'],
174 * });
175 *
176 * // Revoke a previously-granted allow list (back to deny-by-default)
143 - * await composio.experimental.updateAcl('ca_abc', { allowedUserIds: [] });
177 + * await composio.connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
178 * ```
179 *
180 * **Empty-array semantics — read carefully.** Passing `[]` for either
@@ -156,35 +190,13 @@ export class Experimental {
190 * the updated ACL block, call
191 * `composio.connectedAccounts.get(nanoid)` after the promise
192 * resolves and inspect `account.experimental?.aclConfigForShared`.
193 + *
194 + * @deprecated Use `composio.connectedAccounts.updateAcl(...)` instead — ACL updates graduated onto the `connectedAccounts` mount. This experimental alias is kept only for backwards compatibility and will be removed once the API graduates. Prefer the `connectedAccounts` mount; do not generate new code against this alias.
195 */
196 async updateAcl(
197 nanoid: string,
198 params: UpdateConnectedAccountAclParams
199 ): Promise<ConnectedAccountPatchResponse> {
164 - const parsedParams = UpdateConnectedAccountAclParamsSchema.safeParse(params);
165 - if (!parsedParams.success) {
166 - throw new ValidationError('Failed to parse connected account ACL update params', {
167 - cause: parsedParams.error,
168 - });
169 - }
170 -
171 - const body: ConnectedAccountPatchParams = {
172 - experimental: {
173 - acl_config_for_shared: serializeAclConfigForWire(parsedParams.data),
174 - },
175 - };
176 -
177 - try {
178 - return await this.client.connectedAccounts.patch(nanoid, body);
179 - } catch (error) {
180 - if (
181 - error instanceof BadRequestError &&
182 - typeof error.message === 'string' &&
183 - error.message.includes(ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT)
184 - ) {
185 - throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
186 - }
187 - throw error;
188 - }
200 + return updateConnectedAccountAcl(this.client, nanoid, params);
201 }
202 }
ts/packages/core/src/models/MCP.ts
+6
@@ -44,6 +44,12 @@ function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveRespo
44 * MCP (Model Control Protocol) class
45 * Handles MCP server operations.
46 * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
47 + *
48 + * @deprecated Use a session's MCP endpoint instead: `composio.create(userId, { mcp: true })`
49 + * returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now
50 + * opt-in per session; the standalone `composio.mcp` server-management API is kept only for
51 + * backwards compatibility. Prefer the session MCP endpoint; do not generate new code against
52 + * `composio.mcp`. See https://docs.composio.dev/docs/sessions-via-mcp
53 */
54 export class MCP {
55 client: ComposioClient;
ts/packages/core/src/models/SessionContext.ts
+5
@@ -36,6 +36,11 @@ import { withCancellation } from '../utils/cancellation';
36 * When `customToolsMap` is provided, `execute()` checks local tools first
37 * before falling back to the backend API. This allows tool A to call tool B
38 * via `session.execute('B', ...)` without hitting the network.
39 + *
40 + * @internal Internal implementation detail. Not exported from `@composio/core`
41 + * and not part of the public API surface — custom tools receive a
42 + * `SessionContext` instance via their execute function; they never reference
43 + * this class directly. Excluded from the generated SDK reference.
44 */
45 export class SessionContextImpl implements SessionContext {
46 public readonly userId: string;
ts/packages/core/src/models/Sessions.ts new
+21
@@ -0,0 +1,21 @@
1 +import type { Composio as ComposioClient } from '@composio/client';
2 +import type { BaseComposioProvider } from '../provider/BaseProvider';
3 +import type { ComposioConfig } from '../composio';
4 +import { ToolRouter } from './ToolRouter';
5 +
6 +/**
7 + * First-class API for creating and reusing Composio sessions.
8 + *
9 + * `composio.sessions.create(...)` is the canonical session creation entrypoint.
10 + * The top-level `composio.create(...)` method remains as a backwards-compatible
11 + * alias for `composio.sessions.create(...)`.
12 + */
13 +export class Sessions<
14 + TToolCollection,
15 + TTool,
16 + TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
17 +> extends ToolRouter<TToolCollection, TTool, TProvider> {
18 + constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
19 + super(client, config);
20 + }
21 +}
ts/packages/core/src/models/ToolRouter.ts
+39 -9
@@ -9,7 +9,7 @@
9 * const composio = new Composio();
10 * const userId = 'user_123';
11 *
12 - * const session = await composio.experimental.create(userId, {
12 + * const session = await composio.sessions.create(userId, {
13 * toolkits: ['gmail'],
14 * manageConnections: true
15 * });
@@ -19,12 +19,12 @@
19 */
20 import { Composio as ComposioClient } from '@composio/client';
21 import { telemetry } from '../telemetry/Telemetry';
22 -import { BaseComposioProvider } from '../provider/BaseProvider';
23 -import { ComposioConfig } from '../composio';
22 +import type { BaseComposioProvider } from '../provider/BaseProvider';
23 +import type { ComposioConfig } from '../composio';
24 import {
25 ToolRouterCreateSessionConfig,
26 Session,
27 - SessionExperimental,
27 + SessionWithoutMcp,
28 MCPServerType,
29 ToolRouterMCPServerConfig,
30 ToolRouterSessionMetadata,
@@ -46,9 +46,10 @@ import {
46 transformToolRouterTagsParams,
47 transformToolRouterToolsParams,
48 transformToolRouterManageConnectionsParams,
49 - transformToolRouterWorkbenchParams,
49 + transformToolRouterSandboxParams,
50 transformToolRouterToolkitsParams,
51 transformToolRouterMultiAccountParams,
52 + resolveToolRouterSandboxConfig,
53 } from '../lib/toolRouterParams';
54 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
55 import { ToolRouterSession } from './ToolRouterSession';
@@ -69,6 +70,7 @@ function getSessionMetadata(
70 ) {
71 const metadata: ToolRouterSessionMetadata = {
72 preload: session.config.preload,
73 + workbench: session.config.workbench,
74 configVersion: session.config_version,
75 warnings: 'warnings' in session ? (session.warnings ?? []) : [],
76 };
@@ -157,7 +159,7 @@ export class ToolRouter<
159 *
160 * const composio = new Composio();
161 *
160 - * const session = await composio.create('user_123', {
162 + * const session = await composio.sessions.create('user_123', {
163 * toolkits: ['gmail'],
164 * manageConnections: true,
165 * experimental: {
@@ -167,6 +169,19 @@ export class ToolRouter<
169 * });
170 * ```
171 */
172 + // Overloads: passing `{ mcp: true }` surfaces `session.mcp` in the returned
173 + // type. Otherwise the MCP endpoint is omitted from the type (it still exists
174 + // at runtime). See https://docs.composio.dev/docs/sessions-via-mcp
175 + async create(
176 + userId: string,
177 + config: ToolRouterCreateSessionConfig & { mcp: true },
178 + requestOptions?: ComposioRequestOptions
179 + ): Promise<Session<TToolCollection, TTool, TProvider>>;
180 + async create(
181 + userId: string,
182 + config?: ToolRouterCreateSessionConfig,
183 + requestOptions?: ComposioRequestOptions
184 + ): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>;
185 async create(
186 userId: string,
187 config?: ToolRouterCreateSessionConfig,
@@ -203,6 +218,9 @@ export class ToolRouter<
218 }
219
220 const multiAccountPayload = transformToolRouterMultiAccountParams(routerConfig.multiAccount);
221 + const sandboxPayload = transformToolRouterSandboxParams(
222 + resolveToolRouterSandboxConfig(routerConfig)
223 + );
224
225 const connectedAccountsPayload =
226 routerConfig.connectedAccounts === undefined
@@ -224,7 +242,7 @@ export class ToolRouter<
242 manage_connections: transformToolRouterManageConnectionsParams(
243 routerConfig.manageConnections
244 ),
227 - workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),
245 + workbench: sandboxPayload,
246 multi_account: multiAccountPayload,
247 preload: routerConfig.preload,
248 ...(isDirectToolsPreset && {
@@ -280,15 +298,27 @@ export class ToolRouter<
298 *
299 * const composio = new Composio();
300 * const id = 'session_123';
283 - * const session = await composio.toolRouter.use(id);
301 + * const session = await composio.sessions.use(id);
302 *
303 * console.log(session.mcp.url);
304 * console.log(session.mcp.headers);
305 * ```
306 */
307 + // Overloads mirror `create()`: pass `{ mcp: true }` to surface `session.mcp`
308 + // in the returned type. See https://docs.composio.dev/docs/sessions-via-mcp
309 + async use(
310 + id: string,
311 + options: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp: true },
312 + requestOptions?: ComposioRequestOptions
313 + ): Promise<Session<TToolCollection, TTool, TProvider>>;
314 + async use(
315 + id: string,
316 + options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean },
317 + requestOptions?: ComposioRequestOptions
318 + ): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>;
319 async use(
320 id: string,
291 - options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] },
321 + options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean },
322 requestOptions?: ComposioRequestOptions
323 ): Promise<Session<TToolCollection, TTool, TProvider>> {
324 const customTools = options?.customTools;
ts/packages/core/src/models/ToolRouterSession.ts
+35 -3
@@ -1,8 +1,8 @@
1 import { telemetry } from '../telemetry/Telemetry';
2 import { Composio as ComposioClient, BadRequestError } from '@composio/client';
3 -import { BaseComposioProvider } from '../provider/BaseProvider';
4 -import { ComposioConfig } from '../composio';
5 -import { ComposioRequestOptions } from '../types/requestOptions.types';
3 +import type { BaseComposioProvider } from '../provider/BaseProvider';
4 +import type { ComposioConfig } from '../composio';
5 +import type { ComposioRequestOptions } from '../types/requestOptions.types';
6 import { withCancellation } from '../utils/cancellation';
7 import { ComposioRequestCancelledError } from '../errors/SDKErrors';
8 import {
@@ -18,6 +18,7 @@ import {
18 ToolRouterSessionExecuteOptions,
19 ToolRouterSessionMetadata,
20 ToolRouterSessionPreloadConfig,
21 + ToolRouterSessionWorkbenchConfig,
22 ToolRouterSessionWarning,
23 ToolRouterUpdateSessionConfig,
24 ToolRouterUpdateSessionConfigSchema,
@@ -89,15 +90,31 @@ const AuthorizeOptionsSchema = z.object({
90 experimental: ConnectedAccountExperimentalSchema.optional(),
91 });
92
93 +/**
94 + * A Composio session — the object returned by `composio.sessions.create(...)`
95 + * and `composio.sessions.use(...)` (also reachable via the top-level
96 + * `composio.create(...)` / `composio.use(...)` aliases).
97 + *
98 + * This is the canonical session surface. Use it to fetch session-scoped tools,
99 + * authorize toolkits, search, and execute tools. The public return type is
100 + * `Session` (with `mcp` surfaced, returned when `{ mcp: true }` is passed) or
101 + * `SessionWithoutMcp` (the default, with `mcp` omitted from the type); this
102 + * class is the concrete runtime form behind both.
103 + *
104 + * @see {@link Sessions} for the `composio.sessions` factory.
105 + */
106 export class ToolRouterSession<
107 TToolCollection,
108 TTool,
109 TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
110 > {
111 public readonly sessionId: string;
112 + /** Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `{ mcp: true }` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp */
113 public readonly mcp: ToolRouterMCPServerConfig;
114 public readonly experimental: SessionExperimental;
115 public preload: ToolRouterSessionPreloadConfig;
116 + /** Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. */
117 + public sandbox?: ToolRouterSessionWorkbenchConfig;
118 public configVersion?: number;
119 public warnings: ToolRouterSessionWarning[];
120 private readonly preloadedCustomToolSlugs: string[];
@@ -126,6 +143,7 @@ export class ToolRouterSession<
143 files: new ToolRouterSessionFilesMount(client, sessionId),
144 };
145 this.preload = metadata?.preload ?? { tools: [] };
146 + this.sandbox = metadata?.workbench;
147 this.configVersion = metadata?.configVersion;
148 this.warnings = metadata?.warnings ?? [];
149 this.preloadedCustomToolSlugs = metadata?.preloadedCustomToolSlugs ?? [];
@@ -145,6 +163,19 @@ export class ToolRouterSession<
163 telemetry.instrument(this, 'ToolRouterSession');
164 }
165
166 + /**
167 + * Resolved sandbox config for the session.
168 + *
169 + * @deprecated Use `session.sandbox` instead. `workbench` is a backwards-compatible alias and will be removed in a future release.
170 + */
171 + public get workbench(): ToolRouterSessionWorkbenchConfig | undefined {
172 + return this.sandbox;
173 + }
174 +
175 + public set workbench(value: ToolRouterSessionWorkbenchConfig | undefined) {
176 + this.sandbox = value;
177 + }
178 +
179 /**
180 * Get the tools available in the session, formatted for your AI framework.
181 * Requires a provider to be configured in the Composio constructor.
@@ -612,6 +643,7 @@ export class ToolRouterSession<
643 );
644 this.configVersion = response.config_version;
645 this.preload = response.config.preload;
646 + this.sandbox = response.config.workbench;
647 this.warnings = response.warnings ?? [];
648 }
649
ts/packages/core/src/models/ToolRouterSessionFileMount.ts
+5
@@ -21,6 +21,11 @@ import { platform } from '#platform';
21 import { getExtensionFromMimeType } from '../utils/mime';
22 import { getRandomShortId } from '../utils/uuid';
23
24 +/**
25 + * File mount for a Composio session, reached via `session.experimental.files`
26 + * on a session created with `composio.sessions.create(...)`. Upload, list,
27 + * download, and delete files scoped to a single session.
28 + */
29 export class ToolRouterSessionFilesMount {
30 private readonly sessionId: string;
31 private readonly client: ComposioClient;
ts/packages/core/src/models/Tools.ts
+6 -12
@@ -37,7 +37,7 @@ import {
37 ProviderOptions,
38 TransformToolSchemaModifier,
39 } from '../types/modifiers.types';
40 -import { BaseComposioProvider } from '../provider/BaseProvider';
40 +import type { BaseComposioProvider } from '../provider/BaseProvider';
41 import logger from '../utils/logger';
42 import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
43 import {
@@ -48,7 +48,7 @@ import {
48 } from '../errors/ToolErrors';
49 import { ValidationError } from '../errors/ValidationErrors';
50 import { telemetry } from '../telemetry/Telemetry';
51 -import { ComposioConfig } from '../composio';
51 +import type { ComposioConfig } from '../composio';
52 import { getToolkitVersion } from '../utils/toolkitVersion';
53 import { handleToolExecutionError } from '../errors/ToolErrors';
54 import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
@@ -908,11 +908,8 @@ export class Tools<
908 }
909 : undefined,
910 /**
911 - * @deprecated: customConnectionData
912 - * @description
913 - * This parameter is deprecated and will be removed in the future.
914 - * Please use custom_connection_data instead.
915 - *
911 + * @deprecated The `customConnectionData` execute param is deprecated and will be
912 + * removed in a future release. Use `customAuthParams` instead.
913 */
914 custom_connection_data:
915 body.customConnectionData as ComposioToolExecuteParams['custom_connection_data'],
@@ -1249,11 +1246,8 @@ export class Tools<
1246 connected_account_id: toolProxyParams.data.connectedAccountId,
1247 parameters: parameters,
1248 /**
1252 - * @deprecated: customConnectionData
1253 - * @description
1254 - * This parameter is deprecated and will be removed in the future.
1255 - * Please use custom_auth_params instead.
1256 - *
1249 + * @deprecated The `customConnectionData` proxy param is deprecated and will be
1250 + * removed in a future release. Use `customAuthParams` instead.
1251 */
1252 // @ts-ignore
1253 custom_connection_data: toolProxyParams.data.customConnectionData,
ts/packages/core/src/models/Triggers.ts
+322 -2
@@ -24,6 +24,8 @@ import {
24 VerifyWebhookParams,
25 VerifyWebhookParamsSchema,
26 VerifyWebhookResult,
27 + ParseWebhookOptions,
28 + WebhookRequestLike,
29 WebhookPayload,
30 WebhookPayloadV1Schema,
31 WebhookPayloadV2Schema,
@@ -31,6 +33,10 @@ import {
33 WebhookTriggerPayloadV3Schema,
34 WebhookVersion,
35 WebhookVersions,
36 + DefaultWebhookSubscriptionEvents,
37 + SetWebhookSubscriptionParams,
38 + SetWebhookSubscriptionParamsSchema,
39 + WebhookSubscription,
40 } from '../types/triggers.types';
41 import logger from '../utils/logger';
42 import { telemetry } from '../telemetry/Telemetry';
@@ -49,8 +55,8 @@ import {
55 transformTriggerTypeRetrieveResponse,
56 } from '../utils/transformers/triggers';
57 import { ToolkitVersionParam } from '../types/tool.types';
52 -import { ComposioConfig } from '../composio';
53 -import { BaseComposioProvider } from '../provider/BaseProvider';
58 +import type { ComposioConfig } from '../composio';
59 +import type { BaseComposioProvider } from '../provider/BaseProvider';
60 import { hmacSha256Base64, timingSafeEqual } from '../utils/crypto';
61 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
62 import { ComposioRequestOptions } from '../types/requestOptions.types';
@@ -69,6 +75,134 @@ const toStringOrDefault = (value: unknown, defaultValue: string): string => {
75 return str.length > 0 ? str : defaultValue;
76 };
77
78 +const WEBHOOK_SUBSCRIPTIONS_PATH = '/api/v3.1/webhook_subscriptions';
79 +
80 +type RawWebhookSubscription = Record<string, unknown> & {
81 + id?: unknown;
82 + webhook_url?: unknown;
83 + webhookUrl?: unknown;
84 + version?: unknown;
85 + enabled_events?: unknown;
86 + enabledEvents?: unknown;
87 + secret?: unknown;
88 + created_at?: unknown;
89 + createdAt?: unknown;
90 + updated_at?: unknown;
91 + updatedAt?: unknown;
92 +};
93 +
94 +type RawWebhookSubscriptionListResponse = Record<string, unknown> & {
95 + items?: unknown;
96 +};
97 +
98 +const asRecord = (value: unknown): Record<string, unknown> =>
99 + value !== null && typeof value === 'object' && !Array.isArray(value)
100 + ? (value as Record<string, unknown>)
101 + : {};
102 +
103 +const firstString = (value: unknown): string | undefined =>
104 + typeof value === 'string' && value.length > 0 ? value : undefined;
105 +
106 +const stringArray = (value: unknown): string[] =>
107 + Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
108 +
109 +const transformWebhookSubscription = (subscription: unknown): WebhookSubscription => {
110 + const raw = asRecord(subscription) as RawWebhookSubscription;
111 +
112 + // Map to camelCase explicitly — do NOT spread `...raw`, or the response's
113 + // snake_case keys (webhook_url, enabled_events, created_at, ...) leak into the
114 + // public object alongside their camelCase counterparts.
115 + return {
116 + id: firstString(raw.id) ?? '',
117 + webhookUrl: firstString(raw.webhook_url) ?? firstString(raw.webhookUrl) ?? '',
118 + version: (firstString(raw.version) ?? WebhookVersions.V3) as WebhookVersion,
119 + enabledEvents: stringArray(raw.enabled_events).length
120 + ? stringArray(raw.enabled_events)
121 + : stringArray(raw.enabledEvents),
122 + secret: firstString(raw.secret),
123 + createdAt: firstString(raw.created_at) ?? firstString(raw.createdAt),
124 + updatedAt: firstString(raw.updated_at) ?? firstString(raw.updatedAt),
125 + };
126 +};
127 +
128 +const firstWebhookSubscriptionId = (
129 + response: RawWebhookSubscriptionListResponse
130 +): string | undefined => {
131 + const firstItem = Array.isArray(response.items) ? response.items[0] : undefined;
132 + return firstString(asRecord(firstItem).id);
133 +};
134 +
135 +/**
136 + * The signature header names Composio sends with every webhook delivery.
137 + * @private
138 + */
139 +const WEBHOOK_HEADERS = {
140 + id: 'webhook-id',
141 + timestamp: 'webhook-timestamp',
142 + signature: 'webhook-signature',
143 +} as const;
144 +
145 +/**
146 + * Returns true if the value is a Fetch API `Request`.
147 + * @private
148 + */
149 +const isFetchRequest = (request: WebhookRequestLike): request is Request =>
150 + typeof Request !== 'undefined' && request instanceof Request;
151 +
152 +/**
153 + * Reads a single header value case-insensitively from either a `Headers`
154 + * instance or a plain record (where values may be `string | string[]`).
155 + * Returns `undefined` when the header is missing.
156 + * @private
157 + */
158 +const getHeader = (headers: unknown, name: string): string | undefined => {
159 + if (typeof Headers !== 'undefined' && headers instanceof Headers) {
160 + return headers.get(name) ?? undefined;
161 + }
162 +
163 + if (headers === null || typeof headers !== 'object') {
164 + return undefined;
165 + }
166 +
167 + // Plain record: match the header name case-insensitively.
168 + const target = name.toLowerCase();
169 + for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {
170 + if (key.toLowerCase() !== target) {
171 + continue;
172 + }
173 + if (Array.isArray(value)) {
174 + const first = value.find((item): item is string => typeof item === 'string');
175 + return first;
176 + }
177 + return typeof value === 'string' ? value : undefined;
178 + }
179 + return undefined;
180 +};
181 +
182 +/**
183 + * Coerces an object request body (string, Buffer/Uint8Array, or already-parsed
184 + * value) into the raw string form expected by signature verification.
185 + * @private
186 + */
187 +const bodyToString = (body: unknown): string => {
188 + if (typeof body === 'string') {
189 + return body;
190 + }
191 + if (body instanceof Uint8Array) {
192 + return new TextDecoder().decode(body);
193 + }
194 + if (body === null || body === undefined) {
195 + return '';
196 + }
197 + // Already-parsed object (e.g. Next.js Pages Router with the JSON body parser).
198 + // Note: re-stringifying cannot reproduce the exact bytes Composio signed, so
199 + // signature verification on a pre-parsed body is best-effort only.
200 + if (typeof body === 'object') {
201 + return JSON.stringify(body);
202 + }
203 + return String(body);
204 +};
205 +
206 /**
207 * Trigger (Instance) class
208 * /api/v3/trigger_instances
@@ -86,6 +220,50 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
220 telemetry.instrument(this, 'Triggers');
221 }
222
223 + /**
224 + * Create or update the project webhook subscription used for webhook delivery.
225 + *
226 + * If a subscription already exists, the first subscription is updated. Otherwise a new
227 + * subscription is created. By default this subscribes to V3 trigger message events.
228 + *
229 + * @example
230 + * ```ts
231 + * await composio.triggers.setWebhookSubscription({
232 + * webhookUrl: `${APP_URL}/webhooks/composio`,
233 + * });
234 + * ```
235 + */
236 + async setWebhookSubscription(params: SetWebhookSubscriptionParams): Promise<WebhookSubscription> {
237 + const parsedParams = SetWebhookSubscriptionParamsSchema.safeParse(params);
238 +
239 + if (!parsedParams.success) {
240 + throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {
241 + cause: parsedParams.error,
242 + });
243 + }
244 +
245 + const body = {
246 + webhook_url: parsedParams.data.webhookUrl,
247 + enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],
248 + version: parsedParams.data.version ?? WebhookVersions.V3,
249 + };
250 +
251 + const existing = await this.client.get<RawWebhookSubscriptionListResponse>(
252 + WEBHOOK_SUBSCRIPTIONS_PATH,
253 + { query: { limit: 1 } }
254 + );
255 + const subscriptionId = firstWebhookSubscriptionId(existing);
256 +
257 + const subscription = subscriptionId
258 + ? await this.client.patch<RawWebhookSubscription>(
259 + `${WEBHOOK_SUBSCRIPTIONS_PATH}/${encodeURIComponent(subscriptionId)}`,
260 + { body }
261 + )
262 + : await this.client.post<RawWebhookSubscription>(WEBHOOK_SUBSCRIPTIONS_PATH, { body });
263 +
264 + return transformWebhookSubscription(subscription);
265 + }
266 +
267 /**
268 * Fetch list of all the active triggers
269 *
@@ -662,6 +840,148 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
840 await this.pusherService.unsubscribe();
841 }
842
843 + /**
844 + * Parse an incoming webhook HTTP request into a typed, normalized trigger payload.
845 + *
846 + * Dump the incoming request in and get back the parsed Composio trigger event.
847 + * When `verifySecret` is provided, the request signature is verified before the
848 + * payload is returned (delegating to {@link verifyWebhook}); without it, the body
849 + * is parsed without verification.
850 + *
851 + * The `request` may be either a Fetch API `Request` (Next.js App Router, Hono,
852 + * Remix) or a plain `{ body, headers }` object (Express with `express.raw`,
853 + * Next.js Pages Router `req`). The signature headers (`webhook-id`,
854 + * `webhook-timestamp`, `webhook-signature`) are read case-insensitively.
855 + *
856 + * @param {WebhookRequestLike} request - The incoming webhook HTTP request
857 + * @param {ParseWebhookOptions} [options] - Parse options
858 + * @param {string} [options.verifySecret] - Webhook secret; when set, the signature is verified
859 + * @param {number} [options.tolerance=300] - Max webhook age in seconds (only used when verifying)
860 + * @returns {Promise<VerifyWebhookResult>} The parsed (and optionally verified) webhook payload
861 + *
862 + * @throws {ValidationError} If `verifySecret` is set but the signature headers are missing
863 + * @throws {ComposioWebhookSignatureVerificationError} If signature verification fails
864 + * @throws {ComposioWebhookPayloadError} If the payload cannot be parsed
865 + *
866 + * @example
867 + * ```ts
868 + * // Express with express.raw (verify the signature)
869 + * app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => {
870 + * try {
871 + * const result = await composio.triggers.parse(req, {
872 + * verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
873 + * });
874 + * console.log('Trigger:', result.payload.triggerSlug);
875 + * console.log('Event data:', result.payload.payload);
876 + * res.sendStatus(200);
877 + * } catch (error) {
878 + * res.sendStatus(401);
879 + * }
880 + * });
881 + *
882 + * // Express without verifying (parse only)
883 + * app.post('/webhooks/composio', express.raw({ type: 'application/json' }), async (req, res) => {
884 + * const result = await composio.triggers.parse(req);
885 + * console.log('Trigger:', result.payload.triggerSlug);
886 + * res.sendStatus(200);
887 + * });
888 + * ```
889 + *
890 + * @example
891 + * ```ts
892 + * // Next.js App Router (Request) — verify the signature
893 + * export async function POST(request: Request) {
894 + * try {
895 + * const result = await composio.triggers.parse(request, {
896 + * verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
897 + * });
898 + * console.log('Trigger:', result.payload.triggerSlug);
899 + * console.log('Event data:', result.payload.payload);
900 + * return new Response('OK', { status: 200 });
901 + * } catch (error) {
902 + * return new Response('Unauthorized', { status: 401 });
903 + * }
904 + * }
905 + *
906 + * // Next.js App Router — parse only (no verification)
907 + * export async function POST(request: Request) {
908 + * const result = await composio.triggers.parse(request);
909 + * console.log('Trigger:', result.payload.triggerSlug);
910 + * return new Response('OK', { status: 200 });
911 + * }
912 + * ```
913 + */
914 + async parse(
915 + request: WebhookRequestLike,
916 + options?: ParseWebhookOptions
917 + ): Promise<VerifyWebhookResult> {
918 + // Extract the raw body and signature headers from either request shape.
919 + let body: string;
920 + let headers: unknown;
921 + if (isFetchRequest(request)) {
922 + body = await request.text();
923 + headers = request.headers;
924 + } else {
925 + body = bodyToString(request.body);
926 + headers = request.headers;
927 + }
928 +
929 + const verifySecret = options?.verifySecret;
930 +
931 + // Distinguish "caller omitted verifySecret" (explicit opt-out) from
932 + // "caller passed verifySecret but it resolved to empty" (almost always an
933 + // unset COMPOSIO_WEBHOOK_SECRET). The latter must fail loudly rather than
934 + // silently skip verification and accept forged events.
935 + const optedOutOfVerification = options === undefined || !('verifySecret' in options);
936 +
937 + if (optedOutOfVerification) {
938 + // No secret requested: parse without verifying the signature.
939 + const { version, rawPayload, normalizedPayload } = this.parseWebhookPayload(body);
940 + return {
941 + version,
942 + payload: normalizedPayload,
943 + rawPayload,
944 + };
945 + }
946 +
947 + if (!verifySecret) {
948 + throw new ValidationError(
949 + `Cannot verify webhook: 'verifySecret' was provided but is empty — your ` +
950 + `COMPOSIO_WEBHOOK_SECRET is likely unset. Set the secret, or omit 'verifySecret' ` +
951 + `entirely to parse without verification.`
952 + );
953 + }
954 +
955 + // Secret provided: signature headers are required to verify.
956 + const id = getHeader(headers, WEBHOOK_HEADERS.id);
957 + const timestamp = getHeader(headers, WEBHOOK_HEADERS.timestamp);
958 + const signature = getHeader(headers, WEBHOOK_HEADERS.signature);
959 +
960 + if (!id || !timestamp || !signature) {
961 + const missing = [
962 + !id ? `'${WEBHOOK_HEADERS.id}'` : undefined,
963 + !timestamp ? `'${WEBHOOK_HEADERS.timestamp}'` : undefined,
964 + !signature ? `'${WEBHOOK_HEADERS.signature}'` : undefined,
965 + ].filter((header): header is string => header !== undefined);
966 +
967 + throw new ValidationError(
968 + `Cannot verify webhook: missing signature header(s) ${missing.join(', ')}. ` +
969 + `Pass the raw, unparsed request body and ensure the Composio signature headers ` +
970 + `(${WEBHOOK_HEADERS.id}, ${WEBHOOK_HEADERS.timestamp}, ${WEBHOOK_HEADERS.signature}) ` +
971 + `are forwarded to triggers.parse(). To parse without verifying, omit 'verifySecret'.`
972 + );
973 + }
974 +
975 + return this.verifyWebhook({
976 + payload: body,
977 + signature,
978 + id,
979 + timestamp,
980 + secret: verifySecret,
981 + tolerance: options?.tolerance,
982 + });
983 + }
984 +
985 /**
986 * Verify an incoming webhook payload and signature.
987 *
ts/packages/core/src/types/connectedAccounts.types.ts
+5 -5
@@ -194,7 +194,7 @@ export type CreateConnectedAccountResponse = z.infer<typeof CreateConnectedAccou
194
195 export const ConnectedAccountAuthConfigSchema = z.object({
196 id: z.string(),
197 - /** @deprecated use connectedAccount.state.authScheme instead */
197 + /** @deprecated Use `connectedAccount.state.authScheme` instead. */
198 authScheme: AuthSchemeEnum.optional(),
199 isComposioManaged: z.boolean(),
200 isDisabled: z.boolean(),
@@ -206,9 +206,9 @@ export const ConnectedAccountRetrieveResponseSchema: z.ZodType<{
206 authConfig: z.infer<typeof ConnectedAccountAuthConfigSchema>;
207 wordId?: string | null;
208 alias?: string | null;
209 - /** @deprecated use connectedAccount.state instead */
209 + /** @deprecated Use `connectedAccount.state` instead — `data` is a legacy raw credential field. */
210 data?: Record<string, unknown>;
211 - /** @deprecated use connectedAccount.state instead */
211 + /** @deprecated Use `connectedAccount.state` instead — `params` is a legacy raw credential field. */
212 params?: Record<string, unknown>;
213 status: ConnectedAccountStatusEnum;
214 statusReason: string | null;
@@ -225,11 +225,11 @@ export const ConnectedAccountRetrieveResponseSchema: z.ZodType<{
225 wordId: z.string().nullable().optional(),
226 alias: z.string().nullable().optional(),
227 /**
228 - * @deprecated use connectedAccount.state instead
228 + * @deprecated Use `connectedAccount.state` instead — `data` is a legacy raw credential field.
229 */
230 data: z.record(z.string(), z.unknown()).optional(),
231 /**
232 - * @deprecated use connectedAccount.state instead
232 + * @deprecated Use `connectedAccount.state` instead — `params` is a legacy raw credential field.
233 */
234 params: z.record(z.string(), z.unknown()).optional(),
235 status: ConnectedAccountStatusSchema,
ts/packages/core/src/types/toolRouter.types.ts
+101 -43
@@ -22,7 +22,7 @@ export const MCPServerTypeSchema = z.enum(['http', 'sse']);
22 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
23
24 /**
25 - * Sandbox compute tier for the tool router workbench.
25 + * Sandbox compute tier for the session sandbox.
26 *
27 * | Tier | vCPU | RAM |
28 * | -------- | ---- | ----- |
@@ -36,6 +36,29 @@ export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
36 export const SandboxSizeSchema = z.enum(['standard', 'medium', 'large', 'xlarge']);
37 export type SandboxSize = z.infer<typeof SandboxSizeSchema>;
38
39 +export const ToolRouterSandboxConfigSchema = z.object({
40 + enable: z
41 + .boolean()
42 + .default(true)
43 + .describe(
44 + 'Whether to enable the sandbox entirely. Defaults to true. When set to false, no code execution tools (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are available in the session.'
45 + ),
46 + enableProxyExecution: z
47 + .boolean()
48 + .optional()
49 + .describe('Whether to enable proxy execution in the session sandbox'),
50 + autoOffloadThreshold: z
51 + .number()
52 + .optional()
53 + .describe(
54 + 'The auto offload threshold in characters for tool execution to move into the sandbox'
55 + ),
56 + sandboxSize: SandboxSizeSchema.optional().describe(
57 + 'Sandbox compute tier. One of "standard" (1 vCPU / 1 GB), "medium" (2 vCPU / 2 GB), "large" (4 vCPU / 4 GB), or "xlarge" (8 vCPU / 8 GB). Defaults to "standard" server-side. Changing this on an existing session recreates the session sandbox on next access; the in-memory FS is lost, but /mnt/files/ persists.'
58 + ),
59 +});
60 +export type ToolRouterSandboxConfig = z.infer<typeof ToolRouterSandboxConfigSchema>;
61 +
62 // manage connections
63 export const ToolRouterConfigManageConnectionsSchema = z
64 .object({
@@ -185,6 +208,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
208 'Shortcut to expose every tool allowed by the session filters directly in session.tools() and the MCP tool list. This disables meta tools by default (search, multi-execute, manage-connections, and workbench). Use when all tools are known upfront and helper/meta tools are not needed. Without this preset, ToolRouter uses its default configuration with meta tools enabled.'
209 ),
210
211 + mcp: z
212 + .boolean()
213 + .optional()
214 + .describe(
215 + 'When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp'
216 + ),
217 +
218 tools: z
219 .record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema]))
220 .optional()
@@ -220,30 +250,12 @@ const ToolRouterCreateSessionConfigBaseSchema = z
250 .describe(
251 'The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.'
252 ),
223 - workbench: z
224 - .object({
225 - enable: z
226 - .boolean()
227 - .default(true)
228 - .describe(
229 - 'Whether to enable the workbench entirely. Defaults to true. When set to false, no code execution tools (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are available in the session.'
230 - ),
231 - enableProxyExecution: z
232 - .boolean()
233 - .optional()
234 - .describe('Whether to enable proxy execution in the tool router session'),
235 - autoOffloadThreshold: z
236 - .number()
237 - .optional()
238 - .describe(
239 - 'The auto offload threshold in characters for the tool execution to be moved into workbench'
240 - ),
241 - sandboxSize: SandboxSizeSchema.optional().describe(
242 - 'Sandbox compute tier for the workbench. One of "standard" (1 vCPU / 1 GB), "medium" (2 vCPU / 2 GB), "large" (4 vCPU / 4 GB), or "xlarge" (8 vCPU / 8 GB). Defaults to "standard" server-side. Changing this on an existing session recreates the session\'s workbench sandbox on next access; the in-memory FS is lost, but /mnt/files/ persists.'
243 - ),
244 - })
245 - .optional()
246 - .describe('The workbench config for the tool router session'),
253 + sandbox: ToolRouterSandboxConfigSchema.optional().describe(
254 + 'The sandbox config for this session. Prefer this over workbench.'
255 + ),
256 + workbench: ToolRouterSandboxConfigSchema.optional().describe(
257 + 'Deprecated alias for sandbox. Accepted for backwards compatibility.'
258 + ),
259 multiAccount: z
260 .object({
261 enable: z
@@ -312,6 +324,16 @@ const ToolRouterCreateSessionConfigBaseSchema = z
324 .describe('Experimental features configuration - not stable, may be modified or removed'),
325 })
326 .partial()
327 + .superRefine((config, ctx) => {
328 + if (config.sandbox !== undefined && config.workbench !== undefined) {
329 + ctx.addIssue({
330 + code: z.ZodIssueCode.custom,
331 + message:
332 + 'Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.',
333 + path: ['sandbox'],
334 + });
335 + }
336 + })
337 .describe('The config for the tool router session');
338
339 const applyDirectToolsPresetDefaults = (value: unknown): unknown => {
@@ -324,10 +346,12 @@ const applyDirectToolsPresetDefaults = (value: unknown): unknown => {
346 return value;
347 }
348
349 + const hasSandboxConfig = config.sandbox !== undefined || config.workbench !== undefined;
350 +
351 return {
352 ...config,
353 manageConnections: config.manageConnections === undefined ? false : config.manageConnections,
330 - workbench: config.workbench === undefined ? { enable: false } : config.workbench,
354 + ...(hasSandboxConfig ? {} : { sandbox: { enable: false } }),
355 preload: config.preload === undefined ? { tools: PRELOAD_TOOLS_ALL } : config.preload,
356 };
357 };
@@ -338,7 +362,7 @@ export const ToolRouterCreateSessionConfigSchema = z
362 /**
363 * The config for the tool router session.
364 *
341 - * @param {SessionPreset} [sessionPreset] - Shortcut that exposes every tool allowed by the session filters directly in session.tools() and the MCP tool list. Disables search, multi-execute, manage-connections, and workbench by default; explicit overrides for supported fields still win. Without this preset, ToolRouter uses the default configuration with meta tools enabled.
365 + * @param {SessionPreset} [sessionPreset] - Shortcut that exposes every tool allowed by the session filters directly in session.tools() and the MCP tool list. Disables search, multi-execute, manage-connections, and sandbox by default; explicit overrides for supported fields still win. Without this preset, ToolRouter uses the default configuration with meta tools enabled.
366 * @param {ToolRouterToolkitsParamSchema | ToolRouterToolkitsDisabledConfigSchema | ToolRouterToolkitsEnabledConfigSchema} toolkits - The toolkits to use in the tool router session
367 * @param {Record<string, ToolRouterToolsParam | ToolRouterConfigTools>} tools - The tools to configure per toolkit (key is toolkit slug)
368 * @param {Array<'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'>} tags - Global tags to filter tools by behavior
@@ -347,11 +371,12 @@ export const ToolRouterCreateSessionConfigSchema = z
371 * @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.
372 * @param {boolean} [manageConnections.enable] - Whether to use tools to manage connections in the tool router session @default true
373 * @param {string} [manageConnections.callbackUrl] - The callback url to use in the tool router session
350 - * @param {object} workbench - Workbench configuration for tool execution
351 - * @param {boolean} [workbench.enable] - Whether to enable the workbench entirely. Defaults to true. When false, no code execution tools are available.
352 - * @param {boolean} [workbench.enableProxyExecution] - Whether to enable proxy execution
353 - * @param {number} [workbench.autoOffloadThreshold] - Auto offload threshold in characters for moving execution to workbench
354 - * @param {SandboxSize} [workbench.sandboxSize] - Sandbox compute tier: 'standard' (1 vCPU/1 GB, default), 'medium' (2 vCPU/2 GB), 'large' (4 vCPU/4 GB), or 'xlarge' (8 vCPU/8 GB)
374 + * @param {object} sandbox - Sandbox configuration for code execution. Preferred over workbench.
375 + * @param {boolean} [sandbox.enable] - Whether to enable the sandbox entirely. Defaults to true. When false, no code execution tools are available.
376 + * @param {boolean} [sandbox.enableProxyExecution] - Whether to enable proxy execution
377 + * @param {number} [sandbox.autoOffloadThreshold] - Auto offload threshold in characters for moving execution to the sandbox
378 + * @param {SandboxSize} [sandbox.sandboxSize] - Sandbox compute tier: 'standard' (1 vCPU/1 GB, default), 'medium' (2 vCPU/2 GB), 'large' (4 vCPU/4 GB), or 'xlarge' (8 vCPU/8 GB)
379 + * @param {object} workbench - Deprecated alias for sandbox. Accepted for backwards compatibility.
380 * @param {object} [multiAccount] - Multi-account configuration for this session
381 * @param {boolean} [multiAccount.enable] - When true, enables multi-account mode. Falls back to org/project-level config when not set.
382 * @param {number} [multiAccount.maxAccountsPerToolkit] - Max connected accounts per toolkit (2-10, default 5)
@@ -575,10 +600,13 @@ export interface ToolRouterSessionExecuteOptions {
600
601 export type ToolRouterSessionPreloadConfig = SessionCreateResponse.Config.Preload;
602
603 +export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Workbench;
604 +
605 export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
606
607 export interface ToolRouterSessionMetadata {
608 preload?: ToolRouterSessionPreloadConfig;
609 + workbench?: ToolRouterSessionWorkbenchConfig;
610 configVersion?: number;
611 warnings?: ToolRouterSessionWarning[];
612 preloadedCustomToolSlugs?: string[];
@@ -627,7 +655,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
655 authConfigs: z.record(z.string(), z.string()).optional(),
656 connectedAccounts: z
657 .record(z.string(), z.union([z.string(), z.array(z.string())]))
630 - .transform((rec) => {
658 + .transform(rec => {
659 const out: Record<string, string[]> = {};
660 for (const [k, v] of Object.entries(rec)) {
661 out[k] = typeof v === 'string' ? [v] : v;
@@ -639,15 +667,8 @@ export const ToolRouterUpdateSessionConfigSchema = z
667 .union([z.boolean(), ToolRouterConfigManageConnectionsSchema])
668 .nullable()
669 .optional(),
642 - workbench: z
643 - .object({
644 - enable: z.boolean().optional(),
645 - enableProxyExecution: z.boolean().optional(),
646 - autoOffloadThreshold: z.number().optional(),
647 - sandboxSize: SandboxSizeSchema.optional(),
648 - })
649 - .nullable()
650 - .optional(),
670 + sandbox: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
671 + workbench: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
672 multiAccount: z
673 .object({
674 enable: z.boolean().optional(),
@@ -663,7 +684,17 @@ export const ToolRouterUpdateSessionConfigSchema = z
684 .strict()
685 .optional(),
686 })
666 - .partial();
687 + .partial()
688 + .superRefine((config, ctx) => {
689 + if (config.sandbox !== undefined && config.workbench !== undefined) {
690 + ctx.addIssue({
691 + code: z.ZodIssueCode.custom,
692 + message:
693 + 'Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.',
694 + path: ['sandbox'],
695 + });
696 + }
697 + });
698
699 export type ToolRouterUpdateSessionConfig = z.infer<typeof ToolRouterUpdateSessionConfigSchema>;
700
@@ -679,6 +710,18 @@ export interface Session<
710 mcp: ToolRouterMCPServerConfig;
711 /** Stored preload configuration for this session. */
712 preload: ToolRouterSessionPreloadConfig;
713 + /**
714 + * Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side.
715 + *
716 + * This is the read-side counterpart to the `sandbox` key you pass into `create()`.
717 + */
718 + sandbox?: ToolRouterSessionWorkbenchConfig;
719 + /**
720 + * Resolved sandbox config for the session.
721 + *
722 + * @deprecated Use `sandbox` instead. `workbench` is a backwards-compatible alias and will be removed in a future release.
723 + */
724 + workbench?: ToolRouterSessionWorkbenchConfig;
725 /** Server-side config version when returned by the API. */
726 configVersion?: number;
727 /** Non-blocking session creation warnings returned by the API. */
@@ -701,3 +744,18 @@ export interface Session<
744 /** Experimental features (files, assistive prompt, etc.) */
745 experimental: SessionExperimental;
746 }
747 +
748 +/**
749 + * Session type without the typed `mcp` endpoint.
750 + *
751 + * Returned by `create()` / `use()` when `{ mcp: true }` is not passed. The
752 + * hosted MCP endpoint still exists on the underlying session at runtime — this
753 + * only hides it from the type so MCP is an explicit opt-in. Pass `{ mcp: true }`
754 + * to get a `Session` with `session.mcp` surfaced. See
755 + * https://docs.composio.dev/docs/sessions-via-mcp
756 + */
757 +export type SessionWithoutMcp<
758 + TToolCollection,
759 + TTool,
760 + TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
761 +> = Omit<Session<TToolCollection, TTool, TProvider>, 'mcp'>;
ts/packages/core/src/types/triggers.types.ts
+58
@@ -274,6 +274,29 @@ export const WebhookVersions = {
274 } as const;
275 export type WebhookVersion = (typeof WebhookVersions)[keyof typeof WebhookVersions];
276
277 +export const DefaultWebhookSubscriptionEvents = ['composio.trigger.message'] as const;
278 +
279 +export const SetWebhookSubscriptionParamsSchema = z.object({
280 + /** HTTPS URL to receive webhook events. */
281 + webhookUrl: z.string().min(1),
282 + /** Event types to subscribe to. Defaults to trigger messages. */
283 + enabledEvents: z.array(z.string()).min(1).optional(),
284 + /** Webhook payload version. Defaults to V3. */
285 + version: z.enum(['V1', 'V2', 'V3']).optional(),
286 +});
287 +
288 +export type SetWebhookSubscriptionParams = z.infer<typeof SetWebhookSubscriptionParamsSchema>;
289 +
290 +export type WebhookSubscription = {
291 + id: string;
292 + webhookUrl: string;
293 + version: WebhookVersion;
294 + enabledEvents: string[];
295 + secret?: string;
296 + createdAt?: string;
297 + updatedAt?: string;
298 +};
299 +
300 /**
301 * Parameters for verifying a webhook signature
302 */
@@ -329,6 +352,41 @@ export const VerifyWebhookParamsSchema = z.object({
352
353 export type VerifyWebhookParams = z.input<typeof VerifyWebhookParamsSchema>;
354
355 +/**
356 + * An incoming HTTP request that carries a Composio webhook.
357 + *
358 + * Accepts either:
359 + * - A Fetch API `Request` (Next.js App Router, Hono, Remix, Cloudflare Workers).
360 + * - A plain object `{ body, headers }` (Express with `express.raw`, Next.js
361 + * Pages Router `req`). `body` may be a string, a Buffer/Uint8Array, or an
362 + * already-parsed object; `headers` may be a `Headers` instance or a plain
363 + * record of `string | string[] | undefined`.
364 + */
365 +export type WebhookRequestLike =
366 + | Request
367 + | {
368 + body: unknown;
369 + headers: unknown;
370 + };
371 +
372 +/**
373 + * Options for {@link Triggers.parse}.
374 + */
375 +export type ParseWebhookOptions = {
376 + /**
377 + * The webhook secret used to sign the payload (from the Composio dashboard).
378 + * When provided, the request signature is verified before the payload is
379 + * returned. When omitted, the payload is parsed without verification.
380 + */
381 + verifySecret?: string;
382 + /**
383 + * Maximum allowed age of the webhook in seconds (default: 300 = 5 minutes).
384 + * Only used when `verifySecret` is provided. Set to 0 to disable timestamp
385 + * validation.
386 + */
387 + tolerance?: number;
388 +};
389 +
390 /**
391 * Result of a successful webhook verification.
392 * Contains the parsed payload along with version information.
ts/packages/core/src/utils/session.ts
+2 -2
@@ -1,6 +1,6 @@
1 -import { BaseComposioProvider } from '../provider/BaseProvider';
1 +import type { BaseComposioProvider } from '../provider/BaseProvider';
2 import { version } from '../../package.json';
3 -import { ComposioRequestHeaders } from '../types/composio.types';
3 +import type { ComposioRequestHeaders } from '../types/composio.types';
4
5 /**
6 * Extended globalThis interface for runtime detection
ts/packages/core/src/utils/transform.ts
+1 -1
@@ -12,7 +12,7 @@
12 * ```
13 */
14 import { ZodTypeAny, z } from 'zod/v3';
15 -import { logger } from '..';
15 +import logger from './logger';
16
17 export function transform<RawInput>(raw: RawInput) {
18 return {
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+26 -13
@@ -32,6 +32,10 @@ const extendedMockClient = {
32 link: {
33 create: vi.fn(),
34 },
35 + authConfigs: {
36 + list: vi.fn(),
37 + create: vi.fn(),
38 + },
39 };
40
41 describe('ConnectedAccounts', () => {
@@ -1770,13 +1774,7 @@ describe('ConnectedAccounts', () => {
1774 });
1775 });
1776
1773 - describe('composio.experimental.updateAcl', () => {
1774 - let experimental: Experimental;
1775 -
1776 - beforeEach(() => {
1777 - experimental = new Experimental(extendedMockClient as unknown as ComposioClient);
1778 - });
1779 -
1777 + describe('connectedAccounts.updateAcl', () => {
1778 it('serializes PATCH body under experimental.acl_config_for_shared', async () => {
1779 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1780 id: 'ca_abc',
@@ -1784,7 +1782,7 @@ describe('ConnectedAccounts', () => {
1782 success: true,
1783 });
1784
1787 - const result = await experimental.updateAcl('ca_abc', {
1785 + const result = await connectedAccounts.updateAcl('ca_abc', {
1786 allowAllUsers: true,
1787 notAllowedUserIds: ['user_bob'],
1788 });
@@ -1800,6 +1798,21 @@ describe('ConnectedAccounts', () => {
1798 expect(result).toEqual({ id: 'ca_abc', status: 'ACTIVE', success: true });
1799 });
1800
1801 + it('keeps composio.experimental.updateAcl as an alias', async () => {
1802 + const experimental = new Experimental(extendedMockClient as unknown as ComposioClient);
1803 + extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1804 + id: 'ca_abc',
1805 + status: 'ACTIVE',
1806 + success: true,
1807 + });
1808 +
1809 + await experimental.updateAcl('ca_abc', { allowAllUsers: true });
1810 +
1811 + expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1812 + experimental: { acl_config_for_shared: { allow_all_users: true } },
1813 + });
1814 + });
1815 +
1816 it('omits absent fields from the inner block (PATCH semantics)', async () => {
1817 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1818 id: 'ca_abc',
@@ -1807,7 +1820,7 @@ describe('ConnectedAccounts', () => {
1820 success: true,
1821 });
1822
1810 - await experimental.updateAcl('ca_abc', { allowedUserIds: ['user_alice'] });
1823 + await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: ['user_alice'] });
1824
1825 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1826 experimental: {
@@ -1823,7 +1836,7 @@ describe('ConnectedAccounts', () => {
1836 success: true,
1837 });
1838
1826 - await experimental.updateAcl('ca_abc', { allowedUserIds: [] });
1839 + await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
1840
1841 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1842 experimental: { acl_config_for_shared: { allowed_user_ids: [] } },
@@ -1831,7 +1844,7 @@ describe('ConnectedAccounts', () => {
1844 });
1845
1846 it('rejects an empty params object via the refine', async () => {
1834 - await expect(experimental.updateAcl('ca_abc', {})).rejects.toMatchObject({
1847 + await expect(connectedAccounts.updateAcl('ca_abc', {})).rejects.toMatchObject({
1848 name: 'ValidationError',
1849 });
1850 expect(extendedMockClient.connectedAccounts.patch).not.toHaveBeenCalled();
@@ -1848,7 +1861,7 @@ describe('ConnectedAccounts', () => {
1861 );
1862
1863 await expect(
1851 - experimental.updateAcl('ca_abc', { allowAllUsers: true })
1864 + connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })
1865 ).rejects.toBeInstanceOf(ComposioAclOnlyForSharedError);
1866 });
1867
@@ -1856,7 +1869,7 @@ describe('ConnectedAccounts', () => {
1869 const otherError = new Error('connection lost');
1870 extendedMockClient.connectedAccounts.patch.mockRejectedValueOnce(otherError);
1871
1859 - await expect(experimental.updateAcl('ca_abc', { allowAllUsers: true })).rejects.toBe(
1872 + await expect(connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })).rejects.toBe(
1873 otherError
1874 );
1875 });
ts/packages/core/test/core/session.test.ts
+34
@@ -109,6 +109,40 @@ describe('Composio Session Management', () => {
109 'x-sdk-version': version,
110 });
111 });
112 +
113 + it('should expose sessions.create and keep composio.create as a bound alias', async () => {
114 + const composio = new Composio(baseConfig);
115 + const client = composio.getClient() as any;
116 + client.toolRouter.session.create = vi.fn().mockResolvedValue({
117 + session_id: 'session_123',
118 + mcp: {
119 + type: 'http',
120 + url: 'https://mcp.example.com/session_123',
121 + },
122 + config: {
123 + preload: { tools: [] },
124 + },
125 + config_version: 1,
126 + });
127 +
128 + expect(composio.toolRouter).toBe(composio.sessions);
129 +
130 + const sessionFromCanonicalApi = await composio.sessions.create('user_123');
131 + const sessionFromAlias = await composio.create('user_456');
132 +
133 + expect(client.toolRouter.session.create).toHaveBeenNthCalledWith(
134 + 1,
135 + expect.objectContaining({ user_id: 'user_123' }),
136 + undefined
137 + );
138 + expect(client.toolRouter.session.create).toHaveBeenNthCalledWith(
139 + 2,
140 + expect.objectContaining({ user_id: 'user_456' }),
141 + undefined
142 + );
143 + expect(sessionFromCanonicalApi.sessionId).toBe('session_123');
144 + expect(sessionFromAlias.sessionId).toBe('session_123');
145 + });
146 });
147
148 describe('Session Headers Generation', () => {
ts/packages/core/test/lib/toolRouterParams.test.ts
+18
@@ -223,6 +223,15 @@ describe('transformToolRouterUpdateParams', () => {
223 });
224 });
225
226 + it('should handle null for sandbox (clearing)', () => {
227 + const result = transformToolRouterUpdateParams({
228 + sandbox: null,
229 + });
230 + expect(result).toEqual({
231 + workbench: null,
232 + });
233 + });
234 +
235 it('should handle null for workbench (clearing)', () => {
236 const result = transformToolRouterUpdateParams({
237 workbench: null,
@@ -276,6 +285,15 @@ describe('transformToolRouterUpdateParams', () => {
285 expect(mc).toHaveProperty('callback_url', 'https://example.com/callback');
286 });
287
288 + it('should NOT apply default enable:true for sandbox when only enableProxyExecution is provided', () => {
289 + const result = transformToolRouterUpdateParams({
290 + sandbox: { enableProxyExecution: true },
291 + });
292 + const wb = result.workbench as Record<string, unknown>;
293 + expect(wb).not.toHaveProperty('enable');
294 + expect(wb).toHaveProperty('enable_proxy_execution', true);
295 + });
296 +
297 it('should NOT apply default enable:true for workbench when only enableProxyExecution is provided', () => {
298 const result = transformToolRouterUpdateParams({
299 workbench: { enableProxyExecution: true },
ts/packages/core/test/models/toolRouter.test.ts
+25
@@ -1358,6 +1358,22 @@ describe('ToolRouter', () => {
1358 );
1359 });
1360
1361 + it('forwards sandbox config to the existing workbench wire field', async () => {
1362 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1363 +
1364 + await toolRouter.create(userId, {
1365 + sandbox: { enableProxyExecution: false, autoOffloadThreshold: 300, sandboxSize: 'large' },
1366 + });
1367 +
1368 + const payload = mockClient.toolRouter.session.create.mock.calls[0]?.[0];
1369 + expect(payload?.workbench).toEqual({
1370 + enable: true,
1371 + enable_proxy_execution: false,
1372 + auto_offload_threshold: 300,
1373 + sandbox_size: 'large',
1374 + });
1375 + });
1376 +
1377 it('forwards sandboxSize as snake_case sandbox_size on the wire', async () => {
1378 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1379
@@ -1369,6 +1385,15 @@ describe('ToolRouter', () => {
1385 expect(payload?.workbench?.sandbox_size).toBe('large');
1386 });
1387
1388 + it('rejects create config that passes both sandbox and workbench', async () => {
1389 + await expect(
1390 + toolRouter.create(userId, {
1391 + sandbox: { enable: true },
1392 + workbench: { enable: true },
1393 + })
1394 + ).rejects.toThrow('Pass either sandbox or workbench');
1395 + });
1396 +
1397 it('rejects an invalid sandboxSize value via the zod schema', async () => {
1398 await expect(
1399 toolRouter.create(userId, {
ts/packages/core/test/models/triggers.test.ts
+174
@@ -14,6 +14,7 @@ import { PusherService } from '../../src/services/pusher/Pusher';
14 import {
15 ComposioFailedToSubscribeToPusherChannelError,
16 ComposioTriggerTypeNotFoundError,
17 + ComposioWebhookSignatureVerificationError,
18 } from '../../src/errors/TriggerErrors';
19
20 // Mock dependencies
@@ -29,6 +30,9 @@ vi.mock('../../src/services/pusher/Pusher');
30 const createMockClient = () => ({
31 baseURL: 'https://api.composio.dev',
32 apiKey: 'test-api-key',
33 + get: vi.fn(),
34 + post: vi.fn(),
35 + patch: vi.fn(),
36 triggerInstances: {
37 listActive: vi.fn(),
38 upsert: vi.fn(),
@@ -240,6 +244,176 @@ describe('Triggers', () => {
244 });
245 });
246
247 + describe('setWebhookSubscription', () => {
248 + const webhookUrl = 'https://example.com/webhooks/composio';
249 + const rawSubscription = {
250 + id: 'sub_123',
251 + webhook_url: webhookUrl,
252 + version: 'V3',
253 + enabled_events: ['composio.trigger.message'],
254 + secret: 'whsec_123',
255 + created_at: '2026-01-01T00:00:00Z',
256 + updated_at: '2026-01-01T00:00:00Z',
257 + };
258 +
259 + it('should create a webhook subscription when none exists', async () => {
260 + mockClient.get.mockResolvedValue({ items: [] });
261 + mockClient.post.mockResolvedValue(rawSubscription);
262 +
263 + const result = await triggers.setWebhookSubscription({ webhookUrl });
264 +
265 + expect(mockClient.get).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {
266 + query: { limit: 1 },
267 + });
268 + expect(mockClient.post).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {
269 + body: {
270 + webhook_url: webhookUrl,
271 + enabled_events: ['composio.trigger.message'],
272 + version: 'V3',
273 + },
274 + });
275 + expect(mockClient.patch).not.toHaveBeenCalled();
276 + // Only camelCase keys — the snake_case wire fields must not leak through.
277 + expect(result).toEqual({
278 + id: 'sub_123',
279 + webhookUrl,
280 + version: 'V3',
281 + enabledEvents: ['composio.trigger.message'],
282 + secret: 'whsec_123',
283 + createdAt: '2026-01-01T00:00:00Z',
284 + updatedAt: '2026-01-01T00:00:00Z',
285 + });
286 + });
287 +
288 + it('should update the first webhook subscription when one exists', async () => {
289 + mockClient.get.mockResolvedValue({ items: [{ id: 'sub_123' }] });
290 + mockClient.patch.mockResolvedValue(rawSubscription);
291 +
292 + await triggers.setWebhookSubscription({
293 + webhookUrl,
294 + enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],
295 + version: 'V3',
296 + });
297 +
298 + expect(mockClient.patch).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions/sub_123', {
299 + body: {
300 + webhook_url: webhookUrl,
301 + enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'],
302 + version: 'V3',
303 + },
304 + });
305 + expect(mockClient.post).not.toHaveBeenCalled();
306 + });
307 +
308 + it('should throw validation error for invalid webhook subscription parameters', async () => {
309 + await expect(
310 + triggers.setWebhookSubscription({ webhookUrl, enabledEvents: [] })
311 + ).rejects.toThrow(ValidationError);
312 + expect(mockClient.get).not.toHaveBeenCalled();
313 + });
314 + });
315 +
316 + describe('parse', () => {
317 + const webhookSecret = 'test-webhook-secret-12345';
318 + const webhookId = 'msg_test123';
319 +
320 + const v3Payload = {
321 + id: 'evt-123',
322 + timestamp: '2026-01-28T12:00:00Z',
323 + type: 'composio.trigger.message',
324 + metadata: {
325 + log_id: 'log-789',
326 + trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
327 + trigger_id: 'trigger-456',
328 + connected_account_id: 'conn-123',
329 + auth_config_id: 'auth-456',
330 + user_id: 'user-789',
331 + },
332 + data: { subject: 'Test email', from: 'test@example.com' },
333 + };
334 +
335 + // Mirrors the signing format used by Composio: HMAC-SHA256(id.timestamp.payload).
336 + const createSignature = async (timestamp: string, payload: string): Promise<string> => {
337 + const { createHmac } = await import('node:crypto');
338 + const signature = createHmac('sha256', webhookSecret)
339 + .update(`${webhookId}.${timestamp}.${payload}`)
340 + .digest('base64');
341 + return `v1,${signature}`;
342 + };
343 +
344 + it('should parse and verify from a Fetch Request with a valid signature', async () => {
345 + const timestamp = String(Math.floor(Date.now() / 1000));
346 + const body = JSON.stringify(v3Payload);
347 + const signature = await createSignature(timestamp, body);
348 +
349 + const request = new Request('https://example.com/webhooks/composio', {
350 + method: 'POST',
351 + headers: {
352 + 'webhook-id': webhookId,
353 + 'webhook-timestamp': timestamp,
354 + 'webhook-signature': signature,
355 + },
356 + body,
357 + });
358 +
359 + const result = await triggers.parse(request, { verifySecret: webhookSecret });
360 +
361 + expect(result.version).toBe('V3');
362 + expect(result.payload.triggerSlug).toBe('GMAIL_NEW_GMAIL_MESSAGE');
363 + expect(result.payload.payload).toEqual({
364 + subject: 'Test email',
365 + from: 'test@example.com',
366 + });
367 + });
368 +
369 + it('should parse from an Express-style { body, headers } without verifying', async () => {
370 + const body = JSON.stringify(v3Payload);
371 +
372 + const result = await triggers.parse({
373 + body: new TextEncoder().encode(body),
374 + headers: {},
375 + });
376 +
377 + expect(result.version).toBe('V3');
378 + expect(result.payload.triggerSlug).toBe('GMAIL_NEW_GMAIL_MESSAGE');
379 + expect(result.payload.payload).toEqual({
380 + subject: 'Test email',
381 + from: 'test@example.com',
382 + });
383 + });
384 +
385 + it('should throw when verifySecret is set but the signature is invalid', async () => {
386 + const timestamp = String(Math.floor(Date.now() / 1000));
387 + const body = JSON.stringify(v3Payload);
388 +
389 + const request = new Request('https://example.com/webhooks/composio', {
390 + method: 'POST',
391 + headers: {
392 + 'webhook-id': webhookId,
393 + 'webhook-timestamp': timestamp,
394 + 'webhook-signature': 'v1,not-a-valid-signature',
395 + },
396 + body,
397 + });
398 +
399 + await expect(triggers.parse(request, { verifySecret: webhookSecret })).rejects.toThrow(
400 + ComposioWebhookSignatureVerificationError
401 + );
402 + });
403 +
404 + it('should throw a helpful ValidationError when signature headers are missing', async () => {
405 + const body = JSON.stringify(v3Payload);
406 +
407 + await expect(
408 + triggers.parse({ body, headers: {} }, { verifySecret: webhookSecret })
409 + ).rejects.toThrow(ValidationError);
410 +
411 + await expect(
412 + triggers.parse({ body, headers: {} }, { verifySecret: webhookSecret })
413 + ).rejects.toThrow(/missing signature header/i);
414 + });
415 + });
416 +
417 describe('list', () => {
418 it('should list active trigger instances', async () => {
419 mockClient.triggerInstances.listActive.mockResolvedValue(mockTriggerInstances);
ts/packages/core/tsdown.config.ts
+9 -1
@@ -4,7 +4,15 @@ import { baseConfig } from '../../../tsdown.config.base.ts';
4 export default defineConfig({
5 ...baseConfig,
6 tsconfig: 'tsconfig.build.json',
7 - copy: [{ from: 'pack/generated/*', to: '.', flatten: false }],
7 + copy: [
8 + { from: 'pack/generated/*', to: '.', flatten: false },
9 + { from: 'docs/**/*', to: 'dist/docs', flatten: false },
10 + {
11 + from: '../../../docs/content/reference/sdk-reference/typescript/*',
12 + to: 'dist/docs/reference/sdk-reference/typescript',
13 + flatten: true,
14 + },
15 + ],
16 entry: [
17 'src/index.ts',
18 'src/experimental/index.ts',
ts/packages/core/type-tests/sessions-mcp.test-d.ts new
+53
@@ -0,0 +1,53 @@
1 +/**
2 + * Type-level tests for the MCP opt-in on sessions.
3 + *
4 + * `session.mcp` exists at runtime on every session, but is only surfaced in the
5 + * type when `{ mcp: true }` is passed to `create()` / `use()`. These tests fail
6 + * the build (tsconfig.type-tests.json) if that gating regresses.
7 + *
8 + * See: docs/content/docs/sessions-via-mcp.mdx
9 + */
10 +import { Composio } from '../src';
11 +
12 +declare const composio: Composio;
13 +
14 +async function createGating(): Promise<void> {
15 + // Default: no `{ mcp: true }` → `session.mcp` is NOT in the type.
16 + const session = await composio.create('user_123');
17 + // @ts-expect-error mcp is hidden from the type unless `{ mcp: true }` is passed
18 + void session.mcp;
19 +
20 + // Native tools are always available.
21 + await session.tools();
22 +
23 + // Opt-in: `{ mcp: true }` → `session.mcp` is surfaced.
24 + const mcpSession = await composio.create('user_123', { mcp: true });
25 + const _url: string = mcpSession.mcp.url;
26 + void _url;
27 +}
28 +
29 +async function useGating(): Promise<void> {
30 + const session = await composio.use('session_123');
31 + // @ts-expect-error mcp is hidden from the type unless `{ mcp: true }` is passed
32 + void session.mcp;
33 +
34 + const mcpSession = await composio.use('session_123', { mcp: true });
35 + const _url: string = mcpSession.mcp.url;
36 + void _url;
37 +}
38 +
39 +// Regression guard: `create()` / `use()` must keep accepting a trailing
40 +// `requestOptions` (AbortSignal/cancellation) arg — with and without `{ mcp: true }`.
41 +// The `{ mcp: true }` overload refactor previously dropped this from `create()`.
42 +async function requestOptionsArg(): Promise<void> {
43 + const ctrl = new AbortController();
44 + await composio.create('user_123', { toolkits: ['gmail'] }, { signal: ctrl.signal });
45 + await composio.create('user_123', { mcp: true }, { signal: ctrl.signal });
46 + await composio.sessions.create('user_123', undefined, { signal: ctrl.signal });
47 + await composio.use('session_123', { customTools: [] }, { signal: ctrl.signal });
48 + await composio.use('session_123', { mcp: true }, { signal: ctrl.signal });
49 +}
50 +
51 +void createGating;
52 +void useGating;
53 +void requestOptionsArg;
ts/packages/experimental/README.md new
+190
@@ -0,0 +1,190 @@
1 +# `@composio/experimental`
2 +
3 +Experimental Composio integrations and helpers.
4 +
5 +This package currently includes a Pi provider for [`@earendil-works/pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent). It lets Composio tools be passed to Pi SDK sessions as `customTools` and includes a dynamic Tool Router session toolset modeled after the Slack bot integration in `~/composio/slack-bot`.
6 +
7 +## Install
8 +
9 +```bash
10 +pnpm add @composio/core @composio/experimental @earendil-works/pi-coding-agent
11 +```
12 +
13 +## Static tool wrapping
14 +
15 +Use this when you already know the exact Composio tools to expose to Pi.
16 +
17 +```ts
18 +import { Composio } from '@composio/core';
19 +import { PiProvider } from '@composio/experimental';
20 +import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
21 +
22 +const provider = new PiProvider();
23 +const composio = new Composio({
24 + apiKey: process.env.COMPOSIO_API_KEY,
25 + provider,
26 +});
27 +
28 +const tools = await composio.tools.get('default', {
29 + tools: ['GITHUB_CREATE_ISSUE'],
30 +});
31 +
32 +const { session } = await createAgentSession({
33 + cwd: process.cwd(),
34 + sessionManager: SessionManager.inMemory(process.cwd()),
35 + customTools: tools,
36 + tools: ['read', 'bash', ...tools.map(tool => tool.name)],
37 +});
38 +
39 +await session.prompt('Create a GitHub issue for the failing test.');
40 +```
41 +
42 +## Dynamic session helpers
43 +
44 +Use this when Pi should search and execute tools dynamically inside one Tool Router session. Prefer the capability form so your app owns connection management and uses one Pi-style `hooks` object for interception/result transforms.
45 +
46 +```ts
47 +import { Composio } from '@composio/core';
48 +import { PiProvider, createPiComposioSystemPrompt } from '@composio/experimental';
49 +import {
50 + createAgentSession,
51 + DefaultResourceLoader,
52 + getAgentDir,
53 + SessionManager,
54 +} from '@earendil-works/pi-coding-agent';
55 +
56 +const provider = new PiProvider();
57 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
58 +
59 +const composioSession = await composio.sessions.create('slack:T123:U456', {
60 + toolkits: ['github', 'gmail'],
61 + manageConnections: true,
62 + workbench: { enable: true },
63 +});
64 +
65 +const composioTools = provider.createSessionTools({
66 + sessionId: composioSession.sessionId,
67 + search: composioSession.search.bind(composioSession),
68 + execute: composioSession.execute.bind(composioSession),
69 + callbackUrl: 'https://your-app.example.com/auth/callback',
70 + includeWorkbenchTools: true,
71 + connections: {
72 + getToolkitStates: toolkits => composioSession.toolkits({ toolkits }),
73 + authorizeToolkit: (toolkit, options) => composioSession.authorize(toolkit, options),
74 + isConnected: state => state.connection?.isActive === true,
75 + },
76 + hooks: {
77 + search: (ctx, next) => {
78 + ctx.request.toolkits = ctx.request.toolkits?.map(toolkit =>
79 + toolkit === 'slack' ? 'slackbot' : toolkit
80 + );
81 + return next();
82 + },
83 + execute: (ctx, next) => {
84 + if (ctx.request.toolSlug === 'COMPOSIO_MANAGE_CONNECTIONS') {
85 + return ctx.deny('Meta tools are blocked.');
86 + }
87 + return next();
88 + },
89 + remoteWorkbench: async (ctx, next) => {
90 + const result = await next();
91 + await auditWorkbenchRun({ code: ctx.request.code_to_execute, result });
92 + return result;
93 + },
94 + remoteBash: async (ctx, next) => {
95 + if (ctx.request.command.includes('rm -rf')) {
96 + return ctx.deny('Destructive bash commands are blocked.');
97 + }
98 + return next();
99 + },
100 + onAuthLink: async (ctx, next) => {
101 + // DM the user, store the continuation, or redact public output.
102 + await sendConnectionLinkToUser({ url: ctx.url, toolkit: ctx.toolkit });
103 + return { message: 'Connection link sent out-of-band.' };
104 + // To also send the original result/link to the model, use: return next();
105 + },
106 + },
107 + transformResult: async ({ value }) => value,
108 +});
109 +
110 +const loader = new DefaultResourceLoader({
111 + cwd: process.cwd(),
112 + agentDir: getAgentDir(),
113 + systemPromptOverride: () =>
114 + createPiComposioSystemPrompt(composioSession.sessionId, { includeWorkbenchTools: true }),
115 +});
116 +await loader.reload();
117 +
118 +const { session } = await createAgentSession({
119 + cwd: process.cwd(),
120 + resourceLoader: loader,
121 + sessionManager: SessionManager.inMemory(process.cwd()),
122 + customTools: composioTools,
123 + tools: [
124 + 'read',
125 + 'bash',
126 + 'composio_search_tools',
127 + 'composio_manage_connections',
128 + 'composio_execute_tool',
129 + 'composio_remote_workbench',
130 + 'composio_remote_bash',
131 + ],
132 +});
133 +
134 +await session.prompt('Find my recent GitHub issues and summarize the blockers.');
135 +```
136 +
137 +`composio_manage_connections` uses your `connections.getToolkitStates()` and `connections.authorizeToolkit()` handlers. It does **not** call `session.execute('COMPOSIO_MANAGE_CONNECTIONS', ...)` internally.
138 +
139 +The dynamic helpers are:
140 +
141 +- `composio_search_tools` — search Tool Router for exact tool slugs and schemas.
142 +- `composio_manage_connections` — check/initiate user app connections.
143 +- `composio_execute_tool` — execute exact Composio tool slugs in the session.
144 +- `composio_remote_workbench` — execute Python in the Composio remote workbench for large outputs, remote files, and session-authenticated scripting.
145 +- `composio_remote_bash` — run short bash commands in the Composio remote workbench filesystem.
146 +
147 +Workbench helpers are opt-in because the Tool Router session must be created with workbench enabled.
148 +
149 +## Hooks
150 +
151 +`hooks` follows Pi's extension-event style with middleware semantics. Each hook receives a mutable `ctx.request`, `ctx.deny('reason')`, and a typed `next()` function. Calling `await next()` runs the default Composio behavior and returns the result before anything is sent back to the model. Return that result to pass it through, return a replacement value to control what the model sees, or skip `next()` entirely to divert/deny the operation.
152 +
153 +Available hooks:
154 +
155 +- `search(ctx, next)` — rewrite query/toolkit filters, log search results, or return custom search output.
156 +- `manageConnections(ctx, next)` — rewrite requested toolkits, force reauth, log connection state, or return custom connection output.
157 +- `execute(ctx, next)` — block/rewrite tools, route to another session/execute handler, call `ctx.manageConnections(...)`, log outputs, or return a file/workbench reference instead of inline data.
158 +- `remoteWorkbench(ctx, next)` — rewrite Python code/session metadata, audit workbench runs, or replace large outputs with file/workbench references. Calls through the generic `execute` hook when `next()` is used.
159 +- `remoteBash(ctx, next)` — rewrite/block shell commands, enforce safety policy, audit filesystem access, or replace output. Calls through the generic `execute` hook when `next()` is used.
160 +- `onAuthLink(ctx, next)` — send/redact/resume auth links out-of-band. `return next()` keeps the original model-visible result; returning another value replaces it.
161 +
162 +## Auth link handling
163 +
164 +Embedded agents often need to keep Composio connection URLs out of the public transcript. Use `hooks.onAuthLink()` to choose whether the model sees the original result or a redacted replacement:
165 +
166 +```ts
167 +const tools = provider.createSessionTools({
168 + search: composioSession.search.bind(composioSession),
169 + execute: composioSession.execute.bind(composioSession),
170 + connections: {
171 + getToolkitStates: toolkits => composioSession.toolkits({ toolkits }),
172 + authorizeToolkit: (toolkit, options) => composioSession.authorize(toolkit, options),
173 + },
174 + hooks: {
175 + onAuthLink: async (ctx, next) => {
176 + await sendConnectionLinkToUser({ url: ctx.url, toolkit: ctx.toolkit });
177 +
178 + if (shouldAlsoShowLinkToModel(ctx)) {
179 + return next();
180 + }
181 +
182 + return { message: 'Connection link sent out-of-band.' };
183 + },
184 + },
185 +});
186 +```
187 +
188 +## Status
189 +
190 +Experimental. The dynamic helper names and session helper API may change.
ts/packages/experimental/package.json new
+72
@@ -0,0 +1,72 @@
1 +{
2 + "name": "@composio/experimental",
3 + "version": "0.0.1",
4 + "description": "Experimental Composio integrations and helpers",
5 + "main": "src/index.ts",
6 + "type": "module",
7 + "repository": {
8 + "type": "git",
9 + "url": "https://github.com/ComposioHQ/composio.git",
10 + "directory": "ts/packages/experimental"
11 + },
12 + "bugs": {
13 + "url": "https://github.com/ComposioHQ/composio/issues"
14 + },
15 + "homepage": "https://github.com/ComposioHQ/composio/tree/main/ts/packages/experimental#readme",
16 + "publishConfig": {
17 + "access": "public",
18 + "main": "dist/index.mjs",
19 + "types": "dist/index.d.mts"
20 + },
21 + "exports": {
22 + ".": {
23 + "types": "./dist/index.d.mts",
24 + "default": "./dist/index.mjs"
25 + },
26 + "./pi": {
27 + "types": "./dist/index.d.mts",
28 + "default": "./dist/index.mjs"
29 + },
30 + "./workbench": {
31 + "types": "./dist/workbench/index.d.mts",
32 + "default": "./dist/workbench/index.mjs"
33 + }
34 + },
35 + "files": [
36 + "README.md",
37 + "dist"
38 + ],
39 + "scripts": {
40 + "clean": "git clean -xdf node_modules",
41 + "build:python-helpers": "tsx scripts/build-python-helpers.ts",
42 + "check:python-helpers": "tsx scripts/build-python-helpers.ts && git diff --exit-code -- src/workbench/python-helpers.generated.ts",
43 + "build": "pnpm run build:python-helpers && pnpm exec tsdown",
44 + "test": "vitest run",
45 + "typecheck": "tsc --noEmit -p tsconfig.json"
46 + },
47 + "keywords": [
48 + "composio",
49 + "experimental",
50 + "pi",
51 + "coding-agent",
52 + "tools",
53 + "agent"
54 + ],
55 + "author": "",
56 + "license": "ISC",
57 + "dependencies": {
58 + "typebox": "1.1.38"
59 + },
60 + "peerDependencies": {
61 + "@composio/core": ">=0.10.0 <1.0.0",
62 + "@earendil-works/pi-coding-agent": ">=0.79.0 <1.0.0"
63 + },
64 + "devDependencies": {
65 + "@composio/core": "workspace:*",
66 + "@earendil-works/pi-coding-agent": "0.79.8",
67 + "tsdown": "catalog:",
68 + "tsx": "catalog:",
69 + "typescript": "catalog:",
70 + "vitest": "catalog:"
71 + }
72 +}
ts/packages/experimental/scripts/build-python-helpers.ts new
+37
@@ -0,0 +1,37 @@
1 +/**
2 + * Codegen: Python workbench helper source -> generated TS constant.
3 + *
4 + * The workbench helper is authored as real, ruff-lintable / pytest-testable
5 + * Python under `src/workbench/python-helpers/`. The bundler (tsdown) and the
6 + * tests (vitest) both consume a plain committed `.ts` constant, so we generate
7 + * `src/workbench/python-helpers.generated.ts` from the `.py` source-of-truth.
8 + *
9 + * Run: pnpm --filter @composio/experimental run build:python-helpers
10 + */
11 +
12 +import { readFileSync, writeFileSync } from 'node:fs';
13 +import { dirname, join } from 'node:path';
14 +import { fileURLToPath } from 'node:url';
15 +import * as prettier from 'prettier';
16 +
17 +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
18 +const PACKAGE_DIR = join(SCRIPT_DIR, '..');
19 +const PY_SOURCE = join(PACKAGE_DIR, 'src/workbench/python-helpers/composio_helper.py');
20 +const OUTPUT = join(PACKAGE_DIR, 'src/workbench/python-helpers.generated.ts');
21 +
22 +const pyText = readFileSync(PY_SOURCE, 'utf8');
23 +
24 +const raw =
25 + `// GENERATED by scripts/build-python-helpers.ts — do not edit; edit the .py source.\n` +
26 + `// Source: src/workbench/python-helpers/composio_helper.py\n` +
27 + `export const PYTHON_WORKBENCH_HELPER_SOURCE = ${JSON.stringify(pyText)};\n`;
28 +
29 +// Format with the repo's prettier config so the committed file is stable and the
30 +// lint-staged hook / CI freshness check never see drift.
31 +const prettierConfig = await prettier.resolveConfig(OUTPUT);
32 +const generated = await prettier.format(raw, { ...prettierConfig, filepath: OUTPUT });
33 +
34 +writeFileSync(OUTPUT, generated);
35 +
36 +// eslint-disable-next-line no-console
37 +console.log(`Wrote ${OUTPUT} (${pyText.length} chars of Python source)`);
ts/packages/experimental/src/index.ts new
+10
@@ -0,0 +1,10 @@
1 +/**
2 + * Experimental Composio integrations and helpers.
3 + *
4 + * Currently includes the experimental Pi provider for
5 + * @earendil-works/pi-coding-agent.
6 + *
7 + * @packageDocumentation
8 + * @module experimental
9 + */
10 +export * from './pi/index';
ts/packages/experimental/src/pi/auth-links.ts new
+44
@@ -0,0 +1,44 @@
1 +import { runHook } from './hooks';
2 +import { hookControls } from './results';
3 +import type { PiAuthLinkContext, PiHookControls, PiSessionToolCapabilities } from './types';
4 +
5 +export const extractComposioConnectLinks = (value: unknown): string[] => {
6 + const text = stringifyUnknown(value);
7 + const connectLinks = text.match(/https:\/\/connect\.composio\.dev\/[^\s<>)"']+/gi) ?? [];
8 + const genericLinks =
9 + text.match(/https:\/\/[^\s<>)"']*composio[^\s<>)"']*\/link\/[^\s<>)"']+/gi) ?? [];
10 + return [
11 + ...new Set([...connectLinks, ...genericLinks].map(url => url.replace(/[.,;:!?]+$/g, ''))),
12 + ];
13 +};
14 +
15 +const stringifyUnknown = (value: unknown): string => {
16 + if (typeof value === 'string') return value;
17 + try {
18 + return JSON.stringify(value);
19 + } catch {
20 + return String(value);
21 + }
22 +};
23 +
24 +export const applyAuthLinkHandlers = async (
25 + capabilities: PiSessionToolCapabilities,
26 + value: unknown,
27 + context: Omit<PiAuthLinkContext, 'url' | keyof PiHookControls>
28 +): Promise<{ value: unknown; authLinks: string[] }> => {
29 + const links = extractComposioConnectLinks(value);
30 + const run = async (index: number, currentValue: unknown): Promise<unknown> => {
31 + const url = links[index];
32 + if (!url) return currentValue;
33 + return run(
34 + index + 1,
35 + await runHook(
36 + capabilities.hooks?.onAuthLink,
37 + { ...context, ...hookControls, url, result: currentValue },
38 + async () => currentValue
39 + )
40 + );
41 + };
42 +
43 + return { value: await run(0, value), authLinks: links };
44 +};
ts/packages/experimental/src/pi/connections.ts new
+167
@@ -0,0 +1,167 @@
1 +import type {
2 + PiComposioSessionLike,
3 + PiConnectionHandlers,
4 + PiConnectionManagementContext,
5 + PiConnectionManagementResult,
6 + PiConnectionToolkitResult,
7 + PiProviderOptions,
8 + PiSessionToolCapabilities,
9 + PiSessionToolOptions,
10 +} from './types';
11 +import { stringValue } from './utils';
12 +
13 +export const defaultIsToolkitConnected = (state: unknown): boolean => {
14 + if (!state || typeof state !== 'object') return false;
15 + const record = state as Record<string, unknown>;
16 + if (record.isNoAuth === true || record.is_no_auth === true) return true;
17 + if (typeof record.isConnected === 'boolean') return record.isConnected;
18 + if (typeof record.is_connected === 'boolean') return record.is_connected;
19 +
20 + const connection = record.connection as Record<string, unknown> | undefined;
21 + if (connection) {
22 + if (connection.isActive === true || connection.is_active === true) return true;
23 + if (connection.status === 'ACTIVE') return true;
24 + const nestedConnectedAccount = connection.connectedAccount as
25 + | Record<string, unknown>
26 + | undefined;
27 + if (nestedConnectedAccount?.status === 'ACTIVE') return true;
28 + const nestedConnectedAccountSnake = connection.connected_account as
29 + | Record<string, unknown>
30 + | undefined;
31 + if (nestedConnectedAccountSnake?.status === 'ACTIVE') return true;
32 + }
33 +
34 + const connectedAccount = record.connectedAccount as Record<string, unknown> | undefined;
35 + if (connectedAccount?.status === 'ACTIVE') return true;
36 + const connectedAccountSnake = record.connected_account as Record<string, unknown> | undefined;
37 + if (connectedAccountSnake?.status === 'ACTIVE') return true;
38 +
39 + return false;
40 +};
41 +
42 +const toolkitKeyFromState = (state: unknown): string | undefined => {
43 + if (!state || typeof state !== 'object') return undefined;
44 + const record = state as Record<string, unknown>;
45 + const toolkit = record.toolkit as Record<string, unknown> | undefined;
46 + return (
47 + stringValue(record.slug) ??
48 + stringValue(record.toolkitSlug) ??
49 + stringValue(record.toolkit_slug) ??
50 + stringValue(record.name) ??
51 + stringValue(toolkit?.slug)
52 + );
53 +};
54 +
55 +export const normalizeToolkitStateMap = (
56 + raw: unknown,
57 + requestedToolkits: string[]
58 +): Map<string, unknown> => {
59 + const byToolkit = new Map<string, unknown>();
60 + const addState = (toolkit: string | undefined, state: unknown) => {
61 + if (toolkit) byToolkit.set(toolkit.toLowerCase(), state);
62 + };
63 +
64 + if (!raw) return byToolkit;
65 +
66 + if (Array.isArray(raw)) {
67 + raw.forEach((state, index) =>
68 + addState(toolkitKeyFromState(state) ?? requestedToolkits[index], state)
69 + );
70 + return byToolkit;
71 + }
72 +
73 + if (typeof raw === 'object') {
74 + const record = raw as Record<string, unknown>;
75 + if (Array.isArray(record.items)) {
76 + record.items.forEach((state, index) =>
77 + addState(toolkitKeyFromState(state) ?? requestedToolkits[index], state)
78 + );
79 + return byToolkit;
80 + }
81 +
82 + for (const toolkit of requestedToolkits) {
83 + if (record[toolkit] !== undefined) {
84 + addState(toolkit, record[toolkit]);
85 + }
86 + }
87 +
88 + if (byToolkit.size === 0 && requestedToolkits.length === 1) {
89 + addState(toolkitKeyFromState(raw) ?? requestedToolkits[0], raw);
90 + }
91 + }
92 +
93 + return byToolkit;
94 +};
95 +
96 +export const formatDefaultConnectionResult = <TState, TAuthorizeResult>(
97 + results: Record<string, PiConnectionToolkitResult<TState, TAuthorizeResult>>
98 +): PiConnectionManagementResult<TState, TAuthorizeResult> => {
99 + const missing = Object.values(results).filter(result => !result.connected).length;
100 + return {
101 + successful: true,
102 + data: {
103 + message:
104 + missing === 0
105 + ? 'All requested toolkits are connected.'
106 + : 'Connection flow initiated for missing toolkits.',
107 + results,
108 + },
109 + error: null,
110 + };
111 +};
112 +
113 +const inferSessionConnections = (
114 + session: PiComposioSessionLike,
115 + options: PiSessionToolOptions
116 +): PiConnectionHandlers | undefined => {
117 + if (!session.toolkits && !session.authorize) return undefined;
118 + return {
119 + getToolkitStates: session.toolkits
120 + ? toolkits => session.toolkits?.({ toolkits, limit: Math.max(toolkits.length, 1) })
121 + : undefined,
122 + authorizeToolkit: session.authorize
123 + ? (toolkit, authorizeOptions) =>
124 + session.authorize?.(toolkit, {
125 + callbackUrl: authorizeOptions.callbackUrl ?? options.callbackUrl,
126 + alias: authorizeOptions.alias,
127 + experimental: authorizeOptions.experimental,
128 + })
129 + : undefined,
130 + };
131 +};
132 +
133 +const isCapabilityInput = (
134 + value: PiComposioSessionLike | PiSessionToolCapabilities
135 +): value is PiSessionToolCapabilities =>
136 + 'connections' in value ||
137 + 'hooks' in value ||
138 + 'includeWorkbenchTools' in value ||
139 + 'names' in value;
140 +
141 +export const toCapabilities = (
142 + input: PiComposioSessionLike | PiSessionToolCapabilities,
143 + providerOptions: PiProviderOptions,
144 + options: PiSessionToolOptions = {}
145 +): PiSessionToolCapabilities => {
146 + if (isCapabilityInput(input)) {
147 + return {
148 + ...providerOptions,
149 + ...input,
150 + names: { ...(providerOptions as PiSessionToolOptions).names, ...(input.names ?? {}) },
151 + };
152 + }
153 +
154 + const mergedOptions = { ...providerOptions, ...options };
155 + return {
156 + ...mergedOptions,
157 + sessionId: input.sessionId,
158 + search: params => input.search(params),
159 + execute: (toolSlug, args, executeOptions) =>
160 + executeOptions
161 + ? input.execute(toolSlug, args, executeOptions)
162 + : input.execute(toolSlug, args),
163 + connections: inferSessionConnections(input, mergedOptions),
164 + };
165 +};
166 +
167 +export type { PiConnectionManagementContext };
ts/packages/experimental/src/pi/hooks.ts new
+19
@@ -0,0 +1,19 @@
1 +import type { MaybePromise, PiHookNext } from './types';
2 +
3 +export const runHook = async <TResult, TContext>(
4 + hook: ((ctx: TContext, next: PiHookNext<TResult>) => MaybePromise<unknown>) | undefined,
5 + context: TContext,
6 + getDefaultResult: () => MaybePromise<TResult>
7 +): Promise<TResult | unknown> => {
8 + if (!hook) return getDefaultResult();
9 +
10 + const state: { nextResult?: Promise<TResult> } = {};
11 + const next = async (): Promise<TResult> => {
12 + state.nextResult ??= Promise.resolve(getDefaultResult());
13 + return state.nextResult;
14 + };
15 +
16 + const hookValue = await hook(context, next);
17 + if (hookValue !== undefined) return hookValue;
18 + return state.nextResult ?? next();
19 +};
ts/packages/experimental/src/pi/index.ts new
+40
@@ -0,0 +1,40 @@
1 +export { extractComposioConnectLinks } from './auth-links';
2 +export { PiProvider } from './provider';
3 +export { createPiComposioSystemPrompt } from './prompt';
4 +export { denyPiToolCall } from './results';
5 +export { DEFAULT_SESSION_TOOL_NAMES as PI_COMPOSIO_SESSION_TOOL_NAMES } from './types';
6 +export type {
7 + MaybePromise,
8 + PiAuthLinkContext,
9 + PiAuthorizeToolkitOptions,
10 + PiBaseToolContext,
11 + PiComposioSessionLike,
12 + PiConnectionHandlers,
13 + PiConnectionManagementContext,
14 + PiConnectionManagementResult,
15 + PiConnectionToolkitResult,
16 + PiDeniedResult,
17 + PiExecutableSessionLike,
18 + PiExecuteContext,
19 + PiExecuteHandler,
20 + PiExecuteHookContext,
21 + PiHookControls,
22 + PiHookNext,
23 + PiManageConnectionsHookContext,
24 + PiProviderOptions,
25 + PiRemoteBashHookContext,
26 + PiRemoteBashRequest,
27 + PiRemoteWorkbenchHookContext,
28 + PiRemoteWorkbenchRequest,
29 + PiSearchContext,
30 + PiSearchHandler,
31 + PiSearchHookContext,
32 + PiSessionHooks,
33 + PiSessionToolCapabilities,
34 + PiSessionToolName,
35 + PiSessionToolOptions,
36 + PiTool,
37 + PiToolCollection,
38 + PiToolDetails,
39 + PiToolResultFormatter,
40 +} from './types';
ts/packages/experimental/src/pi/prompt.ts new
+16
@@ -0,0 +1,16 @@
1 +export const createPiComposioSystemPrompt = (
2 + sessionId?: string,
3 + options: { includeWorkbenchTools?: boolean } = {}
4 +): string =>
5 + [
6 + "You have Composio tools for working across the user's connected apps.",
7 + 'Use composio_search_tools to find the right tool before executing app actions.',
8 + 'Use composio_manage_connections when an app is not connected; never ask for OAuth secrets or API keys.',
9 + 'Use composio_execute_tool with exact tool slugs and schema-compliant arguments from search results.',
10 + options.includeWorkbenchTools
11 + ? 'Use composio_remote_workbench or composio_remote_bash for large outputs, remote files, or Composio-authenticated scripting in the remote workbench.'
12 + : undefined,
13 + sessionId ? `Composio session id: ${sessionId}` : undefined,
14 + ]
15 + .filter(Boolean)
16 + .join('\n');
ts/packages/experimental/src/pi/provider.ts new
+128
@@ -0,0 +1,128 @@
1 +import {
2 + BaseAgenticProvider,
3 + type ExecuteToolFn,
4 + type McpServerGetResponse,
5 + type McpUrlResponse,
6 + normalizeToolArguments,
7 + type Tool as ComposioTool,
8 + type ToolExecuteResponse,
9 +} from '@composio/core';
10 +import { defineTool } from '@earendil-works/pi-coding-agent';
11 +import type { Static } from 'typebox';
12 +
13 +import { defaultFormatResult, toPiErrorResult, toPiResult } from './results';
14 +import { objectInputSchema } from './schemas';
15 +import { createPiSessionTools } from './session-tools';
16 +import type {
17 + PiComposioSessionLike,
18 + PiProviderOptions,
19 + PiSessionToolCapabilities,
20 + PiSessionToolOptions,
21 + PiTool,
22 + PiToolCollection,
23 +} from './types';
24 +
25 +/**
26 + * Provider for integrating Composio tools with Pi SDK custom tools.
27 + */
28 +export class PiProvider extends BaseAgenticProvider<
29 + PiToolCollection,
30 + PiTool,
31 + McpServerGetResponse
32 +> {
33 + readonly name = 'pi';
34 +
35 + constructor(private readonly options: PiProviderOptions = {}) {
36 + super();
37 + }
38 +
39 + /**
40 + * Wrap a concrete Composio tool as a Pi custom tool definition.
41 + */
42 + wrapTool(composioTool: ComposioTool, executeTool: ExecuteToolFn): PiTool {
43 + const formatter = this.options.formatResult ?? defaultFormatResult;
44 + const catchErrors = this.options.catchErrors ?? true;
45 + const schema = objectInputSchema(composioTool.inputParameters);
46 +
47 + return defineTool({
48 + name: composioTool.slug,
49 + label: `${this.options.labelPrefix ?? 'Composio'}: ${composioTool.name ?? composioTool.slug}`,
50 + description: composioTool.description ?? `Execute ${composioTool.slug} with Composio.`,
51 + promptSnippet: `Use ${composioTool.slug} for ${composioTool.description ?? composioTool.name ?? 'this Composio action'}.`,
52 + parameters: schema,
53 + ...(this.options.executionMode ? { executionMode: this.options.executionMode } : {}),
54 + prepareArguments: args =>
55 + normalizeToolArguments(args, composioTool.slug) as Static<typeof schema>,
56 + execute: async (_toolCallId, params) => {
57 + try {
58 + const args = normalizeToolArguments(params, composioTool.slug);
59 + const result = await executeTool(composioTool.slug, args);
60 + return toPiResult(result, formatter, {
61 + slug: composioTool.slug,
62 + error: (result as ToolExecuteResponse | undefined)?.error,
63 + });
64 + } catch (error) {
65 + if (!catchErrors) throw error;
66 + return toPiErrorResult(error, formatter, { slug: composioTool.slug });
67 + }
68 + },
69 + });
70 + }
71 +
72 + /**
73 + * Wrap multiple concrete Composio tools as Pi custom tools.
74 + */
75 + wrapTools(tools: ComposioTool[], executeTool: ExecuteToolFn): PiToolCollection {
76 + return tools.map(tool => this.wrapTool(tool, executeTool));
77 + }
78 +
79 + createSessionTools<
80 + TSearchResult = unknown,
81 + TExecuteResult = unknown,
82 + TState = unknown,
83 + TAuthorizeResult = unknown,
84 + TToolkitStates = unknown,
85 + >(
86 + capabilities: PiSessionToolCapabilities<
87 + TSearchResult,
88 + TExecuteResult,
89 + TState,
90 + TAuthorizeResult,
91 + TToolkitStates
92 + >
93 + ): PiToolCollection;
94 + createSessionTools<
95 + TSearchResult = unknown,
96 + TExecuteResult = unknown,
97 + TToolkitStates = unknown,
98 + TAuthorizeResult = unknown,
99 + >(
100 + session: PiComposioSessionLike<TSearchResult, TExecuteResult, TToolkitStates, TAuthorizeResult>,
101 + options?: PiSessionToolOptions
102 + ): PiToolCollection;
103 + /**
104 + * Create Slack-bot-style dynamic Composio helpers.
105 + *
106 + * Prefer passing capabilities (`search`, `execute`, `connections`, `hooks`)
107 + * so app code owns auth, interception, and shared/service-session routing.
108 + * Passing a native Tool Router session is also supported; connection
109 + * management uses `session.toolkits()` + `session.authorize()` when present
110 + * and never executes `COMPOSIO_MANAGE_CONNECTIONS` internally.
111 + */
112 + createSessionTools(
113 + input: PiComposioSessionLike | PiSessionToolCapabilities,
114 + options: PiSessionToolOptions = {}
115 + ): PiToolCollection {
116 + return createPiSessionTools(input, this.options, options);
117 + }
118 +
119 + /**
120 + * Transform MCP URL responses into Pi-compatible standard URL entries.
121 + */
122 + wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
123 + return data.map(item => ({
124 + url: new URL(item.url),
125 + name: item.name,
126 + })) as McpServerGetResponse;
127 + }
128 +}
ts/packages/experimental/src/pi/results.ts new
+59
@@ -0,0 +1,59 @@
1 +import type { AgentToolResult } from '@earendil-works/pi-coding-agent';
2 +
3 +import type { PiDeniedResult, PiHookControls, PiToolDetails, PiToolResultFormatter } from './types';
4 +
5 +export const denyPiToolCall = (error: string): PiDeniedResult => ({
6 + successful: false,
7 + error,
8 + data: null,
9 + denied: true,
10 +});
11 +
12 +export const hookControls: PiHookControls = {
13 + deny: denyPiToolCall,
14 +};
15 +
16 +export const defaultFormatResult: PiToolResultFormatter = result => JSON.stringify(result, null, 2);
17 +
18 +export const stringifyError = (error: unknown): string =>
19 + error instanceof Error ? error.message : String(error);
20 +
21 +const isPiDeniedResult = (value: unknown): value is PiDeniedResult =>
22 + !!value &&
23 + typeof value === 'object' &&
24 + (value as Partial<PiDeniedResult>).denied === true &&
25 + (value as Partial<PiDeniedResult>).successful === false;
26 +
27 +export const toPiResult = (
28 + value: unknown,
29 + formatter: PiToolResultFormatter,
30 + details: PiToolDetails = {}
31 +): AgentToolResult<PiToolDetails> => ({
32 + content: [{ type: 'text' as const, text: formatter(value) }],
33 + details: {
34 + ...details,
35 + denied: details.denied ?? (isPiDeniedResult(value) ? true : undefined),
36 + result: value,
37 + },
38 +});
39 +
40 +export const toPiErrorResult = (
41 + error: unknown,
42 + formatter: PiToolResultFormatter,
43 + details: PiToolDetails = {}
44 +): AgentToolResult<PiToolDetails> => {
45 + const message = stringifyError(error);
46 + const value = {
47 + successful: false,
48 + error: message,
49 + data: null,
50 + };
51 + return {
52 + content: [{ type: 'text' as const, text: formatter(value) }],
53 + details: {
54 + ...details,
55 + error: message,
56 + result: value,
57 + },
58 + };
59 +};
ts/packages/experimental/src/pi/schemas.ts new
+22
@@ -0,0 +1,22 @@
1 +import type { Tool as ComposioTool } from '@composio/core';
2 +import { Type, type TSchema } from 'typebox';
3 +
4 +const EmptyObjectSchema = Type.Object({});
5 +
6 +export const ToolkitsSchema = Type.Optional(
7 + Type.Array(Type.String({ description: 'Optional toolkit slug filter, e.g. github, gmail.' }))
8 +);
9 +
10 +export const objectInputSchema = (schema: ComposioTool['inputParameters'] | undefined): TSchema => {
11 + const candidate =
12 + schema && typeof schema === 'object'
13 + ? ({ ...schema } as Record<string, unknown>)
14 + : ({ ...EmptyObjectSchema } as Record<string, unknown>);
15 + if (!candidate.type) candidate.type = 'object';
16 + if (!candidate.properties) candidate.properties = {};
17 + if (candidate.additionalProperties === undefined) candidate.additionalProperties = true;
18 + return Type.Unsafe(candidate);
19 +};
20 +
21 +export const optionalRecordSchema = (description: string) =>
22 + Type.Optional(Type.Record(Type.String(), Type.Any(), { description }));
ts/packages/experimental/src/pi/session-tools.ts new
+577
@@ -0,0 +1,577 @@
1 +import { normalizeToolArguments } from '@composio/core';
2 +import { defineTool } from '@earendil-works/pi-coding-agent';
3 +import { Type } from 'typebox';
4 +
5 +import { applyAuthLinkHandlers } from './auth-links';
6 +import {
7 + defaultIsToolkitConnected,
8 + formatDefaultConnectionResult,
9 + normalizeToolkitStateMap,
10 + toCapabilities,
11 +} from './connections';
12 +import { runHook } from './hooks';
13 +import { defaultFormatResult, hookControls, toPiErrorResult, toPiResult } from './results';
14 +import { optionalRecordSchema, ToolkitsSchema } from './schemas';
15 +import { DEFAULT_SESSION_TOOL_NAMES } from './types';
16 +import type {
17 + PiBaseToolContext,
18 + PiComposioSessionLike,
19 + PiConnectionManagementContext,
20 + PiConnectionToolkitResult,
21 + PiExecuteContext,
22 + PiExecuteHookContext,
23 + PiManageConnectionsHookContext,
24 + PiProviderOptions,
25 + PiRemoteBashHookContext,
26 + PiRemoteBashRequest,
27 + PiRemoteWorkbenchHookContext,
28 + PiRemoteWorkbenchRequest,
29 + PiSearchContext,
30 + PiSearchHookContext,
31 + PiSessionToolCapabilities,
32 + PiSessionToolName,
33 + PiSessionToolOptions,
34 + PiToolCollection,
35 + PiToolDetails,
36 +} from './types';
37 +import { maybeTransform, normalizeToolkits, toolkitFromToolSlug } from './utils';
38 +
39 +// eslint-disable-next-line max-lines-per-function
40 +export const createPiSessionTools = (
41 + input: PiComposioSessionLike | PiSessionToolCapabilities,
42 + providerOptions: PiProviderOptions,
43 + options: PiSessionToolOptions = {}
44 +): PiToolCollection => {
45 + const capabilities = toCapabilities(input, providerOptions, options);
46 + const formatter = capabilities.formatResult ?? defaultFormatResult;
47 + const catchErrors = capabilities.catchErrors ?? true;
48 + const names = { ...DEFAULT_SESSION_TOOL_NAMES, ...(capabilities.names ?? {}) };
49 + const executionMode = capabilities.executionMode;
50 +
51 + const buildBaseContext = (
52 + toolCallId: string,
53 + sourceTool: (typeof DEFAULT_SESSION_TOOL_NAMES)[PiSessionToolName] | string,
54 + originalRequest: unknown
55 + ): PiBaseToolContext => ({
56 + toolCallId,
57 + sourceTool,
58 + sessionId: capabilities.sessionId,
59 + originalRequest,
60 + });
61 +
62 + const manageConnectionsForToolkits = async (
63 + toolCallId: string,
64 + originalRequest: unknown,
65 + toolkits: string[],
66 + reinitiateAll = false
67 + ): Promise<{
68 + value: unknown;
69 + authLinks: string[];
70 + context: PiConnectionManagementContext;
71 + denied?: boolean;
72 + }> => {
73 + const connectionContext: PiConnectionManagementContext = {
74 + ...buildBaseContext(toolCallId, names.manageConnections, originalRequest),
75 + requestedToolkits: toolkits,
76 + callbackUrl: capabilities.callbackUrl,
77 + reinitiateAll,
78 + };
79 + const hookContext: PiManageConnectionsHookContext = {
80 + ...hookControls,
81 + request: { toolkits, reinitiateAll },
82 + context: connectionContext,
83 + };
84 + const authLinks: string[] = [];
85 +
86 + const value = await runHook(capabilities.hooks?.manageConnections, hookContext, async () => {
87 + const requestedToolkits = normalizeToolkits(hookContext.request.toolkits) ?? [];
88 + const shouldReinitiateAll = hookContext.request.reinitiateAll;
89 + connectionContext.requestedToolkits = requestedToolkits;
90 + connectionContext.reinitiateAll = shouldReinitiateAll;
91 +
92 + const statesRaw = await capabilities.connections?.getToolkitStates?.(
93 + requestedToolkits,
94 + connectionContext
95 + );
96 + const states = normalizeToolkitStateMap(statesRaw, requestedToolkits);
97 + const results: Record<string, PiConnectionToolkitResult> = {};
98 +
99 + for (const toolkit of requestedToolkits) {
100 + const state = states.get(toolkit.toLowerCase());
101 + const connected = state
102 + ? (capabilities.connections?.isConnected?.(state, {
103 + toolkit,
104 + request: connectionContext,
105 + }) ?? defaultIsToolkitConnected(state))
106 + : false;
107 +
108 + if (connected && !shouldReinitiateAll) {
109 + results[toolkit] = {
110 + toolkit,
111 + connected: true,
112 + status: 'connected',
113 + state,
114 + };
115 + continue;
116 + }
117 +
118 + if (!capabilities.connections?.authorizeToolkit) {
119 + results[toolkit] = {
120 + toolkit,
121 + connected: false,
122 + status: 'missing_authorize_handler',
123 + state,
124 + };
125 + continue;
126 + }
127 +
128 + const authorization = await capabilities.connections.authorizeToolkit(
129 + toolkit,
130 + {
131 + callbackUrl: capabilities.callbackUrl,
132 + reinitiate: shouldReinitiateAll,
133 + },
134 + connectionContext
135 + );
136 + const handledAuthorization = await applyAuthLinkHandlers(capabilities, authorization, {
137 + ...connectionContext,
138 + toolkit,
139 + result: authorization,
140 + });
141 + authLinks.push(...handledAuthorization.authLinks);
142 + results[toolkit] = {
143 + toolkit,
144 + connected: false,
145 + status: 'auth_initiated',
146 + state,
147 + authorization: handledAuthorization.value,
148 + };
149 + }
150 +
151 + return formatDefaultConnectionResult(results);
152 + });
153 +
154 + return { value, authLinks, context: connectionContext };
155 + };
156 +
157 + const executeWithPolicy = async (
158 + toolCallId: string,
159 + sourceTool: (typeof DEFAULT_SESSION_TOOL_NAMES)[PiSessionToolName] | string,
160 + originalRequest: unknown,
161 + toolSlug: string,
162 + args: Record<string, unknown>,
163 + account?: string
164 + ): Promise<{
165 + value: unknown;
166 + authLinks: string[];
167 + context: PiExecuteContext;
168 + denied?: boolean;
169 + }> => {
170 + const executeContext: PiExecuteContext = {
171 + ...buildBaseContext(toolCallId, sourceTool, originalRequest),
172 + toolSlug,
173 + toolkit: toolkitFromToolSlug(toolSlug),
174 + args,
175 + account,
176 + };
177 + const authLinks: string[] = [];
178 + const hookContext: PiExecuteHookContext = {
179 + ...hookControls,
180 + request: { toolSlug, args, account },
181 + context: executeContext,
182 + manageConnections: async (managedToolkits, manageOptions) => {
183 + const managed = await manageConnectionsForToolkits(
184 + toolCallId,
185 + originalRequest,
186 + managedToolkits,
187 + manageOptions?.reinitiateAll
188 + );
189 + authLinks.push(...managed.authLinks);
190 + return managed.value;
191 + },
192 + };
193 +
194 + const value = await runHook(capabilities.hooks?.execute, hookContext, async () => {
195 + const finalToolSlug = hookContext.request.toolSlug;
196 + const finalArgs = hookContext.request.args;
197 + const finalAccount = hookContext.request.account;
198 + const finalContext: PiExecuteContext = {
199 + ...executeContext,
200 + toolSlug: finalToolSlug,
201 + toolkit: toolkitFromToolSlug(finalToolSlug),
202 + args: finalArgs,
203 + account: finalAccount,
204 + };
205 + hookContext.context = finalContext;
206 +
207 + const execute = hookContext.request.execute ?? capabilities.execute;
208 + const session = hookContext.request.session;
209 + const result = session
210 + ? await session.execute(
211 + finalToolSlug,
212 + finalArgs,
213 + finalAccount ? { account: finalAccount } : undefined
214 + )
215 + : await execute(
216 + finalToolSlug,
217 + finalArgs,
218 + finalAccount ? { account: finalAccount } : undefined,
219 + finalContext
220 + );
221 + const handledResult = await applyAuthLinkHandlers(capabilities, result, {
222 + ...finalContext,
223 + result,
224 + });
225 + authLinks.push(...handledResult.authLinks);
226 + return handledResult.value;
227 + });
228 +
229 + return { value, authLinks, context: hookContext.context };
230 + };
231 +
232 + const searchTools = defineTool({
233 + name: names.search,
234 + label: 'Composio Search Tools',
235 + description:
236 + 'Search Composio for tools that can perform a requested action. Search globally by default; pass toolkits only when intentionally narrowing the search.',
237 + promptSnippet:
238 + 'Use composio_search_tools to discover exact Composio tool slugs and schemas before executing app actions.',
239 + promptGuidelines: [
240 + 'Search Composio before inventing tool slugs or arguments.',
241 + 'Only pass a toolkit filter when you intentionally want to narrow search results.',
242 + ],
243 + parameters: Type.Object({
244 + query: Type.String({
245 + description: 'Natural language description of the action to perform.',
246 + }),
247 + toolkits: ToolkitsSchema,
248 + }),
249 + ...(executionMode ? { executionMode } : {}),
250 + execute: async (toolCallId, params) => {
251 + try {
252 + const requestedToolkits = normalizeToolkits(params.toolkits);
253 + const searchContext: PiSearchContext = {
254 + ...buildBaseContext(toolCallId, names.search, params),
255 + query: params.query,
256 + requestedToolkits,
257 + };
258 + const hookContext: PiSearchHookContext = {
259 + ...hookControls,
260 + request: {
261 + query: params.query,
262 + ...(requestedToolkits ? { toolkits: requestedToolkits } : {}),
263 + },
264 + context: searchContext,
265 + };
266 + const authLinks: string[] = [];
267 + const value = await runHook(capabilities.hooks?.search, hookContext, async () => {
268 + const toolkits = normalizeToolkits(hookContext.request.toolkits);
269 + hookContext.context.query = hookContext.request.query;
270 + hookContext.context.requestedToolkits = toolkits;
271 + const result = await capabilities.search(
272 + {
273 + query: hookContext.request.query,
274 + ...(toolkits ? { toolkits } : {}),
275 + },
276 + hookContext.context
277 + );
278 + const handledResult = await applyAuthLinkHandlers(capabilities, result, {
279 + ...hookContext.context,
280 + result,
281 + });
282 + authLinks.push(...handledResult.authLinks);
283 + return handledResult.value;
284 + });
285 + const transformed = await maybeTransform(capabilities, {
286 + tool: 'search',
287 + requestedToolkits: hookContext.context.requestedToolkits,
288 + value,
289 + context: hookContext.context,
290 + });
291 + return toPiResult(transformed, formatter, { slug: names.search, authLinks });
292 + } catch (error) {
293 + if (!catchErrors) throw error;
294 + return toPiErrorResult(error, formatter, { slug: names.search });
295 + }
296 + },
297 + });
298 +
299 + const manageConnections = defineTool({
300 + name: names.manageConnections,
301 + label: 'Composio Manage Connections',
302 + description:
303 + 'Check whether the user has active connections for requested toolkits and initiate Composio auth when needed.',
304 + promptSnippet:
305 + 'Use composio_manage_connections when a searched tool requires a missing app connection.',
306 + promptGuidelines: [
307 + 'When an app connection is missing, call composio_manage_connections with the toolkit slug.',
308 + 'Never ask the user for OAuth secrets or API keys directly.',
309 + ],
310 + parameters: Type.Object({
311 + toolkits: Type.Array(
312 + Type.String({ description: 'Toolkit slugs to check/connect, e.g. github, gmail.' })
313 + ),
314 + reinitiate_all: Type.Optional(
315 + Type.Boolean({ description: 'Force reconnection even if active connections exist.' })
316 + ),
317 + }),
318 + ...(executionMode ? { executionMode } : {}),
319 + execute: async (toolCallId, params) => {
320 + const toolkits = normalizeToolkits(params.toolkits) ?? [];
321 + try {
322 + const managed = await manageConnectionsForToolkits(
323 + toolCallId,
324 + params,
325 + toolkits,
326 + params.reinitiate_all ?? false
327 + );
328 + const transformed = await maybeTransform(capabilities, {
329 + tool: 'manageConnections',
330 + requestedToolkits: toolkits,
331 + value: managed.value,
332 + context: managed.context,
333 + });
334 + return toPiResult(transformed, formatter, {
335 + slug: names.manageConnections,
336 + authLinks: managed.authLinks,
337 + denied: managed.denied,
338 + });
339 + } catch (error) {
340 + if (!catchErrors) throw error;
341 + return toPiErrorResult(error, formatter, { slug: names.manageConnections });
342 + }
343 + },
344 + });
345 +
346 + const executeTool = defineTool({
347 + name: names.execute,
348 + label: 'Composio Execute Tool',
349 + description:
350 + 'Execute an exact Composio tool slug using the configured Composio execution capability. Use search first so the slug and arguments match the schema.',
351 + promptSnippet:
352 + 'Use composio_execute_tool to execute an exact Composio tool slug returned by composio_search_tools.',
353 + promptGuidelines: [
354 + 'Always use exact tool slugs and schema-compliant arguments.',
355 + 'For missing connections, use composio_manage_connections instead of asking for credentials.',
356 + ],
357 + parameters: Type.Object({
358 + toolSlug: Type.String({
359 + description: 'Exact Composio tool slug, e.g. GITHUB_CREATE_ISSUE.',
360 + }),
361 + arguments: optionalRecordSchema('Tool arguments matching the searched schema.'),
362 + account: Type.Optional(
363 + Type.String({
364 + description:
365 + 'Optional account selector for multi-account sessions. Use connected account id or alias when required.',
366 + })
367 + ),
368 + }),
369 + ...(executionMode ? { executionMode } : {}),
370 + prepareArguments: args =>
371 + normalizeToolArguments(args, names.execute) as {
372 + toolSlug: string;
373 + arguments?: Record<string, unknown>;
374 + account?: string;
375 + },
376 + execute: async (toolCallId, params) => {
377 + const toolSlug = params.toolSlug.trim();
378 + const args = params.arguments ?? {};
379 + try {
380 + const executed = await executeWithPolicy(
381 + toolCallId,
382 + names.execute,
383 + params,
384 + toolSlug,
385 + args,
386 + params.account
387 + );
388 + const transformed = await maybeTransform(capabilities, {
389 + tool: 'execute',
390 + requestedToolkits: toolkitFromToolSlug(executed.context.toolSlug)
391 + ? [toolkitFromToolSlug(executed.context.toolSlug)!]
392 + : undefined,
393 + value: executed.value,
394 + context: executed.context,
395 + });
396 + return toPiResult(transformed, formatter, {
397 + slug: executed.context.toolSlug || names.execute,
398 + authLinks: executed.authLinks,
399 + denied: executed.denied,
400 + });
401 + } catch (error) {
402 + if (!catchErrors) throw error;
403 + return toPiErrorResult(error, formatter, { slug: toolSlug || names.execute });
404 + }
405 + },
406 + });
407 +
408 + if (!capabilities.includeWorkbenchTools) {
409 + return [searchTools, manageConnections, executeTool];
410 + }
411 +
412 + const remoteWorkbench = defineTool({
413 + name: names.remoteWorkbench,
414 + label: 'Composio Remote Workbench',
415 + description:
416 + 'Execute Python code inside the Composio remote workbench for this Tool Router session. Use it for remote files, bulk processing, large tool outputs, and Composio-authenticated scripting.',
417 + promptSnippet:
418 + 'Use composio_remote_workbench for Python scripting in the Composio remote sandbox when data is large, stored in remote files, or needs session-authenticated tool/proxy helpers.',
419 + promptGuidelines: [
420 + 'Use composio_remote_workbench for large data processing or remote workbench files; do not use it for tiny inline transformations.',
421 + 'Split long-running work into small cells and save checkpoints in the workbench filesystem.',
422 + ],
423 + parameters: Type.Object({
424 + code_to_execute: Type.String({
425 + description:
426 + 'Python code to run in the persistent Composio remote workbench. Keep cells focused and avoid long-running jobs.',
427 + }),
428 + timeout: Type.Optional(
429 + Type.Number({
430 + minimum: 1,
431 + maximum: 780,
432 + description:
433 + 'Maximum seconds to allow execution. Defaults to the session/backend workbench timeout.',
434 + })
435 + ),
436 + thought: Type.Optional(
437 + Type.String({ description: 'Concise objective for why this workbench cell is needed.' })
438 + ),
439 + file_path: Type.Optional(
440 + Type.String({
441 + description: 'Remote workbench path/glob to analyze when processing a file.',
442 + })
443 + ),
444 + disabled_tools: Type.Optional(
445 + Type.Array(Type.String({ description: 'Tool slugs to disable for this workbench call.' }))
446 + ),
447 + session_id: Type.Optional(
448 + Type.String({
449 + description:
450 + 'Workbench workflow session id. Defaults to the Composio Tool Router session id.',
451 + })
452 + ),
453 + }),
454 + ...(executionMode ? { executionMode } : {}),
455 + execute: async (toolCallId, params) => {
456 + try {
457 + const request: PiRemoteWorkbenchRequest = {
458 + ...params,
459 + ...(params.session_id || capabilities.sessionId
460 + ? { session_id: params.session_id ?? capabilities.sessionId }
461 + : {}),
462 + };
463 + const hookContext: PiRemoteWorkbenchHookContext = {
464 + ...hookControls,
465 + request,
466 + context: {
467 + ...buildBaseContext(toolCallId, names.remoteWorkbench, params),
468 + toolSlug: 'COMPOSIO_REMOTE_WORKBENCH',
469 + args: request,
470 + },
471 + };
472 + const authLinks: string[] = [];
473 + const details: Pick<PiToolDetails, 'denied'> = {};
474 + const value = await runHook(capabilities.hooks?.remoteWorkbench, hookContext, async () => {
475 + const executed = await executeWithPolicy(
476 + toolCallId,
477 + names.remoteWorkbench,
478 + params,
479 + 'COMPOSIO_REMOTE_WORKBENCH',
480 + hookContext.request
481 + );
482 + authLinks.push(...executed.authLinks);
483 + details.denied = executed.denied;
484 + hookContext.context = executed.context;
485 + return executed.value;
486 + });
487 + const transformed = await maybeTransform(capabilities, {
488 + tool: 'remoteWorkbench',
489 + value,
490 + context: hookContext.context,
491 + });
492 + return toPiResult(transformed, formatter, {
493 + slug: hookContext.context.toolSlug,
494 + authLinks,
495 + denied: details.denied,
496 + });
497 + } catch (error) {
498 + if (!catchErrors) throw error;
499 + return toPiErrorResult(error, formatter, { slug: 'COMPOSIO_REMOTE_WORKBENCH' });
500 + }
501 + },
502 + });
503 +
504 + const remoteBash = defineTool({
505 + name: names.remoteBash,
506 + label: 'Composio Remote Bash',
507 + description:
508 + 'Execute a bash command inside the Composio remote workbench for this Tool Router session.',
509 + promptSnippet:
510 + 'Use composio_remote_bash to inspect or manipulate files in the Composio remote workbench filesystem.',
511 + promptGuidelines: [
512 + 'Use composio_remote_bash for filesystem inspection in the remote workbench, especially for truncated output files.',
513 + 'Keep commands short and non-interactive.',
514 + ],
515 + parameters: Type.Object({
516 + command: Type.String({
517 + description: 'Bash command to execute in the Composio remote workbench.',
518 + }),
519 + session_id: Type.Optional(
520 + Type.String({
521 + description:
522 + 'Workbench workflow session id. Defaults to the Composio Tool Router session id.',
523 + })
524 + ),
525 + }),
526 + ...(executionMode ? { executionMode } : {}),
527 + execute: async (toolCallId, params) => {
528 + try {
529 + const request: PiRemoteBashRequest = {
530 + ...params,
531 + ...(params.session_id || capabilities.sessionId
532 + ? { session_id: params.session_id ?? capabilities.sessionId }
533 + : {}),
534 + };
535 + const hookContext: PiRemoteBashHookContext = {
536 + ...hookControls,
537 + request,
538 + context: {
539 + ...buildBaseContext(toolCallId, names.remoteBash, params),
540 + toolSlug: 'COMPOSIO_REMOTE_BASH_TOOL',
541 + args: request,
542 + },
543 + };
544 + const authLinks: string[] = [];
545 + const details: Pick<PiToolDetails, 'denied'> = {};
546 + const value = await runHook(capabilities.hooks?.remoteBash, hookContext, async () => {
547 + const executed = await executeWithPolicy(
548 + toolCallId,
549 + names.remoteBash,
550 + params,
551 + 'COMPOSIO_REMOTE_BASH_TOOL',
552 + hookContext.request
553 + );
554 + authLinks.push(...executed.authLinks);
555 + details.denied = executed.denied;
556 + hookContext.context = executed.context;
557 + return executed.value;
558 + });
559 + const transformed = await maybeTransform(capabilities, {
560 + tool: 'remoteBash',
561 + value,
562 + context: hookContext.context,
563 + });
564 + return toPiResult(transformed, formatter, {
565 + slug: hookContext.context.toolSlug,
566 + authLinks,
567 + denied: details.denied,
568 + });
569 + } catch (error) {
570 + if (!catchErrors) throw error;
571 + return toPiErrorResult(error, formatter, { slug: 'COMPOSIO_REMOTE_BASH_TOOL' });
572 + }
573 + },
574 + });
575 +
576 + return [searchTools, manageConnections, executeTool, remoteWorkbench, remoteBash];
577 +};
ts/packages/experimental/src/pi/types.ts new
+299
@@ -0,0 +1,299 @@
1 +import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
2 +
3 +export type PiToolDetails = {
4 + slug?: string;
5 + result?: unknown;
6 + error?: string | null;
7 + authLinks?: string[];
8 + denied?: boolean;
9 +};
10 +
11 +export type PiTool = ToolDefinition;
12 +export type PiToolCollection = PiTool[];
13 +
14 +export type PiToolResultFormatter = (result: unknown) => string;
15 +
16 +export type PiDeniedResult = {
17 + successful: false;
18 + error: string;
19 + data: null;
20 + denied: true;
21 +};
22 +
23 +export interface PiHookControls {
24 + /** Return from a hook to explicitly deny/divert the operation with a model-visible error. */
25 + deny(error: string): PiDeniedResult;
26 +}
27 +
28 +export type MaybePromise<T> = T | Promise<T>;
29 +
30 +export type PiHookNext<TResult> = () => Promise<TResult>;
31 +
32 +export interface PiProviderOptions {
33 + /** Prefix shown in Pi's TUI labels. Defaults to `Composio`. */
34 + labelPrefix?: string;
35 + /** Per-tool execution mode. Defaults to Pi's runtime default. */
36 + executionMode?: PiTool['executionMode'];
37 + /** Convert Composio results to the text sent back to the model. */
38 + formatResult?: PiToolResultFormatter;
39 + /** Return thrown errors as structured JSON instead of rethrowing to Pi. Defaults to true. */
40 + catchErrors?: boolean;
41 +}
42 +
43 +export const DEFAULT_SESSION_TOOL_NAMES = {
44 + search: 'composio_search_tools',
45 + manageConnections: 'composio_manage_connections',
46 + execute: 'composio_execute_tool',
47 + remoteWorkbench: 'composio_remote_workbench',
48 + remoteBash: 'composio_remote_bash',
49 +} as const;
50 +
51 +export type PiSessionToolName = keyof typeof DEFAULT_SESSION_TOOL_NAMES;
52 +
53 +export interface PiBaseToolContext {
54 + /** Tool call id passed by Pi. */
55 + toolCallId: string;
56 + /** The Pi helper tool that is currently running. */
57 + sourceTool: string;
58 + /** Optional Composio Tool Router session id for prompts/logging/default workbench session ids. */
59 + sessionId?: string;
60 + /** Original helper request sent by the model. */
61 + originalRequest: unknown;
62 +}
63 +
64 +export interface PiSearchContext extends PiBaseToolContext {
65 + query: string;
66 + requestedToolkits?: string[];
67 +}
68 +
69 +export interface PiConnectionManagementContext extends PiBaseToolContext {
70 + requestedToolkits: string[];
71 + callbackUrl?: string;
72 + reinitiateAll: boolean;
73 +}
74 +
75 +export interface PiExecuteContext extends PiBaseToolContext {
76 + toolSlug: string;
77 + toolkit?: string;
78 + args: Record<string, unknown>;
79 + account?: string;
80 +}
81 +
82 +export interface PiAuthLinkContext<TResult = unknown> extends PiHookControls {
83 + url: string;
84 + toolkit?: string;
85 + sourceTool: string;
86 + originalRequest: unknown;
87 + result: TResult;
88 + sessionId?: string;
89 +}
90 +
91 +export interface PiSessionToolOptions extends PiProviderOptions {
92 + /** Callback URL passed to `authorizeToolkit()` when connection management initiates auth. */
93 + callbackUrl?: string;
94 + /** Include first-class wrappers for COMPOSIO_REMOTE_WORKBENCH and COMPOSIO_REMOTE_BASH_TOOL. Defaults to false. */
95 + includeWorkbenchTools?: boolean;
96 + /** Override the default helper tool names. */
97 + names?: Partial<typeof DEFAULT_SESSION_TOOL_NAMES>;
98 + /** Called before a result is returned to Pi; useful for redacting or routing auth links. */
99 + transformResult?: (params: {
100 + tool: PiSessionToolName;
101 + requestedToolkits?: string[];
102 + value: unknown;
103 + context?: PiBaseToolContext;
104 + }) => unknown | Promise<unknown>;
105 +}
106 +
107 +export interface PiComposioSessionLike<
108 + TSearchResult = unknown,
109 + TExecuteResult = unknown,
110 + TToolkitStates = unknown,
111 + TAuthorizeResult = unknown,
112 +> {
113 + sessionId?: string;
114 + search(params: { query: string; toolkits?: string[] }): Promise<TSearchResult>;
115 + execute(
116 + toolSlug: string,
117 + args?: Record<string, unknown>,
118 + options?: { account?: string }
119 + ): Promise<TExecuteResult>;
120 + /** Native Tool Router connection-state API. Preferred over executing a meta tool. */
121 + toolkits?(options?: {
122 + toolkits?: string[];
123 + isConnected?: boolean;
124 + limit?: number;
125 + cursor?: string;
126 + }): Promise<TToolkitStates>;
127 + authorize?(
128 + toolkit: string,
129 + options?: { callbackUrl?: string; alias?: string; experimental?: unknown }
130 + ): Promise<TAuthorizeResult>;
131 +}
132 +
133 +export interface PiExecutableSessionLike<TExecuteResult = unknown> {
134 + sessionId?: string;
135 + execute(
136 + toolSlug: string,
137 + args?: Record<string, unknown>,
138 + options?: { account?: string }
139 + ): Promise<TExecuteResult>;
140 +}
141 +
142 +export type PiSearchHandler<TSearchResult = unknown> = (
143 + params: { query: string; toolkits?: string[] },
144 + context: PiSearchContext
145 +) => MaybePromise<TSearchResult>;
146 +
147 +export type PiExecuteHandler<TExecuteResult = unknown> = (
148 + toolSlug: string,
149 + args: Record<string, unknown>,
150 + options: { account?: string } | undefined,
151 + context: PiExecuteContext
152 +) => MaybePromise<TExecuteResult>;
153 +
154 +export interface PiAuthorizeToolkitOptions {
155 + callbackUrl?: string;
156 + alias?: string;
157 + experimental?: unknown;
158 + reinitiate?: boolean;
159 +}
160 +
161 +export interface PiConnectionHandlers<
162 + TState = unknown,
163 + TAuthorizeResult = unknown,
164 + TToolkitStates = unknown,
165 +> {
166 + /** Return connection states for the requested toolkits, e.g. from `session.toolkits({ toolkits })`. */
167 + getToolkitStates?: (
168 + toolkits: string[],
169 + context: PiConnectionManagementContext
170 + ) => MaybePromise<TToolkitStates>;
171 + /** Start auth for one toolkit, e.g. via `session.authorize(toolkit, { callbackUrl })`. */
172 + authorizeToolkit?: (
173 + toolkit: string,
174 + options: PiAuthorizeToolkitOptions,
175 + context: PiConnectionManagementContext
176 + ) => Promise<TAuthorizeResult> | TAuthorizeResult;
177 + /** Interpret one state returned by `getToolkitStates()`. Defaults handle common Tool Router shapes. */
178 + isConnected?: (
179 + state: TState,
180 + context: { toolkit: string; request: PiConnectionManagementContext }
181 + ) => boolean;
182 +}
183 +
184 +export interface PiSearchHookContext extends PiHookControls {
185 + request: { query: string; toolkits?: string[] };
186 + context: PiSearchContext;
187 +}
188 +
189 +export interface PiManageConnectionsHookContext extends PiHookControls {
190 + request: { toolkits: string[]; reinitiateAll: boolean };
191 + context: PiConnectionManagementContext;
192 +}
193 +
194 +export interface PiExecuteHookContext<TExecuteResult = unknown> extends PiHookControls {
195 + request: {
196 + toolSlug: string;
197 + args: Record<string, unknown>;
198 + account?: string;
199 + session?: PiExecutableSessionLike<TExecuteResult>;
200 + execute?: PiExecuteHandler<TExecuteResult>;
201 + };
202 + context: PiExecuteContext;
203 + manageConnections: (
204 + toolkits: string[],
205 + options?: { reinitiateAll?: boolean }
206 + ) => Promise<unknown>;
207 +}
208 +
209 +export interface PiRemoteWorkbenchRequest extends Record<string, unknown> {
210 + code_to_execute: string;
211 + timeout?: number;
212 + thought?: string;
213 + file_path?: string;
214 + disabled_tools?: string[];
215 + session_id?: string;
216 +}
217 +
218 +export interface PiRemoteBashRequest extends Record<string, unknown> {
219 + command: string;
220 + session_id?: string;
221 +}
222 +
223 +export interface PiRemoteWorkbenchHookContext extends PiHookControls {
224 + request: PiRemoteWorkbenchRequest;
225 + context: PiExecuteContext;
226 +}
227 +
228 +export interface PiRemoteBashHookContext extends PiHookControls {
229 + request: PiRemoteBashRequest;
230 + context: PiExecuteContext;
231 +}
232 +
233 +export interface PiSessionHooks<
234 + TSearchResult = unknown,
235 + TExecuteResult = unknown,
236 + TState = unknown,
237 + TAuthorizeResult = unknown,
238 +> {
239 + /** Middleware around search. Mutate `ctx.request`, call `next()` to run search, or return a replacement result. */
240 + search?: (ctx: PiSearchHookContext, next: PiHookNext<TSearchResult>) => MaybePromise<unknown>;
241 + /** Middleware around connection management. Mutate `ctx.request`, call `next()` to check/connect, or return a replacement result. */
242 + manageConnections?: (
243 + ctx: PiManageConnectionsHookContext,
244 + next: PiHookNext<PiConnectionManagementResult<TState, TAuthorizeResult>>
245 + ) => MaybePromise<unknown>;
246 + /** Middleware around tool execution. Mutate `ctx.request`, call `next()` to execute, or return a replacement result. */
247 + execute?: (
248 + ctx: PiExecuteHookContext<TExecuteResult>,
249 + next: PiHookNext<TExecuteResult>
250 + ) => MaybePromise<unknown>;
251 + /** Middleware around the remote Python workbench helper. Runs outside, then through, the generic `execute` hook when `next()` is called. */
252 + remoteWorkbench?: (
253 + ctx: PiRemoteWorkbenchHookContext,
254 + next: PiHookNext<TExecuteResult>
255 + ) => MaybePromise<unknown>;
256 + /** Middleware around the remote bash helper. Runs outside, then through, the generic `execute` hook when `next()` is called. */
257 + remoteBash?: (
258 + ctx: PiRemoteBashHookContext,
259 + next: PiHookNext<TExecuteResult>
260 + ) => MaybePromise<unknown>;
261 + /** Middleware for auth links found in any result. Call `next()` to keep the current model-visible result, or return a replacement. */
262 + onAuthLink?: (
263 + ctx: PiAuthLinkContext<TSearchResult | TExecuteResult | TAuthorizeResult>,
264 + next: PiHookNext<TSearchResult | TExecuteResult | TAuthorizeResult>
265 + ) => MaybePromise<unknown>;
266 +}
267 +
268 +export interface PiSessionToolCapabilities<
269 + TSearchResult = unknown,
270 + TExecuteResult = unknown,
271 + TState = unknown,
272 + TAuthorizeResult = unknown,
273 + TToolkitStates = unknown,
274 +> extends PiSessionToolOptions {
275 + /** Optional session id for prompt context and default workbench session ids. */
276 + sessionId?: string;
277 + search: PiSearchHandler<TSearchResult>;
278 + execute: PiExecuteHandler<TExecuteResult>;
279 + connections?: PiConnectionHandlers<TState, TAuthorizeResult, TToolkitStates>;
280 + hooks?: PiSessionHooks<TSearchResult, TExecuteResult, TState, TAuthorizeResult>;
281 +}
282 +
283 +export type PiConnectionToolkitResult<TState = unknown, TAuthorizeResult = unknown> = {
284 + toolkit: string;
285 + connected: boolean;
286 + status: 'connected' | 'auth_initiated' | 'missing_authorize_handler';
287 + state?: TState;
288 + authorization?: TAuthorizeResult;
289 + authLinks?: string[];
290 +};
291 +
292 +export type PiConnectionManagementResult<TState = unknown, TAuthorizeResult = unknown> = {
293 + successful: true;
294 + data: {
295 + message: string;
296 + results: Record<string, PiConnectionToolkitResult<TState, TAuthorizeResult>>;
297 + };
298 + error: null;
299 +};
ts/packages/experimental/src/pi/utils.ts new
+36
@@ -0,0 +1,36 @@
1 +import type { PiSessionToolOptions } from './types';
2 +
3 +export const normalizeToolkits = (value: unknown): string[] | undefined => {
4 + const toolkits = Array.isArray(value)
5 + ? value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)
6 + : typeof value === 'string' && value.trim().length > 0
7 + ? [value]
8 + : [];
9 + const unique = [...new Set(toolkits.map(toolkit => toolkit.trim()))];
10 + return unique.length > 0 ? unique : undefined;
11 +};
12 +
13 +export const maybeTransform = async (
14 + options: Pick<PiSessionToolOptions, 'transformResult'>,
15 + params: Parameters<NonNullable<PiSessionToolOptions['transformResult']>>[0]
16 +): Promise<unknown> => (options.transformResult ? options.transformResult(params) : params.value);
17 +
18 +export const stringValue = (value: unknown): string | undefined =>
19 + typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
20 +
21 +export const toolkitFromToolSlug = (toolSlug: string): string | undefined => {
22 + const normalized = toolSlug.trim().toLowerCase();
23 + if (!normalized || normalized.startsWith('composio_')) return undefined;
24 +
25 + const knownPrefixes: Array<[string, string]> = [
26 + ['google_calendar_', 'googlecalendar'],
27 + ['google_drive_', 'googledrive'],
28 + ['microsoft_teams_', 'microsoftteams'],
29 + ];
30 + for (const [prefix, toolkit] of knownPrefixes) {
31 + if (normalized.startsWith(prefix)) return toolkit;
32 + }
33 +
34 + const [prefix] = normalized.split('_');
35 + return prefix || undefined;
36 +};
ts/packages/experimental/src/workbench/index.ts new
+23
@@ -0,0 +1,23 @@
1 +/**
2 + * Experimental local workbench helpers, exposed on the
3 + * `@composio/experimental/workbench` subpath. **Experimental — shape may change
4 + * in future releases.**
5 + *
6 + * These helpers let you run a Composio Tool Router session in a sandbox you own
7 + * (your filesystem, your shell, your security boundary) instead of Composio's
8 + * hosted remote sandbox. `experimental_createLocalWorkbenchSession` returns a
9 + * Python `helperSource` (exposing `run_composio_tool`, `invoke_llm`,
10 + * `web_search`, `proxy_execute`) plus the `env` that helper needs to reach
11 + * Composio from inside your box. Import them from this subpath:
12 + * `import { experimental_createLocalWorkbenchSession } from '@composio/experimental/workbench';`
13 + *
14 + * @packageDocumentation
15 + * @module experimental/workbench
16 + */
17 +export { experimental_createLocalWorkbenchSession } from './local-workbench';
18 +export {
19 + experimental_createPythonWorkbenchHelperSource,
20 + experimental_createWorkbenchEnv,
21 +} from './shim';
22 +export type { PythonWorkbenchHelperSourceOptions, WorkbenchEnvOptions } from './shim';
23 +export type { LocalWorkbenchSession } from './types';
ts/packages/experimental/src/workbench/local-workbench.ts new
+34
@@ -0,0 +1,34 @@
1 +import type { Composio, Session } from '@composio/core';
2 +import {
3 + experimental_createPythonWorkbenchHelperSource,
4 + experimental_createWorkbenchEnv,
5 +} from './shim';
6 +import type { LocalWorkbenchSession } from './types';
7 +
8 +export async function experimental_createLocalWorkbenchSession(
9 + composio: Composio,
10 + session: Session<unknown, unknown, never>
11 +): Promise<LocalWorkbenchSession> {
12 + if (session.workbench?.enable !== false) {
13 + throw new Error(
14 + 'experimental_createLocalWorkbenchSession requires a session created with workbench.enable: false. ' +
15 + 'The remote workbench and a local sandbox cannot both run for one session.'
16 + );
17 + }
18 +
19 + const { apiKey, baseURL } = composio.getConfig();
20 + if (!apiKey) {
21 + throw new Error('A Composio project API key is required to create a local workbench session');
22 + }
23 +
24 + const env = experimental_createWorkbenchEnv({
25 + sessionId: session.sessionId,
26 + backendUrl: baseURL ?? 'https://backend.composio.dev',
27 + apiKey,
28 + });
29 +
30 + return {
31 + env,
32 + helperSource: experimental_createPythonWorkbenchHelperSource(),
33 + };
34 +}
ts/packages/experimental/src/workbench/python-helpers.generated.ts new
+4
@@ -0,0 +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';
ts/packages/experimental/src/workbench/python-helpers/composio_helper.py new
+402
@@ -0,0 +1,402 @@
1 +import json
2 +import os
3 +import random
4 +import time
5 +import urllib.error
6 +import urllib.parse
7 +import urllib.request
8 +import uuid
9 +from typing import Any, Dict, Literal, Optional
10 +
11 +
12 +# Config is injected by the SDK via an `_INTERNAL` dict in a prologue prepended
13 +# at runtime. When running this file directly (e.g. pytest), default to empty.
14 +try:
15 + _INTERNAL
16 +except NameError:
17 + _INTERNAL = {}
18 +
19 +
20 +DEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")
21 +RATE_LIMIT_PATTERNS = (
22 + "rate limit",
23 + "ratelimit",
24 + "too many requests",
25 + "quota exceeded",
26 + "resource exhausted",
27 +)
28 +
29 +
30 +def _read_env(name, default=None):
31 + value = os.environ.get(name)
32 + return default if value is None or value == "" else value
33 +
34 +
35 +def _require_value(value, label):
36 + if value is None or value == "":
37 + raise RuntimeError("%s is required" % label)
38 + return value
39 +
40 +
41 +def _request_id():
42 + return str(uuid.uuid4())
43 +
44 +
45 +def _session_execute_url():
46 + backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")
47 + session_id = _require_value(
48 + _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),
49 + "COMPOSIO_TOOLROUTER_SESSION_ID",
50 + )
51 + encoded_session_id = urllib.parse.quote(session_id, safe="")
52 + return "%s/api/v3/tool_router/session/%s/execute" % (backend_url, encoded_session_id)
53 +
54 +
55 +def _session_proxy_execute_url():
56 + backend_url = _read_env("BACKEND_URL", "https://backend.composio.dev").rstrip("/")
57 + session_id = _require_value(
58 + _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"),
59 + "COMPOSIO_TOOLROUTER_SESSION_ID",
60 + )
61 + encoded_session_id = urllib.parse.quote(session_id, safe="")
62 + return "%s/api/v3/tool_router/session/%s/proxy_execute" % (
63 + backend_url,
64 + encoded_session_id,
65 + )
66 +
67 +
68 +def _post_json(url, headers, payload, timeout=120):
69 + body = json.dumps(payload).encode("utf-8")
70 + request = urllib.request.Request(url, data=body, headers=headers, method="POST")
71 + try:
72 + with urllib.request.urlopen(request, timeout=timeout) as response:
73 + return response.status, dict(response.headers), response.read().decode("utf-8")
74 + except urllib.error.HTTPError as error:
75 + return error.code, dict(error.headers), error.read().decode("utf-8")
76 +
77 +
78 +def _parse_json(text):
79 + if not text:
80 + return {}
81 + return json.loads(text)
82 +
83 +
84 +def _safe_json(text):
85 + try:
86 + return _parse_json(text)
87 + except json.JSONDecodeError:
88 + return {"raw": text}
89 +
90 +
91 +def _contains_rate_limit_error(payload):
92 + # Only inspect the API "error" field, not the whole body — otherwise benign
93 + # tool output mentioning "rate limit"/"quota" triggers spurious retries.
94 + if not isinstance(payload, dict):
95 + return False
96 + error = payload.get("error")
97 + if not error:
98 + return False
99 + text = json.dumps(error, default=str).lower()
100 + return any(pattern in text for pattern in RATE_LIMIT_PATTERNS)
101 +
102 +
103 +def _retry_delay(attempt, delay_ms):
104 + base_delay = max(delay_ms, 0) / 1000.0
105 + if base_delay == 0:
106 + return
107 + # Exponential backoff: double the delay each attempt (parity with Apollo).
108 + backoff = base_delay * (2 ** attempt)
109 + jitter = random.uniform(0, min(backoff * 0.2, 0.5))
110 + time.sleep(backoff + jitter)
111 +
112 +
113 +def _json_shape(value):
114 + if isinstance(value, dict):
115 + return {key: _json_shape(item) for key, item in value.items()}
116 + if isinstance(value, list):
117 + return [_json_shape(value[0])] if value else []
118 + if value is None:
119 + return "null"
120 + return type(value).__name__
121 +
122 +
123 +def print_json_structure(value):
124 + print(json.dumps(_json_shape(value), indent=2, sort_keys=True))
125 +
126 +
127 +def _track_helper_event(*_args, **_kwargs):
128 + return None
129 +
130 +
131 +def run_composio_tool(
132 + tool_slug,
133 + arguments=None,
134 + retry_params=None,
135 + print_schema_for_tool=True,
136 + *,
137 + account=None,
138 +):
139 + if not tool_slug:
140 + return {}, "tool_slug is required"
141 +
142 + api_key = _require_value(_read_env("COMPOSIO_API_KEY"), "COMPOSIO_API_KEY")
143 + retry_config = {"max_retries": 3, "delay_ms": 2000}
144 + if retry_params:
145 + retry_config.update(retry_params)
146 +
147 + payload = {
148 + "tool_slug": str(tool_slug).strip().upper(),
149 + "arguments": arguments or {},
150 + }
151 + if account is not None:
152 + payload["account"] = account
153 +
154 + headers = {
155 + "Content-Type": "application/json",
156 + "x-api-key": api_key,
157 + "x-request-id": _request_id(),
158 + }
159 + max_retries = int(retry_config.get("max_retries", 3))
160 + delay_ms = int(retry_config.get("delay_ms", 2000))
161 +
162 + for attempt in range(max_retries + 1):
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
171 + return {}, "Composio tool request failed: %s" % error
172 +
173 + if status == 429 and attempt < max_retries:
174 + _retry_delay(attempt, delay_ms)
175 + continue
176 +
177 + if status >= 400:
178 + response_data = _safe_json(text)
179 + return response_data, "Composio tool execution failed with HTTP %s" % status
180 +
181 + try:
182 + response_data = _parse_json(text)
183 + except json.JSONDecodeError as error:
184 + return {"raw": text}, "Failed to parse Composio tool response as JSON: %s" % error
185 +
186 + if _contains_rate_limit_error(response_data) and attempt < max_retries:
187 + _retry_delay(attempt, delay_ms)
188 + continue
189 +
190 + # A failed tool call returns HTTP 200 with a top-level "error" field;
191 + # surface it as the error tuple element so callers don't read it as success.
192 + if isinstance(response_data, dict) and response_data.get("error"):
193 + return response_data, str(response_data["error"])
194 +
195 + if print_schema_for_tool:
196 + print_json_structure(response_data)
197 + return response_data, ""
198 +
199 + return {}, "Composio tool execution failed after retries"
200 +
201 +
202 +def _strip_code_fence(content):
203 + stripped = content.strip()
204 + code_fence = chr(96) * 3
205 + if stripped.startswith(code_fence):
206 + stripped = stripped[3:].strip()
207 + if stripped.lower().startswith("json"):
208 + stripped = stripped[4:].strip()
209 + if stripped.endswith(code_fence):
210 + stripped = stripped[:-3].strip()
211 + elif stripped.lower().startswith("json\n"):
212 + stripped = stripped[5:].strip()
213 + return stripped.strip()
214 +
215 +
216 +def invoke_llm(query, reasoning_effort=None):
217 + if not query:
218 + return "", "query is required"
219 +
220 + system_prompt = (
221 + "You are a generic, smart large language model. "
222 + "When asked to output a JSON, respond only with valid JSON - "
223 + "no other text / code fences / quotes around the JSON."
224 + )
225 + response, error = run_composio_tool(
226 + "COMPOSIO_SEARCH_GROQ_CHAT",
227 + {
228 + "model": DEFAULT_INVOKE_LLM_MODEL,
229 + "messages": [
230 + {"role": "system", "content": system_prompt},
231 + {"role": "user", "content": query},
232 + ],
233 + "temperature": 0.5,
234 + },
235 + None,
236 + False,
237 + )
238 + _track_helper_event("invoke_llm", {"reasoning_effort": reasoning_effort})
239 +
240 + if error:
241 + return "", error
242 +
243 + choices = (response.get("data") or {}).get("choices", "")
244 + if not choices:
245 + return "", "No choices returned from invoke_llm"
246 +
247 + first_choice = choices[0] if isinstance(choices, list) else choices
248 + content = (first_choice.get("message") or {}).get("content", "")
249 + if not content:
250 + return "", "No content returned from invoke_llm"
251 + return _strip_code_fence(content), ""
252 +
253 +
254 +def web_search(query):
255 + if not query:
256 + return "", "query is required"
257 +
258 + response, error = run_composio_tool(
259 + "COMPOSIO_SEARCH_EXA_ANSWER",
260 + {"content": query},
261 + None,
262 + False,
263 + )
264 + _track_helper_event("web_search", {})
265 +
266 + if error:
267 + return "", error
268 + return (response.get("data") or {}).get("answer", ""), ""
269 +
270 +
271 +def proxy_execute(
272 + method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
273 + endpoint: str,
274 + toolkit: str,
275 + query_params: Optional[Dict[str, str]] = None,
276 + body: Optional[object] = None,
277 + headers: Optional[Dict[str, str]] = None,
278 +) -> tuple[Any, str]:
279 + """Call a toolkit's API directly when no Composio tool exists.
280 +
281 + The session resolves the connected account and injects auth server-side, so
282 + your code never handles raw credentials.
283 +
284 + Args:
285 + method: HTTP method to use for the request. Example: "GET"
286 + endpoint: API endpoint to call. Example: "/repos/owner/repo"
287 + toolkit: Name of the toolkit. Example: "GITHUB"
288 + query_params: Query parameters as key-value pairs. Example: {"q": "is:unread"}
289 + body: The request body (required for POST, PUT, and PATCH requests)
290 + headers: HTTP headers as key-value pairs. Example: {"Accept": "application/json"}
291 +
292 + Returns:
293 + tuple[Any, str]:
294 + - data: Response data from the API (None if error)
295 + - error: Error message ("" if no error)
296 + """
297 + # Wrapped end-to-end so the helper always returns a (data, error) tuple
298 + # rather than raising.
299 + try:
300 + valid_methods = ["GET", "POST", "PUT", "DELETE", "PATCH"]
301 + if method.upper() not in valid_methods:
302 + return None, "Invalid HTTP method: " + method
303 +
304 + if not endpoint.strip():
305 + return None, "Endpoint cannot be empty"
306 +
307 + if not toolkit.strip():
308 + return None, "Toolkit cannot be empty"
309 +
310 + if query_params is not None and not isinstance(query_params, dict):
311 + return None, (
312 + "Invalid query_params type: expected dict or None, got "
313 + + type(query_params).__name__
314 + )
315 +
316 + if headers is not None and not isinstance(headers, dict):
317 + return None, (
318 + "Invalid headers type: expected dict or None, got "
319 + + type(headers).__name__
320 + )
321 +
322 + if method.upper() in ["POST", "PUT", "PATCH"] and body is None:
323 + return None, "Body is required for " + method.upper() + " requests"
324 +
325 + if method.upper() in ["GET", "DELETE"] and body is not None:
326 + return None, "Body should not be provided for " + method.upper() + " requests"
327 +
328 + api_key = _read_env("COMPOSIO_API_KEY")
329 + if not api_key:
330 + return None, "Missing environment variable COMPOSIO_API_KEY"
331 + if not _read_env("COMPOSIO_TOOLROUTER_SESSION_ID"):
332 + return None, "Missing environment variable COMPOSIO_TOOLROUTER_SESSION_ID"
333 +
334 + # Convert query_params and headers dicts to the flat parameters array.
335 + parameters = []
336 + if query_params:
337 + for key, value in query_params.items():
338 + parameters.append({"name": key, "value": str(value), "type": "query"})
339 + if headers:
340 + for key, value in headers.items():
341 + parameters.append({"name": key, "value": str(value), "type": "header"})
342 +
343 + payload = {
344 + "toolkit_slug": toolkit.lower(),
345 + "endpoint": endpoint,
346 + "method": method.upper(),
347 + }
348 + if parameters:
349 + payload["parameters"] = parameters
350 + if body is not None:
351 + payload["body"] = body
352 +
353 + request_headers = {
354 + "Content-Type": "application/json",
355 + "x-api-key": api_key,
356 + "x-request-id": _request_id(),
357 + }
358 +
359 + status, _response_headers, text = _post_json(
360 + _session_proxy_execute_url(), request_headers, payload
361 + )
362 +
363 + # Handle HTTP errors explicitly. Always surface a non-empty message so a
364 + # >=400 response never looks like success (an empty error/message field
365 + # must not win over the default).
366 + if status >= 400:
367 + error_msg = "HTTP " + str(status) + " Error"
368 + try:
369 + error_data = json.loads(text)
370 + if isinstance(error_data, dict):
371 + error_msg = (
372 + error_data.get("error") or error_data.get("message") or error_msg
373 + )
374 + except (ValueError, TypeError):
375 + if text:
376 + sanitized = text[:200].replace("\n", " ").strip()
377 + error_msg = "HTTP " + str(status) + ": " + sanitized
378 + return None, str(error_msg)
379 +
380 + response_data = json.loads(text)
381 +
382 + # The session wraps the proxied response as {data, status, headers}; the
383 + # toolkit's own API may still report a >=400 status inside that envelope.
384 + # `status` can arrive as a string or null, so coerce it before comparing
385 + # — a bare `>= 400` against a non-int would raise and mask a valid result.
386 + if isinstance(response_data, dict):
387 + try:
388 + api_status = int(response_data.get("status", 200))
389 + except (TypeError, ValueError):
390 + api_status = 200
391 + if api_status >= 400:
392 + error_msg = "API request failed"
393 + if isinstance(response_data.get("data"), dict):
394 + error_msg = response_data["data"].get(
395 + "message", response_data["data"].get("error", error_msg)
396 + )
397 + return response_data, "API returned status " + str(api_status) + ": " + str(error_msg)
398 + return response_data.get("data"), ""
399 +
400 + return response_data, ""
401 + except Exception as error:
402 + return None, "Failed to execute proxy request: " + str(error)
ts/packages/experimental/src/workbench/shim.ts new
+48
@@ -0,0 +1,48 @@
1 +import { PYTHON_WORKBENCH_HELPER_SOURCE } from './python-helpers.generated';
2 +
3 +export interface WorkbenchEnvOptions {
4 + sessionId: string;
5 + backendUrl: string;
6 + apiKey: string;
7 +}
8 +
9 +export interface PythonWorkbenchHelperSourceOptions {
10 + invokeLlmModel?: string;
11 +}
12 +
13 +function trimTrailingSlashes(value: string): string {
14 + let end = value.length;
15 + while (end > 0 && value.charCodeAt(end - 1) === 47) {
16 + end -= 1;
17 + }
18 + return value.slice(0, end);
19 +}
20 +
21 +export function experimental_createWorkbenchEnv(env: WorkbenchEnvOptions): Record<string, string> {
22 + return {
23 + BACKEND_URL: trimTrailingSlashes(env.backendUrl),
24 + COMPOSIO_TOOLROUTER_SESSION_ID: env.sessionId,
25 + // SECURITY: this is the developer's full *project* API key, placed in the
26 + // sandbox env. Any code or tool output in the sandbox can read it and
27 + // exfiltrate it, so treat the sandbox as your security boundary and rotate
28 + // this key. The execute endpoint also accepts a session-scoped
29 + // `x-session-access-key`; swapping to that (so the project key never enters
30 + // the sandbox) is the planned follow-up.
31 + COMPOSIO_API_KEY: env.apiKey,
32 + };
33 +}
34 +
35 +export function experimental_createPythonWorkbenchHelperSource(
36 + opts: PythonWorkbenchHelperSourceOptions = {}
37 +): string {
38 + // Inject config by prepending an `_INTERNAL` prologue the helper reads from,
39 + // rather than string-substituting a sentinel. The helper `.py` is authored as
40 + // real, lintable/testable Python; the generated constant is verbatim.
41 + // JSON.stringify-of-JSON.stringify yields a double-quoted string literal that
42 + // is valid Python — JSON string escapes are a subset of Python's.
43 + const config = { invoke_llm_model: opts.invokeLlmModel ?? 'openai/gpt-oss-120b' };
44 + const prologue =
45 + `import json as _composio_internal_json\n` +
46 + `_INTERNAL = _composio_internal_json.loads(${JSON.stringify(JSON.stringify(config))})\n`;
47 + return prologue + PYTHON_WORKBENCH_HELPER_SOURCE;
48 +}
ts/packages/experimental/src/workbench/types.ts new
+4
@@ -0,0 +1,4 @@
1 +export interface LocalWorkbenchSession {
2 + helperSource: string;
3 + env: Record<string, string>;
4 +}
ts/packages/experimental/test/pi.test.ts new
+447
@@ -0,0 +1,447 @@
1 +import { describe, expect, it, vi } from 'vitest';
2 +import type { ExecuteToolFn, Tool } from '@composio/core';
3 +import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
4 +import {
5 + PiProvider,
6 + PI_COMPOSIO_SESSION_TOOL_NAMES,
7 + extractComposioConnectLinks,
8 +} from '../src/index';
9 +
10 +const composioTool = {
11 + slug: 'GITHUB_CREATE_ISSUE',
12 + name: 'Create Issue',
13 + description: 'Create a GitHub issue',
14 + inputParameters: {
15 + type: 'object',
16 + properties: {
17 + owner: { type: 'string' },
18 + repo: { type: 'string' },
19 + title: { type: 'string' },
20 + },
21 + required: ['owner', 'repo', 'title'],
22 + },
23 +} as Tool;
24 +
25 +describe('PiProvider', () => {
26 + it('wraps a Composio tool as a Pi custom tool', async () => {
27 + const executeTool = vi.fn(async () => ({
28 + successful: true,
29 + data: { issueNumber: 123 },
30 + error: null,
31 + logId: 'log_123',
32 + })) as unknown as ExecuteToolFn;
33 + const provider = new PiProvider();
34 +
35 + const tool = provider.wrapTool(composioTool, executeTool);
36 +
37 + expect(tool.name).toBe('GITHUB_CREATE_ISSUE');
38 + expect(tool.label).toContain('Create Issue');
39 + expect(tool.parameters).toMatchObject({ type: 'object' });
40 +
41 + const result = await tool.execute(
42 + 'call_1',
43 + { owner: 'ComposioHQ', repo: 'composio', title: 'Test' } as never,
44 + undefined,
45 + undefined,
46 + undefined as never
47 + );
48 +
49 + expect(executeTool).toHaveBeenCalledWith('GITHUB_CREATE_ISSUE', {
50 + owner: 'ComposioHQ',
51 + repo: 'composio',
52 + title: 'Test',
53 + });
54 + expect((result.content[0] as { text: string } | undefined)?.text).toContain('issueNumber');
55 + expect((result.details as { slug?: string }).slug).toBe('GITHUB_CREATE_ISSUE');
56 + });
57 +
58 + it('creates dynamic session tools for search, manage connections, and execute', async () => {
59 + const session = {
60 + sessionId: 'trs_123',
61 + search: vi.fn(async () => ({ results: [{ tool: 'GITHUB_CREATE_ISSUE' }] })),
62 + execute: vi.fn(async (toolSlug: string) => ({
63 + successful: true,
64 + data: { toolSlug },
65 + error: null,
66 + })),
67 + authorize: vi.fn(async (toolkit: string) => ({
68 + redirectUrl: `https://connect.composio.dev/${toolkit}`,
69 + })),
70 + };
71 + const provider = new PiProvider();
72 + const tools = provider.createSessionTools(session);
73 + const piCompatibleTools: ToolDefinition[] = tools;
74 +
75 + expect(piCompatibleTools.map(tool => tool.name)).toEqual([
76 + PI_COMPOSIO_SESSION_TOOL_NAMES.search,
77 + PI_COMPOSIO_SESSION_TOOL_NAMES.manageConnections,
78 + PI_COMPOSIO_SESSION_TOOL_NAMES.execute,
79 + ]);
80 +
81 + const search = tools[0]!;
82 + const searchResult = await search.execute(
83 + 'call_search',
84 + { query: 'create github issue', toolkits: ['github'] } as never,
85 + undefined,
86 + undefined,
87 + undefined as never
88 + );
89 + expect(session.search).toHaveBeenCalledWith({
90 + query: 'create github issue',
91 + toolkits: ['github'],
92 + });
93 + expect((searchResult.content[0] as { text: string } | undefined)?.text).toContain(
94 + 'GITHUB_CREATE_ISSUE'
95 + );
96 +
97 + const execute = tools[2]!;
98 + await execute.execute(
99 + 'call_execute',
100 + { toolSlug: 'GITHUB_CREATE_ISSUE', arguments: { title: 'Hello' }, account: 'acct' } as never,
101 + undefined,
102 + undefined,
103 + undefined as never
104 + );
105 + expect(session.execute).toHaveBeenCalledWith(
106 + 'GITHUB_CREATE_ISSUE',
107 + { title: 'Hello' },
108 + { account: 'acct' }
109 + );
110 + });
111 +
112 + it('can include first-class remote workbench helpers', async () => {
113 + const session = {
114 + sessionId: 'trs_123',
115 + search: vi.fn(),
116 + execute: vi.fn(async (toolSlug: string, args: Record<string, unknown>) => ({
117 + successful: true,
118 + data: { toolSlug, args },
119 + error: null,
120 + })),
121 + authorize: vi.fn(),
122 + };
123 + const provider = new PiProvider();
124 + const tools = provider.createSessionTools(session, { includeWorkbenchTools: true });
125 +
126 + expect(tools.map(tool => tool.name)).toEqual([
127 + PI_COMPOSIO_SESSION_TOOL_NAMES.search,
128 + PI_COMPOSIO_SESSION_TOOL_NAMES.manageConnections,
129 + PI_COMPOSIO_SESSION_TOOL_NAMES.execute,
130 + PI_COMPOSIO_SESSION_TOOL_NAMES.remoteWorkbench,
131 + PI_COMPOSIO_SESSION_TOOL_NAMES.remoteBash,
132 + ]);
133 +
134 + const remoteWorkbench = tools[3]!;
135 + await remoteWorkbench.execute(
136 + 'call_workbench',
137 + { code_to_execute: 'print("hello")' } as never,
138 + undefined,
139 + undefined,
140 + undefined as never
141 + );
142 +
143 + expect(session.execute).toHaveBeenCalledWith('COMPOSIO_REMOTE_WORKBENCH', {
144 + code_to_execute: 'print("hello")',
145 + session_id: 'trs_123',
146 + });
147 +
148 + const remoteBash = tools[4]!;
149 + await remoteBash.execute(
150 + 'call_bash',
151 + { command: 'ls -la', session_id: 'workflow-1' } as never,
152 + undefined,
153 + undefined,
154 + undefined as never
155 + );
156 +
157 + expect(session.execute).toHaveBeenCalledWith('COMPOSIO_REMOTE_BASH_TOOL', {
158 + command: 'ls -la',
159 + session_id: 'workflow-1',
160 + });
161 + });
162 +
163 + it('applies remote workbench and bash hooks', async () => {
164 + const execute = vi.fn(async (toolSlug: string, args: Record<string, unknown>) => ({
165 + successful: true,
166 + data: { toolSlug, args },
167 + error: null,
168 + }));
169 + const provider = new PiProvider();
170 + const tools = provider.createSessionTools({
171 + sessionId: 'trs_123',
172 + search: vi.fn(async () => ({})),
173 + execute,
174 + includeWorkbenchTools: true,
175 + hooks: {
176 + remoteWorkbench: async (ctx, next) => {
177 + ctx.request.code_to_execute = 'print("patched")';
178 + const result = await next();
179 + return { successful: true, data: { wrapped: result }, error: null };
180 + },
181 + remoteBash: ctx => ({
182 + successful: true,
183 + data: { skippedCommand: ctx.request.command },
184 + error: null,
185 + }),
186 + },
187 + });
188 +
189 + const remoteWorkbench = tools[3]!;
190 + const workbenchResult = await remoteWorkbench.execute(
191 + 'call_workbench',
192 + { code_to_execute: 'print("hello")' } as never,
193 + undefined,
194 + undefined,
195 + undefined as never
196 + );
197 +
198 + expect(execute).toHaveBeenCalledWith(
199 + 'COMPOSIO_REMOTE_WORKBENCH',
200 + { code_to_execute: 'print("patched")', session_id: 'trs_123' },
201 + undefined,
202 + expect.objectContaining({ sourceTool: PI_COMPOSIO_SESSION_TOOL_NAMES.remoteWorkbench })
203 + );
204 + expect((workbenchResult.content[0] as { text: string } | undefined)?.text).toContain('wrapped');
205 +
206 + const remoteBash = tools[4]!;
207 + const bashResult = await remoteBash.execute(
208 + 'call_bash',
209 + { command: 'cat secret.txt' } as never,
210 + undefined,
211 + undefined,
212 + undefined as never
213 + );
214 +
215 + expect(execute).not.toHaveBeenCalledWith(
216 + 'COMPOSIO_REMOTE_BASH_TOOL',
217 + expect.anything(),
218 + expect.anything(),
219 + expect.anything()
220 + );
221 + expect((bashResult.content[0] as { text: string } | undefined)?.text).toContain(
222 + 'skippedCommand'
223 + );
224 + });
225 +
226 + it('manages connections through native toolkit-state and authorize handlers without executing a meta tool', async () => {
227 + const session = {
228 + sessionId: 'trs_123',
229 + search: vi.fn(async (_params: { query: string; toolkits?: string[] }) => ({})),
230 + execute: vi.fn(
231 + async (
232 + _toolSlug: string,
233 + _args?: Record<string, unknown>,
234 + _options?: { account?: string }
235 + ) => ({})
236 + ),
237 + toolkits: vi.fn(async (_options?: { toolkits?: string[] }) => ({
238 + items: [
239 + { slug: 'github', connection: { isActive: true } },
240 + { slug: 'gmail', connection: undefined },
241 + ],
242 + })),
243 + authorize: vi.fn(async (toolkit: string, _options?: unknown) => ({
244 + redirectUrl: `https://connect.composio.dev/${toolkit}`,
245 + })),
246 + };
247 + const handleAuthLink = vi.fn();
248 + const provider = new PiProvider();
249 + const [_, manageConnections] = provider.createSessionTools({
250 + sessionId: session.sessionId,
251 + search: session.search,
252 + execute: session.execute,
253 + connections: {
254 + getToolkitStates: (toolkits: string[]) => session.toolkits({ toolkits }),
255 + authorizeToolkit: (toolkit: string, options: unknown) =>
256 + session.authorize(toolkit, options),
257 + },
258 + hooks: { onAuthLink: handleAuthLink },
259 + callbackUrl: 'https://example.com/callback',
260 + });
261 +
262 + const result = await manageConnections!.execute(
263 + 'call_manage',
264 + { toolkits: ['github', 'gmail'] } as never,
265 + undefined,
266 + undefined,
267 + undefined as never
268 + );
269 +
270 + expect(session.toolkits).toHaveBeenCalledWith({ toolkits: ['github', 'gmail'] });
271 + expect(session.authorize).toHaveBeenCalledWith('gmail', {
272 + callbackUrl: 'https://example.com/callback',
273 + reinitiate: false,
274 + });
275 + expect(session.execute).not.toHaveBeenCalledWith(
276 + 'COMPOSIO_MANAGE_CONNECTIONS',
277 + expect.anything(),
278 + expect.anything()
279 + );
280 + expect(handleAuthLink).toHaveBeenCalledWith(
281 + expect.objectContaining({
282 + url: 'https://connect.composio.dev/gmail',
283 + toolkit: 'gmail',
284 + sourceTool: PI_COMPOSIO_SESSION_TOOL_NAMES.manageConnections,
285 + }),
286 + expect.any(Function)
287 + );
288 + expect((result.content[0] as { text: string } | undefined)?.text).toContain('auth_initiated');
289 + });
290 +
291 + it('applies search and execute hooks', async () => {
292 + const search = vi.fn(async () => ({ results: [{ tool: 'SLACKBOT_SEND_MESSAGE' }] }));
293 + const execute = vi.fn(async (toolSlug: string, args: Record<string, unknown>) => ({
294 + successful: true,
295 + data: { toolSlug, args },
296 + error: null,
297 + }));
298 + const provider = new PiProvider();
299 + const tools = provider.createSessionTools({
300 + search,
301 + execute,
302 + hooks: {
303 + search: (ctx, next) => {
304 + ctx.request.toolkits = ctx.request.toolkits?.map(toolkit =>
305 + toolkit === 'slack' ? 'slackbot' : toolkit
306 + );
307 + return next();
308 + },
309 + execute: (ctx, next) => {
310 + if (ctx.request.toolSlug.startsWith('COMPOSIO_')) {
311 + return ctx.deny('meta tools blocked');
312 + }
313 + ctx.request.toolSlug = ctx.request.toolSlug.replace(/^SLACK_/, 'SLACKBOT_');
314 + return next();
315 + },
316 + },
317 + });
318 +
319 + const searchTool = tools[0]!;
320 + await searchTool.execute(
321 + 'call_search',
322 + { query: 'message channel', toolkits: ['slack'] } as never,
323 + undefined,
324 + undefined,
325 + undefined as never
326 + );
327 + expect(search).toHaveBeenCalledWith(
328 + { query: 'message channel', toolkits: ['slackbot'] },
329 + expect.objectContaining({
330 + requestedToolkits: ['slackbot'],
331 + originalRequest: expect.objectContaining({ toolkits: ['slack'] }),
332 + })
333 + );
334 +
335 + const executeTool = tools[2]!;
336 + await executeTool.execute(
337 + 'call_execute',
338 + { toolSlug: 'SLACK_SEND_MESSAGE', arguments: { text: 'hi' } } as never,
339 + undefined,
340 + undefined,
341 + undefined as never
342 + );
343 + expect(execute).toHaveBeenCalledWith(
344 + 'SLACKBOT_SEND_MESSAGE',
345 + { text: 'hi' },
346 + undefined,
347 + expect.objectContaining({ toolSlug: 'SLACKBOT_SEND_MESSAGE' })
348 + );
349 +
350 + const denied = await executeTool.execute(
351 + 'call_execute',
352 + { toolSlug: 'COMPOSIO_MANAGE_CONNECTIONS', arguments: {} } as never,
353 + undefined,
354 + undefined,
355 + undefined as never
356 + );
357 + expect((denied.content[0] as { text: string } | undefined)?.text).toContain(
358 + 'meta tools blocked'
359 + );
360 + expect((denied.details as { denied?: boolean }).denied).toBe(true);
361 + });
362 +
363 + it('lets hooks inspect default results and replace what the model sees', async () => {
364 + const loggedResults: unknown[] = [];
365 + const execute = vi.fn(async (toolSlug: string) => ({
366 + successful: true,
367 + data: { toolSlug, largePayload: 'secret-inline-data' },
368 + error: null,
369 + }));
370 + const provider = new PiProvider();
371 + const tools = provider.createSessionTools({
372 + search: vi.fn(async () => ({})),
373 + execute,
374 + hooks: {
375 + execute: async (_ctx, next) => {
376 + const response = await next();
377 + loggedResults.push(response);
378 + return {
379 + successful: true,
380 + data: { file: '/mnt/composio/tool-output.json' },
381 + error: null,
382 + };
383 + },
384 + },
385 + });
386 +
387 + const result = await tools[2]!.execute(
388 + 'call_execute',
389 + { toolSlug: 'GITHUB_LIST_ISSUES', arguments: {} } as never,
390 + undefined,
391 + undefined,
392 + undefined as never
393 + );
394 +
395 + expect(loggedResults).toEqual([
396 + {
397 + successful: true,
398 + data: { toolSlug: 'GITHUB_LIST_ISSUES', largePayload: 'secret-inline-data' },
399 + error: null,
400 + },
401 + ]);
402 + const text = (result.content[0] as { text: string } | undefined)?.text;
403 + expect(text).toContain('/mnt/composio/tool-output.json');
404 + expect(text).not.toContain('secret-inline-data');
405 + });
406 +
407 + it('lets auth-link hooks choose whether the link goes to the model', async () => {
408 + const provider = new PiProvider();
409 + const tools = provider.createSessionTools({
410 + search: vi.fn(async () => ({})),
411 + execute: vi.fn(async () => ({})),
412 + connections: {
413 + getToolkitStates: () => ({ items: [{ slug: 'gmail', connection: undefined }] }),
414 + authorizeToolkit: toolkit => ({ redirectUrl: `https://connect.composio.dev/${toolkit}` }),
415 + },
416 + hooks: {
417 + onAuthLink: async ctx => {
418 + expect(ctx.url).toBe('https://connect.composio.dev/gmail');
419 + return { message: 'Connection link sent out-of-band.' };
420 + },
421 + },
422 + });
423 +
424 + const result = await tools[1]!.execute(
425 + 'call_manage',
426 + { toolkits: ['gmail'] } as never,
427 + undefined,
428 + undefined,
429 + undefined as never
430 + );
431 +
432 + const text = (result.content[0] as { text: string } | undefined)?.text;
433 + expect(text).toContain('Connection link sent out-of-band.');
434 + expect(text).not.toContain('https://connect.composio.dev/gmail');
435 + expect((result.details as { authLinks?: string[] }).authLinks).toEqual([
436 + 'https://connect.composio.dev/gmail',
437 + ]);
438 + });
439 +
440 + it('extracts Composio connect links from nested results', () => {
441 + expect(
442 + extractComposioConnectLinks({
443 + data: { redirectUrl: 'https://connect.composio.dev/abc123.' },
444 + })
445 + ).toEqual(['https://connect.composio.dev/abc123']);
446 + });
447 +});
ts/packages/experimental/test/workbench/local-workbench.test.ts new
+79
@@ -0,0 +1,79 @@
1 +import { describe, expect, it, vi } from 'vitest';
2 +import { experimental_createLocalWorkbenchSession } from '../../src/workbench';
3 +
4 +function makeComposio(config: { apiKey?: string; baseURL?: string }) {
5 + return {
6 + getConfig: vi.fn().mockReturnValue(config),
7 + };
8 +}
9 +
10 +describe('experimental_createLocalWorkbenchSession', () => {
11 + it('returns helperSource + env for a session with the remote workbench disabled', async () => {
12 + const session = {
13 + sessionId: 'session_123',
14 + workbench: { enable: false },
15 + };
16 + const composio = makeComposio({
17 + apiKey: 'project_key',
18 + baseURL: 'https://backend.test/',
19 + });
20 +
21 + const workbench = await experimental_createLocalWorkbenchSession(
22 + composio as never,
23 + session as never
24 + );
25 +
26 + expect(workbench.env).toEqual({
27 + BACKEND_URL: 'https://backend.test',
28 + COMPOSIO_TOOLROUTER_SESSION_ID: 'session_123',
29 + COMPOSIO_API_KEY: 'project_key',
30 + });
31 + expect(workbench.helperSource).toContain('def run_composio_tool(');
32 + expect(workbench.helperSource).not.toContain('project_key');
33 + // The breaking change: no `session` is returned anymore.
34 + expect('session' in workbench).toBe(false);
35 + });
36 +
37 + it('throws when the session has the remote workbench enabled', async () => {
38 + const session = {
39 + sessionId: 'session_123',
40 + workbench: { enable: true },
41 + };
42 + const composio = makeComposio({
43 + apiKey: 'project_key',
44 + baseURL: 'https://backend.test',
45 + });
46 +
47 + await expect(
48 + experimental_createLocalWorkbenchSession(composio as never, session as never)
49 + ).rejects.toThrow('requires a session created with workbench.enable: false');
50 + });
51 +
52 + it('throws when the session has no workbench config (defaults to remote)', async () => {
53 + const session = {
54 + sessionId: 'session_123',
55 + };
56 + const composio = makeComposio({
57 + apiKey: 'project_key',
58 + baseURL: 'https://backend.test',
59 + });
60 +
61 + await expect(
62 + experimental_createLocalWorkbenchSession(composio as never, session as never)
63 + ).rejects.toThrow('requires a session created with workbench.enable: false');
64 + });
65 +
66 + it('requires a project API key', async () => {
67 + const session = {
68 + sessionId: 'session_123',
69 + workbench: { enable: false },
70 + };
71 + const composio = makeComposio({
72 + baseURL: 'https://backend.test',
73 + });
74 +
75 + await expect(
76 + experimental_createLocalWorkbenchSession(composio as never, session as never)
77 + ).rejects.toThrow('A Composio project API key is required');
78 + });
79 +});
ts/packages/experimental/test/workbench/shim.test.ts new
+224
@@ -0,0 +1,224 @@
1 +import { execFileSync } from 'node:child_process';
2 +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3 +import { tmpdir } from 'node:os';
4 +import { join } from 'node:path';
5 +import { describe, expect, it } from 'vitest';
6 +import { experimental_createPythonWorkbenchHelperSource } from '../../src/workbench';
7 +
8 +describe('experimental_createPythonWorkbenchHelperSource', () => {
9 + it('emits the Apollo-parity Python helpers without remote workbench-only helpers', () => {
10 + const source = experimental_createPythonWorkbenchHelperSource();
11 +
12 + expect(source).toContain('def run_composio_tool(');
13 + expect(source).toContain('def invoke_llm(');
14 + expect(source).toContain('def web_search(');
15 + expect(source).toContain('def proxy_execute(');
16 + expect(source).toContain('"x-api-key": api_key');
17 + expect(source).toContain('/api/v3/tool_router/session/%s/execute');
18 + // proxy_execute uses the public session route with the project key.
19 + expect(source).toContain('/api/v3/tool_router/session/%s/proxy_execute');
20 + // Config is injected via an `_INTERNAL` prologue, read by the helper.
21 + expect(source).toContain('_INTERNAL = _composio_internal_json.loads(');
22 + expect(source).toContain('openai/gpt-oss-120b');
23 + expect(source).toContain(
24 + 'DEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get("invoke_llm_model", "openai/gpt-oss-120b")'
25 + );
26 + expect(source).not.toContain('__COMPOSIO_INVOKE_LLM_MODEL__');
27 + expect(source).not.toContain('upload_local_file');
28 + expect(source).not.toContain('smart_file_extract');
29 + expect(source).not.toContain('get_mount_file_url');
30 + expect(source).not.toContain('x-session-access-key');
31 + expect(source).not.toContain('COMPOSIO_WORKBENCH_ACCESS_KEY');
32 + expect(source).not.toContain('runComposioTool');
33 + expect(source).not.toContain('export async');
34 + });
35 +
36 + it('injects a custom invoke LLM model into the _INTERNAL prologue', () => {
37 + const source = experimental_createPythonWorkbenchHelperSource({
38 + invokeLlmModel: 'custom/model-x',
39 + });
40 +
41 + expect(source).toContain('_INTERNAL = _composio_internal_json.loads(');
42 + expect(source).toContain('custom/model-x');
43 + // The injected JSON is a valid Python double-quoted string literal.
44 + expect(source).toContain('loads("{\\"invoke_llm_model\\":\\"custom/model-x\\"}")');
45 + // The prologue must precede the helper body so `_INTERNAL` is defined first.
46 + expect(source.indexOf('_INTERNAL = _composio_internal_json.loads(')).toBeLessThan(
47 + source.indexOf('DEFAULT_INVOKE_LLM_MODEL = _INTERNAL.get(')
48 + );
49 + });
50 +
51 + it('checks HTTP status before parsing successful JSON responses', () => {
52 + const source = experimental_createPythonWorkbenchHelperSource();
53 +
54 + expect(source.indexOf('if status >= 400:')).toBeLessThan(
55 + source.indexOf('response_data = _parse_json(text)')
56 + );
57 + });
58 +
59 + it('coerces a non-numeric envelope status instead of raising', () => {
60 + const source = experimental_createPythonWorkbenchHelperSource();
61 + const directory = mkdtempSync(join(tmpdir(), 'composio-helper-'));
62 + const scriptPath = join(directory, 'helper_status_test.py');
63 + const testScript = `${source}
64 +
65 +import json as _json
66 +
67 +def _post_json(url, headers, payload, timeout=120):
68 + # The session envelope can report status as a string; a bare ">= 400"
69 + # comparison would raise TypeError and mask the successful result.
70 + return 200, {}, _json.dumps({"data": {"ok": True}, "status": "200"})
71 +
72 +ok_data, ok_error = proxy_execute("GET", "/user", "github")
73 +
74 +def _post_json_error(url, headers, payload, timeout=120):
75 + return 200, {}, _json.dumps({"data": {"message": "nope"}, "status": "404"})
76 +
77 +_post_json = _post_json_error
78 +err_data, err_error = proxy_execute("GET", "/user", "github")
79 +
80 +print(_json.dumps({
81 + "ok_data": ok_data,
82 + "ok_error": ok_error,
83 + "err_error": err_error,
84 +}))
85 +`;
86 +
87 + try {
88 + writeFileSync(scriptPath, testScript);
89 + const output = execFileSync('python3', [scriptPath], {
90 + env: {
91 + ...process.env,
92 + BACKEND_URL: 'https://backend.test/',
93 + COMPOSIO_TOOLROUTER_SESSION_ID: 'session_123',
94 + COMPOSIO_API_KEY: 'project_key',
95 + },
96 + encoding: 'utf8',
97 + });
98 + const parsed = JSON.parse(output);
99 +
100 + // String status "200" is treated as success, not a "Failed to execute" crash.
101 + expect(parsed.ok_data).toEqual({ ok: true });
102 + expect(parsed.ok_error).toBe('');
103 + // String status "404" is surfaced as a non-empty API error.
104 + expect(parsed.err_error).toContain('API returned status 404');
105 + } finally {
106 + rmSync(directory, { recursive: true, force: true });
107 + }
108 + });
109 +
110 + it('round-trips helper calls through the session execute endpoint shape', () => {
111 + const source = experimental_createPythonWorkbenchHelperSource({
112 + invokeLlmModel: 'test/model',
113 + });
114 + const directory = mkdtempSync(join(tmpdir(), 'composio-helper-'));
115 + const scriptPath = join(directory, 'helper_test.py');
116 + const testScript = `${source}
117 +
118 +import json as _json
119 +
120 +_calls = []
121 +
122 +def _post_json(url, headers, payload, timeout=120):
123 + _calls.append({"url": url, "headers": headers, "payload": payload})
124 + if "toolkit_slug" in payload:
125 + return 200, {}, _json.dumps({"data": {"login": "octocat"}, "status": 200})
126 + if payload["tool_slug"] == "COMPOSIO_SEARCH_GROQ_CHAT":
127 + _content = (chr(96) * 3) + 'json\\n{"ok": true}\\n' + (chr(96) * 3)
128 + return 200, {}, _json.dumps({
129 + "data": {
130 + "choices": [
131 + {"message": {"content": _content}}
132 + ]
133 + }
134 + })
135 + if payload["tool_slug"] == "COMPOSIO_SEARCH_EXA_ANSWER":
136 + return 200, {}, _json.dumps({"data": {"answer": "answer text"}})
137 + return 200, {}, _json.dumps({"data": {"ok": True}})
138 +
139 +tool_result, tool_error = run_composio_tool(
140 + "github_get_repo",
141 + {"owner": "composio"},
142 + {"max_retries": 0, "delay_ms": 0},
143 + False,
144 + account="acct_123",
145 +)
146 +llm_result, llm_error = invoke_llm("return JSON")
147 +search_result, search_error = web_search("what is Composio?")
148 +proxy_result, proxy_error = proxy_execute(
149 + "GET", "/user", "github", query_params={"per_page": "1"}
150 +)
151 +
152 +print(_json.dumps({
153 + "calls": _calls,
154 + "tool_result": tool_result,
155 + "tool_error": tool_error,
156 + "llm_result": llm_result,
157 + "llm_error": llm_error,
158 + "search_result": search_result,
159 + "search_error": search_error,
160 + "proxy_result": proxy_result,
161 + "proxy_error": proxy_error,
162 +}))
163 +`;
164 +
165 + try {
166 + writeFileSync(scriptPath, testScript);
167 + const output = execFileSync('python3', [scriptPath], {
168 + env: {
169 + ...process.env,
170 + BACKEND_URL: 'https://backend.test/',
171 + COMPOSIO_TOOLROUTER_SESSION_ID: 'session_123',
172 + COMPOSIO_API_KEY: 'project_key',
173 + },
174 + encoding: 'utf8',
175 + });
176 + const parsed = JSON.parse(output);
177 +
178 + expect(parsed.tool_result).toEqual({ data: { ok: true } });
179 + expect(parsed.tool_error).toBe('');
180 + expect(parsed.llm_result).toBe('{"ok": true}');
181 + expect(parsed.llm_error).toBe('');
182 + expect(parsed.search_result).toBe('answer text');
183 + expect(parsed.search_error).toBe('');
184 + expect(parsed.proxy_result).toEqual({ login: 'octocat' });
185 + expect(parsed.proxy_error).toBe('');
186 + expect(parsed.calls).toHaveLength(4);
187 + expect(parsed.calls[0]).toMatchObject({
188 + url: 'https://backend.test/api/v3/tool_router/session/session_123/execute',
189 + headers: {
190 + 'Content-Type': 'application/json',
191 + 'x-api-key': 'project_key',
192 + },
193 + payload: {
194 + tool_slug: 'GITHUB_GET_REPO',
195 + arguments: { owner: 'composio' },
196 + account: 'acct_123',
197 + },
198 + });
199 + expect(parsed.calls[1].payload).toMatchObject({
200 + tool_slug: 'COMPOSIO_SEARCH_GROQ_CHAT',
201 + arguments: {
202 + model: 'test/model',
203 + temperature: 0.5,
204 + },
205 + });
206 + expect(parsed.calls[2].payload).toEqual({
207 + tool_slug: 'COMPOSIO_SEARCH_EXA_ANSWER',
208 + arguments: { content: 'what is Composio?' },
209 + });
210 + expect(parsed.calls[3]).toMatchObject({
211 + url: 'https://backend.test/api/v3/tool_router/session/session_123/proxy_execute',
212 + headers: { 'x-api-key': 'project_key' },
213 + payload: {
214 + toolkit_slug: 'github',
215 + endpoint: '/user',
216 + method: 'GET',
217 + parameters: [{ name: 'per_page', value: '1', type: 'query' }],
218 + },
219 + });
220 + } finally {
221 + rmSync(directory, { recursive: true, force: true });
222 + }
223 + });
224 +});
ts/packages/experimental/tsconfig.json new
+21
@@ -0,0 +1,21 @@
1 +{
2 + "extends": "../../../tsconfig.base.json",
3 + "compilerOptions": {
4 + "target": "es2022",
5 + "module": "esnext",
6 + "strict": true,
7 + "esModuleInterop": true,
8 + "moduleResolution": "bundler",
9 + "skipLibCheck": true,
10 + "resolveJsonModule": true,
11 + "paths": {
12 + "@composio/core": ["../core/src/index.ts"],
13 + "@composio/json-schema-to-zod": ["../json-schema-to-zod/src/index.ts"],
14 + "#config_defaults": ["../core/src/utils/config-defaults/ConfigDefaults.node.ts"],
15 + "#platform": ["../core/src/platform/node.ts"],
16 + "#files": ["../core/src/models/Files.node.ts"],
17 + "#file_tool_modifier": ["../core/src/utils/modifiers/FileToolModifier.node.ts"]
18 + }
19 + },
20 + "include": ["src", "test"]
21 +}
ts/packages/experimental/tsdown.config.ts new
+8
@@ -0,0 +1,8 @@
1 +import { defineConfig } from 'tsdown';
2 +import { baseConfig } from '../../../tsdown.config.base.ts';
3 +
4 +export default defineConfig({
5 + ...baseConfig,
6 + entry: ['src/index.ts', 'src/workbench/index.ts'],
7 + tsconfig: 'tsconfig.json',
8 +});
ts/packages/experimental/vitest.config.ts new
+22
@@ -0,0 +1,22 @@
1 +import { defineConfig } from 'vitest/config';
2 +import path from 'node:path';
3 +
4 +const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
5 +const coreDir = path.resolve(__dirname, '../core');
6 +const jsonSchemaToZodDir = path.resolve(__dirname, '../json-schema-to-zod');
7 +
8 +export default defineConfig({
9 + resolve: {
10 + alias: {
11 + '@composio/core': path.join(coreDir, 'src/index.ts'),
12 + '@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
13 + '#config_defaults': path.join(coreDir, 'src/utils/config-defaults/ConfigDefaults.node.ts'),
14 + '#platform': path.join(coreDir, 'src/platform/node.ts'),
15 + '#files': path.join(coreDir, 'src/models/Files.node.ts'),
16 + '#file_tool_modifier': path.join(coreDir, 'src/utils/modifiers/FileToolModifier.node.ts'),
17 + },
18 + },
19 + test: {
20 + include: ['test/**/*.test.ts'],
21 + },
22 +});
ts/packages/providers/anthropic/README.md
+15 -8
@@ -96,12 +96,14 @@ const message = await anthropic.messages.create({
96 });
97
98 // Handle tool calls
99 -if (message.content[0].type === 'tool_calls') {
100 - const toolCall = message.content[0];
101 - const result = await composio.provider.executeToolCall('user123', toolCall, {
102 - connectedAccountId: 'account123',
103 - });
104 - console.log('Tool execution result:', result);
99 +// Anthropic returns tool calls as `tool_use` content blocks.
100 +for (const block of message.content) {
101 + if (block.type === 'tool_use') {
102 + const result = await composio.provider.executeToolCall('user123', block, {
103 + connectedAccountId: 'account123',
104 + });
105 + console.log('Tool execution result:', result);
106 + }
107 }
108 ```
109
@@ -138,8 +140,13 @@ const stream = await anthropic.messages.stream({
140 });
141
142 for await (const messageChunk of stream) {
141 - if (messageChunk.type === 'content_block_delta' && messageChunk.delta.type === 'tool_calls') {
142 - const result = await composio.provider.executeToolCall('user123', messageChunk.delta, {
143 + // Anthropic streams tool calls as `tool_use` content blocks, emitted via a
144 + // `content_block_start` event whose `content_block` is the `tool_use` block.
145 + if (
146 + messageChunk.type === 'content_block_start' &&
147 + messageChunk.content_block.type === 'tool_use'
148 + ) {
149 + const result = await composio.provider.executeToolCall('user123', messageChunk.content_block, {
150 connectedAccountId: 'account123',
151 });
152 console.log('Tool execution result:', result);
ts/packages/providers/llamaindex/src/index.ts
+4 -4
@@ -57,15 +57,15 @@ export class LlamaindexProvider extends BaseAgenticProvider<
57 }
58
59 /**
60 - * Transform MCP URL response into Anthropic-specific format.
61 - * By default, Anthropic uses the standard format (same as default),
62 - * but this method is here to show providers can customize if needed.
60 + * Transform an MCP URL response into the LlamaIndex provider's format.
61 + * LlamaIndex uses the standard MCP server response shape, mapping each
62 + * entry to an object with a `URL` instance and its name.
63 *
64 * @param data - The MCP URL response data
65 * @returns Standard MCP server response format
66 */
67 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
68 - // Anthropic uses the standard format
68 + // LlamaIndex uses the standard format
69 return data.map(item => ({
70 url: new URL(item.url),
71 name: item.name,
ts/packages/providers/mastra/src/index.ts
+4 -4
@@ -71,12 +71,12 @@ export class MastraProvider extends BaseAgenticProvider<
71 }
72
73 /**
74 - * Transform MCP URL response into Anthropic-specific format.
75 - * By default, Anthropic uses the standard format (same as default),
76 - * but this method is here to show providers can customize if needed.
74 + * Transform an MCP URL response into the Mastra provider's format.
75 + * Mastra expects a URL map keyed by server name, so each entry is
76 + * reduced into an object of `{ [name]: { url } }`.
77 *
78 * @param data - The MCP URL response data
79 - * @returns Standard MCP server response format
79 + * @returns The MCP servers as a Mastra URL map
80 */
81 wrapMcpServerResponse(data: McpUrlResponse): MastraUrlMap {
82 // Transform to Mastra's URL map format
ts/packages/providers/vercel/src/index.ts
+4 -4
@@ -207,15 +207,15 @@ export class VercelProvider extends BaseAgenticProvider<
207 }
208
209 /**
210 - * Transform MCP URL response into Anthropic-specific format.
211 - * By default, Anthropic uses the standard format (same as default),
212 - * but this method is here to show providers can customize if needed.
210 + * Transform an MCP URL response into the Vercel provider's format.
211 + * Vercel uses the standard MCP server response shape, mapping each
212 + * entry to an object with a `URL` instance and its name.
213 *
214 * @param data - The MCP URL response data
215 * @returns Standard MCP server response format
216 */
217 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
218 - // Anthropic uses the standard format
218 + // Vercel uses the standard format
219 return data.map(item => ({
220 url: new URL(item.url),
221 name: item.name,
ts/packages/slim/README.md new
+17
@@ -0,0 +1,17 @@
1 +# `@composio/slim`
2 +
3 +Slim build of the Composio TypeScript core SDK.
4 +
5 +`@composio/core` intentionally publishes SDK docs and TypeScript source for users who want an inspectable/debuggable package. `@composio/slim` publishes the same built runtime/type artifacts without the packaged `docs/` or `src/` trees.
6 +
7 +```bash
8 +pnpm add @composio/slim
9 +```
10 +
11 +```ts
12 +import { Composio } from '@composio/slim';
13 +
14 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
15 +```
16 +
17 +The API mirrors `@composio/core` for consumers that prefer a smaller installed package.
ts/packages/slim/generated/index.d.ts new
+6
@@ -0,0 +1,6 @@
1 +/**
2 + * Stub file for @composio/core/generated exports.
3 + * Run `composio ts generate` to generate the actual toolkit types.
4 + */
5 +
6 +export declare const Toolkits: {};
ts/packages/slim/generated/index.js new
+18
@@ -0,0 +1,18 @@
1 +/**
2 + * Stub file for @composio/core/generated exports.
3 + * Run `composio ts generate` to generate the actual toolkit types.
4 + */
5 +
6 +const ERROR_MESSAGE = `
7 +@composio/core/generated has not been initialized.
8 +Please run \`composio ts generate\` in your project to generate the toolkit types.
9 +`;
10 +
11 +export const Toolkits = new Proxy(
12 + {},
13 + {
14 + get(_, prop) {
15 + throw new Error(ERROR_MESSAGE);
16 + },
17 + }
18 +);
ts/packages/slim/package.json new
+116
@@ -0,0 +1,116 @@
1 +{
2 + "name": "@composio/slim",
3 + "type": "module",
4 + "version": "0.0.1",
5 + "description": "Slim Composio core package without packaged source or docs",
6 + "main": "dist/index.mjs",
7 + "publishConfig": {
8 + "access": "public",
9 + "main": "dist/index.mjs",
10 + "types": "dist/index.d.mts"
11 + },
12 + "imports": {
13 + "#platform": {
14 + "workerd": "./dist/platform/workerd.mjs",
15 + "edge-light": "./dist/platform/workerd.mjs",
16 + "node": "./dist/platform/node.mjs",
17 + "default": "./dist/platform/node.mjs"
18 + },
19 + "#files": {
20 + "workerd": "./dist/models/Files.workerd.mjs",
21 + "edge-light": "./dist/models/Files.workerd.mjs",
22 + "node": "./dist/models/Files.node.mjs",
23 + "default": "./dist/models/Files.node.mjs"
24 + },
25 + "#file_tool_modifier": {
26 + "workerd": "./dist/utils/modifiers/FileToolModifier.workerd.mjs",
27 + "edge-light": "./dist/utils/modifiers/FileToolModifier.workerd.mjs",
28 + "node": "./dist/utils/modifiers/FileToolModifier.node.mjs",
29 + "default": "./dist/utils/modifiers/FileToolModifier.node.mjs"
30 + },
31 + "#config_defaults": {
32 + "workerd": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
33 + "edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
34 + "node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
35 + "default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
36 + }
37 + },
38 + "exports": {
39 + ".": {
40 + "types": "./dist/index.d.mts",
41 + "default": "./dist/index.mjs"
42 + },
43 + "./experimental": {
44 + "types": "./dist/experimental/index.d.mts",
45 + "default": "./dist/experimental/index.mjs"
46 + },
47 + "./platform": {
48 + "workerd": {
49 + "types": "./dist/platform/workerd.d.mts",
50 + "default": "./dist/platform/workerd.mjs"
51 + },
52 + "edge-light": {
53 + "types": "./dist/platform/workerd.d.mts",
54 + "default": "./dist/platform/workerd.mjs"
55 + },
56 + "node": {
57 + "types": "./dist/platform/node.d.mts",
58 + "default": "./dist/platform/node.mjs"
59 + },
60 + "default": {
61 + "types": "./dist/platform/node.d.mts",
62 + "default": "./dist/platform/node.mjs"
63 + }
64 + },
65 + "./utils/json-schema": {
66 + "types": "./dist/utils/json-schema.d.mts",
67 + "default": "./dist/utils/json-schema.mjs"
68 + },
69 + "./generated": {
70 + "types": "./generated/index.d.ts",
71 + "default": "./generated/index.js"
72 + }
73 + },
74 + "files": [
75 + "README.md",
76 + "dist",
77 + "generated"
78 + ],
79 + "scripts": {
80 + "clean": "git clean -xdf dist generated node_modules",
81 + "build": "pnpm --filter @composio/core build && rm -rf dist generated && cp -R ../core/dist ./dist && rm -rf dist/docs && if [ -d ../core/generated ]; then cp -R ../core/generated ./generated; fi",
82 + "test": "node -e \"import('./dist/index.mjs').then(() => console.log('@composio/slim import ok'))\""
83 + },
84 + "keywords": [
85 + "composio",
86 + "sdk",
87 + "slim"
88 + ],
89 + "author": "",
90 + "contributors": [
91 + "Alberto Schiabel <alberto.schiabel@gmail.com> (https://github.com/jkomyno)"
92 + ],
93 + "license": "ISC",
94 + "peerDependencies": {
95 + "zod": "^3.25 || ^4"
96 + },
97 + "dependencies": {
98 + "@composio/client": "catalog:",
99 + "@composio/json-schema-to-zod": "workspace:*",
100 + "@types/json-schema": "^7.0.15",
101 + "openai": "catalog:",
102 + "picocolors": "catalog:",
103 + "pusher-js": "^8.5.0",
104 + "semver": "^7.8.4",
105 + "zod-to-json-schema": "catalog:"
106 + },
107 + "repository": {
108 + "type": "git",
109 + "url": "https://github.com/ComposioHQ/composio.git",
110 + "directory": "ts/packages/slim"
111 + },
112 + "bugs": {
113 + "url": "https://github.com/ComposioHQ/composio/issues"
114 + },
115 + "homepage": "https://github.com/ComposioHQ/composio/tree/main/ts/packages/slim#readme"
116 +}
ts/packages/slim/turbo.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "extends": ["//"],
3 + "tasks": {
4 + "test": {
5 + "dependsOn": ["build"]
6 + }
7 + }
8 +}