Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(connectors): recover Pipedream connections the Connect UI never reports (#8934)
Eric Hayes9f9f109b9039
diff --git a/Cargo.lock b/Cargo.lockindex 5d011df636..216bfb24e6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15014,6 +15014,7 @@ dependencies = ["async-trait","axum","base64 0.22.1",+ "chrono","futures","http 1.4.0","macro_authorization",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex cf4193f35b..75c3872d5d 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -151,9 +151,15 @@ plugin redirects external popups and breaks the embedded iframe's return path.`pipedream-connect.html` is a separate Vite entry, served at`/app/pipedream-connect.html`, without a Macro browser login. The Connect tokenand one-time state travel only in its URL fragment, which the page removes on-load. Its **Return to Macro** link is consumed by the Tauri navigation bridge+load. When Connect finishes it opens the `macro://` callback itself, keeping+**Return to Macro** as a fallback link; the Tauri navigation bridge consumes itwithout changing the active route. Backend registration still verifies account-ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.+ownership. Done, logout, and the ten-minute timeout retire pending callbacks.++Connect can close without reporting success (an OAuth provider severs its+consent popup's opener) even though Pipedream created the account. Every close+without success, on web and native, asks `/pipedream/mcp/recover` to register+the user's newest account for that app from the last fifteen minutes.### Generaldiff --git a/apps/web/src/lib/core/pipedream/connect-browser.test.ts b/apps/web/src/lib/core/pipedream/connect-browser.test.tsindex 07d94b6ae8..25354fbf42 100644--- a/apps/web/src/lib/core/pipedream/connect-browser.test.ts+++ b/apps/web/src/lib/core/pipedream/connect-browser.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { mountPipedreamBrowserConnect } from './connect-browser';afterEach(() => {@@ -17,7 +17,8 @@ describe('browser connection handoff', () => {);const root = document.createElement('main');document.body.appendChild(root);- mountPipedreamBrowserConnect(root);+ const returnToApp = vi.fn();+ mountPipedreamBrowserConnect(root, returnToApp);expect(location.hash).toBe('');const iframe = document.querySelector('iframe')!;expect(new URL(iframe.src).searchParams.get('token')).toBe('fixture');@@ -29,6 +30,7 @@ describe('browser connection handoff', () => {}));expect(root.querySelector('a')).toBeNull();+ expect(returnToApp).not.toHaveBeenCalled();window.dispatchEvent(new MessageEvent('message', {origin: 'https://pipedream.com',@@ -47,6 +49,7 @@ describe('browser connection handoff', () => {type === 'success' ? 'apn_test' : null);expect(callback.href).not.toContain('fixture');+ expect(returnToApp).toHaveBeenCalledExactlyOnceWith(callback.href);expect(document.querySelector('iframe')).toBeNull();});diff --git a/apps/web/src/lib/core/pipedream/connect-browser.ts b/apps/web/src/lib/core/pipedream/connect-browser.tsindex 8220296400..24a2ed6693 100644--- a/apps/web/src/lib/core/pipedream/connect-browser.ts+++ b/apps/web/src/lib/core/pipedream/connect-browser.ts@@ -2,7 +2,10 @@ import { PIPEDREAM_CALLBACK_PATH } from './connect-callback';import { openPipedreamConnectUI } from './connect-ui';/** Standalone browser handoff; no Macro browser login is needed. */-export function mountPipedreamBrowserConnect(root: HTMLElement) {+export function mountPipedreamBrowserConnect(+ root: HTMLElement,+ returnToApp: (href: string) => void = (href) => window.location.assign(href)+) {const params = new URLSearchParams(window.location.hash.slice(1));history.replaceState(null, '', window.location.pathname);const token = params.get('token');@@ -37,6 +40,9 @@ export function mountPipedreamBrowserConnect(root: HTMLElement) {link.href = callback.href;link.textContent = 'Return to Macro';root.appendChild(link);+ // Hand back to the app without waiting for a click; the link stays as+ // the fallback when the browser blocks or the user dismisses the prompt.+ returnToApp(callback.href);},});}diff --git a/apps/web/src/lib/core/pipedream/connect-native.test.tsx b/apps/web/src/lib/core/pipedream/connect-native.test.tsxindex 26968de0eb..ef23a0c178 100644--- a/apps/web/src/lib/core/pipedream/connect-native.test.tsx+++ b/apps/web/src/lib/core/pipedream/connect-native.test.tsx@@ -42,7 +42,7 @@ describe('native browser connection dialog', () => {expect(mocks.open).toHaveBeenLastCalledWith('plugin:opener|open_url', {url: url.href,});- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ fireEvent.click(screen.getByRole('button', { name: 'Done' }));expect(screen.queryByRole('dialog')).toBeNull();handlePipedreamCallback(PIPEDREAM_CALLBACK_PATH,diff --git a/apps/web/src/lib/core/pipedream/connect-native.tsx b/apps/web/src/lib/core/pipedream/connect-native.tsxindex 9a55c9cef6..f2d57a1a12 100644--- a/apps/web/src/lib/core/pipedream/connect-native.tsx+++ b/apps/web/src/lib/core/pipedream/connect-native.tsx@@ -47,8 +47,8 @@ export function openNativePipedreamConnectUI(<div class="flex flex-col gap-4 p-6 bg-panel text-ink rounded-lg"><Dialog.Title>Finish connecting in your browser</Dialog.Title><Dialog.Description>- Authorize the connection, then choose Return to Macro. If you closed- the browser tab, cancel and try again.+ Authorize the connection in your browser, then come back here. If+ Macro did not pick it up, choose Done and Macro will check for it.</Dialog.Description><Show when={openFailed()}><p role="alert">@@ -63,7 +63,7 @@ export function openNativePipedreamConnectUI(Open browser again</Button><Button variant="ghost" onClick={cancel}>- Cancel+ Done</Button></div></div>diff --git a/apps/web/src/lib/queries/pipedream-connectors.test.ts b/apps/web/src/lib/queries/pipedream-connectors.test.tsindex 66d8f5a0f1..f12b0c98f4 100644--- a/apps/web/src/lib/queries/pipedream-connectors.test.ts+++ b/apps/web/src/lib/queries/pipedream-connectors.test.ts@@ -1,11 +1,12 @@import type { openPipedreamConnectUI } from '@core/pipedream/connect-ui';-import { ok } from 'neverthrow';+import { err, ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({open: vi.fn(),close: vi.fn(),complete: vi.fn(),+ recover: vi.fn(),setData: vi.fn(),invalidate: vi.fn(async () => {}),native: false,@@ -31,6 +32,7 @@ vi.mock('@service-cognition/client', () => ({cognitionApiServiceClient: {createPipedreamToken: async () => ok({ token: 'fixture' }),completePipedreamConnection: mocks.complete,+ recoverPipedreamConnection: mocks.recover,},}));@@ -42,6 +44,9 @@ beforeEach(() => {mocks.userId = 'user-one';mocks.open.mockImplementation(() => ({ close: mocks.close }));mocks.openNative.mockImplementation(() => ({ close: mocks.close }));+ mocks.recover.mockResolvedValue(+ err([{ code: 'NOT_FOUND', message: 'Resource not found' }])+ );});async function connect(native = false) {@@ -79,6 +84,7 @@ describe('verified Pipedream connection completion', () => {);const { pending, event } = await connect();event({ type: 'success', accountId: 'apn_test' });+ await vi.waitFor(() => expect(mocks.complete).toHaveBeenCalled());mocks.userId = 'user-two';complete({ app_slug: 'linear', enabled: true });expect(await pending).toBe('closed');@@ -134,4 +140,33 @@ describe('verified Pipedream connection completion', () => {expect(await pending).toBe('closed');expect(mocks.complete).not.toHaveBeenCalled();});++ it.each([false, true])(+ 'registers an account the Connect UI never reported (native=%s)',+ async (native) => {+ mocks.recover.mockResolvedValue(+ ok({ app_slug: 'linear', enabled: true })+ );+ const { pending, event } = await connect(native);+ event({ type: 'close' });+ expect(await pending).toBe('connected');+ expect(mocks.recover).toHaveBeenCalledExactlyOnceWith({+ app_slug: 'linear',+ server_name: 'Linear',+ });+ expect(mocks.complete).not.toHaveBeenCalled();+ expect(mocks.invalidate).toHaveBeenCalledOnce();+ }+ );++ it('surfaces recovery failures other than a missing account', async () => {+ mocks.recover.mockResolvedValue(+ err([{ code: 'SERVER_ERROR', message: 'boom' }])+ );+ const { pending, event } = await connect();+ const rejected = expect(pending).rejects.toThrow();+ event({ type: 'close' });+ await rejected;+ expect(mocks.setData).not.toHaveBeenCalled();+ });});diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.tsindex 58639147aa..beb432f826 100644--- a/apps/web/src/lib/queries/pipedream-connectors.ts+++ b/apps/web/src/lib/queries/pipedream-connectors.ts@@ -1,6 +1,9 @@-import { openPipedreamConnectUI } from '@core/pipedream/connect-ui';+import {+ openPipedreamConnectUI,+ type PipedreamConnectEvent,+ type PipedreamConnectUI,+} from '@core/pipedream/connect-ui';import { pipedreamSlugsMatch } from '@core/pipedream/slugs';-import { fireAndForget } from '@core/util/fireAndForget';import { isTauri } from '@core/util/platform';import { ThrownResultError, throwOnErr } from '@core/util/result';import { type Span, Telemetry } from '@macro-inc/observability';@@ -257,70 +260,76 @@ async function connectPipedreamAccount(.openNativePipedreamConnectUI: openPipedreamConnectUI;if (currentUserId() !== userId) return 'closed';- const consent = span.span('pipedream.consent');- return await new Promise<PipedreamConnectOutcome>((resolve, reject) => {- let settled = false;- const ui = openConnectUI({- token: token.value.token,- app: args.appSlug,- container: args.container,- onEvent: (event) => {- if (event.type === 'success' && !settled) {- settled = true;- consent.end();- fireAndForget(- (async () => {- try {- if (currentUserId() !== userId) {- resolve('closed');- return;- }- const connection = await span.span(- 'pipedream.register',- async () =>- throwOnErr(- async () =>- await cognitionApiServiceClient.completePipedreamConnection(- {- account_id: event.accountId,- server_name: args.serverName,- }- )- )- );- if (currentUserId() !== userId) {- resolve('closed');- return;- }- if (- !pipedreamSlugsMatch(connection.app_slug, args.appSlug) ||- !connection.enabled- ) {- throw new Error('The requested connector was not enabled');- }- upsertConnection(connection);- await invalidateConnections();- resolve('connected');- } catch (error) {- reject(- error instanceof Error- ? error- : new Error('failed to register Pipedream connection')- );- } finally {- ui.close();- }- })(),- 'pipedream-connect'- );- } else if (event.type === 'close' && !settled) {- settled = true;- consent.end();- resolve('closed');- }- // 'error' events are shown inside the Connect UI itself; the user- // can retry there or close, so they don't settle the promise.- },+ let ui: PipedreamConnectUI | undefined;+ const consented = await span.span(+ 'pipedream.consent',+ async () =>+ new Promise<ConsentResult>((resolve) => {+ ui = openConnectUI({+ token: token.value.token,+ app: args.appSlug,+ container: args.container,+ // 'error' events are shown inside the Connect UI itself; the user+ // can retry there or close, so they don't settle the flow.+ onEvent: (event) => {+ if (event.type !== 'error') resolve(event);+ },+ });+ })+ );+ try {+ if (currentUserId() !== userId) return 'closed';+ const connection =+ consented.type === 'success'+ ? await span.span('pipedream.register', async () =>+ throwOnErr(+ async () =>+ await cognitionApiServiceClient.completePipedreamConnection({+ account_id: consented.accountId,+ server_name: args.serverName,+ })+ )+ )+ : await recoverUnreportedConnection(args, span);+ if (!connection || currentUserId() !== userId) return 'closed';+ if (+ !pipedreamSlugsMatch(connection.app_slug, args.appSlug) ||+ !connection.enabled+ ) {+ throw new Error('The requested connector was not enabled');+ }+ upsertConnection(connection);+ await invalidateConnections();+ return 'connected';+ } finally {+ ui?.close();+ }+}++type ConsentResult = Exclude<PipedreamConnectEvent, { type: 'error' }>;++/**+ * Pipedream's Connect UI drops its success message when an OAuth provider+ * severs the consent popup's opener, reporting only a close although the+ * account exists. Ask the backend to find and register that account.+ */+async function recoverUnreportedConnection(+ args: Parameters<typeof connectPipedreamApp>[0],+ span: Span+): Promise<PipedreamConnectionResponse | undefined> {+ return span.span('pipedream.recover', async (recover) => {+ const result = await cognitionApiServiceClient.recoverPipedreamConnection({+ app_slug: args.appSlug,+ server_name: args.serverName,});- }).finally(() => consent.end());+ if (result.isErr()) {+ if (!result.error.some((e) => e.code === 'NOT_FOUND')) {+ throw new ThrownResultError(result.error);+ }+ recover.setAttr('connector.recovered', false);+ return undefined;+ }+ recover.setAttr('connector.recovered', true);+ return result.value;+ });}diff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.tsindex 579b3d257f..4796bb71bf 100644--- a/apps/web/src/lib/service-clients/service-cognition/client.ts+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts@@ -94,6 +94,10 @@ export type PipedreamCompleteRequest = {account_id: string;server_name?: string;};+export type PipedreamRecoverRequest = {+ app_slug: string;+ server_name?: string;+};export type { PipedreamCatalogEntryResponse } from './generated/schemas/pipedreamCatalogEntryResponse';export type { PipedreamCatalogResponse } from './generated/schemas/pipedreamCatalogResponse';@@ -465,6 +469,19 @@ export const cognitionApiServiceClient = {).map((result) => result);},+ /**+ * Register an account a Connect flow created but the Connect UI never+ * reported. Fails with `NOT_FOUND` when there is none.+ */+ async recoverPipedreamConnection(args: PipedreamRecoverRequest) {+ return (+ await dcsFetch<PipedreamConnectionResponse>(`/pipedream/mcp/recover`, {+ method: 'POST',+ body: JSON.stringify(args),+ })+ ).map((result) => result);+ },+/*** Browse or search Pipedream apps in popularity order, including their* category labels for grouping.diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.tsindex ee7ae7fb9a..9c67bc4920 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts@@ -40,6 +40,7 @@ import type {PipedreamCatalogResponse,PipedreamCompleteRequest,PipedreamConnectionResponse,+ PipedreamRecoverRequest,PipedreamTokenResponse,PipedreamUpdateRequest,ProjectionStateResponse,@@ -2618,6 +2619,81 @@ export const deletePipedreamMcpConnection = async (} as deletePipedreamMcpConnectionResponse;};+/**+ * Called after the Connect UI closes without a success event. Answers 404+when Pipedream has no new account for this user and app.+ * @summary Register an account a Connect flow created but the Connect UI never+reported.+ */+export type recoverPipedreamMcpConnectionResponse200 = {+ data: PipedreamConnectionResponse;+ status: 200;+};++export type recoverPipedreamMcpConnectionResponse401 = {+ data: string;+ status: 401;+};++export type recoverPipedreamMcpConnectionResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type recoverPipedreamMcpConnectionResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type recoverPipedreamMcpConnectionResponse501 = {+ data: ErrorResponse;+ status: 501;+};++export type recoverPipedreamMcpConnectionResponseSuccess =+ recoverPipedreamMcpConnectionResponse200 & {+ headers: Headers;+ };+export type recoverPipedreamMcpConnectionResponseError = (+ | recoverPipedreamMcpConnectionResponse401+ | recoverPipedreamMcpConnectionResponse404+ | recoverPipedreamMcpConnectionResponse500+ | recoverPipedreamMcpConnectionResponse501+) & {+ headers: Headers;+};++export type recoverPipedreamMcpConnectionResponse =+ | recoverPipedreamMcpConnectionResponseSuccess+ | recoverPipedreamMcpConnectionResponseError;++export const getRecoverPipedreamMcpConnectionUrl = () => {+ return `/pipedream/mcp/recover`;+};++export const recoverPipedreamMcpConnection = async (+ pipedreamRecoverRequest: PipedreamRecoverRequest,+ options?: RequestInit+): Promise<recoverPipedreamMcpConnectionResponse> => {+ const res = await fetch(getRecoverPipedreamMcpConnectionUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(pipedreamRecoverRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: recoverPipedreamMcpConnectionResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as recoverPipedreamMcpConnectionResponse;+};+/*** The frontend opens Pipedream's hosted Connect UI with this token; theuser picks (or is deep-linked into) an app and authorizes it there.diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.tsindex 5cc96f0056..cf0a2e687a 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts@@ -218,6 +218,8 @@ export * from './pipedreamCatalogResponseNextCursor';export * from './pipedreamCompleteRequest';export * from './pipedreamCompleteRequestServerName';export * from './pipedreamConnectionResponse';+export * from './pipedreamRecoverRequest';+export * from './pipedreamRecoverRequestServerName';export * from './pipedreamTokenResponse';export * from './pipedreamUpdateRequest';export * from './pipedreamUpdateRequestEnabled';diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequest.tsnew file mode 100644index 0000000000..820a69f61c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequest.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { PipedreamRecoverRequestServerName } from './pipedreamRecoverRequestServerName';++/**+ * Request body for recovering a connect flow whose result the Connect UI+never reported.+ */+export interface PipedreamRecoverRequest {+ /** The Pipedream app the flow was connecting, by name slug. */+ app_slug: string;+ /** Optional display name for the connector, as for completion. */+ server_name?: PipedreamRecoverRequestServerName;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequestServerName.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequestServerName.tsnew file mode 100644index 0000000000..e7c3144356--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamRecoverRequestServerName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Optional display name for the connector, as for completion.+ */+export type PipedreamRecoverRequestServerName = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex 1958491b73..3dedb6d5c9 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -2091,6 +2091,76 @@}}},+ "/pipedream/mcp/recover": {+ "post": {+ "tags": ["pipedream-mcp"],+ "summary": "Register an account a Connect flow created but the Connect UI never\nreported.",+ "description": "Called after the Connect UI closes without a success event. Answers 404\nwhen Pipedream has no new account for this user and app.",+ "operationId": "recover_pipedream_mcp_connection",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamRecoverRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamConnectionResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "501": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/pipedream/mcp/token": {"post": {"tags": ["pipedream-mcp"],@@ -4916,6 +4986,21 @@}}},+ "PipedreamRecoverRequest": {+ "type": "object",+ "description": "Request body for recovering a connect flow whose result the Connect UI\nnever reported.",+ "required": ["app_slug"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "The Pipedream app the flow was connecting, by name slug."+ },+ "server_name": {+ "type": ["string", "null"],+ "description": "Optional display name for the connector, as for completion."+ }+ }+ },"PipedreamTokenResponse": {"type": "object","description": "Response from creating a Pipedream Connect token.",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex 9b0484acf6..24f12abb37 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -215,6 +215,7 @@"cognition.deletePipedreamMcpConnection": "Delete Pipedream Mcp Connection","cognition.listPipedreamMcpConnections": "List Pipedream Mcp Connections","cognition.updatePipedreamMcpConnection": "Update Pipedream Mcp Connection",+ "cognition.recoverPipedreamMcpConnection": "Recover Pipedream Mcp Connection","cognition.createPipedreamMcpToken": "Create Pipedream Mcp Token","cognition.getBatchPreview": "Get Batch Preview","cognition.sendChatMessage": "Send Chat Message",diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex bbdf01b7bb..bda39333e9 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -19,7 +19,7 @@ async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=g.pop()??"";for(let p of g){let a=p.split(``),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p7=/\{[^{}]+\}/g,a7=({path:$,url:O})=>{let j=O,x=O.match(p7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function s0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(i7($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var t0=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),e0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=nj($.headers,O.headers),j},n7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},nj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ij{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new ij,request:new ij,response:new ij}),s7=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t7={"Content-Type":"application/json"},Sj=($={})=>({...b2,headers:t7,parseAs:"auto",querySerializer:s7,...$});var o0=($={})=>{let O=e0(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=e0(O,Q),j()},S=v2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=t0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:s0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?g2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:s0(I),url:z})};return{buildUrl:(Q)=>t0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=o0(Sj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends m2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p7=/\{[^{}]+\}/g,a7=({path:$,url:O})=>{let j=O,x=O.match(p7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function s0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(i7($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var t0=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),e0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=nj($.headers,O.headers),j},n7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},nj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ij{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new ij,request:new ij,response:new ij}),s7=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t7={"Content-Type":"application/json"},Sj=($={})=>({...b2,headers:t7,parseAs:"auto",querySerializer:s7,...$});var o0=($={})=>{let O=e0(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=e0(O,Q),j()},S=v2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=t0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:s0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?g2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:s0(I),url:z})};return{buildUrl:(Q)=>t0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=o0(Sj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends m2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,``);let g=U.split(``);U=g.pop()??"";for(let p of g){let a=p.split(`diff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.tomlindex f3d511c49b..74b37b2809 100644--- a/crates/pipedream_mcp/Cargo.toml+++ b/crates/pipedream_mcp/Cargo.toml@@ -10,6 +10,7 @@ anyhow.workspace = trueasync-trait.workspace = truebase64.workspace = trueaxum.workspace = true+chrono.workspace = truefutures.workspace = truehttp.workspace = truemacro_authorization = { path = "../macro_authorization", default-features = false, features = [diff --git a/crates/pipedream_mcp/src/domain/models.rs b/crates/pipedream_mcp/src/domain/models.rsindex 6f89beb44f..24e7fe4f7a 100644--- a/crates/pipedream_mcp/src/domain/models.rs+++ b/crates/pipedream_mcp/src/domain/models.rs@@ -44,6 +44,8 @@ pub struct PipedreamAccount {pub app_name: String,/// Whether Pipedream considers the account's credentials healthy.pub healthy: bool,+ /// When Pipedream created the account, if it reported it.+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,}/// One connectable app advertised in the catalog.diff --git a/crates/pipedream_mcp/src/domain/ports.rs b/crates/pipedream_mcp/src/domain/ports.rsindex 96878af607..ba6f3bdbd9 100644--- a/crates/pipedream_mcp/src/domain/ports.rs+++ b/crates/pipedream_mcp/src/domain/ports.rs@@ -97,6 +97,14 @@ pub trait PipedreamConnect: Send + Sync + 'static {account_id: &str,) -> impl Future<Output = anyhow::Result<Option<PipedreamAccount>>> + Send;+ /// List the accounts connected for `external_user_id` (our user ID) to+ /// `app_slug`, in no particular order.+ fn list_accounts(+ &self,+ external_user_id: &str,+ app_slug: &str,+ ) -> impl Future<Output = anyhow::Result<Vec<PipedreamAccount>>> + Send;+/// Delete a connected account from Pipedream (revoking our copy of the/// grant).fn delete_account(&self, account_id: &str) -> impl Future<Output = anyhow::Result<()>> + Send;diff --git a/crates/pipedream_mcp/src/domain/service/connect.rs b/crates/pipedream_mcp/src/domain/service/connect.rsindex 1b11b0bb0d..130fb8e84f 100644--- a/crates/pipedream_mcp/src/domain/service/connect.rs+++ b/crates/pipedream_mcp/src/domain/service/connect.rs@@ -75,6 +75,66 @@ whereOk(record)}+/// How far back [`recover_pipedream_connection`] looks for an account the+/// Connect UI failed to report. Longer than the native consent timeout.+pub const RECOVERY_WINDOW: chrono::TimeDelta = chrono::TimeDelta::minutes(15);++/// Register an account Pipedream created but the Connect UI never reported.+///+/// Pipedream's hosted Connect UI loses its success message when an OAuth+/// provider severs the consent popup's opener: the account exists, but the+/// UI reports only `close`. The caller asks here after such a close. The+/// newest account for this user and app created within [`RECOVERY_WINDOW`]+/// of `now` is verified and stored exactly as a reported one would be.+/// Returns `None` when there is no such account, or when it is already the+/// stored one.+#[tracing::instrument(skip(store, pipedream), err)]+pub async fn recover_pipedream_connection<S, P>(+ store: &S,+ pipedream: &P,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ server_name: Option<&str>,+ now: chrono::DateTime<chrono::Utc>,+) -> Result<Option<PipedreamConnection>, PipedreamConnectError>+where+ S: ConnectionStore,+ P: PipedreamConnect,+ anyhow::Error: From<S::Err>,+{+ let accounts = pipedream.list_accounts(user_id.as_ref(), app_slug).await?;+ let Some(newest) = accounts+ .into_iter()+ .filter(|account| {+ account+ .created_at+ .is_some_and(|created_at| created_at >= now - RECOVERY_WINDOW)+ })+ .max_by_key(|account| account.created_at)+ else {+ tracing::info!(found = false, "no recent Pipedream account to recover");+ return Ok(None);+ };++ let existing = store+ .load(user_id, app_slug)+ .await+ .map_err(anyhow::Error::from)?;+ if existing.is_some_and(|record| record.account_id == newest.id) {+ tracing::info!(+ found = true,+ already_stored = true,+ "Pipedream account already stored"+ );+ return Ok(None);+ }++ tracing::info!(found = true, account_id = %newest.id, "recovering unreported Pipedream account");+ complete_pipedream_connection(store, pipedream, user_id, &newest.id, server_name)+ .await+ .map(Some)+}+/// Remove a connected app, revoking its Pipedream account. Returns the/// connection that was removed, or `None` when the app was not connected.///diff --git a/crates/pipedream_mcp/src/domain/service/connect/test.rs b/crates/pipedream_mcp/src/domain/service/connect/test.rsindex fb3fedf4b1..4783f45f94 100644--- a/crates/pipedream_mcp/src/domain/service/connect/test.rs+++ b/crates/pipedream_mcp/src/domain/service/connect/test.rs@@ -83,6 +83,21 @@ impl PipedreamConnect for FakePipedream {Ok(self.accounts.get(account_id).cloned())}+ async fn list_accounts(+ &self,+ external_user_id: &str,+ app_slug: &str,+ ) -> anyhow::Result<Vec<PipedreamAccount>> {+ Ok(self+ .accounts+ .values()+ .filter(|a| {+ a.external_user_id.as_deref() == Some(external_user_id) && a.app_slug == app_slug+ })+ .cloned()+ .collect())+ }+async fn delete_account(&self, account_id: &str) -> anyhow::Result<()> {self.deleted.lock().unwrap().push(account_id.to_owned());Ok(())@@ -96,6 +111,18 @@ fn account(id: &str, external_user_id: Option<&str>, app_slug: &str) -> Pipedreaapp_slug: app_slug.to_owned(),app_name: "Linear".to_owned(),healthy: true,+ created_at: None,+ }+}++fn now() -> chrono::DateTime<chrono::Utc> {+ "2026-10-27T18:00:00Z".parse().unwrap()+}++fn created(id: &str, external_user_id: &str, minutes_ago: i64) -> PipedreamAccount {+ PipedreamAccount {+ created_at: Some(now() - chrono::TimeDelta::minutes(minutes_ago)),+ ..account(id, Some(external_user_id), "linear")}}@@ -268,3 +295,95 @@ async fn disconnect_of_unknown_app_is_a_quiet_noop() {assert!(removed.is_none());assert!(pd.deleted.lock().unwrap().is_empty());}++#[tokio::test]+async fn recovery_stores_the_newest_recent_account_the_ui_never_reported() {+ let store = FakeStore::default();+ let mut pd = FakePipedream::default();+ for account in [+ created("apn_older", "macro|[email protected]", 5),+ created("apn_newest", "macro|[email protected]", 1),+ ] {+ pd.accounts.insert(account.id.clone(), account);+ }++ let record = recover_pipedream_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "linear",+ None,+ now(),+ )+ .await+ .unwrap()+ .expect("recovered");++ assert_eq!(record.account_id, "apn_newest");+ assert!(+ store+ .load(&user("macro|[email protected]"), "linear")+ .await+ .unwrap()+ .is_some()+ );+}++#[tokio::test]+async fn recovery_ignores_accounts_outside_the_window_and_other_users() {+ let store = FakeStore::default();+ let mut pd = FakePipedream::default();+ for account in [+ created("apn_stale", "macro|[email protected]", 60),+ created("apn_theirs", "macro|[email protected]", 1),+ ] {+ pd.accounts.insert(account.id.clone(), account);+ }++ let recovered = recover_pipedream_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "linear",+ None,+ now(),+ )+ .await+ .unwrap();++ assert!(recovered.is_none());+ assert!(store.records.lock().unwrap().is_empty(), "nothing stored");+}++#[tokio::test]+async fn recovery_does_not_report_the_already_stored_account_as_new() {+ let store = FakeStore::default();+ store+ .save(&PipedreamConnection {+ user_id: user("macro|[email protected]"),+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ account_id: "apn_1".into(),+ enabled: true,+ })+ .await+ .unwrap();+ let mut pd = FakePipedream::default();+ pd.accounts.insert(+ "apn_1".into(),+ created("apn_1", "macro|[email protected]", 1),+ );++ let recovered = recover_pipedream_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "linear",+ None,+ now(),+ )+ .await+ .unwrap();++ assert!(recovered.is_none());+}diff --git a/crates/pipedream_mcp/src/inbound/axum_router.rs b/crates/pipedream_mcp/src/inbound/axum_router.rsindex 014cc22136..946d899695 100644--- a/crates/pipedream_mcp/src/inbound/axum_router.rs+++ b/crates/pipedream_mcp/src/inbound/axum_router.rs@@ -3,7 +3,10 @@ use crate::domain::{ports::{ConnectionStore, ConnectorDirectory, PipedreamConnect},service::{catalog::browse_catalog,- connect::{PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server},+ connect::{+ PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server,+ recover_pipedream_connection,+ },},};use axum::{@@ -148,6 +151,10 @@ where"/pipedream/mcp/complete",post(complete_connection::<S, P, Auth>),)+ .route(+ "/pipedream/mcp/recover",+ post(recover_connection::<S, P, Auth>),+ ).route("/pipedream/mcp/catalog",get(browse_catalog_handler::<S, P, Auth>),@@ -195,8 +202,9 @@ pub struct PipedreamWebhookQuery {/// The body is taken as raw JSON on purpose. The payload shape is/// Pipedream's to change, and an endpoint whose whole job is telling us why/// connections fail must not start dropping events with a 422 the day they-/// add a field. Known keys are pulled out so they can be indexed; the rest-/// is logged verbatim.+/// add a field. Only opaque ids, the app, and Pipedream's error text are+/// logged: the payload also carries the Connect token and the account's+/// name and external id, which are personal data.#[tracing::instrument(skip_all)]async fn pipedream_webhook(State(state): State<PipedreamWebhookState>,@@ -209,25 +217,29 @@ async fn pipedream_webhook(return StatusCode::UNAUTHORIZED;}- let event = payload.get("event").and_then(serde_json::Value::as_str);- let external_user_id = payload- .get("external_user_id")- .and_then(serde_json::Value::as_str);- let failed = payload.get("error").is_some()- || event.is_some_and(|e| e.to_ascii_uppercase().contains("ERROR"));+ let str_at = |pointer: &str| payload.pointer(pointer).and_then(serde_json::Value::as_str);+ let event = str_at("/event");+ let error = str_at("/error");+ let account_id = str_at("/account/id");+ let app_slug = str_at("/account/app/name_slug");+ let connect_session_id = payload.get("connect_session_id").map(ToString::to_string);+ let failed = error.is_some() || event.is_some_and(|e| e.to_ascii_uppercase().contains("ERROR"));if failed {tracing::warn!(- event = event,- external_user_id = external_user_id,- payload = %payload,+ event,+ error,+ account_id,+ connector.app_slug = app_slug,+ connect_session_id,"Pipedream connect flow failed");} else {tracing::info!(- event = event,- external_user_id = external_user_id,- payload = %payload,+ event,+ account_id,+ connector.app_slug = app_slug,+ connect_session_id,"Pipedream connect flow event");}@@ -280,6 +292,17 @@ pub struct PipedreamCompleteRequest {server_name: Option<String>,}+/// Request body for recovering a connect flow whose result the Connect UI+/// never reported.+#[derive(Debug, Deserialize, ToSchema)]+pub struct PipedreamRecoverRequest {+ /// The Pipedream app the flow was connecting, by name slug.+ app_slug: String,+ /// Optional display name for the connector, as for completion.+ #[serde(default)]+ server_name: Option<String>,+}+/// A connected MCP app as returned by the API.#[derive(Debug, Serialize, ToSchema)]pub struct PipedreamConnectionResponse {@@ -613,6 +636,56 @@ whereOk(Json(PipedreamConnectionResponse::from_record(&record)))}+#[utoipa::path(+ post,+ path = "/pipedream/mcp/recover",+ tag = "pipedream-mcp",+ operation_id = "recover_pipedream_mcp_connection",+ request_body = PipedreamRecoverRequest,+ responses(+ (status = 200, body = PipedreamConnectionResponse),+ (status = 401, body = String),+ (status = 404, body = ErrorResponse),+ (status = 501, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+/// Register an account a Connect flow created but the Connect UI never+/// reported.+///+/// Called after the Connect UI closes without a success event. Answers 404+/// when Pipedream has no new account for this user and app.+#[tracing::instrument(skip_all, err, fields(connector.app_slug = %body.app_slug))]+pub async fn recover_connection<S, P, Auth>(+ State(state): State<PipedreamRouterState<S, P, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(body): Json<PipedreamRecoverRequest>,+) -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>+where+ S: ConnectionStore,+ P: PipedreamConnect + ConnectorDirectory,+ Auth: MacroAuthorizationService,+ anyhow::Error: From<S::Err>,+{+ let user = &authorization.authorization.user;+ let record = recover_pipedream_connection(+ state.store.as_ref(),+ state.pipedream()?.as_ref(),+ &user.macro_user_id,+ &body.app_slug,+ body.server_name.as_deref(),+ chrono::Utc::now(),+ )+ .await?+ .ok_or(PipedreamHandlerErr::NotFound)?;++ if let Some(hook) = &state.on_auth_completed {+ hook(record.clone()).await;+ }++ Ok(Json(PipedreamConnectionResponse::from_record(&record)))+}+#[utoipa::path(get,path = "/pipedream/mcp/catalog",diff --git a/crates/pipedream_mcp/src/outbound/api.rs b/crates/pipedream_mcp/src/outbound/api.rsindex 0031a7b205..d720b9f87c 100644--- a/crates/pipedream_mcp/src/outbound/api.rs+++ b/crates/pipedream_mcp/src/outbound/api.rs@@ -29,6 +29,10 @@ pub const DEFAULT_MCP_URL: &str = "https://remote.mcp.pipedream.net";/// present a token about to expire mid-request.const TOKEN_EXPIRY_MARGIN: Duration = Duration::from_secs(60);+/// The most accounts one listing asks for; a user holds one per app unless a+/// connect flow went unreported.+const ACCOUNTS_PAGE_LIMIT: &str = "100";+/// Configuration for [`PipedreamClient`].#[derive(Clone, Debug)]pub struct PipedreamConfig {@@ -214,13 +218,32 @@ impl PipedreamConnect for PipedreamClient {let account: AccountResponse =serde_json::from_value(account).context("parsing Pipedream account")?;- Ok(Some(PipedreamAccount {- id: account.id,- external_user_id: account.external_id,- app_slug: account.app.name_slug,- app_name: account.app.name,- healthy: account.healthy.unwrap_or(true),- }))+ Ok(Some(account.into()))+ }++ #[tracing::instrument(skip(self, external_user_id), err)]+ async fn list_accounts(+ &self,+ external_user_id: &str,+ app_slug: &str,+ ) -> anyhow::Result<Vec<PipedreamAccount>> {+ let response = self+ .authed(self.http.get(self.connect_api("/accounts")).query(&[+ ("external_user_id", external_user_id),+ ("app", app_slug),+ ("limit", ACCOUNTS_PAGE_LIMIT),+ ]))+ .await?+ .send()+ .await+ .context("listing Pipedream accounts")?;+ let response = error_for_status(response).await?;++ let accounts: AccountsResponse = response+ .json()+ .await+ .context("decoding Pipedream accounts response")?;+ Ok(accounts.data.into_iter().map(Into::into).collect())}#[tracing::instrument(skip(self), err)]@@ -536,9 +559,28 @@ struct AccountResponse {id: String,external_id: Option<String>,healthy: Option<bool>,+ created_at: Option<chrono::DateTime<chrono::Utc>>,app: AccountApp,}+impl From<AccountResponse> for PipedreamAccount {+ fn from(account: AccountResponse) -> Self {+ Self {+ id: account.id,+ external_user_id: account.external_id,+ app_slug: account.app.name_slug,+ app_name: account.app.name,+ healthy: account.healthy.unwrap_or(true),+ created_at: account.created_at,+ }+ }+}++#[derive(Deserialize)]+struct AccountsResponse {+ data: Vec<AccountResponse>,+}+#[derive(Deserialize)]struct AccountApp {name_slug: String,diff --git a/crates/pipedream_mcp/src/outbound/api/test.rs b/crates/pipedream_mcp/src/outbound/api/test.rsindex ca4f2edb13..5e8b58e731 100644--- a/crates/pipedream_mcp/src/outbound/api/test.rs+++ b/crates/pipedream_mcp/src/outbound/api/test.rs@@ -1,6 +1,6 @@use super::{AppResponse, PipedreamClient, PipedreamConfig, connectable_catalog_entry};use crate::domain::models::{MacroUserIdStr, PipedreamConnection};-use crate::domain::ports::ConnectedAppProxy;+use crate::domain::ports::{ConnectedAppProxy, PipedreamConnect};use http::{HeaderMap, HeaderValue, Method, StatusCode};use std::time::Duration;use wiremock::matchers::{body_json, header, method, path, query_param};@@ -110,3 +110,55 @@ async fn the_proxy_addresses_the_upstream_url_for_the_connected_account() {assert_eq!(response.retry_after(), Some(Duration::from_secs(3)));assert_eq!(response.body, r#"{"object":"error","code":"rate_limited"}"#);}++#[tokio::test]+async fn listing_accounts_filters_by_user_and_app_and_keeps_creation_times() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/oauth/token"))+ .respond_with(ResponseTemplate::new(200).set_body_json(+ serde_json::json!({"access_token": "project-token", "expires_in": 3600}),+ ))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/connect/proj_fixture/accounts"))+ .and(query_param("external_user_id", "macro|[email protected]"))+ .and(query_param("app", "linear"))+ .and(header("authorization", "Bearer project-token"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "page_info": {"total_count": 1},+ "data": [{+ "id": "apn_1",+ "external_id": "macro|[email protected]",+ "healthy": true,+ "created_at": "2026-10-27T18:54:23.000Z",+ "app": {"name_slug": "linear", "name": "Linear"}+ }]+ })))+ .expect(1)+ .mount(&server)+ .await;+ let client = PipedreamClient::new(PipedreamConfig {+ client_id: "fixture".into(),+ client_secret: "fixture".into(),+ project_id: "proj_fixture".into(),+ environment: "development".into(),+ allowed_origins: vec![],+ api_url: server.uri(),+ mcp_url: format!("{}/mcp", server.uri()),+ })+ .unwrap();++ let accounts = client+ .list_accounts("macro|[email protected]", "linear")+ .await+ .unwrap();++ assert_eq!(accounts.len(), 1);+ assert_eq!(accounts[0].id, "apn_1");+ assert_eq!(+ accounts[0].created_at,+ Some("2026-10-27T18:54:23Z".parse().unwrap())+ );+}diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 35662eb5c3..7c38eb1a51 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -23,8 +23,9 @@ not establish that the requested action is supported.For a suitable unconnected app, the assistant offers **Connect <app>**. Clickingit opens the hosted authorization flow over the agent transcript on web. In-native apps, consent opens in the system browser; choose **Return to Macro**-after authorization. The waiting dialog also offers **Cancel**, and callbacks+native apps, consent opens in the system browser, which returns to Macro on its+own after authorization (**Return to Macro** is the fallback link). The waiting+dialog's **Done** checks Pipedream for an account the flow created, and callbacksfrom canceled or expired attempts cannot resume the agent. After thebackend verifies and registers the connection, the agent session sends a visiblecontinuation message in the same conversation. Before that message reaches thediff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex cc9d02df89..2c5d78e4a4 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -528,8 +528,8 @@ connected) or `Specific apps`, which reveals a `Search connectors` box over thePipedream catalog (results are `option` rows; picking one adds it) and a row per picked appwith a connected / not-connected dot for the *current viewer* plus an inline `Connect`that opens the Pipedream Connect flow inside the web page. Native apps open-consent in the system browser; choose **Return to Macro** after authorization-to save the connection in the waiting app. Unconnected picks never block+consent in the system browser, which returns to the waiting app on its own after+authorization (**Return to Macro** is the fallback link). Unconnected picks never blocksaving; each teammate connects their own account. An agent session that calls a pickedbut unconnected app gets a tool result saying so, and the agent's reply renders a`Connect <app>` chip that opens Agents → Connections for that app. The same pagediff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md b/packages/sdk-docs/reference/generated/cognition/types.gen/README.mdindex bdbc4b8113..1c2e3462d4 100644--- a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/README.md@@ -249,11 +249,17 @@- [PipedreamCatalogResponse](type-aliases/PipedreamCatalogResponse.md)- [PipedreamCompleteRequest](type-aliases/PipedreamCompleteRequest.md)- [PipedreamConnectionResponse](type-aliases/PipedreamConnectionResponse.md)+- [PipedreamRecoverRequest](type-aliases/PipedreamRecoverRequest.md)- [PipedreamTokenResponse](type-aliases/PipedreamTokenResponse.md)- [PipedreamUpdateRequest](type-aliases/PipedreamUpdateRequest.md)- [Price](type-aliases/Price.md)- [ProjectionStateResponse](type-aliases/ProjectionStateResponse.md)- [ProjectionStatus](type-aliases/ProjectionStatus.md)+- [RecoverPipedreamMcpConnectionData](type-aliases/RecoverPipedreamMcpConnectionData.md)+- [RecoverPipedreamMcpConnectionError](type-aliases/RecoverPipedreamMcpConnectionError.md)+- [RecoverPipedreamMcpConnectionErrors](type-aliases/RecoverPipedreamMcpConnectionErrors.md)+- [RecoverPipedreamMcpConnectionResponse](type-aliases/RecoverPipedreamMcpConnectionResponse.md)+- [RecoverPipedreamMcpConnectionResponses](type-aliases/RecoverPipedreamMcpConnectionResponses.md)- [RefreshCadence](type-aliases/RefreshCadence.md)- [RejectToolCallData](type-aliases/RejectToolCallData.md)- [RejectToolCallError](type-aliases/RejectToolCallError.md)diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamRecoverRequest.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamRecoverRequest.mdnew file mode 100644index 0000000000..0f41698673--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamRecoverRequest.md@@ -0,0 +1,13 @@+# Type Alias: PipedreamRecoverRequest++> **PipedreamRecoverRequest** = \{ `app_slug`: `string`; `server_name?`: `string` \| `null`; \}++Request body for recovering a connect flow whose result the Connect UI+never reported.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-app_slug"></a> `app_slug` | `string` | The Pipedream app the flow was connecting, by name slug. |+| <a id="property-server_name"></a> `server_name?` | `string` \| `null` | Optional display name for the connector, as for completion. |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionData.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionData.mdnew file mode 100644index 0000000000..af498c828d--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionData.md@@ -0,0 +1,12 @@+# Type Alias: RecoverPipedreamMcpConnectionData++> **RecoverPipedreamMcpConnectionData** = \{ `body`: [`PipedreamRecoverRequest`](PipedreamRecoverRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/pipedream/mcp/recover"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`PipedreamRecoverRequest`](PipedreamRecoverRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/pipedream/mcp/recover"` |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionError.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionError.mdnew file mode 100644index 0000000000..e9df1908ca--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionError.md@@ -0,0 +1,3 @@+# Type Alias: RecoverPipedreamMcpConnectionError++> **RecoverPipedreamMcpConnectionError** = [`RecoverPipedreamMcpConnectionErrors`](RecoverPipedreamMcpConnectionErrors.md)\[keyof [`RecoverPipedreamMcpConnectionErrors`](RecoverPipedreamMcpConnectionErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionErrors.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionErrors.mdnew file mode 100644index 0000000000..a3cd30957c--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionErrors.md@@ -0,0 +1,12 @@+# Type Alias: RecoverPipedreamMcpConnectionErrors++> **RecoverPipedreamMcpConnectionErrors** = \{ `401`: `string`; `404`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); `501`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-401"></a> `401` | `string` |+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-501"></a> `501` | [`ErrorResponse`](ErrorResponse.md) |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponse.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponse.mdnew file mode 100644index 0000000000..4c5f01208e--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponse.md@@ -0,0 +1,3 @@+# Type Alias: RecoverPipedreamMcpConnectionResponse++> **RecoverPipedreamMcpConnectionResponse** = [`RecoverPipedreamMcpConnectionResponses`](RecoverPipedreamMcpConnectionResponses.md)\[keyof [`RecoverPipedreamMcpConnectionResponses`](RecoverPipedreamMcpConnectionResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponses.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponses.mdnew file mode 100644index 0000000000..88d2cc6aa9--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/RecoverPipedreamMcpConnectionResponses.md@@ -0,0 +1,9 @@+# Type Alias: RecoverPipedreamMcpConnectionResponses++> **RecoverPipedreamMcpConnectionResponses** = \{ `200`: [`PipedreamConnectionResponse`](PipedreamConnectionResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`PipedreamConnectionResponse`](PipedreamConnectionResponse.md) |diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.tsindex e2a869d137..c9be5a8d83 100644--- a/packages/sdk/generated/cognition/index.ts+++ b/packages/sdk/generated/cognition/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } from './types.gen';+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamRecoverRequest, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionError, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponse, RecoverPipedreamMcpConnectionResponses, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } from './types.gen';diff --git a/packages/sdk/generated/cognition/sdk.gen.ts b/packages/sdk/generated/cognition/sdk.gen.tsindex 279c90e1c6..da5d812f20 100644--- a/packages/sdk/generated/cognition/sdk.gen.ts+++ b/packages/sdk/generated/cognition/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';+import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -504,6 +504,24 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Register an account a Connect flow created but the Connect UI never+ * reported.+ *+ * Called after the Connect UI closes without a success event. Answers 404+ * when Pipedream has no new account for this user and app.+ */+ public recoverPipedreamMcpConnection<ThrowOnError extends boolean = false>(options: Options<RecoverPipedreamMcpConnectionData, ThrowOnError>): RequestResult<RecoverPipedreamMcpConnectionResponses, RecoverPipedreamMcpConnectionErrors, ThrowOnError> {+ return (options.client ?? this.client).post<RecoverPipedreamMcpConnectionResponses, RecoverPipedreamMcpConnectionErrors, ThrowOnError>({+ url: '/pipedream/mcp/recover',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Create a short-lived Pipedream Connect token for the authenticated user.*diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.tsindex 9cd1b97e0c..75049ad74d 100644--- a/packages/sdk/generated/cognition/types.gen.ts+++ b/packages/sdk/generated/cognition/types.gen.ts@@ -1390,6 +1390,21 @@ export type PipedreamConnectionResponse = {server_name: string;};+/**+ * Request body for recovering a connect flow whose result the Connect UI+ * never reported.+ */+export type PipedreamRecoverRequest = {+ /**+ * The Pipedream app the flow was connecting, by name slug.+ */+ app_slug: string;+ /**+ * Optional display name for the connector, as for completion.+ */+ server_name?: string | null;+};+/*** Response from creating a Pipedream Connect token.*/@@ -3270,6 +3285,28 @@ export type UpdatePipedreamMcpConnectionResponses = {export type UpdatePipedreamMcpConnectionResponse = UpdatePipedreamMcpConnectionResponses[keyof UpdatePipedreamMcpConnectionResponses];+export type RecoverPipedreamMcpConnectionData = {+ body: PipedreamRecoverRequest;+ path?: never;+ query?: never;+ url: '/pipedream/mcp/recover';+};++export type RecoverPipedreamMcpConnectionErrors = {+ 401: string;+ 404: ErrorResponse;+ 500: ErrorResponse;+ 501: ErrorResponse;+};++export type RecoverPipedreamMcpConnectionError = RecoverPipedreamMcpConnectionErrors[keyof RecoverPipedreamMcpConnectionErrors];++export type RecoverPipedreamMcpConnectionResponses = {+ 200: PipedreamConnectionResponse;+};++export type RecoverPipedreamMcpConnectionResponse = RecoverPipedreamMcpConnectionResponses[keyof RecoverPipedreamMcpConnectionResponses];+export type CreatePipedreamMcpTokenData = {body?: never;path?: never;diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.jsonindex 1958491b73..3dedb6d5c9 100644--- a/packages/sdk/specs/cognition.json+++ b/packages/sdk/specs/cognition.json@@ -2091,6 +2091,76 @@}}},+ "/pipedream/mcp/recover": {+ "post": {+ "tags": ["pipedream-mcp"],+ "summary": "Register an account a Connect flow created but the Connect UI never\nreported.",+ "description": "Called after the Connect UI closes without a success event. Answers 404\nwhen Pipedream has no new account for this user and app.",+ "operationId": "recover_pipedream_mcp_connection",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamRecoverRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamConnectionResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "501": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/pipedream/mcp/token": {"post": {"tags": ["pipedream-mcp"],@@ -4916,6 +4986,21 @@}}},+ "PipedreamRecoverRequest": {+ "type": "object",+ "description": "Request body for recovering a connect flow whose result the Connect UI\nnever reported.",+ "required": ["app_slug"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "The Pipedream app the flow was connecting, by name slug."+ },+ "server_name": {+ "type": ["string", "null"],+ "description": "Optional display name for the connector, as for completion."+ }+ }+ },"PipedreamTokenResponse": {"type": "object","description": "Response from creating a Pipedream Connect token.",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex bce56a4631..25422e7c05 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -176,6 +176,7 @@ export const cognitionExcluded = ['listPipedreamMcpConnections','mcpAuthCallback','mcpOauthClientMetadata',+ 'recoverPipedreamMcpConnection','rejectToolCall',// Channel discovery shares the app-only import workflow below.'discoverHandler',diff --git a/services/agent_harness_service/src/cognition/api/swagger.rs b/services/agent_harness_service/src/cognition/api/swagger.rsindex c9063b88d3..5d311248eb 100644--- a/services/agent_harness_service/src/cognition/api/swagger.rs+++ b/services/agent_harness_service/src/cognition/api/swagger.rs@@ -31,8 +31,8 @@ use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryReuse onboarding::inbound::axum_router::{self as onboarding_api, CompleteOnboardingRequest};use pipedream_mcp::inbound::axum_router::{self as pipedream_api, PipedreamCatalogEntryResponse, PipedreamCatalogResponse,- PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse,- PipedreamUpdateRequest,+ PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamRecoverRequest,+ PipedreamTokenResponse, PipedreamUpdateRequest,};use crate::cognition::api::preview::get_batch_preview::{@@ -120,6 +120,7 @@ use utoipa::OpenApi;pipedream_api::delete_connection,pipedream_api::create_connect_token,pipedream_api::complete_connection,+ pipedream_api::recover_connection,pipedream_api::browse_catalog_handler),components(@@ -265,6 +266,7 @@ use utoipa::OpenApi;PipedreamUpdateRequest,PipedreamTokenResponse,PipedreamCompleteRequest,+ PipedreamRecoverRequest,PipedreamCatalogResponse,PipedreamCatalogEntryResponse,model_error_response::ErrorResponse,