# Connection

> Connections: named links to your users' accounts on other services, and what those services can do.

```python
gmail = noclick.Connection.from_name("gmail", integration="gmail", create_if_missing=True)
if not gmail.connected:
    send_to_user(gmail.connect_url)
gmail.wait()
gmail.run("send_email_message", {...})
```

A connection is a name in one scope (a user, or your account's own). Code,
toolkits and agents name it, so they always act in exactly that account; two
accounts on one service are two connections. Reconnecting keeps the name.

An operation that needs no account (`exa`'s web search) needs no connection
either: `noclick.run("exa.search", {...})` and `tools=["exa.search"]` run it
on NoClick's key, for every user. A connection named `exa` holding your own
key takes over the same refs. `Connection.integrations()` finds a service,
and `operations()` says what a connection's service can do.

## Connection

```typescript
class Connection
```

A named connection to an account on another service. Secrets never come
back; `token()` mints an OAuth access token (`credentials:token` scope).
`status` is `pending` until someone connects an account at `connectUrl`,
`connected` after, and `disconnected` once it's revoked (`connectLink()`
mints a link to reconnect it).

The accounts connected in the NoClick app are connections too, in your
account's own scope: `origin` is `"app"` and the id is `credential:<id>`
(their name is the app's, so refer to them by id). They run, look up,
verify and take `requireApproval` like any connection, and an account agent
takes one as a tool (the `Connection`, or `"credential:<id>"`,
`"credential:<id>.operation"`; a user's agent can't); the app connects
them, and `delete()` removes one as the app does. A connect link
(`connectLink()`, `request()`) reconnects one in place: a key typed there
replaces its own in the same credential, so everything using it keeps
working; its owner makes the link, or someone it's shared with to edit. One
shared with your account has `access` `"view"` or `"edit"`: it runs, but its
token, approval rules and deletion stay its owner's.
A Claude or ChatGPT plan you signed in to in the app is one too, an account
agent's `modelConnection`; a plan shared with you, or filled in by someone
else, isn't.

One a teammate shared with a team workspace you're in is that team's to use,
in its workspace only: name the workspace (`organizationId`) to list, find
and run it there. A connection read in a team workspace carries it
(`organizationId`), and everything it does goes there, as the team's work.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string` |  |
| `integration` | `string` |  |
| `credentialType` | `string | null` |  |
| `userId` | `string | null` |  |
| `status` | `ConnectionStatus` |  |
| `origin` | `ConnectionOrigin` | `api` for a named connection, `app` for an account connected in the app. |
| `access` | `ConnectionAccess` | Your account's access: `owner`, or `edit`/`view` on one shared with it. |
| `organizationId` | `string | null` | The team workspace it was read in (`organizationId`), where it runs; `null` in your account's own. |
| `approvalOperations` | `string[]` | Operations its owner approves call by call wherever it runs (`*`: all); `requireApproval` adds to them and `liftApproval` lifts them. |
| `account` | `string | null` | The account it reaches, as the app's Connections list names it: its login, else its email, else who a check verified it as, else the number it links; `null` when none is known. |
| `credentialId` | `string | null` | The id of the account it holds, as a workflow step's `connections` names it, so a step's account is matched to its connection; `null` while none is connected. |
| `testAccount` | `boolean` | Whether it's a test account, which an app's preview writes through as well as reads. |
| `usedBy` | `ConnectionHolder[]` | What holds it: agents (in their tools, as their `modelConnection`, given it by their user, or with a trigger on it), channels and workspaces subscribed to its events, hosted MCP servers with it in their tools, apps that bind it (with the `binding` name) or whose code made it, numbers connected through it, and the automations whose steps use its account (`workflow`: yours, and for an account yours owns, those in its workspace), each with whose it is. |
| `connectedAt` | `Date | null` |  |
| `createdAt` | `Date | null` |  |
| `updatedAt` | `Date | null` |  |
| `connected` | `boolean` |  |
| `connectUrl` | `string | null` | The open link where someone connects (or reconnects) the account, if one is open. |
| `verification` | `Verification | null` |  |
| `shared` | `ConnectionShared | null` | How one connected in the app and shared with your account reaches it, and who shared it; `null` for your own and for a named connection. |
| `health` | `ConnectionHealth | null` | The provider's live word on a linked session (a WhatsApp number's, a Discord install's), read with the connection; `null` where there's nothing to ask or no telling. |
| `plan` | `Plan | null` | A Claude or ChatGPT plan's tier and what it runs; null for any other connection. |
| `usageSummary` | `PlanUsageSummary | null` | A plan's usage over every window, as last read; null until a reading exists (and for any other connection). |
| `consoleUrl` | `string | null` | This connection's kind in the developer console (null off the hosted API). |

Types:

```typescript
/**
 * `pending` until an account is connected, `disconnected` once it's revoked. A pending connection
 * still runs the operations whose `needsAccount` is false, on NoClick's key.
 */
type ConnectionStatus = "pending" | "connected" | "disconnected";

/** `api` for a named connection, `app` for an account connected in the NoClick app. */
type ConnectionOrigin = "api" | "app";

/** Your account's access to a connection: its own, or shared with it to edit or to use. */
type ConnectionAccess = "owner" | "edit" | "view";
```

### Connection.fromName

```typescript
static fromName(
  name: string,
  options?: ConnectionCreateOptions & { createIfMissing?: boolean },
): Connection
```

A lazy reference to the connection called `name` in the current (or
given) user. With `createIfMissing` it's created on first use, for
`integration`: holding `data` when given (a key you hold), pending with a
connect link otherwise. An existing connection is used as it is: `data` and the link options apply
only when it's created. `integration` and `credentialType` say what the connection is, so they're
checked, with or without `createIfMissing`: one of another integration or credential type throws
`Conflict` naming it. Given `integration`, `operations()`, `operation()` and `events()` read the
catalog without loading or creating the connection.

Parameters:

- `name` (`string`, required)
- `options.integration` (`string | { name: string }`): Its integration: a name (`"gmail"`) or an `IntegrationInfo`.
- `options.createIfMissing` (`boolean`)
- `options.credentialType` (`string`)
- `options.data` (`JsonObject`): A credential you hold: the connection holds it at once (validated and probed first).
- `options.redirectUrl` (`string`)
- `options.reason` (`string`)
- `options.sendTo` (`SendTo`): Also deliver the link: "user", "owner" (your account's owner), an email, or an object.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A connection that loads, or is created, the first time it's used. Nothing is sent yet.

Types:

```typescript
type JsonObject = { [key: string]: unknown };

/** Where a connect link is delivered (by email only): the user, an email, or the wire dict. */
type SendTo = "user" | "owner" | true | string | JsonObject;

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Connection.fromId

```typescript
static fromId(
  connectionId: string,
  options?: CallOptions & InWorkspace,
): Connection
```

A lazy reference by NoClick id; `credential:<id>` for an account connected in the app. `organizationId` names a
team workspace you're in, where one shared with that team is used.

Parameters:

- `connectionId` (`string`, required)
- `options.organizationId` (`string`)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A connection that loads the first time you read a field. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Connection.create

```typescript
static create(
  name: string,
  options?: ConnectionCreateOptions & AllowExisting,
): Promise<Connection>
```

Create a connection called `name` (unique per user; a duplicate throws
`Conflict` with `existingId`). With `data` it holds that credential at
once; without, it's pending and `connectUrl` is where someone connects it.
With `allowExisting: true` a taken name returns the connection already there, as it is: its
credential isn't replaced and no link is made. One of another integration still throws the `Conflict`.

Parameters:

- `name` (`string`, required)
- `options.integration` (`string | { name: string }`): Its integration: a name (`"gmail"`) or an `IntegrationInfo`.
- `options.credentialType` (`string`)
- `options.data` (`JsonObject`): A credential you hold: the connection holds it at once (validated and probed first).
- `options.redirectUrl` (`string`)
- `options.reason` (`string`)
- `options.sendTo` (`SendTo`): Also deliver the link: "user", "owner" (your account's owner), an email, or an object.
- `options.allowExisting` (`boolean`): A taken name returns the object already there, as it is: nothing about it changes.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The new connection: `pending` with its `connect_url`, or `connected`
(with its `verification`) when you passed `data`.

Types:

```typescript
type JsonObject = { [key: string]: unknown };

/** Where a connect link is delivered (by email only): the user, an email, or the wire dict. */
type SendTo = "user" | "owner" | true | string | JsonObject;

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Connection.get

```typescript
static get(
  ref: string,
  options?: CallOptions & InWorkspace,
): Promise<Connection>
```

The connection with this id or name; in `organizationId`, a team workspace you're in, one shared with that team.

Parameters:

- `ref` (`string`, required)
- `options.organizationId` (`string`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The connection, loaded.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Connection.list

```typescript
static list(
  options?: ReadOptions & ConnectionFilters & { limit?: number },
): Promise<Connection[]>
```

The current user's connections (the account's own outside `asUser`), or those `userFilter` covers:
named ones newest first, then, in the account's own scope, the accounts connected in the app.
`origin` keeps only `"api"` or `"app"` ones; `organizationId` reads in a team workspace you're in, where those
shared with that team are listed too (and each runs there).

    const fromTheApp = await Connection.list({ origin: "app" });
    const theTeams = await Connection.list({ organizationId: "5c0d9e4a-7b1f-4e2a-9c3d-8f6b2a1e4d70" });

Parameters:

- `options.integration` (`string | { name: string }`)
- `options.origin` (`ConnectionOrigin`)
- `options.organizationId` (`string`): A team workspace you're in (its id): read there, where those shared with that team are listed too.
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching connection (or the first `limit`), fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** `api` for a named connection, `app` for an account connected in the NoClick app. */
type ConnectionOrigin = "api" | "app";
```

### Connection.listPage

```typescript
static listPage(
  options?: ReadOptions & PageOptions & ConnectionFilters,
): Promise<Page<Connection>>
```

One page of connections; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.integration` (`string | { name: string }`)
- `options.origin` (`ConnectionOrigin`)
- `options.organizationId` (`string`): A team workspace you're in (its id): read there, where those shared with that team are listed too.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the connections and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** `api` for a named connection, `app` for an account connected in the NoClick app. */
type ConnectionOrigin = "api" | "app";
```

### Connection.integrations

```typescript
static integrations(
  query?: string,
  options?: { kind?: IntegrationKind; client?: NoClick },
): Promise<IntegrationInfo[]>
```

The services a connection can be made to and the model providers agents think with: every
integration, or those whose name or label contains `query` (case-insensitive), each with how a
person connects it (`connectWith`), how many of its operations run with no account, by its
name (`accountFreeOperationCount`), and the app events an `OnEvent` trigger takes from it
(`events`, empty for one that only acts). `kind: "model"` keeps the model providers an agent's
`modelConnection` names; `kind: "app"` the services whose operations are tools.

    const [crm] = await Connection.integrations("hubspot");
    const hubspot = Connection.fromName("crm", { integration: crm, createIfMissing: true });
    const [tiktok] = await Connection.integrations("tiktok");
    console.log(tiktok.events);   // [] : it publishes, and no OnEvent hears it
    const providers = await Connection.integrations(undefined, { kind: "model" });

Parameters:

- `query` (`string`)
- `options.kind` (`IntegrationKind`)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Each one's `name` (what `integration=` takes), `label`, `kind`, `operation_count`,
`account_free_operation_count` (how many run with no account, by the service's name),
`connect_with` (how a person connects an account), `events` (the app events an
`OnEvent` trigger takes from it, empty for one that only acts) and `subscription`
(whether its link also offers signing in with a Claude or ChatGPT plan).

Types:

```typescript
/**
 * `app`: a service whose operations are tools. `model`: a model provider (`anthropic`, `openai`,
 * `openrouter`, ...) whose connection an agent names as its `modelConnection`, never in `tools`.
 */
type IntegrationKind = "app" | "model";
```

### Connection.only

```typescript
only(...operations: string[]): ConnectionOperations
```

A tool ref to some of its operations, for `tools` (`gmail.only("send_email_message")`);
a lazy `createIfMissing` connection is still created first.

Parameters:

- `operations` (`string[]`, required)

Returns: A ref to just those operations of this connection, to list in `tools=`; `bind(...)` on it fixes
arguments the model mustn't choose.

### Connection.checkout

```typescript
checkout(repository: string, options?: CheckoutOptions): RepoCheckout
```

One of its repositories (`owner/name` on its git host; a `github` connection) checked out in an
agent's workspace, for `Agent` `repos`: cloned into `/workspace/<path>` (the repository's name
when omitted) at a conversation's first turn. The agent's git reaches that repository only,
through NoClick, with a key made for its sandbox; the connection's own token never enters it.
`push` is the branches it may push to, as globs: NoClick refuses a push to any other ref, and
without it the checkout is read-only. `gh` only reads it; give the agent the connection's
operations for pull requests and issues. Sends nothing.

    const github = Connection.fromName("github", { integration: "github", createIfMissing: true });
    const repos = [github.checkout("acme/docs", { push: "noclick/*" })];

Parameters:

- `repository` (`string`, required)
- `options.branch` (`string`): The branch it checks out (the repository's default when omitted).
- `options.path` (`string`): The folder under `/workspace` it's cloned into (the repository's name when omitted).
- `options.push` (`string | string[]`): Branches it may push to, exact or a prefix ending in `/*` (`"noclick/*"`); without it the checkout is read-only.

Returns: A `RepoCheckout` to list in an agent's `repos`.

### Connection.operations

```typescript
operations(options?: { search?: string }): Promise<IntegrationOperation[]>
```

What its integration can do: every operation, or those whose name or description contains
`search` (case-insensitive), with parameter schemas and whether each `needsAccount`.

Parameters:

- `options.search` (`string`)

Returns: Each operation's `name`, `description`, the JSON schema of its `parameters`,
`needs_account` (False when it runs on NoClick's key, with no connection or on a
pending one) and `read_only`, a hint from its name rather than a guarantee.

### Connection.operation

```typescript
operation(name: string): Promise<IntegrationOperation>
```

One of its integration's operations; throws `NotFound` for a name it doesn't have.

Parameters:

- `name` (`string`, required)

Returns: The operation, with the JSON schema of the `parameters` that `run` takes for it.

### Connection.events

```typescript
events(): Promise<IntegrationEvent[]>
```

The app events its integration can wake an agent with, for `OnEvent` (what it pushes as it happens, never a poll).

Returns: Every event, with its `description` and the `filters` it takes
(`channel` for a Slack message, `repository` for a GitHub issue).

### Connection.connectLink

```typescript
connectLink(options?: LinkOptions): Promise<ConnectLink>
```

A new link where someone connects (or reconnects) this connection's
account; `await link.wait()` resolves to the connected `Connection`. The
connection's own `connectUrl` is now this link's. On an account connected in
the app (`credential:<id>`), a key typed there goes into that same
credential, once, before the link expires; one shared with you to use
throws `PermissionDenied`.

Parameters:

- `options.redirectUrl` (`string`)
- `options.reason` (`string`)
- `options.sendTo` (`SendTo`): Also deliver the link: "user", "owner" (your account's owner), an email, or an object.

Returns: The link: its `url`, when it `expires_at`, and where it went when
you set `send_to`. It's also the operation that finishes when
someone connects: `link.wait()` returns the connected `Connection`.
The connection's own `connect_url` is now this link's.

Types:

```typescript
/** Where a connect link is delivered (by email only): the user, an email, or the wire dict. */
type SendTo = "user" | "owner" | true | string | JsonObject;

type JsonObject = { [key: string]: unknown };
```

### Connection.request

```typescript
request(options?: LinkOptions): Promise<ConnectLink>
```

Ask the user (or `sendTo`) to connect it; `await link.wait()` resolves to the `Connection`. A
connection of your account's own has no user: send it to `"owner"` (your account's owner) or an email.

Parameters:

- `options.reason` (`string`)
- `options.sendTo` (`SendTo`, default `"user"`): Also deliver the link: "user", "owner" (your account's owner), an email, or an object.
- `options.redirectUrl` (`string`)

Returns: The link, already sent: `delivered_via` says where it went, and
`.wait()` on it returns the connected `Connection`.

Types:

```typescript
/** Where a connect link is delivered (by email only): the user, an email, or the wire dict. */
type SendTo = "user" | "owner" | true | string | JsonObject;

type JsonObject = { [key: string]: unknown };
```

### Connection.wait

```typescript
wait(options?: { timeoutS?: number }): Promise<this>
```

Resolve once an account is connected (at once when it is). It follows the
connection, not one link: an account connected through any of its links
ends the wait, and a link that lapses after a fresh one was made
(`connectLink()` or `request()`, from anywhere) hands the wait to the fresh
one. Throws `OperationExpired` when the open link lapses with no fresh one,
or `OperationTimeout` after `timeoutS` seconds.

Parameters:

- `options.timeoutS` (`number`)

Returns: This connection, `connected`. After a wait it's reloaded, so `account`
names the account when the provider says who it is.

### Connection.import

```typescript
import(data: JsonObject, options?: { credentialType?: string }): Promise<this>
```

Replace the connection's credential with one you hold (a rotated key), validated first.

Parameters:

- `data` (`JsonObject`, required)
- `options.credentialType` (`string`)

Returns: This connection, holding the new key, with the probe's `verification`.
The key it replaced is deleted.

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Connection.run

```typescript
run(
  operation: string,
  args?: JsonObject,
  options?: { approvalId?: string },
): Promise<R>
```

Run one of the integration's operations in this account. Throws
`NeedsConnection` while pending (an operation whose `needsAccount` is
false runs anyway, on NoClick's key, or on your own key once connected, and needs no
connection at all through `run`) and `CredentialDisconnected` once
revoked (both carry `connectUrl`); a policy may throw `PolicyDenied` or `ApprovalRequired`.
Resolves to the operation's data (what the service answered); a service that refuses the call
throws `UpstreamError` in its own words, its HTTP status in `details.upstream_status`.

Parameters:

- `operation` (`string`, required)
- `args` (`JsonObject`)
- `options.approvalId` (`string`)

Returns: The operation's data, as plain data (what the service answered).

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Connection.lookup

```typescript
lookup(
  field: string,
  options?: { arguments?: JsonObject; search?: string; pageToken?: string },
): Promise<LookupOptions>
```

The allowed values of an ID-like field (channels, repos, sheets) in this account.

Parameters:

- `field` (`string`, required)
- `options.search` (`string`)
- `options.pageToken` (`string`)
- `options.arguments` (`JsonObject`)

Returns: One page of options, each with a `value` to pass and a `label` to show;
`next_page_token` is set when there are more.

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Connection.usage

```typescript
usage(options?: { model?: string; fresh?: boolean }): Promise<PlanUsage>
```

A plan's usage, window by window (a connection that isn't a Claude or ChatGPT plan throws `InvalidRequest`).
`model` keeps the windows that can stop that model; `fresh` asks the provider when the last reading is a few
minutes old, else it's NoClick's last reading.

    const usage = await plan.usage({ model: "claude-opus-5-5", fresh: true });
    if (usage.state === "used_up") console.log(`back at ${usage.availableAt}`);

Parameters:

- `options.fresh` (`boolean`)
- `options.model` (`string`)

Returns: Its `state` (`ok`, `near` from 80% used, `used_up`, `unknown`), its `windows`, the one that
stops it first (`tightest`), when a used-up plan runs again (`available_at`) and what to do meanwhile
(`next_steps`). Raises `InvalidRequest` for a connection that isn't a plan.

### Connection.verify

```typescript
verify(): Promise<Verification | null>
```

Re-check the account against the provider: its things as the provider sees them, who it signs in as, or its
refusal in its own words. Each check asks the provider, so an account makes at most 20 a minute
(`RateLimited` past them).

Returns: The provider's verdict, also kept as `verification`: `reachable` is
`True` when it accepted the account, `False` when it refused it, and
`None` when NoClick can't tell; `message` says what was found, and
`samples`, `noun`, `total`, `account_label` and `error` what
the provider showed or said.

### Connection.requireApproval

```typescript
requireApproval(...operations: string[]): Promise<this>
```

From now on its owner approves each call of these operations wherever it runs (your code, agents, the
app's workflows); `"*"` means every operation. It only adds to `approvalOperations` (`liftApproval`
lifts). On one shared with your account it throws `PermissionDenied`.

    await Connection.fromName("gmail").requireApproval("send_email_message", "delete_message");

Parameters:

- `operations` (`string[]`, required)

Returns: The connection, with its `approval_operations`.

### Connection.liftApproval

```typescript
liftApproval(...operations: string[]): Promise<PolicyChange[]>
```

Let calls of these operations run without its owner's OK again: each named as `approvalOperations` names it,
or none to lift every one (`"*"` lifts the rule for every operation, leaving any named on their own). Signed in
as your account's owner it applies at once, and so it does from your agent (NoClick's assistant, or any agent of
yours) on a turn your own message started, recorded as yours; one a model makes on its own (a turn no message of
yours started, a connected app, a key used through MCP) waits for your approval. From a key it needs one naming
the `approvals:policy` scope (a key with every scope, `*`, holds it only when it's named too) and
`credentials:use`, and it waits a 10-minute undo window, in which `ApprovalPolicy.undo(change.id)` takes it back;
the owner is told. Requiring approval for one of them again meanwhile takes it back too. Returns the change it
made (`pending` while it waits, `effectiveAt` when it takes effect). `PermissionDenied` without the scope, for a
call acting for one of your users or an app's code, or on one shared with your account; `Conflict` when it asks
no approval, or a lift of the same operation already waits.

    const [change] = await Connection.fromName("gmail").liftApproval("send_email_message");
    console.log(change.pending, change.effectiveAt);

Parameters:

- `operations` (`string[]`, required)

Returns: ```python
The change it made: ``pending`` while it waits, ``effective_at`` when it takes effect.
The connection's ``approval_operations`` read as they stand.
```

Raises:
noclick.PermissionDenied: a key without `approvals:policy`, a call acting for one of
your users, an app's code, or one shared with your account.
noclick.InvalidRequest: an operation it asks no approval for.
noclick.Conflict: it asks no approval at all, or a lift of the same operation already waits.

### Connection.rename

```typescript
rename(name: string): Promise<this>
```

Rename an account connected in the app (`origin` `app`): the name your account and the app see, which nothing
finds it by. Its owner renames it, or someone it's shared with to edit (`PermissionDenied` otherwise). A named
connection's name is how code finds it, so it isn't renamed (`InvalidRequest`).

    await (await Connection.get("credential:...")).rename("Sales inbox");

Parameters:

- `name` (`string`, required)

Returns: The connection, with its new `name`.

### Connection.markTestAccount

```typescript
markTestAccount(testAccount?): Promise<this>
```

Mark it as a test account (or, with `false`, not one). An app's preview only reads through a connection;
through a test account it writes as well, as production does. Only the account that connected it marks
it (`PermissionDenied` on one shared with yours), and it must hold an account (`InvalidRequest` while
pending).

    await Connection.fromName("slack-sandbox").markTestAccount();

Parameters:

- `testAccount` (`boolean`, default `true`)

Returns: The connection, with `test_account` set.

### Connection.token

```typescript
token(): Promise<Token>
```

A fresh OAuth access token for calling the provider yourself (`credentials:token` scope). A model
provider's connection never hands out its key or plan token (`PermissionDenied`).

Returns: The access token, its `token_type` and when it `expires_at`; never a
refresh token or an API key.

### Connection.delete

```typescript
delete(): Promise<void>
```

Delete the connection, revoking its account at the provider where possible.

## run

```typescript
function run(
  ref: string,
  args?: JsonObject,
  options?: CallOptions & { approvalId?: string },
): Promise<R>
```

Run one operation by its ref, `"name.operation"`, as `tools` names it. `name` is a connection in
the scope the call acts for (the user's, else the account's), else an integration whose operation
needs no account, which then runs on NoClick's key with no connection at all. A connection named
like the integration (`exa`, holding your own key) wins, so the same ref then runs on your key. An
account connected in the app is `"credential:<id>.operation"`.

Throws like `connection.run`: `NeedsConnection` (or `CredentialDisconnected`) with `connectUrl`
when the connection has no working account, `InvalidRequest` when the operation needs an account
and no connection has that name, `NotFound` when `name` is neither a connection nor an
integration, `PolicyDenied` or `ApprovalRequired` (retry with its `approvalId` once
`err.operation.wait()` resolves to true), and `UpstreamError` when the service refuses the call
(its own words, its HTTP status in `details.upstream_status`). Resolves to the operation's data.

    const results = await run("exa.search", { query: "invoice automation for small businesses" });
    await run("gmail.send_email_message", { to: ["ana@example.com"], subject: "Hi", body: "..." }, { user: "user_42" });

Parameters:

- `ref` (`string`, required)
- `args` (`JsonObject`)
- `options.approvalId` (`string`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The operation's data, as plain data (what the service answered).

Types:

```typescript
type JsonObject = { [key: string]: unknown };

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

## ConnectionOperations

```typescript
class ConnectionOperations
```

Some of a connection's operations as tools (`connection.only(...)`), with the arguments `bind(...)` fixed.

| Attribute | Type | Description |
| --- | --- | --- |
| `connection` | `Connection` |  |
| `operations` | `string[]` |  |
| `bindings` | `JsonObject` | The arguments NoClick fills on every call, out of the model's reach. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### ConnectionOperations.bind

```typescript
bind(args: JsonObject): ConnectionOperations
```

Fix arguments of these operations: a bound parameter leaves the tool's
schema, so the model never sees or sets it, and NoClick fills it on every call. A value may name
the user the call acts for: `{{user.id}}`, `{{user.email}}`, `{{user.name}}` or
`{{user.metadata.<key>}}`. A bound value always wins, over what a model passes through in an
operation's free-form parameters too; a tool whose binding can't be filled isn't offered that
turn. Policy judges the final arguments. Works in agents, toolkits and hosted MCP servers.

    gmail.only("send_email_message").bind({ to: "{{user.email}}" })

Parameters:

- `args` (`JsonObject`, required)

Returns: A new ref with these arguments bound on top of any bound before.

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## ConnectLink

```typescript
class ConnectLink extends Operation
```

A connect page URL that is also the operation tracking it. `wait()` resolves to what it connected: the
`Connection`, or an agent's `AgentToolServer` for that server's sign-in link.

| Attribute | Type | Description |
| --- | --- | --- |
| `url` | `string` | Where the person connects. |
| `expiresAt` | `Date | null` |  |
| `connection` | `string | null` | The connection the link fills. |
| `deliveredVia` | `string[]` | Channels the link went out on when `sendTo` was set (`["email"]`); empty otherwise. |
| `undelivered` | `JsonObject[]` | Channels that failed, each with a `reason`: send the link yourself. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### ConnectLink.list

```typescript
static list(
  options?: KindScopedFilters & { limit?: number },
): Promise<Operation<Connection>[]>
```

Connect-link operations (kind `credential.connect`), newest first. Rows are
operations: the link's URL is only in the response that created it (and on its pending connection).

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.client` (`NoClick`)
- `options.user` (`UserOption`): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).

Returns: Every matching operation (or the first `limit`), fetched page by page;
`wait()` on one returns the connected `Connection`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;
```

### ConnectLink.listPage

```typescript
static listPage(
  options?: KindScopedFilters & PageOptions,
): Promise<Page<Operation<Connection>>>
```

One page of connect-link operations; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.client` (`NoClick`)
- `options.user` (`UserOption`): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).

Returns: A page whose `data` holds the operations and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;
```

### ConnectLink.summary

```typescript
static summary(options?: KindScopedFilters): Promise<OperationSummary>
```

How many connect-link operations match, by status.

Parameters:

- `options.client` (`NoClick`)
- `options.user` (`UserOption`): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.status` (`OperationStatus | "live" | readonly (OperationStatus | "live")[]`): Statuses, or `"live"` for every non-terminal one.
- `options.agent` (`string | ApiObject`): An `Agent` or agent id.
- `options.statusNot` (`OperationStatus | readonly OperationStatus[]`)
- `options.key` (`string`): The requesting key: its id or its prefix (`nk_live_ab12`).
- `options.createdAfter` (`Date | string`)
- `options.createdBefore` (`Date | string`)
- `options.updatedAfter` (`Date | string`): Rows changed since (for polling).
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).

Returns: The `total` that match and a count for every status in `by_status`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type OperationStatus =
  | "queued" | "running" | "awaiting_human"
  | "succeeded" | "failed" | "canceled" | "expired";

/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;
```

## Verification

```typescript
interface Verification
```

Whether the provider accepted the credential (`reachable` null = cannot judge).

| Attribute | Type | Description |
| --- | --- | --- |
| `reachable` | `boolean | null` |  |
| `samples` | `unknown[]` | Things of the account's own, as the provider sees them (`{ label, value }`). |
| `message` | `string | null` |  |
| `hint` | `string | null` |  |
| `noun` | `string | null` | What the samples are ("repositories", "channels"); `null` when the check named none. |
| `total` | `number | null` | How many there are when more than the samples; `null` when the check didn't say. |
| `accountLabel` | `string | null` | Who the account signs in as; `null` when the check didn't say. |
| `proves` | `string | null` | `account` when the answer is the account's own, `reachability` when the provider only accepted the key. |
| `error` | `string | null` | The provider's own words when it turned the account down; `null` otherwise. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## ConnectionShared

```typescript
interface ConnectionShared
```

How an account shared with yours reaches it: shared with your account's person (`you`) or with the team
workspace it's read in (`workspace`), and who shared it (`byName`, `byEmail`).

| Attribute | Type | Description |
| --- | --- | --- |
| `with` | `"you" | "workspace"` |  |
| `byName` | `string | null` |  |
| `byEmail` | `string | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## ConnectionHealth

```typescript
interface ConnectionHealth
```

A provider's live word on a linked session (a WhatsApp number's, a Discord install's).

| Attribute | Type | Description |
| --- | --- | --- |
| `healthy` | `boolean` |  |
| `status` | `string` | The provider's own word for its state (`connected`, `failed`, `installed`). |
| `hint` | `string | null` | What to do when it isn't healthy. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## Token

```typescript
interface Token
```

A short-lived OAuth access token (never a refresh token or API key).

| Attribute | Type | Description |
| --- | --- | --- |
| `accessToken` | `string` |  |
| `tokenType` | `string | null` |  |
| `expiresAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## LookupOption

```typescript
interface LookupOption
```

| Attribute | Type | Description |
| --- | --- | --- |
| `value` | `unknown` |  |
| `label` | `string | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## LookupOptions

```typescript
interface LookupOptions
```

A page of options; pass `nextPageToken` back as `pageToken`.

| Attribute | Type | Description |
| --- | --- | --- |
| `nextPageToken` | `string | null` |  |

### LookupOptions.options

```typescript
options: LookupOption[]
```

## Plan

```typescript
interface Plan
```

A Claude or ChatGPT plan's tier, read at sign-in and each refresh (`tier` and `label` null until then).
`label` is the provider's own name for it ("Ultra", "Max 20x", "Plus"); `runs` the harnesses it can run,
empty when `refusal` says why it runs none ("Claude Free doesn't include Claude Code.").

| Attribute | Type | Description |
| --- | --- | --- |
| `tier` | `string | null` |  |
| `label` | `string | null` |  |
| `runs` | `string[]` |  |
| `refusal` | `string | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## PlanWindow

```typescript
interface PlanWindow
```

One of a plan's usage windows: `used` and `left` are fractions from 0 to 1.

| Attribute | Type | Description |
| --- | --- | --- |
| `kind` | `"five_hour" | "weekly" | "weekly_model" | "other" | string` |  |
| `label` | `string` | "5-hour", "Weekly", "Opus weekly". |
| `models` | `string[]` | The models it limits; empty for one that limits every model. |
| `used` | `number` |  |
| `left` | `number` |  |
| `resetsAt` | `Date | null` | Null once it's past its reset (it then reads as reset, `used` 0). |
| `state` | `"ok" | "near" | "used_up" | string` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## PlanUsage

```typescript
interface PlanUsage extends PlanUsageSummary
```

A plan's full usage reading (`connection.usage()`).

| Attribute | Type | Description |
| --- | --- | --- |
| `windows` | `PlanWindow[]` |  |
| `nextSteps` | `PlanNextStep[]` |  |
| `source` | `"provider" | "harness" | null` |  |
| `plan` | `Plan | null` |  |
| `connection` | `string` | The connection's id (`credential:<id>` for one connected in the app). |
| `integration` | `string | null` | The plan's provider: `anthropic` (a Claude plan) or `openai` (a ChatGPT plan). |

## PlanUsageSummary

```typescript
interface PlanUsageSummary
```

The summary every plan connection carries (`connection.usageSummary`).

| Attribute | Type | Description |
| --- | --- | --- |
| `state` | `PlanUsageState` |  |
| `tightest` | `PlanWindow | null` | The window that stops it first: the used-up one that resets last, else the most used. |
| `availableAt` | `Date | null` | When a used-up plan runs again, else null. |
| `asOf` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
/** How full a plan is: `near` from 0.8 used, `used_up` at 1, `unknown` with no reading yet. */
type PlanUsageState = "ok" | "near" | "used_up" | "unknown";

type JsonObject = { [key: string]: unknown };
```

## PlanNextStep

```typescript
interface PlanNextStep
```

What to do about a plan's usage: wait, run on another of your accounts, NoClick's key, or connect another.

| Attribute | Type | Description |
| --- | --- | --- |
| `kind` | `"wait" | "connection" | "noclick_key" | "connect" | string` |  |
| `label` | `string` |  |
| `until` | `Date | null` |  |
| `connection` | `{ id: string; name: string; integration: string | null; credentialType: string | null } | null` |  |
| `pays` | `"per_use" | "at_cost" | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `state` | `PlanUsageState | null` | Another plan's own state for the model asked about (`near`: it's nearly used too); null for a key. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };

/** How full a plan is: `near` from 0.8 used, `used_up` at 1, `unknown` with no reading yet. */
type PlanUsageState = "ok" | "near" | "used_up" | "unknown";
```

## IntegrationInfo

```typescript
interface IntegrationInfo
```

A service in the catalog (`Connection.integrations()`), such as `gmail`, or a model provider such as `anthropic`.

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `label` | `string | null` |  |
| `kind` | `IntegrationKind` | `"app"`, a service whose operations are tools, or `"model"`, a model provider whose connection an agent names as its `model_connection` (never in `tools=`). |
| `subscription` | `boolean` | Whether its connect link also offers signing in with the provider's plan (a Claude or ChatGPT subscription) instead of pasting a key, signed in by the person it belongs to. |
| `connectWith` | `string[]` | How a person connects an account: `"oauth"` (signing in), `"key"` (pasting a key or token), `"qr"` (scanning a code) or `"purchase"` (a phone number, bought rather than connected). |
| `operationCount` | `number | null` |  |
| `accountFreeOperationCount` | `number` | How many of its operations need no account (0 for most): `run` and `tools` run them on NoClick's key by the integration's name (`"exa.search"`), with no connection. |
| `credentialTypes` | `string[]` | The exact credential types: the `credentialType` that `Connection.create` and `connection.import` take. |
| `events` | `string[]` | The app events an `OnEvent` trigger takes from it (`connection.events()` has their filters). Empty for one that only acts: nothing it does wakes an agent. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
/**
 * `app`: a service whose operations are tools. `model`: a model provider (`anthropic`, `openai`,
 * `openrouter`, ...) whose connection an agent names as its `modelConnection`, never in `tools`.
 */
type IntegrationKind = "app" | "model";

type JsonObject = { [key: string]: unknown };
```

## IntegrationOperation

```typescript
interface IntegrationOperation
```

One operation of an integration, with its JSON-schema `parameters`.

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `description` | `string | null` |  |
| `parameters` | `JsonObject` |  |
| `readOnly` | `boolean | null` | A hint from the operation's name (reads start with `list_`, `get_` and the like), not a guarantee. |
| `scopes` | `string[]` | The OAuth scopes it needs, where NoClick knows them. |
| `needsAccount` | `boolean` | False when it runs on NoClick's key with no account at all (web search, public data), so it runs with no connection (`"exa.search"`) and on a pending one; true otherwise, including when the need depends on its arguments. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## IntegrationEvent

```typescript
interface IntegrationEvent
```

An app event an integration can deliver to an agent's `OnEvent` trigger or a channel's subscription:
its name (`channel_message`, `contact_created`), what it means, and the filters that narrow it, each
with what it matches (one marked `Required.` must be given).

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `description` | `string | null` |  |
| `filters` | `Record<string, string>` |  |
| `shape` | `JsonObject | null` | What its data holds: each field's type (`"string"`, `"integer"`, `"boolean"`, `"null"`, an object, `[...]` for a list), as the event has reached your account. Null until one has. Another account's events never show here. |
| `sample` | `JsonObject | null` | That shape with a placeholder for each value: what `subscription.test()` sends as `data`. Null with `shape`. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
