From c73fabe89844066ee2b0b2168f63a9c8615ddcda Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 18 Nov 2026 17:29:17 -0800 Subject: [PATCH 1/4] feat(search): manage sources and permission uploads through the CLI --- apps/docs/content/docs/cli/organizations.mdx | 195 + apps/docs/content/docs/cli/reference.mdx | 207 + apps/docs/content/docs/search/gitlab.mdx | 39 + apps/docs/openapi-v2-resources.json | 6265 +++++++++++------ .../search/sources/[sourceId]/route.ts | 47 + .../search/sources/prepare/route.ts | 16 + .../[organizationId]/search/sources/route.ts | 58 + .../contracts/knowledge/gitlab-permissions.ts | 29 +- .../api/contracts/v2/list-pagination.test.ts | 3 + .../api/contracts/v2/openapi/organizations.ts | 205 +- .../lib/api/contracts/v2/search-sources.ts | 159 + .../lib/api/mcp/generated/v2-operations.ts | 68 + .../server/routes/v2-route-table.generated.ts | 13 + .../gitlab-group.integration.ts | 102 +- .../manage-search-sources.integration.ts | 254 + .../knowledge/api/search-source-presenter.ts | 30 + .../application/manage-search-sources.ts | 199 + .../lib/knowledge/application/operations.ts | 20 +- apps/sim/lib/knowledge/connectors/service.ts | 2 + .../test-gitlab-csv-permissions-e2e.ts | 107 +- bun.lock | 1 + packages/sim-cli/THIRD_PARTY_LICENSES | 3 + packages/sim-cli/package.json | 1 + .../src/commands/source-permissions.test.ts | 274 + .../src/commands/source-permissions.ts | 131 + packages/sim-cli/src/contract/commands.ts | 31 + packages/sim-cli/src/generated/v2-api.ts | 370 + packages/sim-cli/src/http/client.test.ts | 3 + packages/sim-cli/src/http/client.ts | 3 + packages/sim-cli/src/program.ts | 2 + .../sim-cli/src/transfer/permission-csv.ts | 201 + scripts/check-unused-exports.baseline.json | 2 - 32 files changed, 6715 insertions(+), 2325 deletions(-) create mode 100644 apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts create mode 100644 apps/sim/app/api/v2/organizations/[organizationId]/search/sources/prepare/route.ts create mode 100644 apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts create mode 100644 apps/sim/lib/api/contracts/v2/search-sources.ts create mode 100644 apps/sim/lib/knowledge/__integration__/manage-search-sources.integration.ts create mode 100644 apps/sim/lib/knowledge/api/search-source-presenter.ts create mode 100644 apps/sim/lib/knowledge/application/manage-search-sources.ts create mode 100644 packages/sim-cli/src/commands/source-permissions.test.ts create mode 100644 packages/sim-cli/src/commands/source-permissions.ts create mode 100644 packages/sim-cli/src/transfer/permission-csv.ts diff --git a/apps/docs/content/docs/cli/organizations.mdx b/apps/docs/content/docs/cli/organizations.mdx index e700a73e493..31a83e99a56 100644 --- a/apps/docs/content/docs/cli/organizations.mdx +++ b/apps/docs/content/docs/cli/organizations.mdx @@ -293,6 +293,39 @@ sim organizations search sources permissions imports create [options] API request and response schemas: [createSourcePermissionImport](/api-reference/organizations/createSourcePermissionImport). +### Replace source permissions from two CSV files, uploaded in bounded parts + +```bash +sim organizations search sources permissions upload [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--provider ` | Yes | Permission provider. Accepted values: `gitlab`. | +| `--expected-revision ` | Yes | Revision read before exporting the CSVs. | +| `--user-mapping ` | Yes | Complete user mapping CSV. | +| `--project-permissions ` | Yes | Complete project permissions CSV. | +| `-y, --yes` | Yes | Confirm replacement of all source permissions. | + + + +API request and response schemas: [createSourcePermissionImport](/api-reference/organizations/createSourcePermissionImport), [putSourcePermissionImportPart](/api-reference/organizations/putSourcePermissionImportPart), [completeSourcePermissionImport](/api-reference/organizations/completeSourcePermissionImport). + ### Complete source permission import This replaces the source’s permission grants. Readers omitted from the new grants lose access. @@ -1206,6 +1239,168 @@ sim organizations sso policy update [options] API request and response schemas: [updateSsoPolicy](/api-reference/organizations/updateSsoPolicy). +## Other commands + +### List search sources + +```bash +sim organizations search sources list [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--sort-by ` | No | Field used to sort the result. Defaults to "createdAt". Accepted values: `connectorType`, `createdAt`, `updatedAt`. | +| `--sort-order ` | No | Sort direction. Defaults to "desc". Accepted values: `asc`, `desc`. | +| `--limit ` | No | Maximum items to return (0 for everything). Defaults to `100`. | +| `--cursor ` | No | Continue from nextCursor returned by a previous result. | + + + +API request and response schemas: [listSearchSources](/api-reference/organizations/listSearchSources). + +### Get search source + +```bash +sim organizations search sources get [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | + + + +API request and response schemas: [getSearchSource](/api-reference/organizations/getSearchSource). + +### Create search source + +```bash +sim organizations search sources create [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--connector-type ` | Yes | Registered connector type. | +| `--credential-id ` | No | OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors. | +| `--api-key ` | No | Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). | +| `--source-config ` | Yes | Connector-specific source selection and filtering configuration. (JSON, or @path / @- to read a file or stdin). | +| `--access-mode ` | No | Source-managed permissions (admin), or individually connected member accounts (members). Defaults to "admin". Accepted values: `admin`, `members`. | +| `--permission-config ` | No | Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation. (JSON, or @path / @- to read a file or stdin). | + + + +API request and response schemas: [createSearchSource](/api-reference/organizations/createSearchSource). + +### Update search source + +This updates source settings and may replace its permission grants. + +```bash +sim organizations search sources update [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--api-key ` | No | Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). | +| `--source-config ` | No | Complete replacement source configuration. Read the existing configuration before editing it. (JSON, or @path / @- to read a file or stdin). | +| `--permission-config ` | No | Provider-specific permission update, using the current expectedRevision. Omit to retain permissions. (JSON, or @path / @- to read a file or stdin). | +| `--status ` | No | Pause or resume this source without changing its ID or stored permissions. Accepted values: `active`, `paused`. | +| `-y, --yes` | Yes | Confirm this operation. | + + + +API request and response schemas: [updateSearchSource](/api-reference/organizations/updateSearchSource). + +### Delete search source + +This removes the source and its permission grants. + +```bash +sim organizations search sources delete [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `-y, --yes` | Yes | Confirm this operation. | + + + +API request and response schemas: [deleteSearchSource](/api-reference/organizations/deleteSearchSource). + +### Prepare search sources + +```bash +sim organizations search sources prepare [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--connector-type ` | Yes | Registered connector type. | +| `--access-mode ` | No | Source-managed permissions (admin), or individually connected member accounts (members). Defaults to "admin". Accepted values: `admin`, `members`. | + + + +API request and response schemas: [prepareSearchSources](/api-reference/organizations/prepareSearchSources). + ## Related docs - [Organizations](/platform/organization) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 815f17e290d..246d1391d56 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -4145,6 +4145,213 @@ sim organizations search sources permissions replace [options] API request and response schemas: [replaceSearchSourcePermissions](/api-reference/organizations/replaceSearchSourcePermissions). +### sim organizations search sources permissions upload + +Replace source permissions from two CSV files, uploaded in bounded parts + +```bash +sim organizations search sources permissions upload [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--provider ` | Yes | Permission provider. Accepted values: `gitlab`. | +| `--expected-revision ` | Yes | Revision read before exporting the CSVs. | +| `--user-mapping ` | Yes | Complete user mapping CSV. | +| `--project-permissions ` | Yes | Complete project permissions CSV. | +| `-y, --yes` | Yes | Confirm replacement of all source permissions. | + + + +API request and response schemas: [createSourcePermissionImport](/api-reference/organizations/createSourcePermissionImport), [putSourcePermissionImportPart](/api-reference/organizations/putSourcePermissionImportPart), [completeSourcePermissionImport](/api-reference/organizations/completeSourcePermissionImport). + +### sim organizations search sources create + +Create search source + +```bash +sim organizations search sources create [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--connector-type ` | Yes | Registered connector type. | +| `--credential-id ` | No | OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors. | +| `--api-key ` | No | Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). | +| `--source-config ` | Yes | Connector-specific source selection and filtering configuration. (JSON, or @path / @- to read a file or stdin). | +| `--access-mode ` | No | Source-managed permissions (admin), or individually connected member accounts (members). Defaults to "admin". Accepted values: `admin`, `members`. | +| `--permission-config ` | No | Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation. (JSON, or @path / @- to read a file or stdin). | + + + +API request and response schemas: [createSearchSource](/api-reference/organizations/createSearchSource). + +### sim organizations search sources delete + +Delete search source + +This removes the source and its permission grants. + +```bash +sim organizations search sources delete [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `-y, --yes` | Yes | Confirm this operation. | + + + +API request and response schemas: [deleteSearchSource](/api-reference/organizations/deleteSearchSource). + +### sim organizations search sources get + +Get search source + +```bash +sim organizations search sources get [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | + + + +API request and response schemas: [getSearchSource](/api-reference/organizations/getSearchSource). + +### sim organizations search sources list + +List search sources + +```bash +sim organizations search sources list [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--sort-by ` | No | Field used to sort the result. Defaults to "createdAt". Accepted values: `connectorType`, `createdAt`, `updatedAt`. | +| `--sort-order ` | No | Sort direction. Defaults to "desc". Accepted values: `asc`, `desc`. | +| `--limit ` | No | Maximum items to return (0 for everything). Defaults to `100`. | +| `--cursor ` | No | Continue from nextCursor returned by a previous result. | + + + +API request and response schemas: [listSearchSources](/api-reference/organizations/listSearchSources). + +### sim organizations search sources prepare + +Prepare search sources + +```bash +sim organizations search sources prepare [options] +``` + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--connector-type ` | Yes | Registered connector type. | +| `--access-mode ` | No | Source-managed permissions (admin), or individually connected member accounts (members). Defaults to "admin". Accepted values: `admin`, `members`. | + + + +API request and response schemas: [prepareSearchSources](/api-reference/organizations/prepareSearchSources). + +### sim organizations search sources update + +Update search source + +This updates source settings and may replace its permission grants. + +```bash +sim organizations search sources update [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `sourceId` | Yes | Search source identifier, also used by permission uploads. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--organization ` | Yes | Organization identifier. | +| `--api-key ` | No | Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). | +| `--source-config ` | No | Complete replacement source configuration. Read the existing configuration before editing it. (JSON, or @path / @- to read a file or stdin). | +| `--permission-config ` | No | Provider-specific permission update, using the current expectedRevision. Omit to retain permissions. (JSON, or @path / @- to read a file or stdin). | +| `--status ` | No | Pause or resume this source without changing its ID or stored permissions. Accepted values: `active`, `paused`. | +| `-y, --yes` | Yes | Confirm this operation. | + + + +API request and response schemas: [updateSearchSource](/api-reference/organizations/updateSearchSource). + ### sim organizations invitations create Create organization invitation (OAuth login or personal API key required) diff --git a/apps/docs/content/docs/search/gitlab.mdx b/apps/docs/content/docs/search/gitlab.mdx index 9e0884ca6f8..6460301bf35 100644 --- a/apps/docs/content/docs/search/gitlab.mdx +++ b/apps/docs/content/docs/search/gitlab.mdx @@ -202,6 +202,45 @@ A successful update returns the new revision. The uploader retries identical par An invalid or header-only export leaves the previous grants in place. Alert on failed jobs so revocations aren't missed. If the source should have no readers, choose **Pause search** in the source settings. You can update the grants while the source is paused, then resume search when the grants are correct. +## Manage sources from the CLI + +Organization admins can also configure sources with the [Sim CLI](/cli/organizations). Use a personal Sim API key with Full access, or an OAuth login with the required API scopes. Workspace API keys cannot administer organization sources. + +```bash +sim organizations search sources list --organization "$SIM_ORG_ID" +sim organizations search sources get "$SIM_SOURCE_ID" --organization "$SIM_ORG_ID" +``` + +The returned `id` is `SIM_SOURCE_ID`. Creating an additional group requires a separate source and CI job targeting that ID. Existing sources and CI upload commands remain unchanged. + +For a new source, prepare the shared configuration once, then create the connection: + +```bash +sim organizations search sources prepare --organization "$SIM_ORG_ID" \ + --connector-type gitlab --access-mode admin +sim organizations search sources create --organization "$SIM_ORG_ID" \ + --connector-type gitlab --access-mode admin --api-key @gitlab-pat.txt \ + --source-config @source-config.json --permission-config @permission-config.json +``` + +Use the same host, project/group selection, and permission strategy as Settings. `source-config.json` contains the complete source configuration. `permission-config.json` contains `provider: "gitlab"`, `mode: "csv"`, and both CSVs as `{ "filename": "...", "content": "..." }` under `userMapping` and `projectPermissions`. For large exports, create the source using a valid subset of grants, then upload the full snapshot. The [create API reference](/api-reference/organizations/createSearchSource) describes every field. Keep PAT files and permission files out of version control. + +To change a group, read the source first, edit the complete configuration, and supply matching CSVs with the current permission revision. To rotate only the GitLab PAT, use `sim organizations search sources update --organization --api-key @replacement-pat.txt --permission-config '{"provider":"gitlab","mode":"csv","expectedRevision":}' --yes`. Omitted CSVs retain their grants; a successful rotation advances the revision. Use `--status paused --yes` or `--status active --yes` to pause or resume. Neither action changes the source ID. Integration approval remains a separate organization setting. + +The CLI can replace the Python uploader in an existing CI job: + +```bash +# Pin before running the GitLab export. +REVISION="$(sim organizations search sources permissions get "$SIM_SOURCE_ID" \ + --organization "$SIM_ORG_ID" --output json | jq -er '.revision')" +# Run export-permissions.py here to generate both CSVs. +sim organizations search sources permissions upload "$SIM_SOURCE_ID" \ + --organization "$SIM_ORG_ID" --provider gitlab --expected-revision "$REVISION" \ + --user-mapping users.csv --project-permissions project-permissions.csv --yes +``` + +This uses the same staged-import limits, revision checks, and atomic activation as the Python uploader. A conflict requires a new export; the command never fetches a newer revision to overwrite it. Personal OAuth consent and GitLab token issuance still happen in their respective services. + ## Troubleshooting | Problem | Check | diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 0cbb2f23568..4e811ec7818 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -10717,12 +10717,107 @@ } } }, - "/api/v2/organizations/{organizationId}/sso/providers": { + "/api/v2/organizations/{organizationId}/search/sources/prepare": { + "post": { + "operationId": "prepareSearchSources", + "summary": "Prepare Search sources", + "description": "Idempotently initialize shared Search configuration before creating a source. Does not create a connector or change existing sources. Organization admin required.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "knowledge.search.sources.prepare", + "x-oauth-scope": "api:write", + "tags": ["Organizations"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization identifier.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Organization identifier." + } + } + ], + "requestBody": { + "required": true, + "description": "Source configuration.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrepareSearchSourcesBody" + } + } + } + }, + "responses": { + "200": { + "description": "Source operation result.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrepareSearchSourcesResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/organizations/{organizationId}/search/sources": { "get": { - "operationId": "listSsoProviders", - "summary": "List SSO providers", - "description": "List identity providers owned by the organization. Requires organization Admin access. OIDC client secrets are redacted and SAML private keys are omitted. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization.sso.providers.list", + "operationId": "listSearchSources", + "summary": "List Search sources", + "description": "List source IDs and administrative configuration with cursor pagination. Organization admin required. Credentials and CSV contents are never returned.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "knowledge.search.sources.manage.list", "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ @@ -10738,65 +10833,65 @@ "name": "organizationId", "in": "path", "required": true, - "description": "Organization whose single sign-on settings and verified domains are managed.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "description": "Organization whose single sign-on settings and verified domains are managed." + "description": "Organization identifier." } }, { - "name": "limit", + "name": "sortBy", "in": "query", "required": false, - "description": "Maximum identity providers to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "Field used to sort the result.", "schema": { - "default": 50, - "description": "Maximum identity providers to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 + "default": "createdAt", + "description": "Field used to sort the result.", + "type": "string", + "enum": ["connectorType", "createdAt", "updatedAt"] } }, { - "name": "cursor", + "name": "sortOrder", "in": "query", "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Sort direction.", "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "default": "desc", + "description": "Sort direction.", "type": "string", - "minLength": 1 + "enum": ["asc", "desc"] } }, { - "name": "sortBy", + "name": "limit", "in": "query", "required": false, - "description": "Field used to sort the result.", + "description": "Maximum connectors to return per page. Must be a whole number from 1 to 100. Defaults to 50.", "schema": { - "default": "providerId", - "description": "Field used to sort the result.", - "type": "string", - "enum": ["providerId", "domain"] + "default": 50, + "description": "Maximum connectors to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 } }, { - "name": "sortOrder", + "name": "cursor", "in": "query", "required": false, - "description": "Sort direction.", + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", "schema": { - "default": "asc", - "description": "Sort direction.", + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", "type": "string", - "enum": ["asc", "desc"] + "minLength": 1 } } ], "responses": { "200": { - "description": "A page of identity providers with redacted configuration.", + "description": "Source operation result.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -10811,7 +10906,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListSsoProvidersResponse" + "$ref": "#/components/schemas/ListSearchSourcesResponse" } } } @@ -10843,10 +10938,10 @@ } }, "post": { - "operationId": "saveSsoProvider", - "summary": "Save SSO provider", - "description": "Create or update an organization identity provider’s configuration on a verified domain. Requires organization Admin access and SSO entitlement. Existing providers return 200; creation returns 201. Omission behavior is field-specific; OIDC’s redacted secret marker preserves the saved secret. Identity changes with linked accounts conflict. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organization.sso.providers.save", + "operationId": "createSearchSource", + "summary": "Create Search source", + "description": "Create a source in the prepared organization Search index using the same provider validation as Settings. Use connector-types list for provider configuration. This does not override an explicit integration approval decision. Organization admin required.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "knowledge.connectors.create", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -10862,49 +10957,28 @@ "name": "organizationId", "in": "path", "required": true, - "description": "Organization whose single sign-on settings and verified domains are managed.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "description": "Organization whose single sign-on settings and verified domains are managed." + "description": "Organization identifier." } } ], "requestBody": { "required": true, - "description": "Provider protocol, verified domain, and identity-provider configuration. Omission behavior is field-specific.", + "description": "Source configuration.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SaveSsoProviderBody" + "$ref": "#/components/schemas/CreateSearchSourceBody" } } } }, "responses": { - "200": { - "description": "The saved provider ID, protocol, and whether it was created.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SaveSsoProviderResponse" - } - } - } - }, "201": { - "description": "The saved provider ID, protocol, and whether it was created.", + "description": "Source operation result.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -10919,7 +10993,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SaveSsoProviderResponse" + "$ref": "#/components/schemas/CreateSearchSourceResponse" } } } @@ -10957,12 +11031,12 @@ } } }, - "/api/v2/organizations/{organizationId}/sso/providers/{providerId}": { + "/api/v2/organizations/{organizationId}/search/sources/{sourceId}": { "get": { - "operationId": "getSsoProvider", - "summary": "Get SSO provider", - "description": "Get an identity provider owned by the organization. Requires organization Admin access. OIDC client secrets are redacted and SAML private keys are omitted. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization.sso.providers.list", + "operationId": "getSearchSource", + "summary": "Get Search source", + "description": "Read source configuration and permission revision summaries. Organization admin required.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "knowledge.search.sources.manage.read", "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ @@ -10978,29 +11052,28 @@ "name": "organizationId", "in": "path", "required": true, - "description": "Organization whose single sign-on settings and verified domains are managed.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "description": "Organization whose single sign-on settings and verified domains are managed." + "description": "Organization identifier." } }, { - "name": "providerId", + "name": "sourceId", "in": "path", "required": true, - "description": "Identity provider identifier.", + "description": "Search source identifier, also used by permission uploads.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Identity provider identifier." + "description": "Search source identifier, also used by permission uploads." } } ], "responses": { "200": { - "description": "The identity provider with redacted configuration.", + "description": "Source operation result.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11015,7 +11088,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetSsoProviderResponse" + "$ref": "#/components/schemas/GetSearchSourceResponse" } } } @@ -11046,11 +11119,11 @@ } } }, - "delete": { - "operationId": "deleteSsoProvider", - "summary": "Delete SSO provider", - "description": "Remove an identity provider and clear its primary selection. Requires organization Admin access. Existing accounts, memberships, and sessions remain. Domain sign-in falls back to another verified provider if one remains; use Get SSO policy to inspect whether SSO is still enforced. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organization.sso.providers.delete", + "patch": { + "operationId": "updateSearchSource", + "summary": "Update Search source", + "description": "Update source selection, supported provider credentials, or permission settings; pause or resume a source. Omitted fields are retained. sourceConfig replaces the complete configuration. GitLab token rotation retains saved grants and advances the permission revision; supply permissionConfig with the current expectedRevision for rotation or CSV updates. Organization admin required.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "knowledge.connectors.update", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11066,29 +11139,39 @@ "name": "organizationId", "in": "path", "required": true, - "description": "Organization whose single sign-on settings and verified domains are managed.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "description": "Organization whose single sign-on settings and verified domains are managed." + "description": "Organization identifier." } }, { - "name": "providerId", + "name": "sourceId", "in": "path", "required": true, - "description": "Identity provider identifier.", + "description": "Search source identifier, also used by permission uploads.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Identity provider identifier." + "description": "Search source identifier, also used by permission uploads." } } ], + "requestBody": { + "required": true, + "description": "Source configuration.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateSearchSourceBody" + } + } + } + }, "responses": { "200": { - "description": "Acknowledgement that the identity provider was removed.", + "description": "Source operation result.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11103,7 +11186,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeleteSsoProviderResponse" + "$ref": "#/components/schemas/UpdateSearchSourceResponse" } } } @@ -11123,6 +11206,12 @@ "409": { "$ref": "#/components/responses/Conflict" }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -11133,14 +11222,12 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/organizations/{organizationId}/sso/providers/{providerId}/primary": { - "post": { - "operationId": "setPrimarySsoProvider", - "summary": "Set primary SSO provider", - "description": "Make a verified organization provider handle sign-in for its domain. Requires organization Admin access. Other providers remain available for testing and later switching. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organization.sso.set_primary_provider", + }, + "delete": { + "operationId": "deleteSearchSource", + "summary": "Delete Search source", + "description": "Remove a source and its associated permission grants. Cleanup is asynchronous. Organization admin required.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "knowledge.connectors.delete", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11156,40 +11243,28 @@ "name": "organizationId", "in": "path", "required": true, - "description": "Organization whose single sign-on settings and verified domains are managed.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "description": "Organization whose single sign-on settings and verified domains are managed." + "description": "Organization identifier." } }, { - "name": "providerId", + "name": "sourceId", "in": "path", "required": true, - "description": "Identity provider identifier.", + "description": "Search source identifier, also used by permission uploads.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Identity provider identifier." + "description": "Search source identifier, also used by permission uploads." } } ], - "requestBody": { - "required": false, - "description": "An empty JSON object; the path identifies the provider to make primary.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetPrimarySsoProviderBody" - } - } - } - }, "responses": { "200": { - "description": "The provider selected for its verified domain.", + "description": "Source operation result.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11204,7 +11279,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetPrimarySsoProviderResponse" + "$ref": "#/components/schemas/DeleteSearchSourceResponse" } } } @@ -11224,14 +11299,8 @@ "409": { "$ref": "#/components/responses/Conflict" }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, - "429": { - "$ref": "#/components/responses/RateLimited" + "429": { + "$ref": "#/components/responses/RateLimited" }, "500": { "$ref": "#/components/responses/InternalError" @@ -11242,12 +11311,12 @@ } } }, - "/api/v2/organizations/{organizationId}/sso/policy": { + "/api/v2/organizations/{organizationId}/sso/providers": { "get": { - "operationId": "getSsoPolicy", - "summary": "Get SSO policy", - "description": "Get the stored organization SSO requirement and whether it is currently enforced. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization.sso.read_requirement", + "operationId": "listSsoProviders", + "summary": "List SSO providers", + "description": "List identity providers owned by the organization. Requires organization Admin access. OIDC client secrets are redacted and SAML private keys are omitted. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization.sso.providers.list", "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ @@ -11269,11 +11338,59 @@ "minLength": 1, "description": "Organization whose single sign-on settings and verified domains are managed." } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum identity providers to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum identity providers to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "schema": { + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "type": "string", + "minLength": 1 + } + }, + { + "name": "sortBy", + "in": "query", + "required": false, + "description": "Field used to sort the result.", + "schema": { + "default": "providerId", + "description": "Field used to sort the result.", + "type": "string", + "enum": ["providerId", "domain"] + } + }, + { + "name": "sortOrder", + "in": "query", + "required": false, + "description": "Sort direction.", + "schema": { + "default": "asc", + "description": "Sort direction.", + "type": "string", + "enum": ["asc", "desc"] + } } ], "responses": { "200": { - "description": "The stored SSO requirement and its effective enforcement state.", + "description": "A page of identity providers with redacted configuration.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11288,7 +11405,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetSsoPolicyResponse" + "$ref": "#/components/schemas/ListSsoProvidersResponse" } } } @@ -11319,11 +11436,11 @@ } } }, - "patch": { - "operationId": "updateSsoPolicy", - "summary": "Update SSO policy", - "description": "Require or stop requiring SSO on future sign-ins. Requires organization Admin access. Enabling requires SSO entitlement and a verified provider; disabling remains available after entitlement is lost. Existing sessions remain active. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organization.sso.set_requirement", + "post": { + "operationId": "saveSsoProvider", + "summary": "Save SSO provider", + "description": "Create or update an organization identity provider’s configuration on a verified domain. Requires organization Admin access and SSO entitlement. Existing providers return 200; creation returns 201. Omission behavior is field-specific; OIDC’s redacted secret marker preserves the saved secret. Identity changes with linked accounts conflict. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organization.sso.providers.save", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11349,18 +11466,18 @@ ], "requestBody": { "required": true, - "description": "Whether future sign-ins must use SSO.", + "description": "Provider protocol, verified domain, and identity-provider configuration. Omission behavior is field-specific.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateSsoPolicyBody" + "$ref": "#/components/schemas/SaveSsoProviderBody" } } } }, "responses": { "200": { - "description": "The saved SSO requirement and its effective enforcement state.", + "description": "The saved provider ID, protocol, and whether it was created.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11375,7 +11492,28 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateSsoPolicyResponse" + "$ref": "#/components/schemas/SaveSsoProviderResponse" + } + } + } + }, + "201": { + "description": "The saved provider ID, protocol, and whether it was created.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SaveSsoProviderResponse" } } } @@ -11413,12 +11551,12 @@ } } }, - "/api/v2/organizations/{organizationId}/domains": { + "/api/v2/organizations/{organizationId}/sso/providers/{providerId}": { "get": { - "operationId": "listOrganizationDomains", - "summary": "List organization domains", - "description": "List the organization’s domain claims with cursor pagination. Requires organization membership. Pending DNS challenge values are returned only to administrators using their own credentials. Organizations without Enterprise domain entitlement return an empty list. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organizations.domains.list", + "operationId": "getSsoProvider", + "summary": "Get SSO provider", + "description": "Get an identity provider owned by the organization. Requires organization Admin access. OIDC client secrets are redacted and SAML private keys are omitted. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization.sso.providers.list", "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ @@ -11442,57 +11580,21 @@ } }, { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum domain claims to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "schema": { - "default": 50, - "description": "Maximum domain claims to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 - } - }, - { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", - "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", - "type": "string", - "minLength": 1 - } - }, - { - "name": "sortBy", - "in": "query", - "required": false, - "description": "Field used to sort the result.", - "schema": { - "default": "domain", - "description": "Field used to sort the result.", - "type": "string", - "enum": ["domain"] - } - }, - { - "name": "sortOrder", - "in": "query", - "required": false, - "description": "Sort direction.", + "name": "providerId", + "in": "path", + "required": true, + "description": "Identity provider identifier.", "schema": { - "default": "asc", - "description": "Sort direction.", "type": "string", - "enum": ["asc", "desc"] + "minLength": 1, + "maxLength": 255, + "description": "Identity provider identifier." } } ], "responses": { "200": { - "description": "A page of domain claims; pending challenges are limited to Admins.", + "description": "The identity provider with redacted configuration.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11507,7 +11609,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListOrganizationDomainsResponse" + "$ref": "#/components/schemas/GetSsoProviderResponse" } } } @@ -11538,11 +11640,11 @@ } } }, - "post": { - "operationId": "addOrganizationDomain", - "summary": "Add organization domain", - "description": "Claim a domain and receive its DNS TXT challenge. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. An organization can claim at most 25 domains. Existing claims return `200`; new claims return `201`. A domain verified by another organization returns `409`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organizations.domains.add", + "delete": { + "operationId": "deleteSsoProvider", + "summary": "Delete SSO provider", + "description": "Remove an identity provider and clear its primary selection. Requires organization Admin access. Existing accounts, memberships, and sessions remain. Domain sign-in falls back to another verified provider if one remains; use Get SSO policy to inspect whether SSO is still enforced. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organization.sso.providers.delete", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11564,43 +11666,23 @@ "minLength": 1, "description": "Organization whose single sign-on settings and verified domains are managed." } - } - ], - "requestBody": { - "required": true, - "description": "The domain to claim and verify.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AddOrganizationDomainBody" - } + }, + { + "name": "providerId", + "in": "path", + "required": true, + "description": "Identity provider identifier.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Identity provider identifier." } } - }, + ], "responses": { "200": { - "description": "The domain claim and its pending DNS challenge, when applicable.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AddOrganizationDomainResponse" - } - } - } - }, - "201": { - "description": "The domain claim and its pending DNS challenge, when applicable.", + "description": "Acknowledgement that the identity provider was removed.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11615,7 +11697,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddOrganizationDomainResponse" + "$ref": "#/components/schemas/DeleteSsoProviderResponse" } } } @@ -11635,12 +11717,6 @@ "409": { "$ref": "#/components/responses/Conflict" }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -11653,12 +11729,12 @@ } } }, - "/api/v2/organizations/{organizationId}/domains/{domainId}/verify": { + "/api/v2/organizations/{organizationId}/sso/providers/{providerId}/primary": { "post": { - "operationId": "verifyOrganizationDomain", - "summary": "Verify organization domain", - "description": "Verify domain ownership through its DNS TXT challenge and grant domain trust to matching organization providers. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. Billing-disabled self-hosted deployments may configure operator verification. An already-verified domain is returned unchanged. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organizations.domains.verify", + "operationId": "setPrimarySsoProvider", + "summary": "Set primary SSO provider", + "description": "Make a verified organization provider handle sign-in for its domain. Requires organization Admin access. Other providers remain available for testing and later switching. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organization.sso.set_primary_provider", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11682,32 +11758,32 @@ } }, { - "name": "domainId", + "name": "providerId", "in": "path", "required": true, - "description": "Domain claim owned by this organization.", + "description": "Identity provider identifier.", "schema": { "type": "string", "minLength": 1, "maxLength": 255, - "description": "Domain claim owned by this organization." + "description": "Identity provider identifier." } } ], "requestBody": { "required": false, - "description": "An empty JSON object; verification uses the claim’s current DNS challenge.", + "description": "An empty JSON object; the path identifies the provider to make primary.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/VerifyOrganizationDomainBody" + "$ref": "#/components/schemas/SetPrimarySsoProviderBody" } } } }, "responses": { "200": { - "description": "The domain claim after ownership verification.", + "description": "The provider selected for its verified domain.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11722,7 +11798,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/VerifyOrganizationDomainResponse" + "$ref": "#/components/schemas/SetPrimarySsoProviderResponse" } } } @@ -11760,20 +11836,20 @@ } } }, - "/api/v2/organizations/{organizationId}/domains/{domainId}": { - "delete": { - "operationId": "removeOrganizationDomain", - "summary": "Remove organization domain", - "description": "Remove a domain claim and revoke verified sign-in authority from matching organization providers. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. Existing accounts and memberships remain. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organizations.domains.remove", - "x-oauth-scope": "api:write", + "/api/v2/organizations/{organizationId}/sso/policy": { + "get": { + "operationId": "getSsoPolicy", + "summary": "Get SSO policy", + "description": "Get the stored organization SSO requirement and whether it is currently enforced. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization.sso.read_requirement", + "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ @@ -11787,23 +11863,98 @@ "minLength": 1, "description": "Organization whose single sign-on settings and verified domains are managed." } + } + ], + "responses": { + "200": { + "description": "The stored SSO requirement and its effective enforcement state.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetSsoPolicyResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + }, + "patch": { + "operationId": "updateSsoPolicy", + "summary": "Update SSO policy", + "description": "Require or stop requiring SSO on future sign-ins. Requires organization Admin access. Enabling requires SSO entitlement and a verified provider; disabling remains available after entitlement is lost. Existing sessions remain active. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organization.sso.set_requirement", + "x-oauth-scope": "api:write", + "tags": ["Organizations"], + "security": [ + { + "apiKey": [] }, { - "name": "domainId", + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "organizationId", "in": "path", "required": true, - "description": "Domain claim owned by this organization.", + "description": "Organization whose single sign-on settings and verified domains are managed.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Domain claim owned by this organization." + "description": "Organization whose single sign-on settings and verified domains are managed." } } ], + "requestBody": { + "required": true, + "description": "Whether future sign-ins must use SSO.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateSsoPolicyBody" + } + } + } + }, "responses": { "200": { - "description": "Acknowledgement that the domain claim was removed.", + "description": "The saved SSO requirement and its effective enforcement state.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11818,7 +11969,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RemoveOrganizationDomainResponse" + "$ref": "#/components/schemas/UpdateSsoPolicyResponse" } } } @@ -11838,6 +11989,12 @@ "409": { "$ref": "#/components/responses/Conflict" }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -11850,14 +12007,14 @@ } } }, - "/api/v2/credentials/{credentialId}/members": { + "/api/v2/organizations/{organizationId}/domains": { "get": { - "operationId": "listCredentialMembers", - "summary": "List credential members", - "description": "List explicit credential grants, including revoked grants, and inherited workspace Admin access. Personal API keys and OAuth access tokens can list grants for OAuth or service-account credentials. Requires workspace read access and the `integrations.manage` capability. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "credentials.members.list", + "operationId": "listOrganizationDomains", + "summary": "List organization domains", + "description": "List the organization’s domain claims with cursor pagination. Requires organization membership. Pending DNS challenge values are returned only to administrators using their own credentials. Organizations without Enterprise domain entitlement return an empty list. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organizations.domains.list", "x-oauth-scope": "api:read", - "tags": ["Credentials"], + "tags": ["Organizations"], "security": [ { "apiKey": [] @@ -11868,37 +12025,24 @@ ], "parameters": [ { - "name": "credentialId", + "name": "organizationId", "in": "path", "required": true, - "description": "Credential whose sharing grants are managed.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 255, - "description": "Credential whose sharing grants are managed." - } - }, - { - "name": "workspaceId", - "in": "query", - "required": true, - "description": "Workspace expected to own the credential.", + "description": "Organization whose single sign-on settings and verified domains are managed.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace expected to own the credential." + "description": "Organization whose single sign-on settings and verified domains are managed." } }, { "name": "limit", "in": "query", "required": false, - "description": "Maximum credential members to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "Maximum domain claims to return per page. Must be a whole number from 1 to 100. Defaults to 50.", "schema": { "default": 50, - "description": "Maximum credential members to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "Maximum domain claims to return per page. Must be a whole number from 1 to 100. Defaults to 50.", "type": "integer", "minimum": 1, "maximum": 100 @@ -11919,12 +12063,12 @@ "name": "sortBy", "in": "query", "required": false, - "description": "Field used to sort the result. Do not rely on case-insensitive ordering when sorting by `name`.", + "description": "Field used to sort the result.", "schema": { - "default": "email", - "description": "Field used to sort the result. Do not rely on case-insensitive ordering when sorting by `name`.", + "default": "domain", + "description": "Field used to sort the result.", "type": "string", - "enum": ["email", "name"] + "enum": ["domain"] } }, { @@ -11942,7 +12086,7 @@ ], "responses": { "200": { - "description": "A page of explicit and inherited credential grants.", + "description": "A page of domain claims; pending challenges are limited to Admins.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -11957,7 +12101,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListCredentialMembersResponse" + "$ref": "#/components/schemas/ListOrganizationDomainsResponse" } } } @@ -11974,6 +12118,9 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -11986,12 +12133,12 @@ } }, "post": { - "operationId": "upsertCredentialMember", - "summary": "Upsert credential member", - "description": "Grant or change a current workspace member’s credential role. Requires credential Admin access and the `integrations.manage` capability. Revoked grants become active again; inherited workspace Admins cannot be demoted. A new grant returns `201`; an existing grant returns `200`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "credentials.members.upsert", + "operationId": "addOrganizationDomain", + "summary": "Add organization domain", + "description": "Claim a domain and receive its DNS TXT challenge. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. An organization can claim at most 25 domains. Existing claims return `200`; new claims return `201`. A domain verified by another organization returns `409`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organizations.domains.add", "x-oauth-scope": "api:write", - "tags": ["Credentials"], + "tags": ["Organizations"], "security": [ { "apiKey": [] @@ -12002,44 +12149,31 @@ ], "parameters": [ { - "name": "credentialId", + "name": "organizationId", "in": "path", "required": true, - "description": "Credential whose sharing grants are managed.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 255, - "description": "Credential whose sharing grants are managed." - } - }, - { - "name": "workspaceId", - "in": "query", - "required": true, - "description": "Workspace expected to own the credential.", + "description": "Organization whose single sign-on settings and verified domains are managed.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace expected to own the credential." + "description": "Organization whose single sign-on settings and verified domains are managed." } } ], "requestBody": { "required": true, - "description": "The current workspace member and credential role to grant.", + "description": "The domain to claim and verify.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpsertCredentialMemberBody" + "$ref": "#/components/schemas/AddOrganizationDomainBody" } } } }, "responses": { "200": { - "description": "The saved credential role and whether a grant was created.", + "description": "The domain claim and its pending DNS challenge, when applicable.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12054,13 +12188,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpsertCredentialMemberResponse" + "$ref": "#/components/schemas/AddOrganizationDomainResponse" } } } }, "201": { - "description": "The saved credential role and whether a grant was created.", + "description": "The domain claim and its pending DNS challenge, when applicable.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12075,7 +12209,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpsertCredentialMemberResponse" + "$ref": "#/components/schemas/AddOrganizationDomainResponse" } } } @@ -12092,6 +12226,9 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, "413": { "$ref": "#/components/responses/PayloadTooLarge" }, @@ -12110,14 +12247,14 @@ } } }, - "/api/v2/credentials/{credentialId}/members/{userId}": { - "delete": { - "operationId": "removeCredentialMember", - "summary": "Remove credential member", - "description": "Revoke an active explicit credential grant. Requires credential Admin access and the `integrations.manage` capability. Inherited workspace Admins cannot be removed; an absent or already-revoked grant returns `404`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "credentials.members.remove", + "/api/v2/organizations/{organizationId}/domains/{domainId}/verify": { + "post": { + "operationId": "verifyOrganizationDomain", + "summary": "Verify organization domain", + "description": "Verify domain ownership through its DNS TXT challenge and grant domain trust to matching organization providers. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. Billing-disabled self-hosted deployments may configure operator verification. An already-verified domain is returned unchanged. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organizations.domains.verify", "x-oauth-scope": "api:write", - "tags": ["Credentials"], + "tags": ["Organizations"], "security": [ { "apiKey": [] @@ -12128,45 +12265,43 @@ ], "parameters": [ { - "name": "credentialId", + "name": "organizationId", "in": "path", "required": true, - "description": "Credential whose sharing grants are managed.", + "description": "Organization whose single sign-on settings and verified domains are managed.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Credential whose sharing grants are managed." + "description": "Organization whose single sign-on settings and verified domains are managed." } }, { - "name": "userId", + "name": "domainId", "in": "path", "required": true, - "description": "User whose explicit grant will be revoked.", + "description": "Domain claim owned by this organization.", "schema": { "type": "string", "minLength": 1, "maxLength": 255, - "description": "User whose explicit grant will be revoked." - } - }, - { - "name": "workspaceId", - "in": "query", - "required": true, - "description": "Workspace expected to own the credential.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace expected to own the credential." + "description": "Domain claim owned by this organization." } } ], + "requestBody": { + "required": false, + "description": "An empty JSON object; verification uses the claim’s current DNS challenge.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyOrganizationDomainBody" + } + } + } + }, "responses": { "200": { - "description": "Acknowledgement that the explicit credential grant was revoked.", + "description": "The domain claim after ownership verification.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12181,7 +12316,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RemoveCredentialMemberResponse" + "$ref": "#/components/schemas/VerifyOrganizationDomainResponse" } } } @@ -12198,6 +12333,15 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -12210,39 +12354,50 @@ } } }, - "/api/v2/workspaces/{workspaceId}/permission-config": { - "get": { - "operationId": "getWorkspacePermissionConfig", - "summary": "Get workspace permission config", - "description": "Get the acting user's governing permission group and configuration for a workspace they can access. This describes permission-group restrictions, not the user's workspace role. Group and config are null when no group governs the caller; entitled indicates whether organization permission governance is active. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "permission_groups.read_user_config", - "x-oauth-scope": "api:read", - "tags": ["Workspaces"], + "/api/v2/organizations/{organizationId}/domains/{domainId}": { + "delete": { + "operationId": "removeOrganizationDomain", + "summary": "Remove organization domain", + "description": "Remove a domain claim and revoke verified sign-in authority from matching organization providers. Requires organization Admin access and, when billing is enabled, Enterprise domain entitlement. Existing accounts and memberships remain. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organizations.domains.remove", + "x-oauth-scope": "api:write", + "tags": ["Organizations"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:read"] + "oauthBearer": ["api:write"] } ], "parameters": [ { - "name": "workspaceId", + "name": "organizationId", "in": "path", "required": true, - "description": "Unique workspace identifier.", + "description": "Organization whose single sign-on settings and verified domains are managed.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Unique workspace identifier." + "description": "Organization whose single sign-on settings and verified domains are managed." + } + }, + { + "name": "domainId", + "in": "path", + "required": true, + "description": "Domain claim owned by this organization.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Domain claim owned by this organization." } } ], "responses": { "200": { - "description": "The caller’s effective permission-group configuration.", + "description": "Acknowledgement that the domain claim was removed.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12257,22 +12412,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetWorkspacePermissionConfigResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "permissionGroupId": null, - "groupName": null, - "config": null, - "entitled": false, - "organizationId": null, - "isOrgAdmin": false - } - } - } + "$ref": "#/components/schemas/RemoveOrganizationDomainResponse" } } } @@ -12289,6 +12429,9 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -12301,60 +12444,99 @@ } } }, - "/api/v2/workspaces/{workspaceId}/invitations": { - "post": { - "operationId": "createWorkspaceInvitations", - "summary": "Create workspace invitations", - "description": "Invite people to a workspace or grant access immediately to existing organization members. Requires workspace Admin access and current invitation eligibility; invitations offering organization Admin membership also require organization Admin access. Recipients are processed independently: inspect `failed` even after HTTP `200`, and inspect invitation status before retrying a delivery failure. Existing access is preserved. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "workspace_invitations.send_batch", - "x-oauth-scope": "api:write", - "tags": ["Workspaces"], + "/api/v2/credentials/{credentialId}/members": { + "get": { + "operationId": "listCredentialMembers", + "summary": "List credential members", + "description": "List explicit credential grants, including revoked grants, and inherited workspace Admin access. Personal API keys and OAuth access tokens can list grants for OAuth or service-account credentials. Requires workspace read access and the `integrations.manage` capability. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "credentials.members.list", + "x-oauth-scope": "api:read", + "tags": ["Credentials"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ { - "name": "workspaceId", + "name": "credentialId", "in": "path", "required": true, - "description": "Unique workspace identifier.", + "description": "Credential whose sharing grants are managed.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Credential whose sharing grants are managed." + } + }, + { + "name": "workspaceId", + "in": "query", + "required": true, + "description": "Workspace expected to own the credential.", "schema": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Unique workspace identifier." + "description": "Workspace expected to own the credential." } - } - ], - "requestBody": { - "required": true, - "description": "Recipients and the access to grant.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateWorkspaceInvitationsBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "emails": ["member@example.com"], - "permission": "write", - "membership": "member" - } - } - } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum credential members to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum credential members to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "schema": { + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "type": "string", + "minLength": 1 + } + }, + { + "name": "sortBy", + "in": "query", + "required": false, + "description": "Field used to sort the result. Do not rely on case-insensitive ordering when sorting by `name`.", + "schema": { + "default": "email", + "description": "Field used to sort the result. Do not rely on case-insensitive ordering when sorting by `name`.", + "type": "string", + "enum": ["email", "name"] + } + }, + { + "name": "sortOrder", + "in": "query", + "required": false, + "description": "Sort direction.", + "schema": { + "default": "asc", + "description": "Sort direction.", + "type": "string", + "enum": ["asc", "desc"] } } - }, + ], "responses": { "200": { - "description": "Per-recipient invitation and direct-grant outcomes.", + "description": "A page of explicit and inherited credential grants.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12369,29 +12551,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateWorkspaceInvitationsResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "success": true, - "successful": ["member@example.com"], - "added": [], - "failed": [], - "invitations": [ - { - "id": "invitation-123", - "email": "member@example.com", - "workspaceIds": ["workspace-123"], - "permission": "write", - "membershipIntent": "internal" - } - ] - } - } - } + "$ref": "#/components/schemas/ListCredentialMembersResponse" } } } @@ -12408,15 +12568,6 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "409": { - "$ref": "#/components/responses/Conflict" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -12427,57 +12578,68 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/organizations/{organizationId}/members/{userId}/usage-limit": { - "get": { - "operationId": "getOrganizationMemberUsageLimit", - "summary": "Get organization member credit limit", - "description": "Read a person’s credit cap and credits consumed in the organization billing period. Hosted deployments only. The `userId` identifies an organization member or external collaborator with workspace access in this organization; it is not a membership record ID. Null means no per-person cap, while organization limits still apply. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization_member_usage_limits.read", - "x-oauth-scope": "api:read", - "tags": ["Organizations"], + }, + "post": { + "operationId": "upsertCredentialMember", + "summary": "Upsert credential member", + "description": "Grant or change a current workspace member’s credential role. Requires credential Admin access and the `integrations.manage` capability. Revoked grants become active again; inherited workspace Admins cannot be demoted. A new grant returns `201`; an existing grant returns `200`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "credentials.members.upsert", + "x-oauth-scope": "api:write", + "tags": ["Credentials"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:read"] + "oauthBearer": ["api:write"] } ], "parameters": [ { - "name": "organizationId", + "name": "credentialId", "in": "path", "required": true, - "description": "Organization identifier.", + "description": "Credential whose sharing grants are managed.", "schema": { "type": "string", "minLength": 1, - "description": "Organization identifier." + "maxLength": 255, + "description": "Credential whose sharing grants are managed." } }, { - "name": "userId", - "in": "path", + "name": "workspaceId", + "in": "query", "required": true, - "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it.", + "description": "Workspace expected to own the credential.", "schema": { "type": "string", "minLength": 1, - "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it." + "maxLength": 128, + "description": "Workspace expected to own the credential." } } ], - "responses": { - "200": { - "description": "The person’s current credit cap and billing-period consumption.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" + "requestBody": { + "required": true, + "description": "The current workspace member and credential role to grant.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpsertCredentialMemberBody" + } + } + } + }, + "responses": { + "200": { + "description": "The saved credential role and whether a grant was created.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" }, "X-RateLimit-Reset": { "$ref": "#/components/headers/X-RateLimit-Reset" @@ -12486,19 +12648,28 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetOrganizationMemberUsageLimitResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "creditsUsed": 200, - "creditLimit": 10000, - "billingInterval": "month" - } - } - } + "$ref": "#/components/schemas/UpsertCredentialMemberResponse" + } + } + } + }, + "201": { + "description": "The saved credential role and whether a grant was created.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpsertCredentialMemberResponse" } } } @@ -12515,6 +12686,12 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -12525,14 +12702,16 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - }, - "patch": { - "operationId": "updateOrganizationMemberUsageLimit", - "summary": "Update organization member credit limit", - "description": "Set or clear a person’s credit cap. Hosted deployments only. The `userId` must identify an organization member or external collaborator with workspace access in this organization. The cap is a nonnegative whole number of credits, not dollars: `0` prevents further credit-consuming usage; `null` removes the per-person cap. Organization limits continue to apply. Retrying the same value is safe. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "organization_member_usage_limits.update", + } + }, + "/api/v2/credentials/{credentialId}/members/{userId}": { + "delete": { + "operationId": "removeCredentialMember", + "summary": "Remove credential member", + "description": "Revoke an active explicit credential grant. Requires credential Admin access and the `integrations.manage` capability. Inherited workspace Admins cannot be removed; an absent or already-revoked grant returns `404`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "credentials.members.remove", "x-oauth-scope": "api:write", - "tags": ["Organizations"], + "tags": ["Credentials"], "security": [ { "apiKey": [] @@ -12543,56 +12722,45 @@ ], "parameters": [ { - "name": "organizationId", + "name": "credentialId", "in": "path", "required": true, - "description": "Organization identifier.", + "description": "Credential whose sharing grants are managed.", "schema": { "type": "string", "minLength": 1, - "description": "Organization identifier." + "maxLength": 255, + "description": "Credential whose sharing grants are managed." } }, { "name": "userId", "in": "path", "required": true, - "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it.", + "description": "User whose explicit grant will be revoked.", "schema": { "type": "string", "minLength": 1, - "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it." + "maxLength": 255, + "description": "User whose explicit grant will be revoked." } - } - ], - "requestBody": { - "required": true, - "description": "Credit cap in whole credits; null clears the cap.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateOrganizationMemberUsageLimitBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "creditLimit": 10000 - } - }, - "example2": { - "summary": "Request example 2", - "value": { - "creditLimit": null - } - } - } + }, + { + "name": "workspaceId", + "in": "query", + "required": true, + "description": "Workspace expected to own the credential.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace expected to own the credential." } } - }, + ], "responses": { "200": { - "description": "The saved credit cap, or null when the cap was cleared.", + "description": "Acknowledgement that the explicit credential grant was revoked.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12607,17 +12775,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateOrganizationMemberUsageLimitResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "creditLimit": 10000 - } - } - } + "$ref": "#/components/schemas/RemoveCredentialMemberResponse" } } } @@ -12634,12 +12792,6 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -12652,14 +12804,14 @@ } } }, - "/api/v2/organizations/{organizationId}/usage/summary": { + "/api/v2/workspaces/{workspaceId}/permission-config": { "get": { - "operationId": "getOrganizationUsageSummary", - "summary": "Get organization usage summary", - "description": "Read pooled credits, a usage series, and an exact previous-period comparison when available. Requires organization Admin access and Usage Monitoring: Enterprise when billing is enabled, or deployment enablement when billing is disabled. Defaults to 30 days. Custom dates include both dates in the selected timezone and cannot exceed 92 days. Billing windows exceeding 366 days are rejected. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization_usage.summary.read", + "operationId": "getWorkspacePermissionConfig", + "summary": "Get workspace permission config", + "description": "Get the acting user's governing permission group and configuration for a workspace they can access. This describes permission-group restrictions, not the user's workspace role. Group and config are null when no group governs the caller; entitled indicates whether organization permission governance is active. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "permission_groups.read_user_config", "x-oauth-scope": "api:read", - "tags": ["Organizations"], + "tags": ["Workspaces"], "security": [ { "apiKey": [] @@ -12670,80 +12822,21 @@ ], "parameters": [ { - "name": "organizationId", + "name": "workspaceId", "in": "path", "required": true, - "description": "Organization identifier.", - "schema": { - "type": "string", - "minLength": 1, - "description": "Organization identifier." - } - }, - { - "name": "preset", - "in": "query", - "required": false, - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", - "schema": { - "default": "30d", - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", - "type": "string", - "enum": ["current-period", "previous-period", "7d", "30d", "custom"] - } - }, - { - "name": "startDate", - "in": "query", - "required": false, - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" - } - }, - { - "name": "endDate", - "in": "query", - "required": false, - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" - } - }, - { - "name": "timezone", - "in": "query", - "required": false, - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "schema": { - "default": "UTC", - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "type": "string", - "minLength": 1 - } - }, - { - "name": "workspaceId", - "in": "query", - "required": false, - "description": "Restrict usage to one workspace owned by the organization.", + "description": "Unique workspace identifier.", "schema": { - "description": "Restrict usage to one workspace owned by the organization.", "type": "string", "minLength": 1, - "maxLength": 128 + "maxLength": 128, + "description": "Unique workspace identifier." } } ], "responses": { "200": { - "description": "Reporting bounds, pooled credits, and chronological usage buckets.", + "description": "The caller’s effective permission-group configuration.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12758,30 +12851,19 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetOrganizationUsageSummaryResponse" + "$ref": "#/components/schemas/GetWorkspacePermissionConfigResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { "data": { - "window": { - "start": "2026-06-01T00:00:00.000Z", - "end": "2026-07-01T00:00:00.000Z", - "source": "range" - }, - "bucket": "day", - "totals": { - "credits": 200 - }, - "previousTotals": null, - "series": [ - { - "timestamp": "2026-06-01T00:00:00.000Z", - "credits": 200, - "events": 1 - } - ] + "permissionGroupId": null, + "groupName": null, + "config": null, + "entitled": false, + "organizationId": null, + "isOrgAdmin": false } } } @@ -12813,122 +12895,60 @@ } } }, - "/api/v2/organizations/{organizationId}/usage/breakdown": { - "get": { - "operationId": "getOrganizationUsageBreakdown", - "summary": "Get organization usage breakdown", - "description": "Read ranked usage by member, workspace, workflow, model, BYOK provider, or source. Requires organization Admin access and Usage Monitoring. `other` summarizes groups omitted by the limit. BYOK ranks tokens; other dimensions rank cost. More than 10,000 underlying groups returns `413`; narrow the window or workspace. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization_usage.breakdown.read", - "x-oauth-scope": "api:read", - "tags": ["Organizations"], + "/api/v2/workspaces/{workspaceId}/invitations": { + "post": { + "operationId": "createWorkspaceInvitations", + "summary": "Create workspace invitations", + "description": "Invite people to a workspace or grant access immediately to existing organization members. Requires workspace Admin access and current invitation eligibility; invitations offering organization Admin membership also require organization Admin access. Recipients are processed independently: inspect `failed` even after HTTP `200`, and inspect invitation status before retrying a delivery failure. Existing access is preserved. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "workspace_invitations.send_batch", + "x-oauth-scope": "api:write", + "tags": ["Workspaces"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:read"] + "oauthBearer": ["api:write"] } ], "parameters": [ { - "name": "organizationId", + "name": "workspaceId", "in": "path", "required": true, - "description": "Organization identifier.", - "schema": { - "type": "string", - "minLength": 1, - "description": "Organization identifier." - } - }, - { - "name": "preset", - "in": "query", - "required": false, - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", - "schema": { - "default": "30d", - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", - "type": "string", - "enum": ["current-period", "previous-period", "7d", "30d", "custom"] - } - }, - { - "name": "startDate", - "in": "query", - "required": false, - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" - } - }, - { - "name": "endDate", - "in": "query", - "required": false, - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" - } - }, - { - "name": "timezone", - "in": "query", - "required": false, - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "schema": { - "default": "UTC", - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "type": "string", - "minLength": 1 - } - }, - { - "name": "workspaceId", - "in": "query", - "required": false, - "description": "Restrict usage to one workspace owned by the organization.", + "description": "Unique workspace identifier.", "schema": { - "description": "Restrict usage to one workspace owned by the organization.", "type": "string", "minLength": 1, - "maxLength": 128 - } - }, - { - "name": "dimension", - "in": "query", - "required": true, - "description": "Usage grouping dimension.", - "schema": { - "type": "string", - "enum": ["member", "workspace", "workflow", "model", "byok", "source"], - "description": "Usage grouping dimension." - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum ranked groups to return. Remaining usage is summarized in other. Must be a whole number from 1 to 100. Defaults to 50.", - "schema": { - "default": 50, - "description": "Maximum ranked groups to return. Remaining usage is summarized in other. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 + "maxLength": 128, + "description": "Unique workspace identifier." } } ], + "requestBody": { + "required": true, + "description": "Recipients and the access to grant.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateWorkspaceInvitationsBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "emails": ["member@example.com"], + "permission": "write", + "membership": "member" + } + } + } + } + } + }, "responses": { "200": { - "description": "Ranked usage groups and the combined remainder.", + "description": "Per-recipient invitation and direct-grant outcomes.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -12943,30 +12963,26 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetOrganizationUsageBreakdownResponse" + "$ref": "#/components/schemas/CreateWorkspaceInvitationsResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { "data": { - "dimension": "member", - "rows": [ + "success": true, + "successful": ["member@example.com"], + "added": [], + "failed": [], + "invitations": [ { - "id": "user-123", - "label": "Example Member", - "credits": 200, - "events": 1, - "share": 1 + "id": "invitation-123", + "email": "member@example.com", + "workspaceIds": ["workspace-123"], + "permission": "write", + "membershipIntent": "internal" } - ], - "other": { - "credits": 0, - "events": 0, - "rowCount": 0, - "tokens": 0 - }, - "totalCredits": 200 + ] } } } @@ -12986,9 +13002,15 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, "413": { "$ref": "#/components/responses/PayloadTooLarge" }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -13001,12 +13023,12 @@ } } }, - "/api/v2/organizations/{organizationId}/usage/events": { + "/api/v2/organizations/{organizationId}/members/{userId}/usage-limit": { "get": { - "operationId": "listOrganizationUsageEvents", - "summary": "List organization usage events", - "description": "List usage events, including zero-cost activity. Requires organization Admin access and Usage Monitoring. Defaults to 30 days. Cursors retain the initial reporting window; keep filters and sort unchanged while paging. `sim-chat` covers both chat surfaces. Per-event rounding can yield `credits: 0` with `hasCost: true`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "organization_usage.events.list", + "operationId": "getOrganizationMemberUsageLimit", + "summary": "Get organization member credit limit", + "description": "Read a person’s credit cap and credits consumed in the organization billing period. Hosted deployments only. The `userId` identifies an organization member or external collaborator with workspace access in this organization; it is not a membership record ID. Null means no per-person cap, while organization limits still apply. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization_member_usage_limits.read", "x-oauth-scope": "api:read", "tags": ["Organizations"], "security": [ @@ -13030,127 +13052,141 @@ } }, { - "name": "preset", - "in": "query", - "required": false, - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", + "name": "userId", + "in": "path", + "required": true, + "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it.", "schema": { - "default": "30d", - "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", "type": "string", - "enum": ["current-period", "previous-period", "7d", "30d", "custom"] + "minLength": 1, + "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it." } - }, - { - "name": "startDate", - "in": "query", - "required": false, - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "First calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + } + ], + "responses": { + "200": { + "description": "The person’s current credit cap and billing-period consumption.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetOrganizationMemberUsageLimitResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "creditsUsed": 200, + "creditLimit": 10000, + "billingInterval": "month" + } + } + } + } + } } }, - { - "name": "endDate", - "in": "query", - "required": false, - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "schema": { - "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", - "type": "string", - "format": "date", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" - } + "400": { + "$ref": "#/components/responses/BadRequest" }, - { - "name": "timezone", - "in": "query", - "required": false, - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "schema": { - "default": "UTC", - "description": "IANA timezone for calendar boundaries; defaults to UTC.", - "type": "string", - "minLength": 1 - } + "401": { + "$ref": "#/components/responses/Unauthorized" }, - { - "name": "source", - "in": "query", - "required": false, - "description": "Restrict events to one product surface.", - "schema": { - "description": "Restrict events to one product surface.", - "type": "string", - "enum": [ - "workflow", - "wand", - "sim-chat", - "mcp_copilot", - "mothership_block", - "knowledge-base", - "voice-input", - "enrichment", - "voice-output", - "api-tool" - ] - } + "403": { + "$ref": "#/components/responses/Forbidden" }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum usage events per page. Must be a whole number from 1 to 100. Defaults to 50.", - "schema": { - "default": 50, - "description": "Maximum usage events per page. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 - } + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + }, + "patch": { + "operationId": "updateOrganizationMemberUsageLimit", + "summary": "Update organization member credit limit", + "description": "Set or clear a person’s credit cap. Hosted deployments only. The `userId` must identify an organization member or external collaborator with workspace access in this organization. The cap is a nonnegative whole number of credits, not dollars: `0` prevents further credit-consuming usage; `null` removes the per-person cap. Organization limits continue to apply. Retrying the same value is safe. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "organization_member_usage_limits.update", + "x-oauth-scope": "api:write", + "tags": ["Organizations"], + "security": [ { - "name": "cursor", - "in": "query", - "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", - "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", - "type": "string", - "minLength": 1 - } + "apiKey": [] }, { - "name": "sortBy", - "in": "query", - "required": false, - "description": "Field used to sort the result.", + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization identifier.", "schema": { - "default": "createdAt", - "description": "Field used to sort the result.", "type": "string", - "enum": ["createdAt"] + "minLength": 1, + "description": "Organization identifier." } }, { - "name": "sortOrder", - "in": "query", - "required": false, - "description": "Sort direction.", + "name": "userId", + "in": "path", + "required": true, + "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it.", "schema": { - "default": "desc", - "description": "Sort direction.", "type": "string", - "enum": ["asc", "desc"] + "minLength": 1, + "description": "User ID of an organization member or external collaborator with workspace access in this organization. Use List Organization Members or List Workspace Members to find it." } } ], + "requestBody": { + "required": true, + "description": "Credit cap in whole credits; null clears the cap.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOrganizationMemberUsageLimitBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "creditLimit": 10000 + } + }, + "example2": { + "summary": "Request example 2", + "value": { + "creditLimit": null + } + } + } + } + } + }, "responses": { "200": { - "description": "A page of usage events, including zero-cost activity.", + "description": "The saved credit cap, or null when the cap was cleared.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -13165,24 +13201,15 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListOrganizationUsageEventsResponse" + "$ref": "#/components/schemas/UpdateOrganizationMemberUsageLimitResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": [ - { - "id": "event-123", - "createdAt": "2026-06-01T09:00:00.000Z", - "source": "sim-chat", - "description": "Model usage", - "workflowName": null, - "credits": 200, - "hasCost": true - } - ], - "nextCursor": null + "data": { + "creditLimit": 10000 + } } } } @@ -13201,6 +13228,12 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -13213,14 +13246,14 @@ } } }, - "/api/v2/workspaces/{workspaceId}/access-requests/discovery": { + "/api/v2/organizations/{organizationId}/usage/summary": { "get": { - "operationId": "discoverWorkspaceAccessRequests", - "summary": "Discover workspace access requests", - "description": "Discover the acting user’s access to features, integrations, models, tools, authentication methods, and member credit limits. Returns an empty list while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "access_requests.discover", + "operationId": "getOrganizationUsageSummary", + "summary": "Get organization usage summary", + "description": "Read pooled credits, a usage series, and an exact previous-period comparison when available. Requires organization Admin access and Usage Monitoring: Enterprise when billing is enabled, or deployment enablement when billing is disabled. Defaults to 30 days. Custom dates include both dates in the selected timezone and cannot exceed 92 days. Billing windows exceeding 366 days are rejected. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization_usage.summary.read", "x-oauth-scope": "api:read", - "tags": ["Access Requests"], + "tags": ["Organizations"], "security": [ { "apiKey": [] @@ -13231,113 +13264,80 @@ ], "parameters": [ { - "name": "workspaceId", + "name": "organizationId", "in": "path", "required": true, - "description": "Workspace in which the acting user requests access.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace in which the acting user requests access." - } - }, - { - "name": "search", - "in": "query", - "required": false, - "description": "Case-insensitive substring match against the access item label.", + "description": "Organization identifier.", "schema": { - "description": "Case-insensitive substring match against the access item label.", "type": "string", "minLength": 1, - "maxLength": 200 + "description": "Organization identifier." } }, { - "name": "targetKind", + "name": "preset", "in": "query", "required": false, - "description": "Category of access to discover.", + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", "schema": { - "description": "Category of access to discover.", + "default": "30d", + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", "type": "string", - "enum": [ - "feature", - "integration", - "provider", - "model", - "tool", - "knowledge_connector", - "file_share_auth", - "chat_deploy_auth", - "usage_limit" - ] + "enum": ["current-period", "previous-period", "7d", "30d", "custom"] } }, { - "name": "state", + "name": "startDate", "in": "query", "required": false, - "description": "Filter by the acting user’s current access. Requestable items can be submitted for review.", + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", "schema": { - "description": "Filter by the acting user’s current access. Requestable items can be submitted for review.", + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", "type": "string", - "enum": ["allowed", "requestable", "unavailable"] + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" } }, { - "name": "sortBy", + "name": "endDate", "in": "query", "required": false, - "description": "Field used to sort the result.", + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", "schema": { - "default": "label", - "description": "Field used to sort the result.", + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", "type": "string", - "enum": ["label"] + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" } }, { - "name": "sortOrder", + "name": "timezone", "in": "query", "required": false, - "description": "Sort direction.", + "description": "IANA timezone for calendar boundaries; defaults to UTC.", "schema": { - "default": "asc", - "description": "Sort direction.", + "default": "UTC", + "description": "IANA timezone for calendar boundaries; defaults to UTC.", "type": "string", - "enum": ["asc", "desc"] - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "description": "Maximum access items to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "schema": { - "default": 50, - "description": "Maximum access items to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 + "minLength": 1 } }, { - "name": "cursor", + "name": "workspaceId", "in": "query", "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Restrict usage to one workspace owned by the organization.", "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Restrict usage to one workspace owned by the organization.", "type": "string", - "minLength": 1 + "minLength": 1, + "maxLength": 128 } } ], "responses": { "200": { - "description": "A page of access targets and the acting user’s current access state.", + "description": "Reporting bounds, pooled credits, and chronological usage buckets.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -13352,25 +13352,31 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DiscoverWorkspaceAccessRequestsResponse" + "$ref": "#/components/schemas/GetOrganizationUsageSummaryResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": [ - { - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "label": "Tables", - "state": "requestable", - "reason": null, - "pendingRequestId": null - } - ], - "nextCursor": null + "data": { + "window": { + "start": "2026-06-01T00:00:00.000Z", + "end": "2026-07-01T00:00:00.000Z", + "source": "range" + }, + "bucket": "day", + "totals": { + "credits": 200 + }, + "previousTotals": null, + "series": [ + { + "timestamp": "2026-06-01T00:00:00.000Z", + "credits": 200, + "events": 1 + } + ] + } } } } @@ -13389,9 +13395,6 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "409": { - "$ref": "#/components/responses/Conflict" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -13404,14 +13407,14 @@ } } }, - "/api/v2/workspaces/{workspaceId}/access-requests": { + "/api/v2/organizations/{organizationId}/usage/breakdown": { "get": { - "operationId": "listMyWorkspaceAccessRequests", - "summary": "List my workspace access requests", - "description": "List only the acting user’s requests in this workspace, including resolved history and organization-wide member credit-limit requests. History remains available while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "access_requests.list_mine", + "operationId": "getOrganizationUsageBreakdown", + "summary": "Get organization usage breakdown", + "description": "Read ranked usage by member, workspace, workflow, model, BYOK provider, or source. Requires organization Admin access and Usage Monitoring. `other` summarizes groups omitted by the limit. BYOK ranks tokens; other dimensions rank cost. More than 10,000 underlying groups returns `413`; narrow the window or workspace. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization_usage.breakdown.read", "x-oauth-scope": "api:read", - "tags": ["Access Requests"], + "tags": ["Organizations"], "security": [ { "apiKey": [] @@ -13422,80 +13425,104 @@ ], "parameters": [ { - "name": "workspaceId", + "name": "organizationId", "in": "path", "required": true, - "description": "Workspace in which the acting user requests access.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace in which the acting user requests access." + "description": "Organization identifier." } }, { - "name": "status", + "name": "preset", "in": "query", "required": false, - "description": "Filter by request status; omit to include all statuses.", + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", "schema": { - "description": "Filter by request status; omit to include all statuses.", + "default": "30d", + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", "type": "string", - "enum": ["pending", "fulfilled", "declined", "cancelled", "closed"] + "enum": ["current-period", "previous-period", "7d", "30d", "custom"] } }, { - "name": "sortBy", + "name": "startDate", "in": "query", "required": false, - "description": "Field used to sort the result.", + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", "schema": { - "default": "createdAt", - "description": "Field used to sort the result.", + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", "type": "string", - "enum": ["createdAt", "targetLabel"] + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" } }, { - "name": "sortOrder", + "name": "endDate", "in": "query", "required": false, - "description": "Sort direction.", + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", "schema": { - "default": "desc", - "description": "Sort direction.", + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", "type": "string", - "enum": ["asc", "desc"] + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" } }, { - "name": "limit", + "name": "timezone", "in": "query", "required": false, - "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "IANA timezone for calendar boundaries; defaults to UTC.", "schema": { - "default": 50, - "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 + "default": "UTC", + "description": "IANA timezone for calendar boundaries; defaults to UTC.", + "type": "string", + "minLength": 1 } }, { - "name": "cursor", + "name": "workspaceId", "in": "query", "required": false, - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Restrict usage to one workspace owned by the organization.", "schema": { - "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "description": "Restrict usage to one workspace owned by the organization.", "type": "string", - "minLength": 1 + "minLength": 1, + "maxLength": 128 + } + }, + { + "name": "dimension", + "in": "query", + "required": true, + "description": "Usage grouping dimension.", + "schema": { + "type": "string", + "enum": ["member", "workspace", "workflow", "model", "byok", "source"], + "description": "Usage grouping dimension." + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum ranked groups to return. Remaining usage is summarized in other. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum ranked groups to return. Remaining usage is summarized in other. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 } } ], "responses": { "200": { - "description": "A page of the acting user’s workspace and member-credit requests.", + "description": "Ranked usage groups and the combined remainder.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -13510,36 +13537,31 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListMyWorkspaceAccessRequestsResponse" + "$ref": "#/components/schemas/GetOrganizationUsageBreakdownResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": [ - { - "id": "request-123", - "organizationId": "org-123", - "workspaceId": "workspace-123", - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "targetLabel": "Tables", - "reason": "Maintain team data", - "status": "pending", - "decisionReason": null, - "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": null, - "groupName": "Engineering", - "requester": { + "data": { + "dimension": "member", + "rows": [ + { "id": "user-123", - "name": "Alex Example", - "email": "alex@example.com" + "label": "Example Member", + "credits": 200, + "events": 1, + "share": 1 } - } - ], - "nextCursor": null + ], + "other": { + "credits": 0, + "events": 0, + "rowCount": 0, + "tokens": 0 + }, + "totalCredits": 200 + } } } } @@ -13558,8 +13580,8 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "409": { - "$ref": "#/components/responses/Conflict" + "413": { + "$ref": "#/components/responses/PayloadTooLarge" }, "429": { "$ref": "#/components/responses/RateLimited" @@ -13571,187 +13593,158 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - }, - "post": { - "operationId": "createWorkspaceAccessRequest", - "summary": "Create workspace access request", - "description": "Request access using a target from Discover workspace access requests. Requires access to an organization-owned workspace with requests enabled; external collaborators use their workspace grant. Each requester can have 100 pending requests and submit 100 in 24 hours within the organization. Matching pending requests are reused; an existing request may be closed if access is already available. Permission approvals change the governing group for all affected members. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "access_requests.create", - "x-oauth-scope": "api:write", - "tags": ["Access Requests"], + } + }, + "/api/v2/organizations/{organizationId}/usage/events": { + "get": { + "operationId": "listOrganizationUsageEvents", + "summary": "List organization usage events", + "description": "List usage events, including zero-cost activity. Requires organization Admin access and Usage Monitoring. Defaults to 30 days. Cursors retain the initial reporting window; keep filters and sort unchanged while paging. `sim-chat` covers both chat surfaces. Per-event rounding can yield `credits: 0` with `hasCost: true`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "organization_usage.events.list", + "x-oauth-scope": "api:read", + "tags": ["Organizations"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ { - "name": "workspaceId", + "name": "organizationId", "in": "path", "required": true, - "description": "Workspace in which the acting user requests access.", + "description": "Organization identifier.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace in which the acting user requests access." + "description": "Organization identifier." } - } - ], - "requestBody": { - "required": true, - "description": "A discovered access target and an optional reason for the request.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateWorkspaceAccessRequestBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "reason": "Maintain team data" - } - } - } + }, + { + "name": "preset", + "in": "query", + "required": false, + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", + "schema": { + "default": "30d", + "description": "Reporting window. Custom requires startDate and endDate and is capped at 92 days; other presets reject those bounds. Resolved billing windows are capped at 366 days.", + "type": "string", + "enum": ["current-period", "previous-period", "7d", "30d", "custom"] } - } - }, - "responses": { - "200": { - "description": "The new request, matching pending request, or existing request closed because access became available.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateWorkspaceAccessRequestResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "id": "request-123", - "organizationId": "org-123", - "workspaceId": "workspace-123", - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "targetLabel": "Tables", - "reason": "Maintain team data", - "status": "pending", - "decisionReason": null, - "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": null, - "groupName": "Engineering", - "requester": { - "id": "user-123", - "name": "Alex Example", - "email": "alex@example.com" - } - } - } - } - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "409": { - "$ref": "#/components/responses/Conflict" }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" + { + "name": "startDate", + "in": "query", + "required": false, + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", + "schema": { + "description": "First calendar date included, in the selected timezone. Requires preset=custom.", + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + } }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" + { + "name": "endDate", + "in": "query", + "required": false, + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", + "schema": { + "description": "Last calendar date included, in the selected timezone. Requires preset=custom.", + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + } }, - "429": { - "$ref": "#/components/responses/RateLimited" + { + "name": "timezone", + "in": "query", + "required": false, + "description": "IANA timezone for calendar boundaries; defaults to UTC.", + "schema": { + "default": "UTC", + "description": "IANA timezone for calendar boundaries; defaults to UTC.", + "type": "string", + "minLength": 1 + } }, - "500": { - "$ref": "#/components/responses/InternalError" + { + "name": "source", + "in": "query", + "required": false, + "description": "Restrict events to one product surface.", + "schema": { + "description": "Restrict events to one product surface.", + "type": "string", + "enum": [ + "workflow", + "wand", + "sim-chat", + "mcp_copilot", + "mothership_block", + "knowledge-base", + "voice-input", + "enrichment", + "voice-output", + "api-tool" + ] + } }, - "503": { - "$ref": "#/components/responses/ServiceUnavailable" - } - } - } - }, - "/api/v2/workspaces/{workspaceId}/access-requests/{requestId}/cancel": { - "post": { - "operationId": "cancelWorkspaceAccessRequest", - "summary": "Cancel workspace access request", - "description": "Cancel the acting user’s pending request in this scope, including an organization-wide member credit-limit request. Already resolved requests are returned unchanged. Cancellation remains available while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "access_requests.cancel", - "x-oauth-scope": "api:write", - "tags": ["Access Requests"], - "security": [ { - "apiKey": [] + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum usage events per page. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum usage events per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } }, { - "oauthBearer": ["api:write"] - } - ], - "parameters": [ + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "schema": { + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "type": "string", + "minLength": 1 + } + }, { - "name": "workspaceId", - "in": "path", - "required": true, - "description": "Workspace in which the acting user requests access.", + "name": "sortBy", + "in": "query", + "required": false, + "description": "Field used to sort the result.", "schema": { + "default": "createdAt", + "description": "Field used to sort the result.", "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace in which the acting user requests access." + "enum": ["createdAt"] } }, { - "name": "requestId", - "in": "path", - "required": true, - "description": "Access request identifier.", + "name": "sortOrder", + "in": "query", + "required": false, + "description": "Sort direction.", "schema": { + "default": "desc", + "description": "Sort direction.", "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Access request identifier." + "enum": ["asc", "desc"] } } ], "responses": { "200": { - "description": "The cancelled request, or the unchanged request if already resolved.", + "description": "A page of usage events, including zero-cost activity.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -13766,33 +13759,24 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CancelWorkspaceAccessRequestResponse" + "$ref": "#/components/schemas/ListOrganizationUsageEventsResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": { - "id": "request-123", - "organizationId": "org-123", - "workspaceId": "workspace-123", - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "targetLabel": "Tables", - "reason": "Maintain team data", - "status": "cancelled", - "decisionReason": null, - "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": "2026-06-01T10:00:00.000Z", - "groupName": "Engineering", - "requester": { - "id": "user-123", - "name": "Alex Example", - "email": "alex@example.com" + "data": [ + { + "id": "event-123", + "createdAt": "2026-06-01T09:00:00.000Z", + "source": "sim-chat", + "description": "Model usage", + "workflowName": null, + "credits": 200, + "hasCost": true } - } + ], + "nextCursor": null } } } @@ -13811,9 +13795,6 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "409": { - "$ref": "#/components/responses/Conflict" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -13826,11 +13807,11 @@ } } }, - "/api/v2/organizations/{organizationId}/access-requests/discovery": { + "/api/v2/workspaces/{workspaceId}/access-requests/discovery": { "get": { - "operationId": "discoverOrganizationAccessRequests", - "summary": "Discover organization access requests", - "description": "Discover the acting user’s access to features, integrations, models, tools, authentication methods, and member credit limits. Returns an empty list while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "operationId": "discoverWorkspaceAccessRequests", + "summary": "Discover workspace access requests", + "description": "Discover the acting user’s access to features, integrations, models, tools, authentication methods, and member credit limits. Returns an empty list while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", "x-sim-operation": "access_requests.discover", "x-oauth-scope": "api:read", "tags": ["Access Requests"], @@ -13844,14 +13825,15 @@ ], "parameters": [ { - "name": "organizationId", + "name": "workspaceId", "in": "path", "required": true, - "description": "Organization that owns the access requests.", + "description": "Workspace in which the acting user requests access.", "schema": { "type": "string", "minLength": 1, - "description": "Organization that owns the access requests." + "maxLength": 128, + "description": "Workspace in which the acting user requests access." } }, { @@ -13964,7 +13946,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DiscoverOrganizationAccessRequestsResponse" + "$ref": "#/components/schemas/DiscoverWorkspaceAccessRequestsResponse" }, "examples": { "example1": { @@ -14016,11 +13998,11 @@ } } }, - "/api/v2/organizations/{organizationId}/access-requests/mine": { + "/api/v2/workspaces/{workspaceId}/access-requests": { "get": { - "operationId": "listMyOrganizationAccessRequests", - "summary": "List my organization access requests", - "description": "List the acting user’s organization-level requests and member credit-limit requests, including resolved history. For workspace-scoped requests, use List my workspace access requests. History remains available while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "operationId": "listMyWorkspaceAccessRequests", + "summary": "List my workspace access requests", + "description": "List only the acting user’s requests in this workspace, including resolved history and organization-wide member credit-limit requests. History remains available while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", "x-sim-operation": "access_requests.list_mine", "x-oauth-scope": "api:read", "tags": ["Access Requests"], @@ -14034,14 +14016,15 @@ ], "parameters": [ { - "name": "organizationId", + "name": "workspaceId", "in": "path", "required": true, - "description": "Organization that owns the access requests.", + "description": "Workspace in which the acting user requests access.", "schema": { "type": "string", "minLength": 1, - "description": "Organization that owns the access requests." + "maxLength": 128, + "description": "Workspace in which the acting user requests access." } }, { @@ -14106,7 +14089,7 @@ ], "responses": { "200": { - "description": "A page of the acting user’s organization and member-credit requests.", + "description": "A page of the acting user’s workspace and member-credit requests.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -14121,7 +14104,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListMyOrganizationAccessRequestsResponse" + "$ref": "#/components/schemas/ListMyWorkspaceAccessRequestsResponse" }, "examples": { "example1": { @@ -14131,7 +14114,7 @@ { "id": "request-123", "organizationId": "org-123", - "workspaceId": null, + "workspaceId": "workspace-123", "target": { "kind": "feature", "configKey": "hideTablesTab" @@ -14182,13 +14165,11 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/organizations/{organizationId}/access-requests": { + }, "post": { - "operationId": "createOrganizationAccessRequest", - "summary": "Create organization access request", - "description": "Request access using a target from Discover organization access requests. Requires organization membership and requests enabled. Each requester can have 100 pending requests and submit 100 in 24 hours within the organization. Matching pending requests are reused; an existing request may be closed if access is already available. Permission approvals change the governing group for all affected members. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "operationId": "createWorkspaceAccessRequest", + "summary": "Create workspace access request", + "description": "Request access using a target from Discover workspace access requests. Requires access to an organization-owned workspace with requests enabled; external collaborators use their workspace grant. Each requester can have 100 pending requests and submit 100 in 24 hours within the organization. Matching pending requests are reused; an existing request may be closed if access is already available. Permission approvals change the governing group for all affected members. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", "x-sim-operation": "access_requests.create", "x-oauth-scope": "api:write", "tags": ["Access Requests"], @@ -14202,14 +14183,15 @@ ], "parameters": [ { - "name": "organizationId", + "name": "workspaceId", "in": "path", "required": true, - "description": "Organization that owns the access requests.", + "description": "Workspace in which the acting user requests access.", "schema": { "type": "string", "minLength": 1, - "description": "Organization that owns the access requests." + "maxLength": 128, + "description": "Workspace in which the acting user requests access." } } ], @@ -14219,7 +14201,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateOrganizationAccessRequestBody" + "$ref": "#/components/schemas/CreateWorkspaceAccessRequestBody" }, "examples": { "example1": { @@ -14253,7 +14235,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateOrganizationAccessRequestResponse" + "$ref": "#/components/schemas/CreateWorkspaceAccessRequestResponse" }, "examples": { "example1": { @@ -14262,7 +14244,7 @@ "data": { "id": "request-123", "organizationId": "org-123", - "workspaceId": null, + "workspaceId": "workspace-123", "target": { "kind": "feature", "configKey": "hideTablesTab" @@ -14317,12 +14299,133 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - }, + } + }, + "/api/v2/workspaces/{workspaceId}/access-requests/{requestId}/cancel": { + "post": { + "operationId": "cancelWorkspaceAccessRequest", + "summary": "Cancel workspace access request", + "description": "Cancel the acting user’s pending request in this scope, including an organization-wide member credit-limit request. Already resolved requests are returned unchanged. Cancellation remains available while requests are disabled. Requires access to the workspace; external collaborators use their workspace grant. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "access_requests.cancel", + "x-oauth-scope": "api:write", + "tags": ["Access Requests"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "workspaceId", + "in": "path", + "required": true, + "description": "Workspace in which the acting user requests access.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace in which the acting user requests access." + } + }, + { + "name": "requestId", + "in": "path", + "required": true, + "description": "Access request identifier.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Access request identifier." + } + } + ], + "responses": { + "200": { + "description": "The cancelled request, or the unchanged request if already resolved.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CancelWorkspaceAccessRequestResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "id": "request-123", + "organizationId": "org-123", + "workspaceId": "workspace-123", + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "targetLabel": "Tables", + "reason": "Maintain team data", + "status": "cancelled", + "decisionReason": null, + "createdAt": "2026-06-01T09:00:00.000Z", + "decidedAt": "2026-06-01T10:00:00.000Z", + "groupName": "Engineering", + "requester": { + "id": "user-123", + "name": "Alex Example", + "email": "alex@example.com" + } + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/organizations/{organizationId}/access-requests/discovery": { "get": { - "operationId": "listOrganizationAccessRequests", - "summary": "List organization access requests", - "description": "List requests across the organization for administrator review. Includes requests from organization members and external workspace collaborators; history remains available while requests are disabled. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "access_requests.list_organization", + "operationId": "discoverOrganizationAccessRequests", + "summary": "Discover organization access requests", + "description": "Discover the acting user’s access to features, integrations, models, tools, authentication methods, and member credit limits. Returns an empty list while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "access_requests.discover", "x-oauth-scope": "api:read", "tags": ["Access Requests"], "security": [ @@ -14346,14 +14449,47 @@ } }, { - "name": "status", + "name": "search", "in": "query", "required": false, - "description": "Filter by request status; omit to include all statuses.", + "description": "Case-insensitive substring match against the access item label.", "schema": { - "description": "Filter by request status; omit to include all statuses.", + "description": "Case-insensitive substring match against the access item label.", "type": "string", - "enum": ["pending", "fulfilled", "declined", "cancelled", "closed"] + "minLength": 1, + "maxLength": 200 + } + }, + { + "name": "targetKind", + "in": "query", + "required": false, + "description": "Category of access to discover.", + "schema": { + "description": "Category of access to discover.", + "type": "string", + "enum": [ + "feature", + "integration", + "provider", + "model", + "tool", + "knowledge_connector", + "file_share_auth", + "chat_deploy_auth", + "usage_limit" + ] + } + }, + { + "name": "state", + "in": "query", + "required": false, + "description": "Filter by the acting user’s current access. Requestable items can be submitted for review.", + "schema": { + "description": "Filter by the acting user’s current access. Requestable items can be submitted for review.", + "type": "string", + "enum": ["allowed", "requestable", "unavailable"] } }, { @@ -14362,10 +14498,10 @@ "required": false, "description": "Field used to sort the result.", "schema": { - "default": "createdAt", + "default": "label", "description": "Field used to sort the result.", "type": "string", - "enum": ["createdAt", "targetLabel"] + "enum": ["label"] } }, { @@ -14374,7 +14510,7 @@ "required": false, "description": "Sort direction.", "schema": { - "default": "desc", + "default": "asc", "description": "Sort direction.", "type": "string", "enum": ["asc", "desc"] @@ -14384,10 +14520,10 @@ "name": "limit", "in": "query", "required": false, - "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "Maximum access items to return per page. Must be a whole number from 1 to 100. Defaults to 50.", "schema": { "default": 50, - "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "description": "Maximum access items to return per page. Must be a whole number from 1 to 100. Defaults to 50.", "type": "integer", "minimum": 1, "maximum": 100 @@ -14403,23 +14539,11 @@ "type": "string", "minLength": 1 } - }, - { - "name": "search", - "in": "query", - "required": false, - "description": "Case-insensitive substring match against the target label or requester name or email.", - "schema": { - "description": "Case-insensitive substring match against the target label or requester name or email.", - "type": "string", - "minLength": 1, - "maxLength": 200 - } } ], "responses": { "200": { - "description": "A page of requests across the organization for Admin review.", + "description": "A page of access targets and the acting user’s current access state.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -14434,7 +14558,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListOrganizationAccessRequestsResponse" + "$ref": "#/components/schemas/DiscoverOrganizationAccessRequestsResponse" }, "examples": { "example1": { @@ -14442,25 +14566,14 @@ "value": { "data": [ { - "id": "request-123", - "organizationId": "org-123", - "workspaceId": "workspace-123", "target": { "kind": "feature", "configKey": "hideTablesTab" }, - "targetLabel": "Tables", - "reason": "Maintain team data", - "status": "pending", - "decisionReason": null, - "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": null, - "groupName": "Engineering", - "requester": { - "id": "user-123", - "name": "Alex Example", - "email": "alex@example.com" - } + "label": "Tables", + "state": "requestable", + "reason": null, + "pendingRequestId": null } ], "nextCursor": null @@ -14497,20 +14610,20 @@ } } }, - "/api/v2/organizations/{organizationId}/access-requests/{requestId}/cancel": { - "post": { - "operationId": "cancelOrganizationAccessRequest", - "summary": "Cancel organization access request", - "description": "Cancel the acting user’s pending request in this scope, including an organization-wide member credit-limit request. Already resolved requests are returned unchanged. Cancellation remains available while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "access_requests.cancel", - "x-oauth-scope": "api:write", + "/api/v2/organizations/{organizationId}/access-requests/mine": { + "get": { + "operationId": "listMyOrganizationAccessRequests", + "summary": "List my organization access requests", + "description": "List the acting user’s organization-level requests and member credit-limit requests, including resolved history. For workspace-scoped requests, use List my workspace access requests. History remains available while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "access_requests.list_mine", + "x-oauth-scope": "api:read", "tags": ["Access Requests"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ @@ -14526,139 +14639,68 @@ } }, { - "name": "requestId", - "in": "path", - "required": true, - "description": "Access request identifier.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Access request identifier." - } - } - ], - "responses": { - "200": { - "description": "The cancelled request, or the unchanged request if already resolved.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CancelOrganizationAccessRequestResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "id": "request-123", - "organizationId": "org-123", - "workspaceId": null, - "target": { - "kind": "feature", - "configKey": "hideTablesTab" - }, - "targetLabel": "Tables", - "reason": "Maintain team data", - "status": "cancelled", - "decisionReason": null, - "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": "2026-06-01T10:00:00.000Z", - "groupName": "Engineering", - "requester": { - "id": "user-123", - "name": "Alex Example", - "email": "alex@example.com" - } - } - } - } - } - } + "name": "status", + "in": "query", + "required": false, + "description": "Filter by request status; omit to include all statuses.", + "schema": { + "description": "Filter by request status; omit to include all statuses.", + "type": "string", + "enum": ["pending", "fulfilled", "declined", "cancelled", "closed"] } }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "409": { - "$ref": "#/components/responses/Conflict" - }, - "429": { - "$ref": "#/components/responses/RateLimited" - }, - "500": { - "$ref": "#/components/responses/InternalError" - }, - "503": { - "$ref": "#/components/responses/ServiceUnavailable" - } - } - } - }, - "/api/v2/organizations/{organizationId}/access-requests/{requestId}/preview": { - "get": { - "operationId": "previewOrganizationAccessRequest", - "summary": "Preview organization access request", - "description": "Preview the current permission changes, affected group and audience, or member credit cap. Review `canApply`, `changes`, `impact`, and `fingerprint` before resolving. Permission changes affect the entire governing group, not only the requester. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "access_requests.preview", - "x-oauth-scope": "api:read", - "tags": ["Access Requests"], - "security": [ { - "apiKey": [] + "name": "sortBy", + "in": "query", + "required": false, + "description": "Field used to sort the result.", + "schema": { + "default": "createdAt", + "description": "Field used to sort the result.", + "type": "string", + "enum": ["createdAt", "targetLabel"] + } }, { - "oauthBearer": ["api:read"] - } - ], - "parameters": [ - { - "name": "organizationId", - "in": "path", - "required": true, - "description": "Organization that owns the access requests.", + "name": "sortOrder", + "in": "query", + "required": false, + "description": "Sort direction.", "schema": { + "default": "desc", + "description": "Sort direction.", "type": "string", - "minLength": 1, - "description": "Organization that owns the access requests." + "enum": ["asc", "desc"] } }, { - "name": "requestId", - "in": "path", - "required": true, - "description": "Access request identifier.", + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", "schema": { + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Access request identifier." + "minLength": 1 } } ], "responses": { "200": { - "description": "The proposed group or credit-cap change, affected audience, and fingerprint.", + "description": "A page of the acting user’s organization and member-credit requests.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -14673,18 +14715,17 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PreviewOrganizationAccessRequestResponse" + "$ref": "#/components/schemas/ListMyOrganizationAccessRequestsResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": { - "resolutionKind": "permission", - "request": { + "data": [ + { "id": "request-123", "organizationId": "org-123", - "workspaceId": "workspace-123", + "workspaceId": null, "target": { "kind": "feature", "configKey": "hideTablesTab" @@ -14701,31 +14742,9 @@ "name": "Alex Example", "email": "alex@example.com" } - }, - "group": { - "id": "group-123", - "name": "Engineering" - }, - "changes": [ - { - "configKey": "hideTablesTab", - "label": "Tables", - "before": true, - "after": false - } - ], - "impact": { - "memberCount": 2, - "workspaceCount": 1, - "workspaceNames": ["Engineering"], - "truncated": false - }, - "fingerprint": "current-preview-fingerprint", - "canApply": true, - "unavailableReason": null, - "currentLimitCredits": null, - "newLimitCredits": null - } + } + ], + "nextCursor": null } } } @@ -14759,12 +14778,12 @@ } } }, - "/api/v2/organizations/{organizationId}/access-requests/{requestId}/resolve": { + "/api/v2/organizations/{organizationId}/access-requests": { "post": { - "operationId": "resolveOrganizationAccessRequest", - "summary": "Resolve organization access request", - "description": "Apply a reviewed request or decline it with a reason. Applying requires the preview fingerprint; changed policy or membership returns a conflict. Credit requests also require a higher `newLimitCredits`. Already resolved requests are returned unchanged. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "access_requests.resolve", + "operationId": "createOrganizationAccessRequest", + "summary": "Create organization access request", + "description": "Request access using a target from Discover organization access requests. Requires organization membership and requests enabled. Each requester can have 100 pending requests and submit 100 in 24 hours within the organization. Matching pending requests are reused; an existing request may be closed if access is already available. Permission approvals change the governing group for all affected members. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "access_requests.create", "x-oauth-scope": "api:write", "tags": ["Access Requests"], "security": [ @@ -14786,34 +14805,25 @@ "minLength": 1, "description": "Organization that owns the access requests." } - }, - { - "name": "requestId", - "in": "path", - "required": true, - "description": "Access request identifier.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Access request identifier." - } } ], "requestBody": { "required": true, - "description": "Apply the reviewed fingerprint, with a higher credit cap when applicable, or decline with a reason.", + "description": "A discovered access target and an optional reason for the request.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ResolveOrganizationAccessRequestBody" + "$ref": "#/components/schemas/CreateOrganizationAccessRequestBody" }, "examples": { "example1": { "summary": "Request example 1", "value": { - "action": "apply", - "expectedFingerprint": "current-preview-fingerprint" + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "reason": "Maintain team data" } } } @@ -14822,7 +14832,7 @@ }, "responses": { "200": { - "description": "The applied or declined request, or its unchanged resolved state.", + "description": "The new request, matching pending request, or existing request closed because access became available.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -14837,7 +14847,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ResolveOrganizationAccessRequestResponse" + "$ref": "#/components/schemas/CreateOrganizationAccessRequestResponse" }, "examples": { "example1": { @@ -14846,17 +14856,17 @@ "data": { "id": "request-123", "organizationId": "org-123", - "workspaceId": "workspace-123", + "workspaceId": null, "target": { "kind": "feature", "configKey": "hideTablesTab" }, "targetLabel": "Tables", "reason": "Maintain team data", - "status": "fulfilled", + "status": "pending", "decisionReason": null, "createdAt": "2026-06-01T09:00:00.000Z", - "decidedAt": "2026-06-01T10:00:00.000Z", + "decidedAt": null, "groupName": "Engineering", "requester": { "id": "user-123", @@ -14901,14 +14911,12 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/organizations/{organizationId}/access-requests/settings": { + }, "get": { - "operationId": "getOrganizationAccessRequestSettings", - "summary": "Get organization access request settings", - "description": "Get whether the organization allows new access requests and approvals. This preference does not enable features unavailable in the deployment or subscription. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "access_requests.get_settings", + "operationId": "listOrganizationAccessRequests", + "summary": "List organization access requests", + "description": "List requests across the organization for administrator review. Includes requests from organization members and external workspace collaborators; history remains available while requests are disabled. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "access_requests.list_organization", "x-oauth-scope": "api:read", "tags": ["Access Requests"], "security": [ @@ -14930,16 +14938,87 @@ "minLength": 1, "description": "Organization that owns the access requests." } - } - ], - "responses": { - "200": { - "description": "Whether new requests and approvals are allowed.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { + }, + { + "name": "status", + "in": "query", + "required": false, + "description": "Filter by request status; omit to include all statuses.", + "schema": { + "description": "Filter by request status; omit to include all statuses.", + "type": "string", + "enum": ["pending", "fulfilled", "declined", "cancelled", "closed"] + } + }, + { + "name": "sortBy", + "in": "query", + "required": false, + "description": "Field used to sort the result.", + "schema": { + "default": "createdAt", + "description": "Field used to sort the result.", + "type": "string", + "enum": ["createdAt", "targetLabel"] + } + }, + { + "name": "sortOrder", + "in": "query", + "required": false, + "description": "Sort direction.", + "schema": { + "default": "desc", + "description": "Sort direction.", + "type": "string", + "enum": ["asc", "desc"] + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "schema": { + "default": 50, + "description": "Maximum access requests to return per page. Must be a whole number from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "schema": { + "description": "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.", + "type": "string", + "minLength": 1 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Case-insensitive substring match against the target label or requester name or email.", + "schema": { + "description": "Case-insensitive substring match against the target label or requester name or email.", + "type": "string", + "minLength": 1, + "maxLength": 200 + } + } + ], + "responses": { + "200": { + "description": "A page of requests across the organization for Admin review.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { "$ref": "#/components/headers/X-RateLimit-Remaining" }, "X-RateLimit-Reset": { @@ -14949,15 +15028,36 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GetOrganizationAccessRequestSettingsResponse" + "$ref": "#/components/schemas/ListOrganizationAccessRequestsResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { - "data": { - "allowRequests": true - } + "data": [ + { + "id": "request-123", + "organizationId": "org-123", + "workspaceId": "workspace-123", + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "targetLabel": "Tables", + "reason": "Maintain team data", + "status": "pending", + "decisionReason": null, + "createdAt": "2026-06-01T09:00:00.000Z", + "decidedAt": null, + "groupName": "Engineering", + "requester": { + "id": "user-123", + "name": "Alex Example", + "email": "alex@example.com" + } + } + ], + "nextCursor": null } } } @@ -14989,12 +15089,14 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - }, - "patch": { - "operationId": "updateOrganizationAccessRequestSettings", - "summary": "Update organization access request settings", - "description": "Allow or pause new access requests and approvals. Pausing preserves history, cancellation, and decline, and does not revoke previously granted access. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "access_requests.update_settings", + } + }, + "/api/v2/organizations/{organizationId}/access-requests/{requestId}/cancel": { + "post": { + "operationId": "cancelOrganizationAccessRequest", + "summary": "Cancel organization access request", + "description": "Cancel the acting user’s pending request in this scope, including an organization-wide member credit-limit request. Already resolved requests are returned unchanged. Cancellation remains available while requests are disabled. Requires organization membership. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "access_requests.cancel", "x-oauth-scope": "api:write", "tags": ["Access Requests"], "security": [ @@ -15016,30 +15118,23 @@ "minLength": 1, "description": "Organization that owns the access requests." } - } - ], - "requestBody": { - "required": true, - "description": "Whether new requests and approvals are allowed.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateOrganizationAccessRequestSettingsBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "allowRequests": false - } - } - } + }, + { + "name": "requestId", + "in": "path", + "required": true, + "description": "Access request identifier.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Access request identifier." } } - }, + ], "responses": { "200": { - "description": "The saved setting for new requests and approvals.", + "description": "The cancelled request, or the unchanged request if already resolved.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -15054,14 +15149,32 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateOrganizationAccessRequestSettingsResponse" + "$ref": "#/components/schemas/CancelOrganizationAccessRequestResponse" }, "examples": { "example1": { "summary": "Response example 1", "value": { "data": { - "allowRequests": false + "id": "request-123", + "organizationId": "org-123", + "workspaceId": null, + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "targetLabel": "Tables", + "reason": "Maintain team data", + "status": "cancelled", + "decisionReason": null, + "createdAt": "2026-06-01T09:00:00.000Z", + "decidedAt": "2026-06-01T10:00:00.000Z", + "groupName": "Engineering", + "requester": { + "id": "user-123", + "name": "Alex Example", + "email": "alex@example.com" + } } } } @@ -15084,12 +15197,6 @@ "409": { "$ref": "#/components/responses/Conflict" }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -15101,40 +15208,527 @@ } } } - } - }, - "components": { - "securitySchemes": { - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-Key", - "description": "Send a personal or workspace API key in `X-API-Key`. See [key types and access](https://docs.sim.ai/api-reference/authentication#key-types); operations that reject workspace keys say so in their description." - }, - "oauthBearer": { - "type": "oauth2", - "description": "Send a Sim OAuth access token in `Authorization: Bearer`. See [OAuth authentication and scopes](https://docs.sim.ai/api-reference/authentication#oauth-access-tokens).", - "flows": { - "authorizationCode": { - "authorizationUrl": "https://www.sim.ai/api/auth/oauth2/authorize", - "tokenUrl": "https://www.sim.ai/api/auth/oauth2/token", - "refreshUrl": "https://www.sim.ai/api/auth/oauth2/token", - "scopes": { - "api:read": "Read your workspaces, workflows, files, tables, and logs", - "api:write": "Read, create, change, run, and delete resources in your workspaces", - "offline_access": "Stay signed in without asking again" + }, + "/api/v2/organizations/{organizationId}/access-requests/{requestId}/preview": { + "get": { + "operationId": "previewOrganizationAccessRequest", + "summary": "Preview organization access request", + "description": "Preview the current permission changes, affected group and audience, or member credit cap. Review `canApply`, `changes`, `impact`, and `fingerprint` before resolving. Permission changes affect the entire governing group, not only the requester. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "access_requests.preview", + "x-oauth-scope": "api:read", + "tags": ["Access Requests"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:read"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization that owns the access requests.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Organization that owns the access requests." + } + }, + { + "name": "requestId", + "in": "path", + "required": true, + "description": "Access request identifier.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Access request identifier." } } - } - } - }, - "headers": { - "X-RateLimit-Limit": { - "description": "Maximum requests allowed in the current window.", - "schema": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, + ], + "responses": { + "200": { + "description": "The proposed group or credit-cap change, affected audience, and fingerprint.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreviewOrganizationAccessRequestResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "resolutionKind": "permission", + "request": { + "id": "request-123", + "organizationId": "org-123", + "workspaceId": "workspace-123", + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "targetLabel": "Tables", + "reason": "Maintain team data", + "status": "pending", + "decisionReason": null, + "createdAt": "2026-06-01T09:00:00.000Z", + "decidedAt": null, + "groupName": "Engineering", + "requester": { + "id": "user-123", + "name": "Alex Example", + "email": "alex@example.com" + } + }, + "group": { + "id": "group-123", + "name": "Engineering" + }, + "changes": [ + { + "configKey": "hideTablesTab", + "label": "Tables", + "before": true, + "after": false + } + ], + "impact": { + "memberCount": 2, + "workspaceCount": 1, + "workspaceNames": ["Engineering"], + "truncated": false + }, + "fingerprint": "current-preview-fingerprint", + "canApply": true, + "unavailableReason": null, + "currentLimitCredits": null, + "newLimitCredits": null + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/organizations/{organizationId}/access-requests/{requestId}/resolve": { + "post": { + "operationId": "resolveOrganizationAccessRequest", + "summary": "Resolve organization access request", + "description": "Apply a reviewed request or decline it with a reason. Applying requires the preview fingerprint; changed policy or membership returns a conflict. Credit requests also require a higher `newLimitCredits`. Already resolved requests are returned unchanged. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "access_requests.resolve", + "x-oauth-scope": "api:write", + "tags": ["Access Requests"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization that owns the access requests.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Organization that owns the access requests." + } + }, + { + "name": "requestId", + "in": "path", + "required": true, + "description": "Access request identifier.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Access request identifier." + } + } + ], + "requestBody": { + "required": true, + "description": "Apply the reviewed fingerprint, with a higher credit cap when applicable, or decline with a reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResolveOrganizationAccessRequestBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "action": "apply", + "expectedFingerprint": "current-preview-fingerprint" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The applied or declined request, or its unchanged resolved state.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResolveOrganizationAccessRequestResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "id": "request-123", + "organizationId": "org-123", + "workspaceId": "workspace-123", + "target": { + "kind": "feature", + "configKey": "hideTablesTab" + }, + "targetLabel": "Tables", + "reason": "Maintain team data", + "status": "fulfilled", + "decisionReason": null, + "createdAt": "2026-06-01T09:00:00.000Z", + "decidedAt": "2026-06-01T10:00:00.000Z", + "groupName": "Engineering", + "requester": { + "id": "user-123", + "name": "Alex Example", + "email": "alex@example.com" + } + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/organizations/{organizationId}/access-requests/settings": { + "get": { + "operationId": "getOrganizationAccessRequestSettings", + "summary": "Get organization access request settings", + "description": "Get whether the organization allows new access requests and approvals. This preference does not enable features unavailable in the deployment or subscription. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "access_requests.get_settings", + "x-oauth-scope": "api:read", + "tags": ["Access Requests"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:read"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization that owns the access requests.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Organization that owns the access requests." + } + } + ], + "responses": { + "200": { + "description": "Whether new requests and approvals are allowed.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetOrganizationAccessRequestSettingsResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "allowRequests": true + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + }, + "patch": { + "operationId": "updateOrganizationAccessRequestSettings", + "summary": "Update organization access request settings", + "description": "Allow or pause new access requests and approvals. Pausing preserves history, cancellation, and decline, and does not revoke previously granted access. Requires organization Admin access. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "access_requests.update_settings", + "x-oauth-scope": "api:write", + "tags": ["Access Requests"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "organizationId", + "in": "path", + "required": true, + "description": "Organization that owns the access requests.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Organization that owns the access requests." + } + } + ], + "requestBody": { + "required": true, + "description": "Whether new requests and approvals are allowed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOrganizationAccessRequestSettingsBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "allowRequests": false + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The saved setting for new requests and approvals.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOrganizationAccessRequestSettingsResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "allowRequests": false + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + } + }, + "components": { + "securitySchemes": { + "apiKey": { + "type": "apiKey", + "in": "header", + "name": "X-API-Key", + "description": "Send a personal or workspace API key in `X-API-Key`. See [key types and access](https://docs.sim.ai/api-reference/authentication#key-types); operations that reject workspace keys say so in their description." + }, + "oauthBearer": { + "type": "oauth2", + "description": "Send a Sim OAuth access token in `Authorization: Bearer`. See [OAuth authentication and scopes](https://docs.sim.ai/api-reference/authentication#oauth-access-tokens).", + "flows": { + "authorizationCode": { + "authorizationUrl": "https://www.sim.ai/api/auth/oauth2/authorize", + "tokenUrl": "https://www.sim.ai/api/auth/oauth2/token", + "refreshUrl": "https://www.sim.ai/api/auth/oauth2/token", + "scopes": { + "api:read": "Read your workspaces, workflows, files, tables, and logs", + "api:write": "Read, create, change, run, and delete resources in your workspaces", + "offline_access": "Stay signed in without asking again" + } + } + } + } + }, + "headers": { + "X-RateLimit-Limit": { + "description": "Maximum requests allowed in the current window.", + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, "title": "Rate limit", "description": "Maximum requests allowed in the current window." } @@ -23838,86 +24432,372 @@ "additionalProperties": false, "description": "Patch of group settings. Omitted keys remain unchanged; each supplied array replaces that entire list." }, - "isDefault": { - "description": "Whether the group is the organization default. Only one group can be the default.", - "type": "boolean" + "isDefault": { + "description": "Whether the group is the organization default. Only one group can be the default.", + "type": "boolean" + }, + "workspaceIds": { + "description": "Workspace identifiers for a non-default group. Required on creation; an empty update makes the group inactive.", + "maxItems": 500, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false, + "title": "Update permission group request", + "description": "Group fields and restriction keys to change; supplied lists replace their contents.", + "examples": [ + { + "description": "Restricted workspace access" + } + ] + }, + "V2PermissionGroupDeletion": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Deleted permission group identifier." + }, + "deleted": { + "type": "boolean", + "const": true, + "description": "Whether the group was permanently deleted." + } + }, + "required": ["id", "deleted"], + "additionalProperties": false, + "title": "Permission group deletion", + "description": "Acknowledges permanent group deletion." + }, + "DeletePermissionGroupResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2PermissionGroupDeletion" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Delete permission group response", + "description": "Acknowledgement that the group and its assignments were deleted.", + "examples": [ + { + "data": { + "id": "group-123", + "deleted": true + } + } + ] + }, + "V2PermissionGroupMember": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Membership assignment identifier." + }, + "userId": { + "type": "string", + "description": "Organization member assigned to the group." + }, + "assignedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "When the member was assigned." + }, + "userName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Member display name." + }, + "userEmail": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Member email address." + }, + "userImage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Member avatar URL." + } + }, + "required": ["id", "userId", "assignedAt", "userName", "userEmail", "userImage"], + "additionalProperties": false, + "title": "Permission group member", + "description": "An explicit permission-group membership assignment." + }, + "ListPermissionGroupMembersResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/V2PermissionGroupMember" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List permission group members response", + "description": "A page of explicit group membership assignments.", + "examples": [ + { + "data": [ + { + "id": "assignment-123", + "userId": "user-123", + "assignedAt": "2026-06-01T09:00:00.000Z", + "userName": "Example Member", + "userEmail": "member@example.com", + "userImage": null + } + ], + "nextCursor": null + } + ] + }, + "V2PermissionGroupAssignment": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Membership assignment identifier." + }, + "permissionGroupId": { + "type": "string", + "description": "Group receiving the member." }, - "workspaceIds": { - "description": "Workspace identifiers for a non-default group. Required on creation; an empty update makes the group inactive.", - "maxItems": 500, - "type": "array", - "items": { - "type": "string", - "minLength": 1 + "organizationId": { + "type": "string", + "description": "Organization that owns the group." + }, + "userId": { + "type": "string", + "description": "User assigned to the group." + }, + "assignedBy": { + "type": "string", + "description": "User who made the assignment." + }, + "assignedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "When the assignment was created." + } + }, + "required": [ + "id", + "permissionGroupId", + "organizationId", + "userId", + "assignedBy", + "assignedAt" + ], + "additionalProperties": false, + "title": "Permission group assignment", + "description": "The newly created membership assignment." + }, + "AddPermissionGroupMemberResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2PermissionGroupAssignment" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Add permission group member response", + "description": "The new explicit membership assignment.", + "examples": [ + { + "data": { + "id": "assignment-123", + "permissionGroupId": "group-123", + "organizationId": "org-123", + "userId": "user-123", + "assignedBy": "admin-123", + "assignedAt": "2026-06-01T09:00:00.000Z" } } + ] + }, + "AddPermissionGroupMemberRequest": { + "type": "object", + "properties": { + "userId": { + "type": "string", + "minLength": 1, + "description": "Existing organization member to add." + } }, + "required": ["userId"], "additionalProperties": false, - "title": "Update permission group request", - "description": "Group fields and restriction keys to change; supplied lists replace their contents.", + "title": "Add permission group member request", + "description": "The organization member to assign to this group.", "examples": [ { - "description": "Restricted workspace access" + "userId": "user-123" } ] }, - "V2PermissionGroupDeletion": { + "V2PermissionGroupMemberDeletion": { "type": "object", "properties": { - "id": { + "userId": { "type": "string", - "description": "Deleted permission group identifier." + "description": "User whose membership assignment was removed." }, "deleted": { "type": "boolean", "const": true, - "description": "Whether the group was permanently deleted." + "description": "Whether the assignment was removed." } }, - "required": ["id", "deleted"], + "required": ["userId", "deleted"], "additionalProperties": false, - "title": "Permission group deletion", - "description": "Acknowledges permanent group deletion." + "title": "Permission group member deletion", + "description": "Acknowledges membership removal." }, - "DeletePermissionGroupResponse": { + "RemovePermissionGroupMemberResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/V2PermissionGroupDeletion" + "$ref": "#/components/schemas/V2PermissionGroupMemberDeletion" } }, "required": ["data"], "additionalProperties": false, - "title": "Delete permission group response", - "description": "Acknowledgement that the group and its assignments were deleted.", + "title": "Remove permission group member response", + "description": "Acknowledgement that the explicit assignment was removed.", "examples": [ { "data": { - "id": "group-123", + "userId": "user-123", "deleted": true } } ] }, - "V2PermissionGroupMember": { + "V2PermissionGroupBulkAdd": { + "type": "object", + "properties": { + "added": { + "type": "number", + "description": "Number of members added." + }, + "skipped": { + "type": "number", + "description": "Number of selected organization members already in the group." + } + }, + "required": ["added", "skipped"], + "additionalProperties": false, + "title": "Permission group bulk addition", + "description": "Counts of added and already assigned organization members." + }, + "BulkAddPermissionGroupMembersResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2PermissionGroupBulkAdd" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Bulk add permission group members response", + "description": "Counts of added members and existing assignments skipped.", + "examples": [ + { + "data": { + "added": 1, + "skipped": 0 + } + } + ] + }, + "BulkAddPermissionGroupMembersRequest": { + "type": "object", + "properties": { + "userIds": { + "description": "Organization member identifiers. Existing group members are skipped; users outside the organization are ignored.", + "minItems": 1, + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "addAllOrganizationMembers": { + "description": "Add every current organization member in bounded batches within one transaction. Cannot be combined with userIds.", + "type": "boolean" + } + }, + "additionalProperties": false, + "title": "Bulk add permission group members request", + "description": "Selected organization members or the entire current organization roster.", + "examples": [ + { + "userIds": ["user-123"] + } + ] + }, + "V2Organization": { "type": "object", "properties": { "id": { "type": "string", - "description": "Membership assignment identifier." + "description": "Organization identifier." }, - "userId": { + "name": { "type": "string", - "description": "Organization member assigned to the group." + "description": "Organization display name." }, - "assignedAt": { + "slug": { "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the member was assigned." + "description": "Organization slug." }, - "userName": { + "logo": { "anyOf": [ { "type": "string" @@ -23926,9 +24806,36 @@ "type": "null" } ], - "description": "Member display name." + "description": "Organization logo URL, or null when unset." }, - "userEmail": { + "role": { + "type": "string", + "enum": ["owner", "admin", "member"], + "description": "The acting user’s role in this organization." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "When the organization was created." + } + }, + "required": ["id", "name", "slug", "logo", "role", "createdAt"], + "additionalProperties": false, + "title": "Organization", + "description": "An organization the acting user belongs to." + }, + "ListOrganizationsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/V2Organization" + }, + "description": "Items in the current page." + }, + "nextCursor": { "anyOf": [ { "type": "string" @@ -23937,32 +24844,78 @@ "type": "null" } ], - "description": "Member email address." + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List organizations response", + "description": "A page of organizations and the acting user’s role in each.", + "examples": [ + { + "data": [ + { + "id": "org-123", + "name": "Example Organization", + "slug": "example", + "logo": null, + "role": "admin", + "createdAt": "2026-06-01T09:00:00.000Z" + } + ], + "nextCursor": null + } + ] + }, + "GetOrganizationResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2Organization" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get organization response", + "description": "Organization metadata and the acting user’s role.", + "examples": [ + { + "data": { + "id": "org-123", + "name": "Example Organization", + "slug": "example", + "logo": null, + "role": "admin", + "createdAt": "2026-06-01T09:00:00.000Z" + } + } + ] + }, + "V2OrganizationWorkspace": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Workspace identifier." }, - "userImage": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Member avatar URL." + "name": { + "type": "string", + "description": "Workspace display name." } }, - "required": ["id", "userId", "assignedAt", "userName", "userEmail", "userImage"], + "required": ["id", "name"], "additionalProperties": false, - "title": "Permission group member", - "description": "An explicit permission-group membership assignment." + "title": "Organization workspace", + "description": "A workspace owned by the organization." }, - "ListPermissionGroupMembersResponse": { + "ListOrganizationWorkspacesResponse": { "type": "object", "properties": { "data": { "type": "array", "items": { - "$ref": "#/components/schemas/V2PermissionGroupMember" + "$ref": "#/components/schemas/V2OrganizationWorkspace" }, "description": "Items in the current page." }, @@ -23980,140 +24933,166 @@ }, "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "List permission group members response", - "description": "A page of explicit group membership assignments.", + "title": "List organization workspaces response", + "description": "A page of active workspaces owned by the organization.", "examples": [ { "data": [ { - "id": "assignment-123", - "userId": "user-123", - "assignedAt": "2026-06-01T09:00:00.000Z", - "userName": "Example Member", - "userEmail": "member@example.com", - "userImage": null + "id": "workspace-123", + "name": "Engineering" } ], "nextCursor": null } ] }, - "V2PermissionGroupAssignment": { + "V2OrganizationMember": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "Membership assignment identifier." - }, - "permissionGroupId": { + "userId": { "type": "string", - "description": "Group receiving the member." + "description": "User identifier; use this identifier to update or remove the member." }, - "organizationId": { + "name": { "type": "string", - "description": "Organization that owns the group." + "description": "Member display name." }, - "userId": { + "email": { "type": "string", - "description": "User assigned to the group." + "description": "Member email address." }, - "assignedBy": { + "role": { "type": "string", - "description": "User who made the assignment." + "enum": ["owner", "admin", "member"], + "description": "Organization role; separate from workspace permissions." }, - "assignedAt": { + "joinedAt": { "type": "string", "format": "date-time", "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the assignment was created." + "description": "When the user joined the organization." } }, - "required": [ - "id", - "permissionGroupId", - "organizationId", - "userId", - "assignedBy", - "assignedAt" - ], + "required": ["userId", "name", "email", "role", "joinedAt"], "additionalProperties": false, - "title": "Permission group assignment", - "description": "The newly created membership assignment." + "title": "Organization member", + "description": "An organization membership identified by user ID." }, - "AddPermissionGroupMemberResponse": { + "ListOrganizationMembersResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/V2OrganizationMember" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List organization members response", + "description": "A page of organization members and their organization roles.", + "examples": [ + { + "data": [ + { + "userId": "user-123", + "name": "Example Member", + "email": "member@example.com", + "role": "member", + "joinedAt": "2026-06-01T09:00:00.000Z" + } + ], + "nextCursor": null + } + ] + }, + "UpdateOrganizationMemberResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/V2PermissionGroupAssignment" + "$ref": "#/components/schemas/V2OrganizationMember" } }, "required": ["data"], "additionalProperties": false, - "title": "Add permission group member response", - "description": "The new explicit membership assignment.", + "title": "Update organization member response", + "description": "The member with the updated organization role.", "examples": [ { "data": { - "id": "assignment-123", - "permissionGroupId": "group-123", - "organizationId": "org-123", "userId": "user-123", - "assignedBy": "admin-123", - "assignedAt": "2026-06-01T09:00:00.000Z" + "name": "Example Member", + "email": "member@example.com", + "role": "admin", + "joinedAt": "2026-06-01T09:00:00.000Z" } } ] }, - "AddPermissionGroupMemberRequest": { + "UpdateOrganizationMemberBody": { "type": "object", "properties": { - "userId": { + "role": { "type": "string", - "minLength": 1, - "description": "Existing organization member to add." + "enum": ["member", "admin"], + "description": "New organization role. Ownership transfers use a separate operation." } }, - "required": ["userId"], + "required": ["role"], "additionalProperties": false, - "title": "Add permission group member request", - "description": "The organization member to assign to this group.", + "title": "Update organization member body", + "description": "The new organization role for this member.", "examples": [ { - "userId": "user-123" + "role": "admin" } ] }, - "V2PermissionGroupMemberDeletion": { + "V2OrganizationMemberDeletion": { "type": "object", "properties": { "userId": { "type": "string", - "description": "User whose membership assignment was removed." + "description": "User removed from the organization." }, "deleted": { "type": "boolean", "const": true, - "description": "Whether the assignment was removed." + "description": "Whether membership and organization workspace access were removed." } }, "required": ["userId", "deleted"], "additionalProperties": false, - "title": "Permission group member deletion", - "description": "Acknowledges membership removal." + "title": "Organization member removal", + "description": "Acknowledges removal of an organization member." }, - "RemovePermissionGroupMemberResponse": { + "RemoveOrganizationMemberResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/V2PermissionGroupMemberDeletion" + "$ref": "#/components/schemas/V2OrganizationMemberDeletion" } }, "required": ["data"], "additionalProperties": false, - "title": "Remove permission group member response", - "description": "Acknowledgement that the explicit assignment was removed.", + "title": "Remove organization member response", + "description": "Acknowledgement that organization access was removed.", "examples": [ { "data": { @@ -24123,121 +25102,76 @@ } ] }, - "V2PermissionGroupBulkAdd": { - "type": "object", - "properties": { - "added": { - "type": "number", - "description": "Number of members added." - }, - "skipped": { - "type": "number", - "description": "Number of selected organization members already in the group." - } - }, - "required": ["added", "skipped"], - "additionalProperties": false, - "title": "Permission group bulk addition", - "description": "Counts of added and already assigned organization members." - }, - "BulkAddPermissionGroupMembersResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2PermissionGroupBulkAdd" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Bulk add permission group members response", - "description": "Counts of added members and existing assignments skipped.", - "examples": [ - { - "data": { - "added": 1, - "skipped": 0 - } - } - ] - }, - "BulkAddPermissionGroupMembersRequest": { - "type": "object", - "properties": { - "userIds": { - "description": "Organization member identifiers. Existing group members are skipped; users outside the organization are ignored.", - "minItems": 1, - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "addAllOrganizationMembers": { - "description": "Add every current organization member in bounded batches within one transaction. Cannot be combined with userIds.", - "type": "boolean" - } - }, - "additionalProperties": false, - "title": "Bulk add permission group members request", - "description": "Selected organization members or the entire current organization roster.", - "examples": [ - { - "userIds": ["user-123"] - } - ] - }, - "V2Organization": { + "V2OrganizationInvitation": { "type": "object", "properties": { "id": { "type": "string", - "description": "Organization identifier." + "description": "Invitation identifier." + }, + "organizationId": { + "type": "string", + "description": "Organization that owns the invitation." + }, + "email": { + "type": "string", + "description": "Email address of the invitee." }, - "name": { + "role": { "type": "string", - "description": "Organization display name." + "enum": ["member", "admin"], + "description": "Organization role offered to an internal invitee." }, - "slug": { + "kind": { "type": "string", - "description": "Organization slug." + "enum": ["organization", "workspace"], + "description": "Whether the invitation originated from organization or workspace administration." }, - "logo": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Organization logo URL, or null when unset." + "membershipIntent": { + "type": "string", + "enum": ["internal", "external"], + "description": "Whether acceptance joins the organization or grants workspace access only." }, - "role": { + "status": { "type": "string", - "enum": ["owner", "admin", "member"], - "description": "The acting user’s role in this organization." + "enum": ["pending", "accepted", "rejected", "cancelled", "expired"], + "description": "Current invitation status; elapsed pending invitations are reported as expired." }, "createdAt": { "type": "string", "format": "date-time", "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the organization was created." + "description": "When the invitation was created." + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "When the invitation expires." } }, - "required": ["id", "name", "slug", "logo", "role", "createdAt"], + "required": [ + "id", + "organizationId", + "email", + "role", + "kind", + "membershipIntent", + "status", + "createdAt", + "expiresAt" + ], "additionalProperties": false, - "title": "Organization", - "description": "An organization the acting user belongs to." + "title": "Organization invitation", + "description": "Invitation metadata without its acceptance token." }, - "ListOrganizationsResponse": { + "ListOrganizationInvitationsResponse": { "type": "object", "properties": { "data": { "type": "array", "items": { - "$ref": "#/components/schemas/V2Organization" + "$ref": "#/components/schemas/V2OrganizationInvitation" }, "description": "Items in the current page." }, @@ -24255,50 +25189,113 @@ }, "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "List organizations response", - "description": "A page of organizations and the acting user’s role in each.", + "title": "List organization invitations response", + "description": "A page of invitations, including their current status.", "examples": [ { "data": [ { - "id": "org-123", - "name": "Example Organization", - "slug": "example", - "logo": null, - "role": "admin", - "createdAt": "2026-06-01T09:00:00.000Z" + "id": "invitation-123", + "organizationId": "org-123", + "email": "member@example.com", + "role": "member", + "kind": "organization", + "membershipIntent": "internal", + "status": "pending", + "createdAt": "2026-06-01T09:00:00.000Z", + "expiresAt": "2026-06-08T09:00:00.000Z" } ], "nextCursor": null } ] }, - "GetOrganizationResponse": { + "CreateOrganizationInvitationResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/V2Organization" + "$ref": "#/components/schemas/V2OrganizationInvitation" } }, "required": ["data"], "additionalProperties": false, - "title": "Get organization response", - "description": "Organization metadata and the acting user’s role.", + "title": "Create organization invitation response", + "description": "The pending organization invitation.", "examples": [ { "data": { - "id": "org-123", - "name": "Example Organization", - "slug": "example", - "logo": null, - "role": "admin", - "createdAt": "2026-06-01T09:00:00.000Z" + "id": "invitation-123", + "organizationId": "org-123", + "email": "member@example.com", + "role": "member", + "kind": "organization", + "membershipIntent": "internal", + "status": "pending", + "createdAt": "2026-06-01T09:00:00.000Z", + "expiresAt": "2026-06-08T09:00:00.000Z" } } ] }, - "V2OrganizationWorkspace": { + "CreateOrganizationInvitationBody": { + "type": "object", + "properties": { + "email": { + "type": "string", + "minLength": 1, + "maxLength": 254, + "format": "email", + "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$", + "description": "Email address of the person to invite." + }, + "role": { + "default": "member", + "description": "Organization role to offer. Defaults to member; grants no workspace-specific permissions.", + "type": "string", + "enum": ["member", "admin"] + } + }, + "required": ["email"], + "additionalProperties": false, + "title": "Create organization invitation body", + "description": "Invitee email and organization role to offer.", + "examples": [ + { + "email": "member@example.com", + "role": "member" + } + ] + }, + "GetOrganizationInvitationResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2OrganizationInvitation" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get organization invitation response", + "description": "Invitation metadata without its acceptance token.", + "examples": [ + { + "data": { + "id": "invitation-123", + "organizationId": "org-123", + "email": "member@example.com", + "role": "member", + "kind": "organization", + "membershipIntent": "internal", + "status": "pending", + "createdAt": "2026-06-01T09:00:00.000Z", + "expiresAt": "2026-06-08T09:00:00.000Z" + } + } + ] + }, + "V2OrganizationInvitationWorkspace": { "type": "object", "properties": { "id": { @@ -24308,20 +25305,38 @@ "name": { "type": "string", "description": "Workspace display name." + }, + "permission": { + "type": "string", + "enum": ["admin", "write", "read"], + "description": "Workspace permission offered by the invitation." + }, + "archivedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + { + "type": "null" + } + ], + "description": "When the workspace was archived, or null while active." } }, - "required": ["id", "name"], + "required": ["id", "name", "permission", "archivedAt"], "additionalProperties": false, - "title": "Organization workspace", - "description": "A workspace owned by the organization." + "title": "Organization invitation workspace", + "description": "A workspace grant attached to an invitation, separate from organization membership." }, - "ListOrganizationWorkspacesResponse": { + "ListOrganizationInvitationWorkspacesResponse": { "type": "object", "properties": { "data": { "type": "array", "items": { - "$ref": "#/components/schemas/V2OrganizationWorkspace" + "$ref": "#/components/schemas/V2OrganizationInvitationWorkspace" }, "description": "Items in the current page." }, @@ -24339,410 +25354,621 @@ }, "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "List organization workspaces response", - "description": "A page of active workspaces owned by the organization.", + "title": "List organization invitation workspaces response", + "description": "Workspace grants retained on an invitation.", "examples": [ { "data": [ { "id": "workspace-123", - "name": "Engineering" + "name": "Engineering", + "permission": "write", + "archivedAt": null } ], "nextCursor": null } ] }, - "V2OrganizationMember": { + "ResendOrganizationInvitationResponse": { "type": "object", "properties": { - "userId": { - "type": "string", - "description": "User identifier; use this identifier to update or remove the member." - }, - "name": { - "type": "string", - "description": "Member display name." - }, - "email": { - "type": "string", - "description": "Member email address." - }, - "role": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/V2OrganizationInvitation" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Resend organization invitation response", + "description": "The pending invitation with its renewed expiry.", + "examples": [ + { + "data": { + "id": "invitation-123", + "organizationId": "org-123", + "email": "member@example.com", + "role": "member", + "kind": "organization", + "membershipIntent": "internal", + "status": "pending", + "createdAt": "2026-06-01T09:00:00.000Z", + "expiresAt": "2026-06-08T09:00:00.000Z" + } + } + ] + }, + "ResendOrganizationInvitationBody": { + "default": {}, + "title": "Resend organization invitation body", + "description": "An empty JSON object; the pending invitation supplies the recipient and role.", + "examples": [{}], + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "V2OrganizationInvitationRevocation": { + "type": "object", + "properties": { + "id": { "type": "string", - "enum": ["owner", "admin", "member"], - "description": "Organization role; separate from workspace permissions." + "description": "Revoked invitation identifier." }, - "joinedAt": { + "status": { "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the user joined the organization." + "const": "cancelled", + "description": "Revocation cancels the invitation and prevents acceptance." } }, - "required": ["userId", "name", "email", "role", "joinedAt"], + "required": ["id", "status"], "additionalProperties": false, - "title": "Organization member", - "description": "An organization membership identified by user ID." + "title": "Organization invitation revocation", + "description": "Acknowledges cancellation of a pending invitation." }, - "ListOrganizationMembersResponse": { + "RevokeOrganizationInvitationResponse": { "type": "object", "properties": { "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/V2OrganizationMember" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + "description": "Response data.", + "$ref": "#/components/schemas/V2OrganizationInvitationRevocation" } }, - "required": ["data", "nextCursor"], + "required": ["data"], "additionalProperties": false, - "title": "List organization members response", - "description": "A page of organization members and their organization roles.", + "title": "Revoke organization invitation response", + "description": "Acknowledgement that the pending invitation was cancelled.", "examples": [ { - "data": [ - { - "userId": "user-123", - "name": "Example Member", - "email": "member@example.com", - "role": "member", - "joinedAt": "2026-06-01T09:00:00.000Z" - } - ], - "nextCursor": null + "data": { + "id": "invitation-123", + "status": "cancelled" + } } ] }, - "UpdateOrganizationMemberResponse": { + "SearchSourcePermissionRevision": { + "type": "object", + "properties": { + "revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current permission revision." + } + }, + "required": ["revision"], + "additionalProperties": false, + "title": "Search source permission revision", + "description": "Revision of this source’s permission grants." + }, + "SearchSourcePermissionResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationMember" + "$ref": "#/components/schemas/SearchSourcePermissionRevision" } }, "required": ["data"], "additionalProperties": false, - "title": "Update organization member response", - "description": "The member with the updated organization role.", + "title": "Search source permission response", + "description": "Current revision of the source permission grants.", "examples": [ { "data": { - "userId": "user-123", - "name": "Example Member", - "email": "member@example.com", - "role": "admin", - "joinedAt": "2026-06-01T09:00:00.000Z" + "revision": 3 } } ] }, - "UpdateOrganizationMemberBody": { + "ReplaceSearchSourcePermissionsBody": { "type": "object", "properties": { - "role": { - "type": "string", - "enum": ["member", "admin"], - "description": "New organization role. Ownership transfers use a separate operation." + "expectedRevision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Permission revision read before exporting the grants." + }, + "permissions": { + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Provider of the configured Search source." + }, + "userMapping": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "CSV filename without path separators." + }, + "content": { + "type": "string", + "minLength": 1, + "description": "UTF-8 CSV contents, up to 8 MiB. Both files travel in one request body limited to 10 MiB after JSON encoding." + } + }, + "required": ["filename", "content"], + "additionalProperties": false, + "description": "GitLab user IDs and their verified Sim email addresses." + }, + "projectPermissions": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "CSV filename without path separators." + }, + "content": { + "type": "string", + "minLength": 1, + "description": "UTF-8 CSV contents, up to 8 MiB. Both files travel in one request body limited to 10 MiB after JSON encoding." + } + }, + "required": ["filename", "content"], + "additionalProperties": false, + "description": "GitLab project paths and the IDs of users granted access." + } + }, + "required": ["provider", "userMapping", "projectPermissions"], + "additionalProperties": false + } + ], + "description": "Complete permission grants in the source provider’s format." } }, - "required": ["role"], + "required": ["expectedRevision", "permissions"], "additionalProperties": false, - "title": "Update organization member body", - "description": "The new organization role for this member.", + "title": "Search source permission grants", + "description": "The expected revision and complete replacement grants for the provider.", "examples": [ { - "role": "admin" + "expectedRevision": 2, + "permissions": { + "provider": "gitlab", + "userMapping": { + "filename": "users.csv", + "content": "user_id,email\n42,reader@example.com\n" + }, + "projectPermissions": { + "filename": "projects.csv", + "content": "project_path,user_id\nteam/project,42\n" + } + } } ] }, - "V2OrganizationMemberDeletion": { + "CreateSourcePermissionImportResponse": { "type": "object", "properties": { - "userId": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Permission import identifier." + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload completion deadline in UTC." + } + }, + "required": ["id", "expiresAt"], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Create source permission import response", + "description": "Permission import result." + }, + "CreateSourcePermissionImportBody": { + "type": "object", + "properties": { + "provider": { "type": "string", - "description": "User removed from the organization." + "const": "gitlab", + "description": "Provider of the configured source." }, - "deleted": { - "type": "boolean", - "const": true, - "description": "Whether membership and organization workspace access were removed." + "expectedRevision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 2147483646, + "description": "Permission revision pinned before exporting the CSVs." + }, + "userMapping": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "pattern": "^[^\\p{Cc}/\\\\]+$", + "description": "CSV filename without path separators." + }, + "parts": { + "type": "integer", + "minimum": 1, + "maximum": 4096, + "description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts." + }, + "rowCount": { + "type": "integer", + "minimum": 1, + "maximum": 500000, + "description": "Physical user records, excluding headers and empty lines. Must be between parts and parts × 5,000." + } + }, + "required": ["filename", "parts", "rowCount"], + "additionalProperties": false, + "description": "Complete user identity mapping." + }, + "projectPermissions": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "pattern": "^[^\\p{Cc}/\\\\]+$", + "description": "CSV filename without path separators." + }, + "parts": { + "type": "integer", + "minimum": 1, + "maximum": 4096, + "description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts." + }, + "rowCount": { + "type": "integer", + "minimum": 1, + "maximum": 5000000, + "description": "Physical data records, excluding headers and empty lines. Must be between parts and parts × 5,000." + } + }, + "required": ["filename", "parts", "rowCount"], + "additionalProperties": false, + "description": "Complete project membership snapshot." } }, - "required": ["userId", "deleted"], + "required": ["provider", "expectedRevision", "userMapping", "projectPermissions"], "additionalProperties": false, - "title": "Organization member removal", - "description": "Acknowledges removal of an organization member." + "description": "Permission import input.", + "title": "Create source permission import" }, - "RemoveOrganizationMemberResponse": { + "PutSourcePermissionImportResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationMemberDeletion" + "type": "object", + "properties": { + "nextPart": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Next expected part number." + } + }, + "required": ["nextPart"], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Remove organization member response", - "description": "Acknowledgement that organization access was removed.", - "examples": [ - { - "data": { - "userId": "user-123", - "deleted": true - } - } - ] + "title": "Upload source permission import part response", + "description": "Permission import result." }, - "V2OrganizationInvitation": { + "PutSourcePermissionImportBody": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "Invitation identifier." - }, - "organizationId": { - "type": "string", - "description": "Organization that owns the invitation." - }, - "email": { - "type": "string", - "description": "Email address of the invitee." - }, - "role": { - "type": "string", - "enum": ["member", "admin"], - "description": "Organization role offered to an internal invitee." - }, - "kind": { - "type": "string", - "enum": ["organization", "workspace"], - "description": "Whether the invitation originated from organization or workspace administration." - }, - "membershipIntent": { - "type": "string", - "enum": ["internal", "external"], - "description": "Whether acceptance joins the organization or grants workspace access only." - }, - "status": { - "type": "string", - "enum": ["pending", "accepted", "rejected", "cancelled", "expired"], - "description": "Current invitation status; elapsed pending invitations are reported as expired." - }, - "createdAt": { + "field": { "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the invitation was created." + "enum": ["userMapping", "projectPermissions"], + "description": "CSV file this part belongs to." }, - "expiresAt": { + "content": { "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "When the invitation expires." + "minLength": 1, + "description": "Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part." } }, - "required": [ - "id", - "organizationId", - "email", - "role", - "kind", - "membershipIntent", - "status", - "createdAt", - "expiresAt" - ], + "required": ["field", "content"], "additionalProperties": false, - "title": "Organization invitation", - "description": "Invitation metadata without its acceptance token." + "title": "Upload source permission import part", + "description": "Permission import input." }, - "ListOrganizationInvitationsResponse": { + "CompleteSourcePermissionImportResponse": { "type": "object", "properties": { "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/V2OrganizationInvitation" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List organization invitations response", - "description": "A page of invitations, including their current status.", - "examples": [ - { - "data": [ - { - "id": "invitation-123", - "organizationId": "org-123", - "email": "member@example.com", - "role": "member", - "kind": "organization", - "membershipIntent": "internal", - "status": "pending", - "createdAt": "2026-06-01T09:00:00.000Z", - "expiresAt": "2026-06-08T09:00:00.000Z" + "type": "object", + "properties": { + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991, + "description": "Permission revision committed by this import." } - ], - "nextCursor": null - } - ] - }, - "CreateOrganizationInvitationResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationInvitation" + }, + "required": ["revision"], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Create organization invitation response", - "description": "The pending organization invitation.", - "examples": [ - { - "data": { - "id": "invitation-123", - "organizationId": "org-123", - "email": "member@example.com", - "role": "member", - "kind": "organization", - "membershipIntent": "internal", - "status": "pending", - "createdAt": "2026-06-01T09:00:00.000Z", - "expiresAt": "2026-06-08T09:00:00.000Z" - } - } - ] + "title": "Complete source permission import response", + "description": "Permission import result." }, - "CreateOrganizationInvitationBody": { + "CompleteSourcePermissionImportBody": { "type": "object", - "properties": { - "email": { - "type": "string", - "minLength": 1, - "maxLength": 254, - "format": "email", - "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$", - "description": "Email address of the person to invite." - }, - "role": { - "default": "member", - "description": "Organization role to offer. Defaults to member; grants no workspace-specific permissions.", - "type": "string", - "enum": ["member", "admin"] - } - }, - "required": ["email"], + "properties": {}, "additionalProperties": false, - "title": "Create organization invitation body", - "description": "Invitee email and organization role to offer.", - "examples": [ - { - "email": "member@example.com", - "role": "member" - } - ] + "title": "Complete source permission import", + "description": "Permission import input." }, - "GetOrganizationInvitationResponse": { + "PrepareSearchSourcesResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationInvitation" + "type": "object", + "properties": { + "ready": { + "type": "boolean", + "const": true, + "description": "Shared Search configuration is ready for source creation." + } + }, + "required": ["ready"], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Get organization invitation response", - "description": "Invitation metadata without its acceptance token.", - "examples": [ - { - "data": { - "id": "invitation-123", - "organizationId": "org-123", - "email": "member@example.com", - "role": "member", - "kind": "organization", - "membershipIntent": "internal", - "status": "pending", - "createdAt": "2026-06-01T09:00:00.000Z", - "expiresAt": "2026-06-08T09:00:00.000Z" - } - } - ] + "title": "Prepare Search sources response", + "description": "Source operation result." }, - "V2OrganizationInvitationWorkspace": { + "PrepareSearchSourcesBody": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "Workspace identifier." - }, - "name": { - "type": "string", - "description": "Workspace display name." - }, - "permission": { + "connectorType": { "type": "string", - "enum": ["admin", "write", "read"], - "description": "Workspace permission offered by the invitation." + "minLength": 1, + "maxLength": 100, + "description": "Registered connector type." }, - "archivedAt": { - "anyOf": [ - { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" - }, - { - "type": "null" - } - ], - "description": "When the workspace was archived, or null while active." + "accessMode": { + "default": "admin", + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." } }, - "required": ["id", "name", "permission", "archivedAt"], + "required": ["connectorType"], "additionalProperties": false, - "title": "Organization invitation workspace", - "description": "A workspace grant attached to an invitation, separate from organization membership." + "title": "Prepare Search sources input", + "description": "Source configuration." }, - "ListOrganizationInvitationWorkspacesResponse": { + "ListSearchSourcesResponse": { "type": "object", "properties": { "data": { "type": "array", "items": { - "$ref": "#/components/schemas/V2OrganizationInvitationWorkspace" + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique connector identifier." + }, + "connectorType": { + "type": "string", + "minLength": 1, + "description": "Registered external source type." + }, + "credentialId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "OAuth credential identifier, or the saved credential an `apiKey` source syncs with (see `auth.savedCredential`); null for unauthenticated sources and for `apiKey` sources that use an inline API key." + }, + "sourceConfig": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." + }, + "description": "Connector-specific source selection and filtering configuration." + }, + "status": { + "type": "string", + "enum": ["active", "paused", "pending", "syncing", "error", "disabled"], + "description": "Current connector state. `pending` means a sync is queued but not yet running." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was created." + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was last updated." + }, + "accessMode": { + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." + }, + "approved": { + "type": "boolean", + "description": "Whether the organization has approved this integration. Approval is independent of source status." + }, + "permissionConfig": { + "anyOf": [ + { + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Permission provider." + }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current revision of the stored permissions." + }, + "userMapping": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "User mapping file summary, or null when not supplied." + }, + "projectPermissions": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Project permission file summary, or null when not supplied." + } + }, + "required": [ + "provider", + "mode", + "revision", + "userMapping", + "projectPermissions" + ], + "additionalProperties": false + } + ] + }, + { + "type": "null" + } + ], + "description": "Permission revision and file summaries, without CSV contents." + } + }, + "required": [ + "id", + "connectorType", + "credentialId", + "sourceConfig", + "status", + "createdAt", + "updatedAt", + "accessMode", + "approved", + "permissionConfig" + ], + "additionalProperties": false }, "description": "Items in the current page." }, @@ -24760,143 +25986,715 @@ }, "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "List organization invitation workspaces response", - "description": "Workspace grants retained on an invitation.", - "examples": [ - { - "data": [ - { - "id": "workspace-123", - "name": "Engineering", - "permission": "write", - "archivedAt": null + "title": "List Search sources response", + "description": "Source operation result." + }, + "GetSearchSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique connector identifier." + }, + "connectorType": { + "type": "string", + "minLength": 1, + "description": "Registered external source type." + }, + "credentialId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "OAuth credential identifier, or the saved credential an `apiKey` source syncs with (see `auth.savedCredential`); null for unauthenticated sources and for `apiKey` sources that use an inline API key." + }, + "sourceConfig": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." + }, + "description": "Connector-specific source selection and filtering configuration." + }, + "status": { + "type": "string", + "enum": ["active", "paused", "pending", "syncing", "error", "disabled"], + "description": "Current connector state. `pending` means a sync is queued but not yet running." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was created." + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was last updated." + }, + "accessMode": { + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." + }, + "approved": { + "type": "boolean", + "description": "Whether the organization has approved this integration. Approval is independent of source status." + }, + "permissionConfig": { + "anyOf": [ + { + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Permission provider." + }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current revision of the stored permissions." + }, + "userMapping": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "User mapping file summary, or null when not supplied." + }, + "projectPermissions": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Project permission file summary, or null when not supplied." + } + }, + "required": [ + "provider", + "mode", + "revision", + "userMapping", + "projectPermissions" + ], + "additionalProperties": false + } + ] + }, + { + "type": "null" + } + ], + "description": "Permission revision and file summaries, without CSV contents." + } + }, + "required": [ + "id", + "connectorType", + "credentialId", + "sourceConfig", + "status", + "createdAt", + "updatedAt", + "accessMode", + "approved", + "permissionConfig" + ], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get Search source response", + "description": "Source operation result." + }, + "CreateSearchSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique connector identifier." + }, + "connectorType": { + "type": "string", + "minLength": 1, + "description": "Registered external source type." + }, + "credentialId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "OAuth credential identifier, or the saved credential an `apiKey` source syncs with (see `auth.savedCredential`); null for unauthenticated sources and for `apiKey` sources that use an inline API key." + }, + "sourceConfig": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." + }, + "description": "Connector-specific source selection and filtering configuration." + }, + "status": { + "type": "string", + "enum": ["active", "paused", "pending", "syncing", "error", "disabled"], + "description": "Current connector state. `pending` means a sync is queued but not yet running." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was created." + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was last updated." + }, + "accessMode": { + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." + }, + "approved": { + "type": "boolean", + "description": "Whether the organization has approved this integration. Approval is independent of source status." + }, + "permissionConfig": { + "anyOf": [ + { + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Permission provider." + }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current revision of the stored permissions." + }, + "userMapping": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "User mapping file summary, or null when not supplied." + }, + "projectPermissions": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Project permission file summary, or null when not supplied." + } + }, + "required": [ + "provider", + "mode", + "revision", + "userMapping", + "projectPermissions" + ], + "additionalProperties": false + } + ] + }, + { + "type": "null" + } + ], + "description": "Permission revision and file summaries, without CSV contents." } + }, + "required": [ + "id", + "connectorType", + "credentialId", + "sourceConfig", + "status", + "createdAt", + "updatedAt", + "accessMode", + "approved", + "permissionConfig" ], - "nextCursor": null - } - ] - }, - "ResendOrganizationInvitationResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationInvitation" + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Resend organization invitation response", - "description": "The pending invitation with its renewed expiry.", - "examples": [ - { - "data": { - "id": "invitation-123", - "organizationId": "org-123", - "email": "member@example.com", - "role": "member", - "kind": "organization", - "membershipIntent": "internal", - "status": "pending", - "createdAt": "2026-06-01T09:00:00.000Z", - "expiresAt": "2026-06-08T09:00:00.000Z" - } - } - ] - }, - "ResendOrganizationInvitationBody": { - "default": {}, - "title": "Resend organization invitation body", - "description": "An empty JSON object; the pending invitation supplies the recipient and role.", - "examples": [{}], - "type": "object", - "properties": {}, - "additionalProperties": false + "title": "Create Search source response", + "description": "Source operation result." }, - "V2OrganizationInvitationRevocation": { + "CreateSearchSourceBody": { "type": "object", "properties": { - "id": { + "connectorType": { "type": "string", - "description": "Revoked invitation identifier." + "minLength": 1, + "maxLength": 100, + "description": "Registered connector type." }, - "status": { + "credentialId": { + "description": "OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors.", "type": "string", - "const": "cancelled", - "description": "Revocation cancels the invitation and prevents acceptance." + "minLength": 1, + "maxLength": 255 + }, + "apiKey": { + "description": "Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference.", + "type": "string", + "minLength": 1, + "maxLength": 10000 + }, + "sourceConfig": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." + }, + "description": "Connector-specific source selection and filtering configuration." + }, + "accessMode": { + "default": "admin", + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." + }, + "permissionConfig": { + "description": "Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation.", + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Provider of the configured Search source." + }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "expectedRevision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current permission revision obtained before generating this snapshot." + }, + "userMapping": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "CSV filename without path separators." + }, + "content": { + "type": "string", + "minLength": 1, + "description": "UTF-8 CSV contents, up to 8 MiB. Both files travel in one request body limited to 10 MiB after JSON encoding." + } + }, + "required": ["filename", "content"], + "additionalProperties": false, + "description": "GitLab user IDs and their verified Sim email addresses." + }, + "projectPermissions": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "CSV filename without path separators." + }, + "content": { + "type": "string", + "minLength": 1, + "description": "UTF-8 CSV contents, up to 8 MiB. Both files travel in one request body limited to 10 MiB after JSON encoding." + } + }, + "required": ["filename", "content"], + "additionalProperties": false, + "description": "GitLab project paths and the IDs of users granted access." + } + }, + "required": ["provider", "mode"], + "additionalProperties": false + } + ] } }, - "required": ["id", "status"], + "required": ["connectorType", "sourceConfig"], "additionalProperties": false, - "title": "Organization invitation revocation", - "description": "Acknowledges cancellation of a pending invitation." + "title": "Create Search source input", + "description": "Source configuration." }, - "RevokeOrganizationInvitationResponse": { + "UpdateSearchSourceResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/V2OrganizationInvitationRevocation" + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique connector identifier." + }, + "connectorType": { + "type": "string", + "minLength": 1, + "description": "Registered external source type." + }, + "credentialId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "OAuth credential identifier, or the saved credential an `apiKey` source syncs with (see `auth.savedCredential`); null for unauthenticated sources and for `apiKey` sources that use an inline API key." + }, + "sourceConfig": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." + }, + "description": "Connector-specific source selection and filtering configuration." + }, + "status": { + "type": "string", + "enum": ["active", "paused", "pending", "syncing", "error", "disabled"], + "description": "Current connector state. `pending` means a sync is queued but not yet running." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was created." + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Time the connector was last updated." + }, + "accessMode": { + "type": "string", + "enum": ["admin", "members"], + "description": "Source-managed permissions (admin), or individually connected member accounts (members)." + }, + "approved": { + "type": "boolean", + "description": "Whether the organization has approved this integration. Approval is independent of source status." + }, + "permissionConfig": { + "anyOf": [ + { + "oneOf": [ + { + "type": "object", + "properties": { + "provider": { + "type": "string", + "const": "gitlab", + "description": "Permission provider." + }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current revision of the stored permissions." + }, + "userMapping": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "User mapping file summary, or null when not supplied." + }, + "projectPermissions": { + "anyOf": [ + { + "type": "object", + "properties": { + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Uploaded CSV filename." + }, + "uploadedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "Upload time in UTC." + }, + "rowCount": { + "type": "integer", + "minimum": 0, + "maximum": 5000000, + "description": "Number of uploaded data records." + } + }, + "required": ["filename", "uploadedAt", "rowCount"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Project permission file summary, or null when not supplied." + } + }, + "required": [ + "provider", + "mode", + "revision", + "userMapping", + "projectPermissions" + ], + "additionalProperties": false + } + ] + }, + { + "type": "null" + } + ], + "description": "Permission revision and file summaries, without CSV contents." + } + }, + "required": [ + "id", + "connectorType", + "credentialId", + "sourceConfig", + "status", + "createdAt", + "updatedAt", + "accessMode", + "approved", + "permissionConfig" + ], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Revoke organization invitation response", - "description": "Acknowledgement that the pending invitation was cancelled.", - "examples": [ - { - "data": { - "id": "invitation-123", - "status": "cancelled" - } - } - ] - }, - "SearchSourcePermissionRevision": { - "type": "object", - "properties": { - "revision": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Current permission revision." - } - }, - "required": ["revision"], - "additionalProperties": false, - "title": "Search source permission revision", - "description": "Revision of this source’s permission grants." + "title": "Update Search source response", + "description": "Source operation result." }, - "SearchSourcePermissionResponse": { + "UpdateSearchSourceBody": { "type": "object", "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/SearchSourcePermissionRevision" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Search source permission response", - "description": "Current revision of the source permission grants.", - "examples": [ - { - "data": { - "revision": 3 + "apiKey": { + "description": "Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token.", + "type": "string", + "minLength": 1, + "maxLength": 10000 + }, + "sourceConfig": { + "description": "Complete replacement source configuration. Read the existing configuration before editing it.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Connector-specific source configuration value." } - } - ] - }, - "ReplaceSearchSourcePermissionsBody": { - "type": "object", - "properties": { - "expectedRevision": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Permission revision read before exporting the grants." }, - "permissions": { + "permissionConfig": { + "description": "Provider-specific permission update, using the current expectedRevision. Omit to retain permissions.", "oneOf": [ { "type": "object", @@ -24906,6 +26704,17 @@ "const": "gitlab", "description": "Provider of the configured Search source." }, + "mode": { + "type": "string", + "enum": ["administrator", "csv"], + "description": "Administrator lookup or externally managed CSV permissions." + }, + "expectedRevision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Current permission revision obtained before generating this snapshot." + }, "userMapping": { "type": "object", "properties": { @@ -24945,35 +26754,22 @@ "description": "GitLab project paths and the IDs of users granted access." } }, - "required": ["provider", "userMapping", "projectPermissions"], + "required": ["provider", "mode"], "additionalProperties": false } - ], - "description": "Complete permission grants in the source provider’s format." + ] + }, + "status": { + "description": "Pause or resume this source without changing its ID or stored permissions.", + "type": "string", + "enum": ["active", "paused"] } }, - "required": ["expectedRevision", "permissions"], "additionalProperties": false, - "title": "Search source permission grants", - "description": "The expected revision and complete replacement grants for the provider.", - "examples": [ - { - "expectedRevision": 2, - "permissions": { - "provider": "gitlab", - "userMapping": { - "filename": "users.csv", - "content": "user_id,email\n42,reader@example.com\n" - }, - "projectPermissions": { - "filename": "projects.csv", - "content": "project_path,user_id\nteam/project,42\n" - } - } - } - ] + "title": "Update Search source input", + "description": "Source configuration." }, - "CreateSourcePermissionImportResponse": { + "DeleteSearchSourceResponse": { "type": "object", "properties": { "data": { @@ -24981,170 +26777,23 @@ "properties": { "id": { "type": "string", - "description": "Permission import identifier." - }, - "expiresAt": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "Upload completion deadline in UTC." - } - }, - "required": ["id", "expiresAt"], - "additionalProperties": false, - "description": "Response data." - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Create source permission import response", - "description": "Permission import result." - }, - "CreateSourcePermissionImportBody": { - "type": "object", - "properties": { - "provider": { - "type": "string", - "const": "gitlab", - "description": "Provider of the configured source." - }, - "expectedRevision": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 2147483646, - "description": "Permission revision pinned before exporting the CSVs." - }, - "userMapping": { - "type": "object", - "properties": { - "filename": { - "type": "string", - "minLength": 1, - "maxLength": 255, - "pattern": "^[^\\p{Cc}/\\\\]+$", - "description": "CSV filename without path separators." - }, - "parts": { - "type": "integer", - "minimum": 1, - "maximum": 4096, - "description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts." - }, - "rowCount": { - "type": "integer", - "minimum": 1, - "maximum": 500000, - "description": "Physical user records, excluding headers and empty lines. Must be between parts and parts × 5,000." - } - }, - "required": ["filename", "parts", "rowCount"], - "additionalProperties": false, - "description": "Complete user identity mapping." - }, - "projectPermissions": { - "type": "object", - "properties": { - "filename": { - "type": "string", - "minLength": 1, - "maxLength": 255, - "pattern": "^[^\\p{Cc}/\\\\]+$", - "description": "CSV filename without path separators." - }, - "parts": { - "type": "integer", - "minimum": 1, - "maximum": 4096, - "description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts." + "description": "Deleted Search source identifier." }, - "rowCount": { - "type": "integer", - "minimum": 1, - "maximum": 5000000, - "description": "Physical data records, excluding headers and empty lines. Must be between parts and parts × 5,000." - } - }, - "required": ["filename", "parts", "rowCount"], - "additionalProperties": false, - "description": "Complete project membership snapshot." - } - }, - "required": ["provider", "expectedRevision", "userMapping", "projectPermissions"], - "additionalProperties": false, - "description": "Permission import input.", - "title": "Create source permission import" - }, - "PutSourcePermissionImportResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "nextPart": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Next expected part number." - } - }, - "required": ["nextPart"], - "additionalProperties": false, - "description": "Response data." - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Upload source permission import part response", - "description": "Permission import result." - }, - "PutSourcePermissionImportBody": { - "type": "object", - "properties": { - "field": { - "type": "string", - "enum": ["userMapping", "projectPermissions"], - "description": "CSV file this part belongs to." - }, - "content": { - "type": "string", - "minLength": 1, - "description": "Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part." - } - }, - "required": ["field", "content"], - "additionalProperties": false, - "title": "Upload source permission import part", - "description": "Permission import input." - }, - "CompleteSourcePermissionImportResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "revision": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991, - "description": "Permission revision committed by this import." + "deleted": { + "type": "boolean", + "const": true, + "description": "The source was removed; permission cleanup continues asynchronously." } }, - "required": ["revision"], + "required": ["id", "deleted"], "additionalProperties": false, "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Complete source permission import response", - "description": "Permission import result." - }, - "CompleteSourcePermissionImportBody": { - "type": "object", - "properties": {}, - "additionalProperties": false, - "title": "Complete source permission import", - "description": "Permission import input." + "title": "Delete Search source response", + "description": "Source operation result." }, "ListSsoProvidersResponse": { "type": "object", diff --git a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts new file mode 100644 index 00000000000..f4411be40fb --- /dev/null +++ b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts @@ -0,0 +1,47 @@ +import { + v2DeleteSearchSourceContract, + v2GetSearchSourceContract, + v2UpdateSearchSourceContract, +} from '@/lib/api/contracts/v2/search-sources' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2OrganizationErrorPolicy } from '@/lib/api/server/routes/organizations' +import { toV2SearchSource } from '@/lib/knowledge/api/search-source-presenter' +import { + deleteManagedSearchSource, + readManagedSearchSource, + updateManagedSearchSource, +} from '@/lib/knowledge/application/manage-search-sources' +import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' + +export const GET = defineV2JsonRoute({ + contract: v2GetSearchSourceContract, + operation: searchSourceOperations.read, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params }) => params, + useCase: readManagedSearchSource, + present: ({ connector }) => ({ data: toV2SearchSource(connector) }), +}) + +export const PATCH = defineV2JsonRoute({ + contract: v2UpdateSearchSourceContract, + operation: knowledgeOperations.updateConnector.organizationOperation, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params, body }) => ({ ...params, updates: body }), + useCase: updateManagedSearchSource, + present: ({ connector }) => ({ data: toV2SearchSource(connector) }), +}) + +export const DELETE = defineV2JsonRoute({ + contract: v2DeleteSearchSourceContract, + operation: knowledgeOperations.deleteConnector.organizationOperation, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params }) => params, + useCase: deleteManagedSearchSource, + present: ({ connectorId }) => ({ data: { id: connectorId, deleted: true as const } }), +}) diff --git a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/prepare/route.ts b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/prepare/route.ts new file mode 100644 index 00000000000..0e7cc8ebccf --- /dev/null +++ b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/prepare/route.ts @@ -0,0 +1,16 @@ +import { v2PrepareSearchSourcesContract } from '@/lib/api/contracts/v2/search-sources' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2OrganizationErrorPolicy } from '@/lib/api/server/routes/organizations' +import { knowledgeOperations } from '@/lib/knowledge/application/operations' +import { prepareSearchSource } from '@/lib/knowledge/application/sim-search' + +export const POST = defineV2JsonRoute({ + contract: v2PrepareSearchSourcesContract, + operation: knowledgeOperations.prepareSearchSource, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params, body }) => ({ ...params, ...body }), + useCase: prepareSearchSource, + present: () => ({ data: { ready: true as const } }), +}) diff --git a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts new file mode 100644 index 00000000000..164945c5340 --- /dev/null +++ b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts @@ -0,0 +1,58 @@ +import { + v2CreateSearchSourceContract, + v2ListSearchSourcesContract, +} from '@/lib/api/contracts/v2/search-sources' +import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2OrganizationErrorPolicy } from '@/lib/api/server/routes/organizations' +import { toV2SearchSource } from '@/lib/knowledge/api/search-source-presenter' +import { + createManagedSearchSource, + listManagedSearchSources, +} from '@/lib/knowledge/application/manage-search-sources' +import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' +import { cursorSortKey, decodeOffsetCursor, encodeOffsetCursor } from '@/app/api/v2/lib/response' + +const cursorScope = (organizationId: string) => + cursorScopeKey(cursorRoute(v2ListSearchSourcesContract, { organizationId }), {}) + +export const GET = defineV2JsonRoute({ + contract: v2ListSearchSourcesContract, + operation: searchSourceOperations.list, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params, query }) => ({ + ...params, + sortBy: query.sortBy, + sortOrder: query.sortOrder, + limit: query.limit, + offset: decodeOffsetCursor( + query.cursor, + cursorSortKey(query.sortBy, query.sortOrder), + cursorScope(params.organizationId) + ), + }), + useCase: listManagedSearchSources, + present: ({ connectors, hasMore, offset, limit }, { params, query }) => ({ + data: connectors.map(toV2SearchSource), + nextCursor: hasMore + ? encodeOffsetCursor( + cursorSortKey(query.sortBy, query.sortOrder), + cursorScope(params.organizationId), + offset + limit + ) + : null, + }), +}) + +export const POST = defineV2JsonRoute({ + contract: v2CreateSearchSourceContract, + operation: knowledgeOperations.createConnector.organizationOperation, + auth: v2ApiKeyAuth, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2OrganizationErrorPolicy, + mapInput: ({ params, body }) => ({ ...params, ...body }), + useCase: createManagedSearchSource, + present: ({ connector }) => ({ data: toV2SearchSource(connector) }), +}) diff --git a/apps/sim/lib/api/contracts/knowledge/gitlab-permissions.ts b/apps/sim/lib/api/contracts/knowledge/gitlab-permissions.ts index 5b7efa25225..58a14ad59d6 100644 --- a/apps/sim/lib/api/contracts/knowledge/gitlab-permissions.ts +++ b/apps/sim/lib/api/contracts/knowledge/gitlab-permissions.ts @@ -16,7 +16,9 @@ const gitLabCsvUploadSchema = z export const gitLabPermissionInputSchema = z .object({ provider: z.literal('gitlab').describe('Provider of the configured Search source.'), - mode: z.enum(GITLAB_PERMISSION_MODES), + mode: z + .enum(GITLAB_PERMISSION_MODES) + .describe('Administrator lookup or externally managed CSV permissions.'), expectedRevision: z .number() .int() @@ -33,15 +35,26 @@ export const gitLabPermissionInputSchema = z .strict() export type GitLabPermissionUploadInput = z.input const gitLabCsvFileSummarySchema = z.object({ - filename: z.string().min(1).max(255), - uploadedAt: z.string().datetime(), - rowCount: z.number().int().nonnegative().max(PERMISSION_IMPORT_MAX_ROWS), + filename: z.string().min(1).max(255).describe('Uploaded CSV filename.'), + uploadedAt: z.string().datetime().describe('Upload time in UTC.'), + rowCount: z + .number() + .int() + .nonnegative() + .max(PERMISSION_IMPORT_MAX_ROWS) + .describe('Number of uploaded data records.'), }) export const gitLabPermissionSummarySchema = z.object({ - provider: z.literal('gitlab'), - mode: z.enum(GITLAB_PERMISSION_MODES), + provider: z.literal('gitlab').describe('Permission provider.'), + mode: z + .enum(GITLAB_PERMISSION_MODES) + .describe('Administrator lookup or externally managed CSV permissions.'), revision: z.number().int().nonnegative().describe('Current revision of the stored permissions.'), - userMapping: gitLabCsvFileSummarySchema.nullable(), - projectPermissions: gitLabCsvFileSummarySchema.nullable(), + userMapping: gitLabCsvFileSummarySchema + .nullable() + .describe('User mapping file summary, or null when not supplied.'), + projectPermissions: gitLabCsvFileSummarySchema + .nullable() + .describe('Project permission file summary, or null when not supplied.'), }) export type GitLabPermissionData = z.output diff --git a/apps/sim/lib/api/contracts/v2/list-pagination.test.ts b/apps/sim/lib/api/contracts/v2/list-pagination.test.ts index 31c06b539b4..c61975c9cb2 100644 --- a/apps/sim/lib/api/contracts/v2/list-pagination.test.ts +++ b/apps/sim/lib/api/contracts/v2/list-pagination.test.ts @@ -38,6 +38,7 @@ import { listContractFiles, MAX_SCHEMA_DEPTH } from '@/lib/api/contracts/v2/test /** Lists that accept `limit` + `cursor` and can return a non-null `nextCursor`. */ const PAGED_LISTS = [ + 'GET /api/v2/organizations/[organizationId]/search/sources', 'GET /api/v2/organizations/[organizationId]/domains', 'GET /api/v2/credentials/[credentialId]/members', 'GET /api/v2/organizations/[organizationId]/sso/providers', @@ -269,6 +270,7 @@ const CURSOR_BINDINGS: Record = { 'sortOrder', ], 'GET /api/v2/knowledge': ['workspaceId', 'scope', 'folderPath', 'search', 'sortBy', 'sortOrder'], + 'GET /api/v2/organizations/[organizationId]/search/sources': ['sortBy', 'sortOrder'], 'GET /api/v2/knowledge/[knowledgeBaseId]/connectors': ['workspaceId', 'sortBy', 'sortOrder'], 'GET /api/v2/knowledge/[knowledgeBaseId]/connectors/[connectorId]/documents': [ 'workspaceId', @@ -407,6 +409,7 @@ const CURSOR_BOUND_PATH_PARAMS: Record = { ], 'GET /api/v2/files/[fileId]/versions': ['fileId'], + 'GET /api/v2/organizations/[organizationId]/search/sources': ['organizationId'], 'GET /api/v2/knowledge/[knowledgeBaseId]/connectors': ['knowledgeBaseId'], 'GET /api/v2/knowledge/[knowledgeBaseId]/connectors/[connectorId]/documents': [ 'knowledgeBaseId', diff --git a/apps/sim/lib/api/contracts/v2/openapi/organizations.ts b/apps/sim/lib/api/contracts/v2/openapi/organizations.ts index 97a795c58d9..5297e0ffd94 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/organizations.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/organizations.ts @@ -21,6 +21,14 @@ import { v2RevokeOrganizationInvitationContract, v2UpdateOrganizationMemberContract, } from '@/lib/api/contracts/v2/organizations' +import { + v2CreateSearchSourceContract, + v2DeleteSearchSourceContract, + v2GetSearchSourceContract, + v2ListSearchSourcesContract, + v2PrepareSearchSourcesContract, + v2UpdateSearchSourceContract, +} from '@/lib/api/contracts/v2/search-sources' import { v2CompleteSourcePermissionImportContract, v2CreateSourcePermissionImportContract, @@ -28,7 +36,11 @@ import { } from '@/lib/api/contracts/v2/source-permission-imports' import { defineOpenApiRoute } from '@/lib/api/openapi/types' import { invitationOperations } from '@/lib/invitations/application/operations' -import { searchSourcePermissionOperations } from '@/lib/knowledge/application/operations' +import { + knowledgeOperations, + searchSourceOperations, + searchSourcePermissionOperations, +} from '@/lib/knowledge/application/operations' import { organizationOperations } from '@/lib/organizations/application/operations' const TIMESTAMP = '2026-06-01T09:00:00.000Z' @@ -733,4 +745,195 @@ export const organizationOpenApiRoutes = [ ), } ), + defineOpenApiRoute( + v2PrepareSearchSourcesContract, + { + applicationOperation: knowledgeOperations.prepareSearchSource, + operationId: 'prepareSearchSources', + summary: 'Prepare Search sources', + description: + 'Idempotently initialize shared Search configuration before creating a source. Does not create a connector or change existing sources. Organization admin required.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2PrepareSearchSourcesContract.params, + 'PrepareSearchSourcesParams', + 'Prepare Search sources parameters', + 'Organization and source identifiers.' + ), + query: v2PrepareSearchSourcesContract.query, + body: documentedSchema( + v2PrepareSearchSourcesContract.body, + 'PrepareSearchSourcesBody', + 'Prepare Search sources input', + 'Source configuration.' + ), + response: documentedSchema( + v2PrepareSearchSourcesContract.response.schema, + 'PrepareSearchSourcesResponse', + 'Prepare Search sources response', + 'Source operation result.' + ), + } + ), + defineOpenApiRoute( + v2ListSearchSourcesContract, + { + applicationOperation: searchSourceOperations.list, + operationId: 'listSearchSources', + summary: 'List Search sources', + description: + 'List source IDs and administrative configuration with cursor pagination. Organization admin required. Credentials and CSV contents are never returned.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2ListSearchSourcesContract.params, + 'ListSearchSourcesParams', + 'List Search sources parameters', + 'Organization and source identifiers.' + ), + query: documentedSchema( + v2ListSearchSourcesContract.query, + 'ListSearchSourcesQuery', + 'List Search sources query', + 'Pagination and ordering.' + ), + response: documentedSchema( + v2ListSearchSourcesContract.response.schema, + 'ListSearchSourcesResponse', + 'List Search sources response', + 'Source operation result.' + ), + } + ), + defineOpenApiRoute( + v2GetSearchSourceContract, + { + applicationOperation: searchSourceOperations.read, + operationId: 'getSearchSource', + summary: 'Get Search source', + description: + 'Read source configuration and permission revision summaries. Organization admin required.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2GetSearchSourceContract.params, + 'GetSearchSourceParams', + 'Get Search source parameters', + 'Organization and source identifiers.' + ), + query: v2GetSearchSourceContract.query, + response: documentedSchema( + v2GetSearchSourceContract.response.schema, + 'GetSearchSourceResponse', + 'Get Search source response', + 'Source operation result.' + ), + } + ), + defineOpenApiRoute( + v2CreateSearchSourceContract, + { + applicationOperation: knowledgeOperations.createConnector.organizationOperation, + operationId: 'createSearchSource', + summary: 'Create Search source', + description: + 'Create a source in the prepared organization Search index using the same provider validation as Settings. Use connector-types list for provider configuration. This does not override an explicit integration approval decision. Organization admin required.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2CreateSearchSourceContract.params, + 'CreateSearchSourceParams', + 'Create Search source parameters', + 'Organization and source identifiers.' + ), + query: v2CreateSearchSourceContract.query, + body: documentedSchema( + v2CreateSearchSourceContract.body, + 'CreateSearchSourceBody', + 'Create Search source input', + 'Source configuration.' + ), + response: documentedSchema( + v2CreateSearchSourceContract.response.schema, + 'CreateSearchSourceResponse', + 'Create Search source response', + 'Source operation result.' + ), + } + ), + defineOpenApiRoute( + v2UpdateSearchSourceContract, + { + applicationOperation: knowledgeOperations.updateConnector.organizationOperation, + operationId: 'updateSearchSource', + summary: 'Update Search source', + description: + 'Update source selection, supported provider credentials, or permission settings; pause or resume a source. Omitted fields are retained. sourceConfig replaces the complete configuration. GitLab token rotation retains saved grants and advances the permission revision; supply permissionConfig with the current expectedRevision for rotation or CSV updates. Organization admin required.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2UpdateSearchSourceContract.params, + 'UpdateSearchSourceParams', + 'Update Search source parameters', + 'Organization and source identifiers.' + ), + query: v2UpdateSearchSourceContract.query, + body: documentedSchema( + v2UpdateSearchSourceContract.body, + 'UpdateSearchSourceBody', + 'Update Search source input', + 'Source configuration.' + ), + response: documentedSchema( + v2UpdateSearchSourceContract.response.schema, + 'UpdateSearchSourceResponse', + 'Update Search source response', + 'Source operation result.' + ), + } + ), + defineOpenApiRoute( + v2DeleteSearchSourceContract, + { + applicationOperation: knowledgeOperations.deleteConnector.organizationOperation, + operationId: 'deleteSearchSource', + summary: 'Delete Search source', + description: + 'Remove a source and its associated permission grants. Cleanup is asynchronous. Organization admin required.', + tags: ['Organizations'], + errors: RESOURCE_CONFLICT_ERRORS, + success: { description: 'Source operation result.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2DeleteSearchSourceContract.params, + 'DeleteSearchSourceParams', + 'Delete Search source parameters', + 'Organization and source identifiers.' + ), + query: v2DeleteSearchSourceContract.query, + response: documentedSchema( + v2DeleteSearchSourceContract.response.schema, + 'DeleteSearchSourceResponse', + 'Delete Search source response', + 'Source operation result.' + ), + } + ), ] as const diff --git a/apps/sim/lib/api/contracts/v2/search-sources.ts b/apps/sim/lib/api/contracts/v2/search-sources.ts new file mode 100644 index 00000000000..686ac31e5b7 --- /dev/null +++ b/apps/sim/lib/api/contracts/v2/search-sources.ts @@ -0,0 +1,159 @@ +import { z } from 'zod' +import { + connectorPermissionConfigSchema, + connectorPermissionSummarySchema, +} from '@/lib/api/contracts/knowledge/connector-permissions' +import { + noInputSchema, + nonEmptyIdSchema, + organizationIdSchema, +} from '@/lib/api/contracts/primitives' +import { defineRouteContract } from '@/lib/api/contracts/types' +import { + v2CreateKnowledgeConnectorBodySchema, + v2KnowledgeConnectorSchema, + v2ListKnowledgeConnectorsQuerySchema, +} from '@/lib/api/contracts/v2/knowledge' +import { v2CursorListResponse, v2DataResponse } from '@/lib/api/contracts/v2/shared' + +const collectionPath = '/api/v2/organizations/[organizationId]/search/sources' +const organizationParams = z.strictObject({ + organizationId: organizationIdSchema.describe('Organization identifier.'), +}) +const sourceParams = organizationParams.extend({ + sourceId: nonEmptyIdSchema.describe('Search source identifier, also used by permission uploads.'), +}) +const accessMode = z + .enum(['admin', 'members']) + .describe( + 'Source-managed permissions (admin), or individually connected member accounts (members).' + ) +const apiKey = v2CreateKnowledgeConnectorBodySchema.shape.apiKey +const sourceConfig = v2CreateKnowledgeConnectorBodySchema.shape.sourceConfig + +export const v2SearchSourceSchema = v2KnowledgeConnectorSchema + .pick({ + id: true, + connectorType: true, + credentialId: true, + sourceConfig: true, + status: true, + createdAt: true, + updatedAt: true, + }) + .extend({ + accessMode, + approved: z + .boolean() + .describe( + 'Whether the organization has approved this integration. Approval is independent of source status.' + ), + permissionConfig: connectorPermissionSummarySchema + .nullable() + .describe('Permission revision and file summaries, without CSV contents.'), + }) + +export const v2PrepareSearchSourcesContract = defineRouteContract({ + method: 'POST', + path: `${collectionPath}/prepare`, + params: organizationParams, + query: noInputSchema, + body: z.strictObject({ + connectorType: v2CreateKnowledgeConnectorBodySchema.shape.connectorType, + accessMode: accessMode.default('admin'), + }), + response: { + mode: 'json', + schema: v2DataResponse( + z.strictObject({ + ready: z + .literal(true) + .describe('Shared Search configuration is ready for source creation.'), + }) + ), + }, +}) + +export const v2ListSearchSourcesContract = defineRouteContract({ + method: 'GET', + path: collectionPath, + params: organizationParams, + query: v2ListKnowledgeConnectorsQuerySchema.omit({ workspaceId: true }), + response: { mode: 'json', schema: v2CursorListResponse(v2SearchSourceSchema) }, +}) + +export const v2GetSearchSourceContract = defineRouteContract({ + method: 'GET', + path: `${collectionPath}/[sourceId]`, + params: sourceParams, + query: noInputSchema, + response: { mode: 'json', schema: v2DataResponse(v2SearchSourceSchema) }, +}) + +export const v2CreateSearchSourceContract = defineRouteContract({ + method: 'POST', + path: collectionPath, + params: organizationParams, + query: noInputSchema, + body: v2CreateKnowledgeConnectorBodySchema + .omit({ workspaceId: true, syncIntervalMinutes: true }) + .extend({ + accessMode: accessMode.default('admin'), + permissionConfig: connectorPermissionConfigSchema + .optional() + .describe( + 'Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation.' + ), + }), + response: { mode: 'json', status: 201, schema: v2DataResponse(v2SearchSourceSchema) }, +}) + +export const v2UpdateSearchSourceContract = defineRouteContract({ + method: 'PATCH', + path: `${collectionPath}/[sourceId]`, + params: sourceParams, + query: noInputSchema, + body: z + .strictObject({ + apiKey: apiKey.describe( + 'Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token.' + ), + sourceConfig: sourceConfig + .optional() + .describe( + 'Complete replacement source configuration. Read the existing configuration before editing it.' + ), + permissionConfig: connectorPermissionConfigSchema + .optional() + .describe( + 'Provider-specific permission update, using the current expectedRevision. Omit to retain permissions.' + ), + status: z + .enum(['active', 'paused']) + .optional() + .describe('Pause or resume this source without changing its ID or stored permissions.'), + }) + .refine( + (body) => Object.values(body).some((value) => value !== undefined), + 'Provide at least one of apiKey, sourceConfig, permissionConfig, or status.' + ), + response: { mode: 'json', schema: v2DataResponse(v2SearchSourceSchema) }, +}) + +export const v2DeleteSearchSourceContract = defineRouteContract({ + method: 'DELETE', + path: `${collectionPath}/[sourceId]`, + params: sourceParams, + query: noInputSchema, + response: { + mode: 'json', + schema: v2DataResponse( + z.strictObject({ + id: z.string().describe('Deleted Search source identifier.'), + deleted: z + .literal(true) + .describe('The source was removed; permission cleanup continues asynchronously.'), + }) + ), + }, +}) diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 444779a2a6f..b9483156dd8 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -200,6 +200,14 @@ import { v2ListSandboxesContract, v2UpdateSandboxContract, } from '@/lib/api/contracts/v2/sandboxes' +import { + v2CreateSearchSourceContract, + v2DeleteSearchSourceContract, + v2GetSearchSourceContract, + v2ListSearchSourcesContract, + v2PrepareSearchSourcesContract, + v2UpdateSearchSourceContract, +} from '@/lib/api/contracts/v2/search-sources' import { v2DeleteSecretContract, v2ListSecretsContract, @@ -850,6 +858,16 @@ export const V2_MCP_OPERATIONS = { workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/sandboxes/route').then((route) => route.POST), }, + createSearchSource: { + contract: v2CreateSearchSourceContract, + summary: 'Create Search source', + description: + 'Create a source in the prepared organization Search index using the same provider validation as Settings. Use connector-types list for provider configuration. This does not override an explicit integration approval decision. Organization admin required.\n\nOAuth scope: `api:write`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/route').then( + (route) => route.POST + ), + }, createServiceAccountCredential: { contract: v2CreateServiceAccountCredentialContract, summary: 'Create service-account credential', @@ -1110,6 +1128,16 @@ export const V2_MCP_OPERATIONS = { workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/sandboxes/[sandboxId]/route').then((route) => route.DELETE), }, + deleteSearchSource: { + contract: v2DeleteSearchSourceContract, + summary: 'Delete Search source', + description: + 'Remove a source and its associated permission grants. Cleanup is asynchronous. Organization admin required.\n\nOAuth scope: `api:write`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route').then( + (route) => route.DELETE + ), + }, deleteSecret: { contract: v2DeleteSecretContract, summary: 'Delete secret', @@ -1553,6 +1581,16 @@ export const V2_MCP_OPERATIONS = { 'Get a sandbox’s dependency configuration, current build state, and any build failure. Requires workspace read access.\n\nOAuth scope: `api:read`.', handler: () => import('@/app/api/v2/sandboxes/[sandboxId]/route').then((route) => route.GET), }, + getSearchSource: { + contract: v2GetSearchSourceContract, + summary: 'Get Search source', + description: + 'Read source configuration and permission revision summaries. Organization admin required.\n\nOAuth scope: `api:read`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route').then( + (route) => route.GET + ), + }, getSearchSourcePermissions: { contract: v2GetSearchSourcePermissionsContract, summary: 'Get Search source permission revision', @@ -2126,6 +2164,16 @@ export const V2_MCP_OPERATIONS = { 'List reusable dependency environments for Function blocks, including language packages, managed CLIs, and system packages. Requires workspace read access. Existing sandboxes remain visible after a plan downgrade.\n\nOAuth scope: `api:read`.', handler: () => import('@/app/api/v2/sandboxes/route').then((route) => route.GET), }, + listSearchSources: { + contract: v2ListSearchSourcesContract, + summary: 'List Search sources', + description: + 'List source IDs and administrative configuration with cursor pagination. Organization admin required. Credentials and CSV contents are never returned.\n\nOAuth scope: `api:read`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/route').then( + (route) => route.GET + ), + }, listSecrets: { contract: v2ListSecretsContract, summary: 'List secrets', @@ -2345,6 +2393,16 @@ export const V2_MCP_OPERATIONS = { 'Move up to 100 workflows to one folder with workspace write access. Each move succeeds or fails independently; missing, archived, or locked workflows appear in `failed`. Duplicate IDs are ignored. Workspace folder trees exceeding 10,000 folders return `413`.\n\nOAuth scope: `api:write`.', handler: () => import('@/app/api/v2/workflows/move/route').then((route) => route.POST), }, + prepareSearchSources: { + contract: v2PrepareSearchSourcesContract, + summary: 'Prepare Search sources', + description: + 'Idempotently initialize shared Search configuration before creating a source. Does not create a connector or change existing sources. Organization admin required.\n\nOAuth scope: `api:write`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/prepare/route').then( + (route) => route.POST + ), + }, previewOrganizationAccessRequest: { contract: v2PreviewOrganizationAccessRequestContract, summary: 'Preview organization access request', @@ -2989,6 +3047,16 @@ export const V2_MCP_OPERATIONS = { workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/sandboxes/[sandboxId]/route').then((route) => route.PATCH), }, + updateSearchSource: { + contract: v2UpdateSearchSourceContract, + summary: 'Update Search source', + description: + 'Update source selection, supported provider credentials, or permission settings; pause or resume a source. Omitted fields are retained. sourceConfig replaces the complete configuration. GitLab token rotation retains saved grants and advances the permission revision; supply permissionConfig with the current expectedRevision for rotation or CSV updates. Organization admin required.\n\nOAuth scope: `api:write`.', + handler: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route').then( + (route) => route.PATCH + ), + }, updateSkill: { contract: v2UpdateSkillContract, summary: 'Update skill', diff --git a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts index fd0f0617920..ad9450ee737 100644 --- a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts +++ b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts @@ -450,6 +450,15 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ '@/app/api/v2/organizations/[organizationId]/permission-groups/[groupId]/members/bulk/route' ), }, + { + pattern: '/api/v2/organizations/{organizationId}/search/sources', + load: () => import('@/app/api/v2/organizations/[organizationId]/search/sources/route'), + }, + { + pattern: '/api/v2/organizations/{organizationId}/search/sources/{sourceId}', + load: () => + import('@/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route'), + }, { pattern: '/api/v2/organizations/{organizationId}/search/sources/{sourceId}/permissions', load: () => @@ -480,6 +489,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ '@/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions/imports/[importId]/parts/[partNumber]/route' ), }, + { + pattern: '/api/v2/organizations/{organizationId}/search/sources/prepare', + load: () => import('@/app/api/v2/organizations/[organizationId]/search/sources/prepare/route'), + }, { pattern: '/api/v2/organizations/{organizationId}/sso/policy', load: () => import('@/app/api/v2/organizations/[organizationId]/sso/policy/route'), diff --git a/apps/sim/lib/knowledge/__integration__/gitlab-group.integration.ts b/apps/sim/lib/knowledge/__integration__/gitlab-group.integration.ts index f8f5c27d49f..da9b7984eb3 100644 --- a/apps/sim/lib/knowledge/__integration__/gitlab-group.integration.ts +++ b/apps/sim/lib/knowledge/__integration__/gitlab-group.integration.ts @@ -36,6 +36,10 @@ vi.mock('@/lib/core/security/input-validation.server', async (original) => { import { seedKnowledgeAclFixture } from '@/lib/knowledge/__integration__/seed-source-access-fixture' import { updateKnowledgeConnectorAccess } from '@/lib/knowledge/application/connector-access' import { createKnowledgeConnector } from '@/lib/knowledge/application/connectors' +import { + createManagedSearchSource, + updateManagedSearchSource, +} from '@/lib/knowledge/application/manage-search-sources' import { readSearchSourcePermissions, replaceSearchSourcePermissions, @@ -62,6 +66,8 @@ describe('GitLab group Search permission boundary', () => { let nativeGroup = false const checks: string[] = [] const token = 'disposable-group-test-token' + const rotatedToken = 'disposable-rotated-group-test-token' + let rejectOriginalToken = false const principal = (userId: string): Principal => ({ kind: 'personal_api_key', userId, @@ -92,9 +98,13 @@ describe('GitLab group Search permission boundary', () => { response.writeHead(status, { 'content-type': 'application/json', ...headers }) response.end(JSON.stringify(body)) } + const acceptedTokens = rejectOriginalToken ? [rotatedToken] : [token, rotatedToken] if ( - request.headers['private-token'] !== token && - request.headers.authorization !== `Bearer ${token}` + !acceptedTokens.some( + (accepted) => + request.headers['private-token'] === accepted || + request.headers.authorization === `Bearer ${accepted}` + ) ) return reply(401, {}) if (providerState === 'revoked') return reply(401, {}) @@ -330,7 +340,19 @@ describe('GitLab group Search permission boundary', () => { }) legacyId = (await create({ host: config.host, project: '11', contentTypes: 'issues' })) .connector.id - sourceId = (await create(config)).connector.id + sourceId = ( + await createManagedSearchSource.execute({ + principal: principal(ids.aliceId), + input: { + organizationId: ids.organizationId, + connectorType: 'gitlab', + accessMode: 'admin', + apiKey: token, + sourceConfig: config, + permissionConfig: { ...permissions(), mode: 'csv' }, + }, + }) + ).connector.id }, 60000) afterAll(async () => { @@ -877,4 +899,78 @@ describe('GitLab group Search permission boundary', () => { nativeGroup = false } }) + + it('rotates the Search token atomically while retaining grants and rejecting stale revisions', async () => { + const before = await loadConnectorPermissionSnapshot(sourceId) + if (!before) throw new Error('Missing group fixture') + const [previous] = await db + .select() + .from(knowledgeConnector) + .where(eq(knowledgeConnector.id, sourceId)) + const input = { + organizationId: ids.organizationId, + sourceId, + updates: { + apiKey: rotatedToken, + permissionConfig: { + provider: 'gitlab' as const, + mode: 'csv' as const, + expectedRevision: before.revision, + }, + }, + } + const updated = await updateManagedSearchSource.execute({ + principal: principal(ids.aliceId), + input, + }) + expect(updated.connector.id).toBe(sourceId) + expect(JSON.stringify(updated)).not.toContain(rotatedToken) + const after = await loadConnectorPermissionSnapshot(sourceId) + expect(after).toMatchObject({ + revision: before.revision + 1, + metadata: before.metadata, + payload: before.payload, + }) + const [saved] = await db + .select() + .from(knowledgeConnector) + .where(eq(knowledgeConnector.id, sourceId)) + expect(saved?.encryptedApiKey).not.toBe(previous?.encryptedApiKey) + expect(saved?.nextSyncAt).toBeNull() + expect(saved?.nextMemberSyncAt).toBeNull() + rejectOriginalToken = true + try { + const alice = await search(ids.aliceId, '11') + const aliceAdditional = await search(ids.aliceId, '13') + const bob = await search(ids.bobId, '12') + expect( + new Set( + [...alice.results, ...aliceAdditional.results].map( + (row) => decodeLiveReference(row.documentId).container + ) + ) + ).toEqual(new Set(['11', '13'])) + expect( + new Set(bob.results.map((row) => decodeLiveReference(row.documentId).container)) + ).toEqual(new Set(['12'])) + const first = alice.results[0] + if (!first) throw new Error('Missing authorized result after token rotation') + expect((await read(ids.aliceId, first.documentId)).chunks.length).toBeGreaterThan(0) + await expect(read(ids.bobId, first.documentId)).rejects.toMatchObject({ code: 'not_found' }) + await expect( + updateManagedSearchSource.execute({ principal: principal(ids.aliceId), input }) + ).rejects.toMatchObject({ code: 'conflict' }) + expect(await loadConnectorPermissionSnapshot(sourceId)).toEqual(after) + const [unchanged] = await db + .select() + .from(knowledgeConnector) + .where(eq(knowledgeConnector.id, sourceId)) + expect(unchanged).toEqual(saved) + } finally { + rejectOriginalToken = false + } + checks.push( + 'Search source token rotation preserves grants and rejects stale revisions atomically' + ) + }) }) diff --git a/apps/sim/lib/knowledge/__integration__/manage-search-sources.integration.ts b/apps/sim/lib/knowledge/__integration__/manage-search-sources.integration.ts new file mode 100644 index 00000000000..2c5240ffe85 --- /dev/null +++ b/apps/sim/lib/knowledge/__integration__/manage-search-sources.integration.ts @@ -0,0 +1,254 @@ +import { db } from '@sim/db' +import { + knowledgeBase, + knowledgeConnector, + member, + organization, + organizationSearchIntegration, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { + createPersonalApiKeyPrincipal, + createWorkspaceApiKeyPrincipal, +} from '@sim/testing/factories/principal.factory' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' + +vi.mock('@/connectors/registry.server', async () => { + const { gitlabConnectorMeta } = await import('@/connectors/gitlab/meta') + return { + CONNECTOR_REGISTRY: { + gitlab: { + ...gitlabConnectorMeta, + configFields: [], + validateConfig: async (_token: string, config: Record) => + config.project === 'invalid' + ? { valid: false, error: 'Project not accessible' } + : { valid: true }, + }, + }, + } +}) + +import { seedKnowledgeAclFixture } from '@/lib/knowledge/__integration__/seed-source-access-fixture' +import { + createManagedSearchSource, + deleteManagedSearchSource, + listManagedSearchSources, + readManagedSearchSource, + updateManagedSearchSource, +} from '@/lib/knowledge/application/manage-search-sources' +import { prepareSearchSource } from '@/lib/knowledge/application/sim-search' + +describe('organization Search source administration', () => { + const owners: Awaited>[] = [] + beforeAll(async () => { + for (let i = 0; i < 2; i++) { + const owner = await seedKnowledgeAclFixture() + owners.push(owner) + await db.insert(member).values([ + { + id: generateId(), + organizationId: owner.organizationId, + userId: owner.aliceId, + role: 'owner', + }, + { + id: generateId(), + organizationId: owner.organizationId, + userId: owner.bobId, + role: 'member', + }, + ]) + await db + .update(knowledgeBase) + .set({ workspaceId: null, organizationId: owner.organizationId, isSearchIndex: true }) + .where(eq(knowledgeBase.id, owner.knowledgeBaseId)) + } + }) + afterAll(async () => { + for (const owner of owners) { + await deleteWorkspaceFixture(db, eq(workspace.id, owner.workspaceId)) + await db.delete(organization).where(eq(organization.id, owner.organizationId)) + await db.delete(user).where(inArray(user.id, [owner.aliceId, owner.bobId])) + } + await db.$client.end() + }) + + it('denies members, workspace keys, foreign sources, and ordinary knowledge bases', async () => { + const owner = owners[0] + const input = { organizationId: owner.organizationId, sourceId: owner.connectorId } + for (const principal of [ + createPersonalApiKeyPrincipal({ userId: owner.bobId }), + createWorkspaceApiKeyPrincipal({ workspaceId: owner.workspaceId }), + ]) { + for (const action of [ + () => readManagedSearchSource.execute({ principal, input }), + () => + listManagedSearchSources.execute({ + principal, + input: { organizationId: input.organizationId, limit: 10 }, + }), + () => + updateManagedSearchSource.execute({ + principal, + input: { ...input, updates: { status: 'paused' } }, + }), + () => deleteManagedSearchSource.execute({ principal, input }), + () => + createManagedSearchSource.execute({ + principal, + input: { + organizationId: input.organizationId, + connectorType: 'gitlab', + accessMode: 'admin', + apiKey: 'fixture-token', + sourceConfig: { host: 'gitlab.example.com', project: '123' }, + }, + }), + () => + prepareSearchSource.execute({ + principal, + input: { + organizationId: input.organizationId, + connectorType: 'gitlab', + accessMode: 'admin', + }, + }), + ]) + await expect(action()).rejects.toMatchObject( + principal.kind === 'workspace_api_key' + ? { + code: 'forbidden', + detailCode: expect.stringMatching( + /^(WORKSPACE_KEY_OPERATION_NOT_PERMITTED|PRINCIPAL_KIND_NOT_PERMITTED)$/ + ), + } + : { name: 'ForbiddenOperationError' } + ) + } + const principal = createPersonalApiKeyPrincipal({ userId: owner.aliceId }) + await expect( + readManagedSearchSource.execute({ + principal, + input: { ...input, sourceId: owners[1].connectorId }, + }) + ).rejects.toMatchObject({ code: 'not_found' }) + await db + .update(knowledgeBase) + .set({ isSearchIndex: false, organizationId: null, workspaceId: owner.workspaceId }) + .where(eq(knowledgeBase.id, owner.knowledgeBaseId)) + try { + await expect( + updateManagedSearchSource.execute({ + principal, + input: { ...input, updates: { status: 'paused' } }, + }) + ).rejects.toMatchObject({ code: 'not_found' }) + } finally { + await db + .update(knowledgeBase) + .set({ isSearchIndex: true, organizationId: owner.organizationId, workspaceId: null }) + .where(eq(knowledgeBase.id, owner.knowledgeBaseId)) + } + const [unchanged] = await db + .select() + .from(knowledgeConnector) + .where(eq(knowledgeConnector.id, owner.connectorId)) + expect(unchanged.status).toBe('syncing') + }) + + it('initializes one canonical organization Search index on concurrent first use', async () => { + const owner = owners[1] + await db + .update(knowledgeBase) + .set({ organizationId: null, workspaceId: owner.workspaceId, isSearchIndex: false }) + .where(eq(knowledgeBase.id, owner.knowledgeBaseId)) + const input = { + organizationId: owner.organizationId, + connectorType: 'gitlab', + accessMode: 'admin' as const, + } + const principal = createPersonalApiKeyPrincipal({ userId: owner.aliceId }) + await expect( + createManagedSearchSource.execute({ + principal, + input: { + ...input, + apiKey: 'fixture-token', + sourceConfig: { host: 'gitlab.example.com', project: '123' }, + }, + }) + ).rejects.toMatchObject({ code: 'conflict' }) + const prepared = await Promise.all( + [1, 2].map(() => prepareSearchSource.execute({ principal, input })) + ) + expect(prepared[0].knowledgeBaseId).not.toBe(owner.knowledgeBaseId) + expect(prepared[1].knowledgeBaseId).toBe(prepared[0].knowledgeBaseId) + const indexes = await db + .select() + .from(knowledgeBase) + .where(eq(knowledgeBase.organizationId, owner.organizationId)) + expect(indexes).toHaveLength(1) + }) + + it('reuses preparation, validates creation, and preserves source identity through pause and deletion', async () => { + const owner = owners[0] + const principal = createPersonalApiKeyPrincipal({ userId: owner.aliceId }) + const preparation = { + organizationId: owner.organizationId, + connectorType: 'gitlab', + accessMode: 'admin' as const, + } + const prepared = await Promise.all( + [1, 2].map(() => prepareSearchSource.execute({ principal, input: preparation })) + ) + expect(prepared.map((result) => result.knowledgeBaseId)).toEqual([ + owner.knowledgeBaseId, + owner.knowledgeBaseId, + ]) + const input = { + ...preparation, + apiKey: 'fixture-pat-not-a-real-secret', + sourceConfig: { host: 'gitlab.example.com', project: 'invalid' }, + } + await expect(createManagedSearchSource.execute({ principal, input })).rejects.toThrow( + 'Project not accessible' + ) + const before = await listManagedSearchSources.execute({ + principal, + input: { organizationId: owner.organizationId, limit: 100 }, + }) + expect(before.connectors).toHaveLength(1) + await db + .insert(organizationSearchIntegration) + .values({ organizationId: owner.organizationId, connectorType: 'gitlab', approved: false }) + const created = await createManagedSearchSource.execute({ + principal, + input: { ...input, sourceConfig: { ...input.sourceConfig, project: '123' } }, + }) + expect(created.connector.approved).toBe(false) + expect(created.connector).not.toHaveProperty('encryptedApiKey') + const [stored] = await db + .select() + .from(knowledgeConnector) + .where(eq(knowledgeConnector.id, created.connector.id)) + expect(stored.encryptedApiKey).toBeTruthy() + expect(stored.encryptedApiKey).not.toBe(input.apiKey) + const target = { organizationId: owner.organizationId, sourceId: created.connector.id } + for (const status of ['paused', 'active'] as const) { + const updated = await updateManagedSearchSource.execute({ + principal, + input: { ...target, updates: { status } }, + }) + expect(updated.connector).toMatchObject({ id: target.sourceId, status, approved: false }) + } + await deleteManagedSearchSource.execute({ principal, input: target }) + await expect( + readManagedSearchSource.execute({ principal, input: target }) + ).rejects.toMatchObject({ code: 'not_found' }) + }) +}) diff --git a/apps/sim/lib/knowledge/api/search-source-presenter.ts b/apps/sim/lib/knowledge/api/search-source-presenter.ts new file mode 100644 index 00000000000..86f642bb73e --- /dev/null +++ b/apps/sim/lib/knowledge/api/search-source-presenter.ts @@ -0,0 +1,30 @@ +import type { z } from 'zod' +import type { connectorPermissionSummarySchema } from '@/lib/api/contracts/knowledge/connector-permissions' +import { v2SearchSourceSchema } from '@/lib/api/contracts/v2/search-sources' + +/** Projects only public source configuration; credentials and permission contents never leave the server. */ +export function toV2SearchSource(connector: { + id: string + connectorType: string + credentialId: string | null + sourceConfig: unknown + status: string + accessMode: string + approved: boolean + createdAt: Date + updatedAt: Date + permissionConfig?: z.output +}) { + return v2SearchSourceSchema.parse({ + id: connector.id, + connectorType: connector.connectorType, + credentialId: connector.credentialId, + sourceConfig: connector.sourceConfig, + status: connector.status, + accessMode: connector.accessMode, + approved: connector.approved, + permissionConfig: connector.permissionConfig ?? null, + createdAt: connector.createdAt.toISOString(), + updatedAt: connector.updatedAt.toISOString(), + }) +} diff --git a/apps/sim/lib/knowledge/application/manage-search-sources.ts b/apps/sim/lib/knowledge/application/manage-search-sources.ts new file mode 100644 index 00000000000..21a8f8842fa --- /dev/null +++ b/apps/sim/lib/knowledge/application/manage-search-sources.ts @@ -0,0 +1,199 @@ +import type { Principal } from '@sim/auth/principal' +import { + defineAuthorizedOrganizationUseCase, + type OrganizationUseCaseContext, +} from '@/lib/core/application/authorized-organization-use-case' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' +import { + type CreateKnowledgeConnectorInput, + createKnowledgeConnector, + deleteKnowledgeConnector, + type ListKnowledgeConnectorsInput, + listKnowledgeConnectors, + readKnowledgeConnector, + type UpdateKnowledgeConnectorInput, + updateKnowledgeConnector, +} from '@/lib/knowledge/application/connectors' +import { resolveActiveKnowledgeConnectorContext } from '@/lib/knowledge/application/contexts' +import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' +import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy' +import { findSearchIndex } from '@/lib/knowledge/search/search-index' + +interface SourceInput { + organizationId: string + sourceId: string +} +type CreateInput = Pick< + CreateKnowledgeConnectorInput, + 'connectorType' | 'credentialId' | 'apiKey' | 'permissionConfig' | 'sourceConfig' +> & { + organizationId: string + accessMode: 'admin' | 'members' +} +type ListInput = Pick & { + organizationId: string +} + +async function requireSearchSource(principal: Principal, input: SourceInput) { + const context = await resolveActiveKnowledgeConnectorContext( + { + connectorId: input.sourceId, + assertedOrganizationId: input.organizationId, + }, + principal + ) + if ( + !context.knowledgeBase.isSearchIndex || + !['admin', 'members'].includes(context.connector.accessMode) + ) + throw new OrchestrationError('not_found', 'Search source not found') + return context +} + +/** Lists administrative source configuration without exposing stored credentials or CSV contents. */ +export const listManagedSearchSources = defineAuthorizedOrganizationUseCase({ + operation: searchSourceOperations.list, + async execute({ principal, input, request }: OrganizationUseCaseContext) { + const index = await findSearchIndex({ + kind: 'organization', + organizationId: input.organizationId, + }) + if (!index) + return { + connectors: [], + hasMore: false, + offset: input.offset ?? 0, + limit: input.limit ?? 100, + } + const result = await listKnowledgeConnectors.execute({ + principal, + request, + input: { + knowledgeBaseId: index.id, + assertedOrganizationId: input.organizationId, + sortBy: input.sortBy, + sortOrder: input.sortOrder, + limit: input.limit, + offset: input.offset, + }, + }) + const approvals = await listOrganizationSearchApprovals(input.organizationId) + return { + ...result, + connectors: result.connectors.map((connector) => ({ + ...connector, + approved: approvals.get(connector.connectorType) === true, + })), + } + }, +}) + +/** Resolves the canonical organization source before reading its administrative configuration. */ +export const readManagedSearchSource = defineAuthorizedOrganizationUseCase({ + operation: searchSourceOperations.read, + async execute({ principal, input, request }: OrganizationUseCaseContext) { + const context = await requireSearchSource(principal, input) + const result = await readKnowledgeConnector.execute({ + principal, + request, + input: { + knowledgeBaseId: context.knowledgeBaseId, + connectorId: input.sourceId, + assertedOrganizationId: input.organizationId, + }, + }) + const approvals = await listOrganizationSearchApprovals(input.organizationId) + return { + connector: { + ...result.connector, + approved: approvals.get(result.connector.connectorType) === true, + }, + } + }, +}) + +/** Creates a source in the prepared Search index using the same validation and write as Settings. */ +export const createManagedSearchSource = defineAuthorizedOrganizationUseCase({ + operation: knowledgeOperations.createConnector.organizationOperation, + async execute({ principal, input, request }: OrganizationUseCaseContext) { + await requireOrganizationSearchAvailable(input.organizationId) + const index = await findSearchIndex({ + kind: 'organization', + organizationId: input.organizationId, + }) + if (!index) + throw new OrchestrationError( + 'conflict', + 'Prepare Search sources for this organization before creating a source.' + ) + const { organizationId, ...configuration } = input + const result = await createKnowledgeConnector.execute({ + principal, + request, + input: { + ...configuration, + knowledgeBaseId: index.id, + assertedOrganizationId: organizationId, + syncIntervalMinutes: 0, + source: 'api', + }, + }) + const approvals = await listOrganizationSearchApprovals(organizationId) + return { + connector: { + ...result.connector, + approved: approvals.get(result.connector.connectorType) === true, + }, + } + }, +}) + +/** Updates source settings while retaining the connector's permission revision and token rules. */ +export const updateManagedSearchSource = defineAuthorizedOrganizationUseCase({ + operation: knowledgeOperations.updateConnector.organizationOperation, + async execute({ + principal, + input, + request, + }: OrganizationUseCaseContext< + SourceInput & { updates: UpdateKnowledgeConnectorInput['updates'] } + >) { + await requireSearchSource(principal, input) + const result = await updateKnowledgeConnector.execute({ + principal, + request, + input: { + connectorId: input.sourceId, + assertedOrganizationId: input.organizationId, + updates: input.updates, + source: 'api', + }, + }) + const approvals = await listOrganizationSearchApprovals(input.organizationId) + return { + connector: { + ...result.connector, + approved: approvals.get(result.connector.connectorType) === true, + }, + } + }, +}) + +/** Removes only the resolved Search source, retaining the existing durable permission cleanup. */ +export const deleteManagedSearchSource = defineAuthorizedOrganizationUseCase({ + operation: knowledgeOperations.deleteConnector.organizationOperation, + async execute({ principal, input, request }: OrganizationUseCaseContext) { + await requireSearchSource(principal, input) + return deleteKnowledgeConnector.execute({ + principal, + request, + input: { + connectorId: input.sourceId, + assertedOrganizationId: input.organizationId, + deleteDocuments: true, + source: 'api', + }, + }) + }, +}) diff --git a/apps/sim/lib/knowledge/application/operations.ts b/apps/sim/lib/knowledge/application/operations.ts index 32d98788516..f6749ac2871 100644 --- a/apps/sim/lib/knowledge/application/operations.ts +++ b/apps/sim/lib/knowledge/application/operations.ts @@ -852,10 +852,11 @@ export const knowledgeOperations = { prepareSearchSource: defineKnowledgeOperation( defineWorkspaceOperation({ id: 'knowledge.search.sources.prepare', + oauthScope: 'api:write', minimumRole: 'admin', workspaceApiKey: 'deny', capability: 'knowledge.use', - principalKinds: ['session'], + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], }), { organizationDelegation: 'allow' } ), @@ -1031,6 +1032,23 @@ function defineKnowledgeSessionOperation( return Object.freeze(operation) } +export const searchSourceOperations = { + list: defineOrganizationOperation({ + id: 'knowledge.search.sources.manage.list', + oauthScope: 'api:read', + minimumRole: 'admin', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'knowledge.use', + }), + read: defineOrganizationOperation({ + id: 'knowledge.search.sources.manage.read', + oauthScope: 'api:read', + minimumRole: 'admin', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'knowledge.use', + }), +} as const + export const searchSourcePermissionOperations = { read: defineOrganizationOperation({ minimumRole: 'admin', diff --git a/apps/sim/lib/knowledge/connectors/service.ts b/apps/sim/lib/knowledge/connectors/service.ts index d29172556fd..6a08d9593a4 100644 --- a/apps/sim/lib/knowledge/connectors/service.ts +++ b/apps/sim/lib/knowledge/connectors/service.ts @@ -8,6 +8,7 @@ export interface ActiveKnowledgeConnectorReference { knowledgeBaseId: string connectorType: string status: string + accessMode: string } /** Resolves a connector's canonical active parent without trusting a caller-supplied KB ID. */ @@ -20,6 +21,7 @@ export async function getActiveKnowledgeConnectorReference( knowledgeBaseId: knowledgeConnector.knowledgeBaseId, connectorType: knowledgeConnector.connectorType, status: knowledgeConnector.status, + accessMode: knowledgeConnector.accessMode, }) .from(knowledgeConnector) .where(and(eq(knowledgeConnector.id, connectorId), connectorIsLive())) diff --git a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts index f16d59e0fde..400ee2f459e 100644 --- a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts +++ b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts @@ -1,5 +1,10 @@ import assert from 'node:assert/strict' -import { writeFile } from 'node:fs/promises' +import { execFile } from 'node:child_process' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' import { assertDisposableTestDatabaseUrl } from '@sim/db/testing/test-infrastructure' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' @@ -103,7 +108,7 @@ try { for (const id of [org, otherOrg]) { await tx`insert into organization (id, name, slug) values (${id}, 'GitLab CSV fixture', ${id})` await tx`insert into member (id, organization_id, user_id, role) - values (${generateId()}, ${id}, ${id === org ? admin : otherAdmin}, 'admin')` + values (${generateId()}, ${id}, ${id === org ? admin : otherAdmin}, 'owner')` } await tx`insert into member (id, organization_id, user_id, role) values (${generateId()}, ${org}, ${member}, 'member')` @@ -139,6 +144,46 @@ try { values (${source}, 'project', ${`u:${initialEmail}`})` }) await checkRevision(await request(adminKey), 1) + const sourcePath = path().replace(/\/permissions$/, '') + const sourceRequest = (token: string, method = 'GET', body?: unknown, suffix = '') => + fetch(new URL(`${sourcePath}${suffix}`, base), { + method, + headers: { 'X-API-Key': token, 'Content-Type': 'application/json' }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + redirect: 'error', + signal: AbortSignal.timeout(180_000), + }) + const sourceResponse = await sourceRequest(adminKey) + assert.equal(sourceResponse.status, 200) + const sourceText = await sourceResponse.text() + const sourceData = JSON.parse(sourceText).data + assert.equal(sourceData.id, source) + assert.equal(sourceData.permissionConfig.revision, 1) + assert(!sourceText.includes(pat)) + assert(!sourceText.includes(initialEmail)) + for (const token of [memberKey, workspaceKey]) { + assert.equal((await sourceRequest(token)).status, 403) + assert.equal((await sourceRequest(token, 'PATCH', { status: 'paused' })).status, 403) + assert.equal((await sourceRequest(token, 'DELETE')).status, 403) + } + const list = await fetch(new URL(sourcePath.slice(0, sourcePath.lastIndexOf('/')), base), { + headers: { 'X-API-Key': adminKey }, + redirect: 'error', + }) + assert.equal(list.status, 200) + assert.deepEqual( + (await list.json()).data.map((row: { id: string }) => row.id), + [source] + ) + for (const status of ['paused', 'active']) { + const response = await sourceRequest(adminKey, 'PATCH', { status }) + assert.equal(response.status, 200, await response.clone().text()) + assert.equal((await response.json()).data.id, source) + await checkRevision(await request(adminKey), 1) + } + checks.push( + 'Source discovery and pause/resume preserve IDs and CSV revisions; administrative reads exclude secrets and deny member and workspace keys' + ) checks.push( 'An organization admin can read the revision without exposing the CSV contents or PAT' ) @@ -627,6 +672,64 @@ try { scale.phase = 'verified' await writeReport('running') } + const current = await request(adminKey) + assert.equal(current.status, 200) + const revision = (await current.json()).data.revision + const directory = await mkdtemp(join(tmpdir(), 'sim-permission-cli-e2e-')) + try { + await writeFile(join(directory, 'users.csv'), `user_id,email\n1,${initialEmail}\n`, { + mode: 0o600, + }) + await writeFile(join(directory, 'projects.csv'), `project_path,user_id\n${project},1\n`, { + mode: 0o600, + }) + const cli = await promisify(execFile)( + 'bun', + [ + '--no-env-file', + fileURLToPath(new URL('../../../packages/sim-cli/src/index.ts', import.meta.url)), + '--endpoint', + base.origin, + '--output', + 'json', + 'organizations', + 'search', + 'sources', + 'permissions', + 'upload', + source, + '--organization', + org, + '--provider', + 'gitlab', + '--expected-revision', + String(revision), + '--user-mapping', + 'users.csv', + '--project-permissions', + 'projects.csv', + '--yes', + ], + { + cwd: directory, + env: { ...process.env, SIM_CONFIG_DIR: directory, SIM_API_KEY: adminKey, NO_COLOR: '1' }, + timeout: 180_000, + maxBuffer: 1024 * 1024, + } + ) + assert.equal(JSON.parse(cli.stdout).revision, revision + 1) + } finally { + await rm(directory, { recursive: true, force: true }) + } + await checkRevision(await request(adminKey), revision + 1) + checks.push( + 'The production CLI uploads both CSVs through real HTTP and commits exactly one new permission revision' + ) + const removed = await sourceRequest(adminKey, 'DELETE') + assert.equal(removed.status, 200, await removed.clone().text()) + assert.deepEqual(await removed.json(), { data: { id: source, deleted: true } }) + assert.equal((await request(adminKey)).status, 404) + checks.push('Source deletion removes permission access through the public API') } catch (error) { failure = getErrorMessage(error) } finally { diff --git a/bun.lock b/bun.lock index 01773fa57c9..15ab73f2ff6 100644 --- a/bun.lock +++ b/bun.lock @@ -759,6 +759,7 @@ "dependencies": { "chalk": "5.6.2", "commander": "^11.1.0", + "csv-parse": "7.0.3", "js-yaml": "4.3.2", "minisearch": "7.2.0", "proper-lockfile": "4.1.2", diff --git a/packages/sim-cli/THIRD_PARTY_LICENSES b/packages/sim-cli/THIRD_PARTY_LICENSES index d8eff820553..1a97d1081a0 100644 --- a/packages/sim-cli/THIRD_PARTY_LICENSES +++ b/packages/sim-cli/THIRD_PARTY_LICENSES @@ -6,6 +6,9 @@ Copyright (c) Sindre Sorhus (https://sindresorhus.com) commander Copyright (c) 2011 TJ Holowaychuk +csv-parse +Copyright (c) 2010 Adaltas + js-yaml Copyright (C) 2011-2015 by Vitaly Puzrin diff --git a/packages/sim-cli/package.json b/packages/sim-cli/package.json index 2b8e13c56df..c14595cccd5 100644 --- a/packages/sim-cli/package.json +++ b/packages/sim-cli/package.json @@ -52,6 +52,7 @@ "dependencies": { "chalk": "5.6.2", "commander": "^11.1.0", + "csv-parse": "7.0.3", "js-yaml": "4.3.2", "minisearch": "7.2.0", "proper-lockfile": "4.1.2" diff --git a/packages/sim-cli/src/commands/source-permissions.test.ts b/packages/sim-cli/src/commands/source-permissions.test.ts new file mode 100644 index 00000000000..ef7fe71c60e --- /dev/null +++ b/packages/sim-cli/src/commands/source-permissions.test.ts @@ -0,0 +1,274 @@ +import { describe, expect, it, vi } from 'vitest' +import { runEmbeddedCli } from '#sim-cli/embed' + +vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} })) + +const identity = { endpoint: 'https://sim.test', apiKey: 'test-key' } +const args = [ + 'organizations', + 'search', + 'sources', + 'permissions', + 'upload', + 'source-1', + '--organization', + 'org_test', + '--provider', + 'gitlab', + '--expected-revision', + '7', + '--user-mapping', + 'users.csv', + '--project-permissions', + 'projects.csv', + '--yes', +] + +function snapshot(content: string, dispose: () => Promise) { + return { + size: Buffer.byteLength(content), + stream: async () => new Blob([content]).stream(), + dispose, + } +} + +describe('Search permission CSV upload', () => { + it('cancels a stalled snapshot and releases its read lease', async () => { + const controller = new AbortController() + let disposed = false + let cancelled = false + const result = await runEmbeddedCli( + args, + { ...identity, signal: controller.signal }, + { + openFile: async () => ({ + size: 100, + stream: async () => + new ReadableStream({ + pull() { + controller.abort() + }, + cancel() { + cancelled = true + }, + }), + dispose: async () => { + disposed = true + }, + }), + } + ) + expect(result.exitCode).toBe(1) + expect(disposed).toBe(true) + expect(cancelled).toBe(true) + expect(result.stderr).toContain('cancelled') + }) + + it('splits multibyte records by bytes before the row limit without corrupting quoted fields', async () => { + const content = `${'項'.repeat(500)},"quoted"\nline` + const row = `"${content.replaceAll('"', '""')}",42\n` + const parts: string[] = [] + const result = await runEmbeddedCli( + args, + { + ...identity, + transport: async (url, init) => { + const path = String(url) + const body = JSON.parse(String(init?.body ?? '{}')) + if (path.endsWith('/imports')) return Response.json({ data: { id: 'import-1' } }) + if (path.endsWith('/complete')) return Response.json({ data: { revision: 8 } }) + if (body.field === 'projectPermissions') parts.push(body.content) + return Response.json({ data: { nextPart: Number(path.split('/').at(-1)) + 1 } }) + }, + }, + { + openFile: async (path) => + snapshot(path === 'users.csv' ? '42,p@example.com\n' : row.repeat(800), async () => {}), + } + ) + expect(result.exitCode, result.stderr).toBe(0) + expect(parts).toHaveLength(2) + expect(parts.every((part) => Buffer.byteLength(part) <= 1024 * 1024)).toBe(true) + expect(parts.map((part) => part.slice('project_path,user_id\n'.length)).join('')).toBe( + row.repeat(800) + ) + }) + + it('retries identical committed parts and a lost completion response without opening another import', async () => { + const calls: { path: string; body: string }[] = [] + let partFailed = false + let completionFailed = false + const result = await runEmbeddedCli( + args, + { + ...identity, + transport: async (url, init) => { + const path = new URL(String(url)).pathname + calls.push({ path, body: String(init?.body ?? '') }) + if (path.endsWith('/imports')) return Response.json({ data: { id: 'import-1' } }) + if (path.endsWith('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/parts/0') && !partFailed) { + partFailed = true + return Response.json( + { error: { message: 'Try again' } }, + { status: 503, headers: { 'retry-after': '1' } } + ) + } + if (path.endsWith('/complete')) { + if (!completionFailed) { + completionFailed = true + return new Response( + new ReadableStream({ + start(stream) { + stream.error(new Error('lost response')) + }, + }), + { status: 200 } + ) + } + return Response.json({ data: { revision: 8 } }) + } + return Response.json({ data: { nextPart: path.endsWith('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/parts/0') ? 1 : 2 } }) + }, + }, + { + openFile: async (path) => + snapshot(path === 'users.csv' ? '1,p@example.com\n' : 'team/repo,1\n', async () => {}), + } + ) + expect(result.exitCode, result.stderr).toBe(0) + expect(calls.filter(({ path }) => path.endsWith('/imports'))).toHaveLength(1) + expect(calls[1]).toEqual(calls[2]) + expect(calls.at(-1)).toEqual(calls.at(-2)) + expect(JSON.parse(result.stdout).revision).toBe(8) + }) + it('stages immutable bounded parts, preserves CSV records, and activates only after both files', async () => { + const requests: { path: string; body: Record }[] = [] + const released: string[] = [] + const users = '\ufeffuser_id,email\r\n42,"person@example.com"\r\n' + const grants = `project_path,user_id\n${'team/repo,42\n'.repeat(5001)}` + const result = await runEmbeddedCli( + args, + { + ...identity, + transport: async (url, init) => { + const path = new URL(String(url)).pathname + const body = init?.body ? (JSON.parse(String(init.body)) as Record) : {} + requests.push({ path, body }) + const data = path.endsWith('/imports') + ? { id: 'import-1', expiresAt: '2027-01-01T00:00:00Z' } + : path.endsWith('/complete') + ? { revision: 8 } + : { nextPart: requests.length - 1 } + return Response.json({ data }) + }, + }, + { + openFile: async (path) => + snapshot(path === 'users.csv' ? users : grants, async () => { + released.push(path) + }), + } + ) + expect(result.exitCode, result.stderr).toBe(0) + expect(requests[0].body).toMatchObject({ + expectedRevision: 7, + userMapping: { rowCount: 1, parts: 1 }, + projectPermissions: { rowCount: 5001, parts: 2 }, + }) + const parts = requests.slice(1, -1) + expect(parts.map(({ body }) => body.field)).toEqual([ + 'userMapping', + 'projectPermissions', + 'projectPermissions', + ]) + expect(parts.every(({ body }) => Buffer.byteLength(String(body.content)) <= 1024 * 1024)).toBe( + true + ) + expect( + parts + .slice(1) + .reduce((n, { body }) => n + (String(body.content).match(/team\/repo,42/g)?.length ?? 0), 0) + ).toBe(5001) + expect(requests.at(-1)?.path).toMatch(/\/import-1\/complete$/) + expect(JSON.parse(result.stdout)).toMatchObject({ revision: 8 }) + expect(released.sort()).toEqual(['projects.csv', 'users.csv']) + }) + + it('refuses malformed or oversized records before creating an import', async () => { + for (const content of [ + 'user_id,email\n42,"unfinished', + `user_id,email\n42,${'x'.repeat(9000)}\n`, + ]) { + let requests = 0 + let released = false + const result = await runEmbeddedCli( + args, + { + ...identity, + transport: async () => { + requests++ + return Response.json({}) + }, + }, + { + openFile: async () => + snapshot(content, async () => { + released = true + }), + } + ) + expect(result.exitCode).toBe(1) + expect(requests).toBe(0) + expect(released).toBe(true) + expect(result.stderr).not.toContain(content) + } + }) + + it('never activates or changes the pinned revision after a conflict', async () => { + const paths: string[] = [] + const result = await runEmbeddedCli( + args, + { + ...identity, + transport: async (url) => { + const path = String(url) + paths.push(path) + return path.endsWith('/imports') + ? Response.json({ data: { id: 'import-1' } }) + : Response.json( + { error: { code: 'CONFLICT', message: 'Permissions changed' } }, + { status: 409 } + ) + }, + }, + { + openFile: async (path) => + snapshot( + path === 'users.csv' + ? 'user_id,email\n42,p@example.com\n' + : 'project_path,user_id\nteam/repo,42\n', + async () => {} + ), + } + ) + expect(result.exitCode).toBe(1) + expect(paths).toHaveLength(2) + expect(paths.some((path) => path.endsWith('/complete'))).toBe(false) + }) + + it('requires confirmation and cannot read the embedding server filesystem', async () => { + for (const argv of [args.filter((arg) => arg !== '--yes'), args]) { + let requests = 0 + const result = await runEmbeddedCli(argv, { + ...identity, + transport: async () => { + requests++ + return Response.json({}) + }, + }) + expect(result.exitCode).toBe(1) + expect(requests).toBe(0) + expect(result.stderr).toMatch(/--yes|no machine/) + } + }) +}) diff --git a/packages/sim-cli/src/commands/source-permissions.ts b/packages/sim-cli/src/commands/source-permissions.ts new file mode 100644 index 00000000000..67ad47b5de0 --- /dev/null +++ b/packages/sim-cli/src/commands/source-permissions.ts @@ -0,0 +1,131 @@ +import { readFile } from 'node:fs/promises' +import { setTimeout } from 'node:timers/promises' +import { backoffWithJitter } from '@sim/utils/retry' +import { type Command, Option } from 'commander' +import { printProtocolResult } from '#sim-cli/commands/protocol/result' +import type { + CompleteSourcePermissionImportResponse, + CreateSourcePermissionImportResponse, + PutSourcePermissionImportPartResponse, +} from '#sim-cli/generated/v2-api' +import { SimApiError } from '#sim-cli/http/client' +import { apiCommand } from '#sim-cli/runtime/called-operations' +import { type PermissionCsvProvider, stagePermissionCsvs } from '#sim-cli/transfer/permission-csv' + +/** Adds a bounded CSV upload workflow over the existing revisioned import operations. */ +export function attachSourcePermissionCommands(program: Command): void { + let parent = program + for (const name of ['organizations', 'search', 'sources', 'permissions']) { + const child = parent.commands.find((command) => command.name() === name) + if (!child) throw new Error(`Missing generated command group: ${name}`) + parent = child + } + const [command, connect] = apiCommand(parent, 'upload', [ + 'createSourcePermissionImport', + 'putSourcePermissionImportPart', + 'completeSourcePermissionImport', + ]) + command + .argument('', 'Search source identifier') + .description('Replace source permissions from two CSV files, uploaded in bounded parts') + .allowExcessArguments(false) + .requiredOption('--organization ', 'Organization identifier') + .addOption( + new Option('--provider ', 'Permission provider') + .choices(['gitlab']) + .makeOptionMandatory() + ) + .requiredOption('--expected-revision ', 'Revision read before exporting the CSVs') + .requiredOption('--user-mapping ', 'Complete user mapping CSV') + .requiredOption('--project-permissions ', 'Complete project permissions CSV') + .option('-y, --yes', 'Confirm replacement of all source permissions (required)') + .action( + async ( + sourceId: string, + options: { + organization: string + provider: PermissionCsvProvider + expectedRevision: string + userMapping: string + projectPermissions: string + yes?: boolean + } + ) => { + if (!options.yes) + throw new SimApiError( + 'This replaces all source permissions. Re-run with --yes to confirm.', + 0 + ) + const expectedRevision = Number(options.expectedRevision) + if ( + !Number.isInteger(expectedRevision) || + expectedRevision <= 0 || + expectedRevision >= 2147483647 + ) + throw new SimApiError('--expected-revision must be an integer from 1 to 2147483646.', 0) + const { client, profile } = connect() + const signal = profile.signal + const staged = await stagePermissionCsvs(options.provider, options, signal) + const params = { organizationId: options.organization, sourceId } + const retry = async (request: () => Promise): Promise => { + for (let attempt = 1; ; attempt++) { + signal?.throwIfAborted() + try { + return await request() + } catch (error) { + if ( + !(error instanceof SimApiError) || + attempt >= 5 || + (error.code !== 'RESPONSE_READ_FAILED' && + error.status !== 0 && + error.status !== 429 && + error.status < 500) + ) + throw error + await setTimeout( + backoffWithJitter(attempt, error.retryAfterMs, { maxMs: 300_000 }), + undefined, + { signal } + ) + } + } + } + try { + const started = await client.request( + 'createSourcePermissionImport', + { + params, + body: { provider: options.provider, expectedRevision, ...staged.manifest }, + } + ) + const importParams = { ...params, importId: started.data.id } + for (const [partNumber, part] of staged.parts.entries()) { + const content = await readFile(part.path, 'utf8') + const result = await retry(() => + client.request( + 'putSourcePermissionImportPart', + { + params: { ...importParams, partNumber: String(partNumber) }, + body: { field: part.field, content }, + } + ) + ) + if (result.data.nextPart !== partNumber + 1) + throw new SimApiError( + 'The server returned an unexpected upload position. Permissions were not activated.', + 0 + ) + } + const result = await retry(() => + client.request( + 'completeSourcePermissionImport', + { params: importParams } + ) + ) + printProtocolResult(profile.output, { sourceId, revision: result.data.revision }) + } finally { + await staged.dispose() + } + } + ) +} diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 1117f07dc80..03565c10542 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -1280,6 +1280,37 @@ export const CLI_CONTRACT: CliContract = { columns: [{ header: 'id' }, { header: 'name' }, { header: 'role' }], }, getOrganization: { command: 'organizations get' }, + prepareSearchSources: { + command: 'organizations search sources prepare', + pathFlags: ORGANIZATION_FLAG, + }, + listSearchSources: { + command: 'organizations search sources list', + pathFlags: ORGANIZATION_FLAG, + columns: [ + { header: 'id' }, + { header: 'provider', path: 'connectorType' }, + { header: 'status' }, + { header: 'approved', format: 'bool' }, + ], + }, + getSearchSource: { command: 'organizations search sources get', pathFlags: ORGANIZATION_FLAG }, + createSearchSource: { + command: 'organizations search sources create', + pathFlags: ORGANIZATION_FLAG, + flags: { apiKey: { textSource: true } }, + }, + updateSearchSource: { + command: 'organizations search sources update', + pathFlags: ORGANIZATION_FLAG, + flags: { apiKey: { textSource: true } }, + confirm: 'This updates source settings and may replace its permission grants.', + }, + deleteSearchSource: { + command: 'organizations search sources delete', + pathFlags: ORGANIZATION_FLAG, + confirm: 'This removes the source and its permission grants.', + }, getSearchSourcePermissions: { command: 'organizations search sources permissions get', pathFlags: ORGANIZATION_FLAG, diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 8769a98025e..68717b67b1e 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -3343,6 +3343,63 @@ export type CreateSandboxResponse = { data: CreateSandboxResponseRef0 } +/** `POST /api/v2/organizations/[organizationId]/search/sources` */ +export type CreateSearchSourceParams = { + organizationId: string +} + +export type CreateSearchSourceQuery = Record + +export type CreateSearchSourceBody = { + connectorType: string + credentialId?: string + apiKey?: string + sourceConfig: Record + accessMode?: 'admin' | 'members' + permissionConfig?: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + expectedRevision?: number + userMapping?: { + filename: string + content: string + } + projectPermissions?: { + filename: string + content: string + } + } +} + +export type CreateSearchSourceResponse = { + data: { + id: string + connectorType: string + credentialId: string | null + sourceConfig: Record + status: 'active' | 'paused' | 'pending' | 'syncing' | 'error' | 'disabled' + createdAt: string + updatedAt: string + accessMode: 'admin' | 'members' + approved: boolean + permissionConfig: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + revision: number + userMapping: { + filename: string + uploadedAt: string + rowCount: number + } | null + projectPermissions: { + filename: string + uploadedAt: string + rowCount: number + } | null + } | null + } +} + /** `POST /api/v2/credentials` */ export type CreateServiceAccountCredentialQuery = Record @@ -4664,6 +4721,21 @@ export type DeleteSandboxResponse = { data: DeleteSandboxResponseRef0 } +/** `DELETE /api/v2/organizations/[organizationId]/search/sources/[sourceId]` */ +export type DeleteSearchSourceParams = { + organizationId: string + sourceId: string +} + +export type DeleteSearchSourceQuery = Record + +export type DeleteSearchSourceResponse = { + data: { + id: string + deleted: true + } +} + /** `DELETE /api/v2/secrets/[name]` */ export type DeleteSecretParams = { name: string @@ -7273,6 +7345,43 @@ export type GetSandboxResponse = { data: GetSandboxResponseRef0 } +/** `GET /api/v2/organizations/[organizationId]/search/sources/[sourceId]` */ +export type GetSearchSourceParams = { + organizationId: string + sourceId: string +} + +export type GetSearchSourceQuery = Record + +export type GetSearchSourceResponse = { + data: { + id: string + connectorType: string + credentialId: string | null + sourceConfig: Record + status: 'active' | 'paused' | 'pending' | 'syncing' | 'error' | 'disabled' + createdAt: string + updatedAt: string + accessMode: 'admin' | 'members' + approved: boolean + permissionConfig: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + revision: number + userMapping: { + filename: string + uploadedAt: string + rowCount: number + } | null + projectPermissions: { + filename: string + uploadedAt: string + rowCount: number + } | null + } | null + } +} + /** `GET /api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions` */ export type GetSearchSourcePermissionsParams = { organizationId: string @@ -10452,6 +10561,48 @@ export type ListSandboxesResponse = { nextCursor: string | null } +/** `GET /api/v2/organizations/[organizationId]/search/sources` */ +export type ListSearchSourcesParams = { + organizationId: string +} + +export type ListSearchSourcesQuery = { + sortBy?: 'connectorType' | 'createdAt' | 'updatedAt' + sortOrder?: 'asc' | 'desc' + limit?: number + cursor?: string +} + +export type ListSearchSourcesResponse = { + data: Array<{ + id: string + connectorType: string + credentialId: string | null + sourceConfig: Record + status: 'active' | 'paused' | 'pending' | 'syncing' | 'error' | 'disabled' + createdAt: string + updatedAt: string + accessMode: 'admin' | 'members' + approved: boolean + permissionConfig: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + revision: number + userMapping: { + filename: string + uploadedAt: string + rowCount: number + } | null + projectPermissions: { + filename: string + uploadedAt: string + rowCount: number + } | null + } | null + }> + nextCursor: string | null +} + /** `GET /api/v2/secrets` */ export type ListSecretsQuery = { workspaceId: string @@ -11469,6 +11620,24 @@ export type MoveWorkflowsResponse = { data: MoveWorkflowsResponseRef0 } +/** `POST /api/v2/organizations/[organizationId]/search/sources/prepare` */ +export type PrepareSearchSourcesParams = { + organizationId: string +} + +export type PrepareSearchSourcesQuery = Record + +export type PrepareSearchSourcesBody = { + connectorType: string + accessMode?: 'admin' | 'members' +} + +export type PrepareSearchSourcesResponse = { + data: { + ready: true + } +} + /** `GET /api/v2/organizations/[organizationId]/access-requests/[requestId]/preview` */ export type PreviewOrganizationAccessRequestParams = { organizationId: string @@ -15620,6 +15789,62 @@ export type UpdateSandboxResponse = { data: UpdateSandboxResponseRef0 } +/** `PATCH /api/v2/organizations/[organizationId]/search/sources/[sourceId]` */ +export type UpdateSearchSourceParams = { + organizationId: string + sourceId: string +} + +export type UpdateSearchSourceQuery = Record + +export type UpdateSearchSourceBody = { + apiKey?: string + sourceConfig?: Record + permissionConfig?: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + expectedRevision?: number + userMapping?: { + filename: string + content: string + } + projectPermissions?: { + filename: string + content: string + } + } + status?: 'active' | 'paused' +} + +export type UpdateSearchSourceResponse = { + data: { + id: string + connectorType: string + credentialId: string | null + sourceConfig: Record + status: 'active' | 'paused' | 'pending' | 'syncing' | 'error' | 'disabled' + createdAt: string + updatedAt: string + accessMode: 'admin' | 'members' + approved: boolean + permissionConfig: { + provider: 'gitlab' + mode: 'administrator' | 'csv' + revision: number + userMapping: { + filename: string + uploadedAt: string + rowCount: number + } | null + projectPermissions: { + filename: string + uploadedAt: string + rowCount: number + } | null + } | null + } +} + /** `PATCH /api/v2/skills/[skillId]` */ export type UpdateSkillParams = { skillId: string @@ -17926,6 +18151,44 @@ export const V2_OPERATIONS = { }, }, }, + createSearchSource: { + method: 'POST', + path: '/api/v2/organizations/[organizationId]/search/sources', + pathParams: ['organizationId'] as const, + pathParamDocs: { organizationId: 'Organization identifier.' }, + responseMode: 'json', + summary: 'Create Search source', + body: { + connectorType: { kind: 'string', required: true, describe: 'Registered connector type.' }, + credentialId: { + kind: 'string', + describe: + 'OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors.', + }, + apiKey: { + kind: 'string', + describe: + 'Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference.', + }, + sourceConfig: { + kind: 'object', + required: true, + describe: 'Connector-specific source selection and filtering configuration.', + }, + accessMode: { + kind: 'enum', + values: ['admin', 'members'] as const, + default: 'admin', + describe: + 'Source-managed permissions (admin), or individually connected member accounts (members).', + }, + permissionConfig: { + kind: 'object', + describe: + 'Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation.', + }, + }, + }, createServiceAccountCredential: { method: 'POST', path: '/api/v2/credentials', @@ -18577,6 +18840,17 @@ export const V2_OPERATIONS = { workspaceId: { kind: 'string', required: true, describe: 'Workspace that owns the sandbox.' }, }, }, + deleteSearchSource: { + method: 'DELETE', + path: '/api/v2/organizations/[organizationId]/search/sources/[sourceId]', + pathParams: ['organizationId', 'sourceId'] as const, + pathParamDocs: { + organizationId: 'Organization identifier.', + sourceId: 'Search source identifier, also used by permission uploads.', + }, + responseMode: 'json', + summary: 'Delete Search source', + }, deleteSecret: { method: 'DELETE', path: '/api/v2/secrets/[name]', @@ -19864,6 +20138,17 @@ export const V2_OPERATIONS = { workspaceId: { kind: 'string', required: true, describe: 'Workspace that owns the sandbox.' }, }, }, + getSearchSource: { + method: 'GET', + path: '/api/v2/organizations/[organizationId]/search/sources/[sourceId]', + pathParams: ['organizationId', 'sourceId'] as const, + pathParamDocs: { + organizationId: 'Organization identifier.', + sourceId: 'Search source identifier, also used by permission uploads.', + }, + responseMode: 'json', + summary: 'Get Search source', + }, getSearchSourcePermissions: { method: 'GET', path: '/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions', @@ -22258,6 +22543,40 @@ export const V2_OPERATIONS = { }, }, }, + listSearchSources: { + method: 'GET', + path: '/api/v2/organizations/[organizationId]/search/sources', + pathParams: ['organizationId'] as const, + pathParamDocs: { organizationId: 'Organization identifier.' }, + responseMode: 'json', + summary: 'List Search sources', + query: { + sortBy: { + kind: 'enum', + values: ['connectorType', 'createdAt', 'updatedAt'] as const, + default: 'createdAt', + describe: 'Field used to sort the result.', + }, + sortOrder: { + kind: 'enum', + values: ['asc', 'desc'] as const, + default: 'desc', + describe: 'Sort direction.', + }, + limit: { + kind: 'integer', + default: 50, + maximum: 100, + describe: + 'Maximum connectors to return per page. Must be a whole number from 1 to 100. Defaults to 50.', + }, + cursor: { + kind: 'string', + describe: + 'Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor.', + }, + }, + }, listSecrets: { method: 'GET', path: '/api/v2/secrets', @@ -23302,6 +23621,24 @@ export const V2_OPERATIONS = { }, }, }, + prepareSearchSources: { + method: 'POST', + path: '/api/v2/organizations/[organizationId]/search/sources/prepare', + pathParams: ['organizationId'] as const, + pathParamDocs: { organizationId: 'Organization identifier.' }, + responseMode: 'json', + summary: 'Prepare Search sources', + body: { + connectorType: { kind: 'string', required: true, describe: 'Registered connector type.' }, + accessMode: { + kind: 'enum', + values: ['admin', 'members'] as const, + default: 'admin', + describe: + 'Source-managed permissions (admin), or individually connected member accounts (members).', + }, + }, + }, previewOrganizationAccessRequest: { method: 'GET', path: '/api/v2/organizations/[organizationId]/access-requests/[requestId]/preview', @@ -25572,6 +25909,39 @@ export const V2_OPERATIONS = { }, }, }, + updateSearchSource: { + method: 'PATCH', + path: '/api/v2/organizations/[organizationId]/search/sources/[sourceId]', + pathParams: ['organizationId', 'sourceId'] as const, + pathParamDocs: { + organizationId: 'Organization identifier.', + sourceId: 'Search source identifier, also used by permission uploads.', + }, + responseMode: 'json', + summary: 'Update Search source', + body: { + apiKey: { + kind: 'string', + describe: + 'Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token.', + }, + sourceConfig: { + kind: 'object', + describe: + 'Complete replacement source configuration. Read the existing configuration before editing it.', + }, + permissionConfig: { + kind: 'object', + describe: + 'Provider-specific permission update, using the current expectedRevision. Omit to retain permissions.', + }, + status: { + kind: 'enum', + values: ['active', 'paused'] as const, + describe: 'Pause or resume this source without changing its ID or stored permissions.', + }, + }, + }, updateSkill: { method: 'PATCH', path: '/api/v2/skills/[skillId]', diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index 3ac273dbcb2..0110810f69a 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -457,6 +457,7 @@ describe('destructive operations are gated', () => { 'completeSourcePermissionImport', 'replaceWorkflowChatDeployment', 'replaceSearchSourcePermissions', + 'updateSearchSource', 'replaceWorkflowState', 'revertWorkflowVersion', 'updateRowsByFilter', @@ -545,6 +546,8 @@ describe('destructive operations are gated', () => { 'createServiceAccountCredential', 'createSkill', 'createSourcePermissionImport', + 'createSearchSource', + 'prepareSearchSources', 'createTable', 'createTableExport', 'createTableFolder', diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 3241e038c4b..a160554996d 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -1,3 +1,4 @@ +import { parseRetryAfter } from '@sim/utils/retry' import { truncate } from '@sim/utils/string' import { writeStderr } from '#sim-cli/output/io' import { hasProgressTerminal, styles } from '#sim-cli/output/presentation' @@ -12,6 +13,7 @@ import { warnIfCredentialOverCleartext, warnIfProxyIgnored } from './environment * request. */ export class SimApiError extends Error { + retryAfterMs: number | null = null constructor( message: string, readonly status: number, @@ -716,6 +718,7 @@ export class SimClient { if (!response.ok) { const raw = await readResponseText(response) const error = toApiError(url, response, raw) + error.retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), 300_000) if (response.status === 401) { error.message = `${error.message} — run: sim login --profile ${this.profile.authProfile}` } diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index c5da098746a..adb77b81075 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -6,6 +6,7 @@ import { attachCredentialCommands } from './commands/credentials' import { attachProtocolCommands } from './commands/protocol/index' import { cliCommand } from './commands/search' import { attachSecretCommands } from './commands/secrets' +import { attachSourcePermissionCommands } from './commands/source-permissions' import { telemetryCommand } from './commands/telemetry' import { OUTPUT_FORMATS } from './config/index' import { @@ -205,6 +206,7 @@ export function buildProgram( attachCredentialCommands(program) attachProtocolCommands(program) attachSecretCommands(program) + attachSourcePermissionCommands(program) program.addHelpText('after', options.helpText ?? HELP_EPILOGUE) program.addHelpText('beforeAll', ({ command }) => diff --git a/packages/sim-cli/src/transfer/permission-csv.ts b/packages/sim-cli/src/transfer/permission-csv.ts new file mode 100644 index 00000000000..600a93b1a6f --- /dev/null +++ b/packages/sim-cli/src/transfer/permission-csv.ts @@ -0,0 +1,201 @@ +import { constants } from 'node:fs' +import { mkdtemp, open, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { addAbortSignal, Readable } from 'node:stream' +import { parse } from 'csv-parse' +import { embedStore } from '#sim-cli/embed-context' +import { SimApiError } from '#sim-cli/http/client' +import { embeddedFileKey } from '#sim-cli/transfer/local-file' + +const PART_BYTES = 1024 * 1024 +const PART_ROWS = 5000 +const MAX_BYTES = 1024 * 1024 * 1024 +const MAX_PARTS = 4096 + +const CSV_PROVIDERS = { + gitlab: { + userMapping: { header: ['user_id', 'email'], maxRows: 500_000 }, + projectPermissions: { header: ['project_path', 'user_id'], maxRows: 5_000_000 }, + }, +} as const + +export type PermissionCsvProvider = keyof typeof CSV_PROVIDERS +type CsvField = keyof (typeof CSV_PROVIDERS)['gitlab'] +interface CsvManifest { + filename: string + rowCount: number + parts: number +} + +async function* snapshotChunks(stream: ReadableStream, signal?: AbortSignal) { + const reader = stream.getReader() + const cancel = () => { + void reader.cancel(signal?.reason).catch(() => {}) + } + signal?.addEventListener('abort', cancel, { once: true }) + try { + while (true) { + signal?.throwIfAborted() + const chunk = await reader.read() + signal?.throwIfAborted() + if (chunk.done) return + yield chunk.value + } + } finally { + signal?.removeEventListener('abort', cancel) + await reader.cancel() + reader.releaseLock() + } +} + +/** Freezes CSV records into private, bounded parts before declaring the import manifest. */ +export async function stagePermissionCsvs( + provider: PermissionCsvProvider, + paths: Record, + signal?: AbortSignal +) { + const directory = await mkdtemp(join(tmpdir(), 'sim-permissions-')) + const parts: { field: CsvField; path: string }[] = [] + const manifest = {} as Record + let totalBytes = 0 + let inputBytes = 0 + const dispose = () => rm(directory, { recursive: true, force: true }) + try { + for (const field of ['userMapping', 'projectPermissions'] as const) { + signal?.throwIfAborted() + const path = paths[field] + const filename = basename(embeddedFileKey(path)) + if (!filename.trim() || filename.length > 255 || /[\p{Cc}/\\]/u.test(filename)) + throw new SimApiError( + 'Use CSV filenames of 1–255 characters without control characters.', + 0 + ) + const embedded = embedStore.getStore() + if (embedded && !embedded.openFile) + throw new SimApiError('This invocation has no machine to read from', 0) + const snapshot = await embedded?.openFile?.(embeddedFileKey(path)) + const handle = embedded + ? undefined + : await open(path, constants.O_RDONLY | constants.O_NONBLOCK) + let stream: Readable | undefined + let snapshotStream: ReadableStream | undefined + try { + const before = await handle?.stat() + if (before && !before.isFile()) + throw new SimApiError(`${field}: use a regular CSV file.`, 0) + const size = snapshot?.size ?? before?.size + if ( + size === undefined || + !Number.isSafeInteger(size) || + size <= 0 || + size > MAX_BYTES - inputBytes + ) + throw new SimApiError('CSV files must be nonempty and total at most 1 GiB.', 0) + inputBytes += size + const readSignal = + snapshot?.signal && signal + ? AbortSignal.any([snapshot.signal, signal]) + : (snapshot?.signal ?? signal) + snapshotStream = await snapshot?.stream() + stream = snapshotStream + ? Readable.from(snapshotChunks(snapshotStream, readSignal)) + : handle?.createReadStream({ autoClose: false }) + if (!stream) throw new SimApiError(`Cannot read ${field}.`, 0) + if (readSignal) addAbortSignal(readSignal, stream) + const source = stream + const decode = async function* () { + const decoder = new TextDecoder('utf-8', { fatal: true }) + let bytes = 0 + for await (const chunk of source) { + signal?.throwIfAborted() + snapshot?.signal?.throwIfAborted() + bytes += chunk.length + if (bytes > size) throw new SimApiError(`${field}: input changed during staging.`, 0) + for (let offset = 0; offset < chunk.length; offset += 65_536) { + readSignal?.throwIfAborted() + yield decoder.decode(chunk.subarray(offset, offset + 65_536), { stream: true }) + } + } + if (bytes !== size) throw new SimApiError(`${field}: input changed during staging.`, 0) + yield decoder.decode() + } + const definition = CSV_PROVIDERS[provider][field] + const header = `${definition.header.join(',')}\n` + let content = header + let partBytes = Buffer.byteLength(header) + let partRows = 0 + let rowCount = 0 + const startPart = parts.length + const save = async () => { + if (parts.length >= MAX_PARTS || totalBytes + partBytes > MAX_BYTES) + throw new SimApiError('Permission import exceeds 4,096 parts or 1 GiB.', 0) + const partPath = join(directory, String(parts.length)) + await writeFile(partPath, content, { mode: 0o600, flag: 'wx' }) + parts.push({ field, path: partPath }) + totalBytes += partBytes + } + const parser = parse({ bom: true, skip_empty_lines: true, max_record_size: 8192 }) + const decoded = Readable.from(decode()) + decoded.on('error', (error) => parser.destroy(error)) + decoded.pipe(parser) + let first = true + try { + const records: AsyncIterable = parser + for await (const row of records) { + if (row.length !== 2 || row.some((cell) => cell.length > 4096)) + throw new SimApiError( + `${field}: expected two CSV columns of at most 4,096 characters.`, + 0 + ) + if (first && row.every((cell, index) => cell.trim() === definition.header[index])) { + first = false + continue + } + first = false + rowCount++ + if (rowCount > definition.maxRows) + throw new SimApiError(`${field}: exceeds ${definition.maxRows} data records.`, 0) + const record = `${row.map((cell) => (/[",\r\n]/.test(cell) ? `"${cell.replaceAll('"', '""')}"` : cell)).join(',')}\n` + const bytes = Buffer.byteLength(record) + if (partRows === PART_ROWS || partBytes + bytes > PART_BYTES) { + await save() + content = header + partBytes = Buffer.byteLength(header) + partRows = 0 + } + content += record + partBytes += bytes + partRows++ + } + } finally { + decoded.destroy() + parser.destroy() + } + const after = await handle?.stat() + if (before && after && (before.size !== after.size || before.mtimeMs !== after.mtimeMs)) + throw new SimApiError(`${field}: input changed during staging. Rerun the export.`, 0) + if (!rowCount) throw new SimApiError(`${field}: at least one data record is required.`, 0) + await save() + manifest[field] = { filename, rowCount, parts: parts.length - startPart } + } catch (error) { + if (signal?.aborted || snapshot?.signal?.aborted) + throw new SimApiError('Permission CSV upload cancelled.', 0) + if (error instanceof SimApiError) throw error + throw new SimApiError( + `${field}: could not read valid UTF-8 CSV. Check the file, quoting, and record lengths.`, + 0 + ) + } finally { + stream?.destroy() + if (snapshotStream && !snapshotStream.locked) await snapshotStream.cancel() + await handle?.close() + await snapshot?.dispose() + } + } + return { manifest, parts, dispose } + } catch (error) { + await dispose() + throw error + } +} diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 3ad7f87c93d..9a86932b6a3 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -3267,7 +3267,6 @@ "apps/sim/lib/api/contracts/v2/knowledge.ts#v2BulkKnowledgeDocumentsBodySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2BulkKnowledgeDocumentsDataSchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2CreateKnowledgeBaseBodySchema", - "apps/sim/lib/api/contracts/v2/knowledge.ts#v2CreateKnowledgeConnectorBodySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2CreateKnowledgeDocumentUploadBodySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2CreateKnowledgeDocumentUploadDataSchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2DeleteKnowledgeConnectorQuerySchema", @@ -3294,7 +3293,6 @@ "apps/sim/lib/api/contracts/v2/knowledge.ts#v2KnowledgeSearchTagFilterSchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2ListKnowledgeBasesQuerySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2ListKnowledgeConnectorDocumentsQuerySchema", - "apps/sim/lib/api/contracts/v2/knowledge.ts#v2ListKnowledgeConnectorsQuerySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2ListKnowledgeDocumentsQuerySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2RestoreKnowledgeBaseBodySchema", "apps/sim/lib/api/contracts/v2/knowledge.ts#v2SyncKnowledgeConnectorBodySchema", From b38b556b2d9c4252b18849813cf9c5eb7d3c9bb2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 18 Nov 2026 17:45:04 -0800 Subject: [PATCH 2/4] fix(search): align source operations and complete CLI imports --- apps/docs/openapi-v2-resources.json | 6 +- .../scripts/fixtures/content-baseline.json | 121 +++++++++++++++++- .../search/sources/[sourceId]/route.ts | 6 +- .../[organizationId]/search/sources/route.ts | 4 +- .../api/contracts/v2/openapi/organizations.ts | 6 +- .../server/routes/copilot-refused-routes.json | 30 +++++ .../application/manage-search-sources.ts | 8 +- .../lib/knowledge/application/operations.ts | 21 +++ .../test-gitlab-csv-permissions-e2e.ts | 9 +- .../src/commands/source-permissions.ts | 2 +- .../sim-cli/src/transfer/permission-csv.ts | 1 + 11 files changed, 194 insertions(+), 20 deletions(-) diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 4e811ec7818..373b8384fb1 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -10941,7 +10941,7 @@ "operationId": "createSearchSource", "summary": "Create Search source", "description": "Create a source in the prepared organization Search index using the same provider validation as Settings. Use connector-types list for provider configuration. This does not override an explicit integration approval decision. Organization admin required.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "knowledge.connectors.create", + "x-sim-operation": "knowledge.search.sources.manage.create", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11123,7 +11123,7 @@ "operationId": "updateSearchSource", "summary": "Update Search source", "description": "Update source selection, supported provider credentials, or permission settings; pause or resume a source. Omitted fields are retained. sourceConfig replaces the complete configuration. GitLab token rotation retains saved grants and advances the permission revision; supply permissionConfig with the current expectedRevision for rotation or CSV updates. Organization admin required.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "knowledge.connectors.update", + "x-sim-operation": "knowledge.search.sources.manage.update", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ @@ -11227,7 +11227,7 @@ "operationId": "deleteSearchSource", "summary": "Delete Search source", "description": "Remove a source and its associated permission grants. Cleanup is asynchronous. Organization admin required.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "knowledge.connectors.delete", + "x-sim-operation": "knowledge.search.sources.manage.delete", "x-oauth-scope": "api:write", "tags": ["Organizations"], "security": [ diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index b41bd6ac861..599bb16963f 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -6199,6 +6199,13 @@ "bytes": 80, "line": 266 }, + { + "lang": "bash", + "meta": null, + "sha256": "412f8bcf9151f7075294ba9e7cfcbb86581e91dbd1b217775e9fb6958df71a2e", + "bytes": 72, + "line": 298 + }, { "lang": "bash", "meta": null, @@ -6422,6 +6429,48 @@ "sha256": "c3410310e5eccb2e0a7440b8d3cbfc2508270890a08ec5a85c5b8cc5c5a3b8b8", "bytes": 45, "line": 1025 + }, + { + "lang": "bash", + "meta": null, + "sha256": "91c6910aa33b8d3c65dccd59a480a9d986eadf89d8d4974ade0c8cb47c7ac821", + "bytes": 47, + "line": 1246 + }, + { + "lang": "bash", + "meta": null, + "sha256": "34378bac1290005ec4e6a46fc968c097307dc2dd27dffd2ed275b885dcc8502b", + "bytes": 57, + "line": 1268 + }, + { + "lang": "bash", + "meta": null, + "sha256": "483447579062e117424ae72463645f166fea91b8a87fe6efcf48a24a3a8145f8", + "bytes": 49, + "line": 1296 + }, + { + "lang": "bash", + "meta": null, + "sha256": "7deac995bc8ac114dae3500bb4792b73fdb39f5b666f4a2886428320e1ffbd00", + "bytes": 60, + "line": 1322 + }, + { + "lang": "bash", + "meta": null, + "sha256": "e57bccfdde20412a95b0aeb601448b791eb566d28af3b17bbc16d1e62bbcfb4c", + "bytes": 60, + "line": 1357 + }, + { + "lang": "bash", + "meta": null, + "sha256": "303d009467865566416478bccdf9e95291862e222144f55ca61bae5d446fa9d5", + "bytes": 50, + "line": 1386 } ], "links": [ @@ -11213,7 +11262,7 @@ "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", "bytes": 276, - "line": 788 + "line": 824 }, { "lang": "bash", @@ -12034,6 +12083,55 @@ "bytes": 73, "line": 4629 }, + { + "lang": "bash", + "meta": null, + "sha256": "412f8bcf9151f7075294ba9e7cfcbb86581e91dbd1b217775e9fb6958df71a2e", + "bytes": 72, + "line": 4152 + }, + { + "lang": "bash", + "meta": null, + "sha256": "483447579062e117424ae72463645f166fea91b8a87fe6efcf48a24a3a8145f8", + "bytes": 49, + "line": 4187 + }, + { + "lang": "bash", + "meta": null, + "sha256": "e57bccfdde20412a95b0aeb601448b791eb566d28af3b17bbc16d1e62bbcfb4c", + "bytes": 60, + "line": 4215 + }, + { + "lang": "bash", + "meta": null, + "sha256": "34378bac1290005ec4e6a46fc968c097307dc2dd27dffd2ed275b885dcc8502b", + "bytes": 57, + "line": 4246 + }, + { + "lang": "bash", + "meta": null, + "sha256": "91c6910aa33b8d3c65dccd59a480a9d986eadf89d8d4974ade0c8cb47c7ac821", + "bytes": 47, + "line": 4276 + }, + { + "lang": "bash", + "meta": null, + "sha256": "303d009467865566416478bccdf9e95291862e222144f55ca61bae5d446fa9d5", + "bytes": 50, + "line": 4300 + }, + { + "lang": "bash", + "meta": null, + "sha256": "7deac995bc8ac114dae3500bb4792b73fdb39f5b666f4a2886428320e1ffbd00", + "bytes": 60, + "line": 4324 + }, { "lang": "bash", "meta": null, @@ -177288,6 +177386,27 @@ "sha256": "b47b752aa05ada4c5cc86ae0288d5ddd6962cc494914734782a2e1af473dc702", "bytes": 166, "line": 178 + }, + { + "lang": "bash", + "meta": null, + "sha256": "41bf831b3ed549af4ccc27fd71179fb8ba17801331f112f2db934e7ea324ed34", + "bytes": 149, + "line": 209 + }, + { + "lang": "bash", + "meta": null, + "sha256": "282cedbb813458343d7648d9a180ea6116c7453e5147d376f2bfcb71758d1fea", + "bytes": 344, + "line": 218 + }, + { + "lang": "bash", + "meta": null, + "sha256": "ea459f99a80af3f528ef2c82b80c981a8db1ddabcbb90881b4b1ce0fc2d4de54", + "bytes": 476, + "line": 232 } ], "links": [ diff --git a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts index f4411be40fb..8c605f8dbce 100644 --- a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts +++ b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/[sourceId]/route.ts @@ -11,7 +11,7 @@ import { readManagedSearchSource, updateManagedSearchSource, } from '@/lib/knowledge/application/manage-search-sources' -import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' +import { searchSourceOperations } from '@/lib/knowledge/application/operations' export const GET = defineV2JsonRoute({ contract: v2GetSearchSourceContract, @@ -26,7 +26,7 @@ export const GET = defineV2JsonRoute({ export const PATCH = defineV2JsonRoute({ contract: v2UpdateSearchSourceContract, - operation: knowledgeOperations.updateConnector.organizationOperation, + operation: searchSourceOperations.update, auth: v2ApiKeyAuth, rateLimit: v2RateLimits.publicApi, errorPolicy: v2OrganizationErrorPolicy, @@ -37,7 +37,7 @@ export const PATCH = defineV2JsonRoute({ export const DELETE = defineV2JsonRoute({ contract: v2DeleteSearchSourceContract, - operation: knowledgeOperations.deleteConnector.organizationOperation, + operation: searchSourceOperations.delete, auth: v2ApiKeyAuth, rateLimit: v2RateLimits.publicApi, errorPolicy: v2OrganizationErrorPolicy, diff --git a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts index 164945c5340..5586ef40916 100644 --- a/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts +++ b/apps/sim/app/api/v2/organizations/[organizationId]/search/sources/route.ts @@ -10,7 +10,7 @@ import { createManagedSearchSource, listManagedSearchSources, } from '@/lib/knowledge/application/manage-search-sources' -import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' +import { searchSourceOperations } from '@/lib/knowledge/application/operations' import { cursorSortKey, decodeOffsetCursor, encodeOffsetCursor } from '@/app/api/v2/lib/response' const cursorScope = (organizationId: string) => @@ -48,7 +48,7 @@ export const GET = defineV2JsonRoute({ export const POST = defineV2JsonRoute({ contract: v2CreateSearchSourceContract, - operation: knowledgeOperations.createConnector.organizationOperation, + operation: searchSourceOperations.create, auth: v2ApiKeyAuth, rateLimit: v2RateLimits.publicApi, errorPolicy: v2OrganizationErrorPolicy, diff --git a/apps/sim/lib/api/contracts/v2/openapi/organizations.ts b/apps/sim/lib/api/contracts/v2/openapi/organizations.ts index 5297e0ffd94..1ea208c05c8 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/organizations.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/organizations.ts @@ -843,7 +843,7 @@ export const organizationOpenApiRoutes = [ defineOpenApiRoute( v2CreateSearchSourceContract, { - applicationOperation: knowledgeOperations.createConnector.organizationOperation, + applicationOperation: searchSourceOperations.create, operationId: 'createSearchSource', summary: 'Create Search source', description: @@ -877,7 +877,7 @@ export const organizationOpenApiRoutes = [ defineOpenApiRoute( v2UpdateSearchSourceContract, { - applicationOperation: knowledgeOperations.updateConnector.organizationOperation, + applicationOperation: searchSourceOperations.update, operationId: 'updateSearchSource', summary: 'Update Search source', description: @@ -911,7 +911,7 @@ export const organizationOpenApiRoutes = [ defineOpenApiRoute( v2DeleteSearchSourceContract, { - applicationOperation: knowledgeOperations.deleteConnector.organizationOperation, + applicationOperation: searchSourceOperations.delete, operationId: 'deleteSearchSource', summary: 'Delete Search source', description: diff --git a/apps/sim/lib/api/server/routes/copilot-refused-routes.json b/apps/sim/lib/api/server/routes/copilot-refused-routes.json index ad009740389..8ea813379b7 100644 --- a/apps/sim/lib/api/server/routes/copilot-refused-routes.json +++ b/apps/sim/lib/api/server/routes/copilot-refused-routes.json @@ -179,6 +179,31 @@ "path": "/api/v2/organizations/[organizationId]/permission-groups/[groupId]/members/bulk", "operation": "permission_groups.members.bulk_add" }, + { + "method": "GET", + "path": "/api/v2/organizations/[organizationId]/search/sources", + "operation": "knowledge.search.sources.manage.list" + }, + { + "method": "POST", + "path": "/api/v2/organizations/[organizationId]/search/sources", + "operation": "knowledge.search.sources.manage.create" + }, + { + "method": "GET", + "path": "/api/v2/organizations/[organizationId]/search/sources/[sourceId]", + "operation": "knowledge.search.sources.manage.read" + }, + { + "method": "PATCH", + "path": "/api/v2/organizations/[organizationId]/search/sources/[sourceId]", + "operation": "knowledge.search.sources.manage.update" + }, + { + "method": "DELETE", + "path": "/api/v2/organizations/[organizationId]/search/sources/[sourceId]", + "operation": "knowledge.search.sources.manage.delete" + }, { "method": "GET", "path": "/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions", @@ -204,6 +229,11 @@ "path": "/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions/imports/[importId]/parts/[partNumber]", "operation": "knowledge.search.source_permissions.replace" }, + { + "method": "POST", + "path": "/api/v2/organizations/[organizationId]/search/sources/prepare", + "operation": "knowledge.search.sources.prepare" + }, { "method": "GET", "path": "/api/v2/organizations/[organizationId]/sso/policy", diff --git a/apps/sim/lib/knowledge/application/manage-search-sources.ts b/apps/sim/lib/knowledge/application/manage-search-sources.ts index 21a8f8842fa..676f75cace1 100644 --- a/apps/sim/lib/knowledge/application/manage-search-sources.ts +++ b/apps/sim/lib/knowledge/application/manage-search-sources.ts @@ -16,7 +16,7 @@ import { updateKnowledgeConnector, } from '@/lib/knowledge/application/connectors' import { resolveActiveKnowledgeConnectorContext } from '@/lib/knowledge/application/contexts' -import { knowledgeOperations, searchSourceOperations } from '@/lib/knowledge/application/operations' +import { searchSourceOperations } from '@/lib/knowledge/application/operations' import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy' import { findSearchIndex } from '@/lib/knowledge/search/search-index' @@ -115,7 +115,7 @@ export const readManagedSearchSource = defineAuthorizedOrganizationUseCase({ /** Creates a source in the prepared Search index using the same validation and write as Settings. */ export const createManagedSearchSource = defineAuthorizedOrganizationUseCase({ - operation: knowledgeOperations.createConnector.organizationOperation, + operation: searchSourceOperations.create, async execute({ principal, input, request }: OrganizationUseCaseContext) { await requireOrganizationSearchAvailable(input.organizationId) const index = await findSearchIndex({ @@ -151,7 +151,7 @@ export const createManagedSearchSource = defineAuthorizedOrganizationUseCase({ /** Updates source settings while retaining the connector's permission revision and token rules. */ export const updateManagedSearchSource = defineAuthorizedOrganizationUseCase({ - operation: knowledgeOperations.updateConnector.organizationOperation, + operation: searchSourceOperations.update, async execute({ principal, input, @@ -182,7 +182,7 @@ export const updateManagedSearchSource = defineAuthorizedOrganizationUseCase({ /** Removes only the resolved Search source, retaining the existing durable permission cleanup. */ export const deleteManagedSearchSource = defineAuthorizedOrganizationUseCase({ - operation: knowledgeOperations.deleteConnector.organizationOperation, + operation: searchSourceOperations.delete, async execute({ principal, input, request }: OrganizationUseCaseContext) { await requireSearchSource(principal, input) return deleteKnowledgeConnector.execute({ diff --git a/apps/sim/lib/knowledge/application/operations.ts b/apps/sim/lib/knowledge/application/operations.ts index f6749ac2871..9310010ee50 100644 --- a/apps/sim/lib/knowledge/application/operations.ts +++ b/apps/sim/lib/knowledge/application/operations.ts @@ -1033,6 +1033,27 @@ function defineKnowledgeSessionOperation( } export const searchSourceOperations = { + create: defineOrganizationOperation({ + id: 'knowledge.search.sources.manage.create', + oauthScope: 'api:write', + minimumRole: 'admin', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'knowledge.use', + }), + update: defineOrganizationOperation({ + id: 'knowledge.search.sources.manage.update', + oauthScope: 'api:write', + minimumRole: 'admin', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'knowledge.use', + }), + delete: defineOrganizationOperation({ + id: 'knowledge.search.sources.manage.delete', + oauthScope: 'api:write', + minimumRole: 'admin', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'knowledge.use', + }), list: defineOrganizationOperation({ id: 'knowledge.search.sources.manage.list', oauthScope: 'api:read', diff --git a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts index 400ee2f459e..e7774ad5c61 100644 --- a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts +++ b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts @@ -40,6 +40,7 @@ const otherOrg = generateId() const admin = generateId() const member = generateId() const otherAdmin = generateId() +const billingOwner = generateId() const workspace = generateId() const kb = generateId() const source = generateId() @@ -101,14 +102,16 @@ async function writeReport(status: 'running' | 'failed' | 'passed') { try { await writeReport('running') await sql.begin(async (tx) => { - for (const id of [admin, member, otherAdmin]) { + for (const id of [admin, member, otherAdmin, billingOwner]) { await tx`insert into "user" (id, name, email, email_verified, created_at, updated_at) values (${id}, 'GitLab CSV fixture', ${`${id}@fixture.test`}, true, now(), now())` } for (const id of [org, otherOrg]) { await tx`insert into organization (id, name, slug) values (${id}, 'GitLab CSV fixture', ${id})` await tx`insert into member (id, organization_id, user_id, role) - values (${generateId()}, ${id}, ${id === org ? admin : otherAdmin}, 'owner')` + values (${generateId()}, ${id}, ${id === org ? admin : otherAdmin}, 'admin')` + await tx`insert into member (id, organization_id, user_id, role) + values (${generateId()}, ${id}, ${billingOwner}, 'owner')` } await tx`insert into member (id, organization_id, user_id, role) values (${generateId()}, ${org}, ${member}, 'member')` @@ -738,7 +741,7 @@ try { await tx`delete from workspace where id = ${workspace}` await tx`delete from project where id = ${workspace}` await tx`delete from organization where id in (${org}, ${otherOrg})` - await tx`delete from "user" where id in (${admin}, ${member}, ${otherAdmin})` + await tx`delete from "user" where id in (${admin}, ${member}, ${otherAdmin}, ${billingOwner})` }) } catch (error) { failure ??= getErrorMessage(error) diff --git a/packages/sim-cli/src/commands/source-permissions.ts b/packages/sim-cli/src/commands/source-permissions.ts index 67ad47b5de0..44db5504b08 100644 --- a/packages/sim-cli/src/commands/source-permissions.ts +++ b/packages/sim-cli/src/commands/source-permissions.ts @@ -119,7 +119,7 @@ export function attachSourcePermissionCommands(program: Command): void { const result = await retry(() => client.request( 'completeSourcePermissionImport', - { params: importParams } + { params: importParams, body: {} } ) ) printProtocolResult(profile.output, { sourceId, revision: result.data.revision }) diff --git a/packages/sim-cli/src/transfer/permission-csv.ts b/packages/sim-cli/src/transfer/permission-csv.ts index 600a93b1a6f..ae63472bd24 100644 --- a/packages/sim-cli/src/transfer/permission-csv.ts +++ b/packages/sim-cli/src/transfer/permission-csv.ts @@ -20,6 +20,7 @@ const CSV_PROVIDERS = { }, } as const +/** Providers with a supported CSV permission format and bounded upload manifest. */ export type PermissionCsvProvider = keyof typeof CSV_PROVIDERS type CsvField = keyof (typeof CSV_PROVIDERS)['gitlab'] interface CsvManifest { From 19ddc8ea147f98bfa6cbe6ed0e8ec314fe6be816 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 18 Nov 2026 17:53:56 -0800 Subject: [PATCH 3/4] fix(cli): preserve upload errors and support early Node 20 --- .../scripts/fixtures/content-baseline.json | 2 +- .../test-gitlab-csv-permissions-e2e.ts | 7 +- .../src/commands/source-permissions.test.ts | 67 ++++++++++++++----- packages/sim-cli/src/http/client.ts | 2 +- .../sim-cli/src/transfer/permission-csv.ts | 28 ++++---- 5 files changed, 72 insertions(+), 34 deletions(-) diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 599bb16963f..b89569db304 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -11262,7 +11262,7 @@ "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", "bytes": 276, - "line": 824 + "line": 788 }, { "lang": "bash", diff --git a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts index e7774ad5c61..45ece5a54f2 100644 --- a/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts +++ b/apps/sim/scripts/test-gitlab-csv-permissions-e2e.ts @@ -41,6 +41,7 @@ const admin = generateId() const member = generateId() const otherAdmin = generateId() const billingOwner = generateId() +const otherBillingOwner = generateId() const workspace = generateId() const kb = generateId() const source = generateId() @@ -102,7 +103,7 @@ async function writeReport(status: 'running' | 'failed' | 'passed') { try { await writeReport('running') await sql.begin(async (tx) => { - for (const id of [admin, member, otherAdmin, billingOwner]) { + for (const id of [admin, member, otherAdmin, billingOwner, otherBillingOwner]) { await tx`insert into "user" (id, name, email, email_verified, created_at, updated_at) values (${id}, 'GitLab CSV fixture', ${`${id}@fixture.test`}, true, now(), now())` } @@ -111,7 +112,7 @@ try { await tx`insert into member (id, organization_id, user_id, role) values (${generateId()}, ${id}, ${id === org ? admin : otherAdmin}, 'admin')` await tx`insert into member (id, organization_id, user_id, role) - values (${generateId()}, ${id}, ${billingOwner}, 'owner')` + values (${generateId()}, ${id}, ${id === org ? billingOwner : otherBillingOwner}, 'owner')` } await tx`insert into member (id, organization_id, user_id, role) values (${generateId()}, ${org}, ${member}, 'member')` @@ -741,7 +742,7 @@ try { await tx`delete from workspace where id = ${workspace}` await tx`delete from project where id = ${workspace}` await tx`delete from organization where id in (${org}, ${otherOrg})` - await tx`delete from "user" where id in (${admin}, ${member}, ${otherAdmin}, ${billingOwner})` + await tx`delete from "user" where id in (${admin}, ${member}, ${otherAdmin}, ${billingOwner}, ${otherBillingOwner})` }) } catch (error) { failure ??= getErrorMessage(error) diff --git a/packages/sim-cli/src/commands/source-permissions.test.ts b/packages/sim-cli/src/commands/source-permissions.test.ts index ef7fe71c60e..17856bbf2c2 100644 --- a/packages/sim-cli/src/commands/source-permissions.test.ts +++ b/packages/sim-cli/src/commands/source-permissions.test.ts @@ -33,35 +33,70 @@ function snapshot(content: string, dispose: () => Promise) { } describe('Search permission CSV upload', () => { - it('cancels a stalled snapshot and releases its read lease', async () => { + it('cancels a stalled snapshot on Node 20 without AbortSignal.any and releases its lease', async () => { const controller = new AbortController() + const snapshotController = new AbortController() + const originalAny = Object.getOwnPropertyDescriptor(AbortSignal, 'any') + Object.defineProperty(AbortSignal, 'any', { value: undefined, configurable: true }) let disposed = false let cancelled = false + try { + const result = await runEmbeddedCli( + args, + { ...identity, signal: controller.signal }, + { + openFile: async () => ({ + size: 100, + signal: snapshotController.signal, + stream: async () => + new ReadableStream({ + pull() { + controller.abort() + }, + cancel() { + cancelled = true + }, + }), + dispose: async () => { + disposed = true + }, + }), + } + ) + expect(result.exitCode).toBe(1) + expect(disposed).toBe(true) + expect(cancelled).toBe(true) + expect(result.stderr).toContain('cancelled') + } finally { + if (originalAny) Object.defineProperty(AbortSignal, 'any', originalAny) + } + }) + + it('preserves snapshot I/O failures instead of blaming CSV syntax', async () => { + let requests = 0 const result = await runEmbeddedCli( args, - { ...identity, signal: controller.signal }, + { + ...identity, + transport: async () => { + requests++ + return Response.json({}) + }, + }, { openFile: async () => ({ size: 100, - stream: async () => - new ReadableStream({ - pull() { - controller.abort() - }, - cancel() { - cancelled = true - }, - }), - dispose: async () => { - disposed = true + stream: async () => { + throw new Error('Remote snapshot reader unavailable') }, + dispose: async () => {}, }), } ) expect(result.exitCode).toBe(1) - expect(disposed).toBe(true) - expect(cancelled).toBe(true) - expect(result.stderr).toContain('cancelled') + expect(requests).toBe(0) + expect(result.stderr).toContain('Remote snapshot reader unavailable') + expect(result.stderr).not.toContain('quoting') }) it('splits multibyte records by bytes before the row limit without corrupting quoted fields', async () => { diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index a160554996d..0db293d4231 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -401,7 +401,7 @@ function resolveTimeoutMs(env: NodeJS.ProcessEnv = process.env): number { * on the earliest 20.x releases calling it would throw a bare `TypeError` * before the request was ever made — turning a supported runtime into a crash. */ -function combineSignals( +export function combineSignals( caller: AbortSignal | undefined, timeout: AbortSignal | undefined ): AbortSignal | undefined { diff --git a/packages/sim-cli/src/transfer/permission-csv.ts b/packages/sim-cli/src/transfer/permission-csv.ts index ae63472bd24..8c1798634c5 100644 --- a/packages/sim-cli/src/transfer/permission-csv.ts +++ b/packages/sim-cli/src/transfer/permission-csv.ts @@ -3,9 +3,9 @@ import { mkdtemp, open, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { addAbortSignal, Readable } from 'node:stream' -import { parse } from 'csv-parse' +import { CsvError, parse } from 'csv-parse' import { embedStore } from '#sim-cli/embed-context' -import { SimApiError } from '#sim-cli/http/client' +import { combineSignals, SimApiError } from '#sim-cli/http/client' import { embeddedFileKey } from '#sim-cli/transfer/local-file' const PART_BYTES = 1024 * 1024 @@ -94,10 +94,7 @@ export async function stagePermissionCsvs( ) throw new SimApiError('CSV files must be nonempty and total at most 1 GiB.', 0) inputBytes += size - const readSignal = - snapshot?.signal && signal - ? AbortSignal.any([snapshot.signal, signal]) - : (snapshot?.signal ?? signal) + const readSignal = combineSignals(snapshot?.signal, signal) snapshotStream = await snapshot?.stream() stream = snapshotStream ? Readable.from(snapshotChunks(snapshotStream, readSignal)) @@ -107,6 +104,13 @@ export async function stagePermissionCsvs( const source = stream const decode = async function* () { const decoder = new TextDecoder('utf-8', { fatal: true }) + const decodeText = (chunk?: Uint8Array): string => { + try { + return decoder.decode(chunk, { stream: chunk !== undefined }) + } catch { + throw new SimApiError(`${field}: CSV must contain valid UTF-8.`, 0) + } + } let bytes = 0 for await (const chunk of source) { signal?.throwIfAborted() @@ -115,11 +119,11 @@ export async function stagePermissionCsvs( if (bytes > size) throw new SimApiError(`${field}: input changed during staging.`, 0) for (let offset = 0; offset < chunk.length; offset += 65_536) { readSignal?.throwIfAborted() - yield decoder.decode(chunk.subarray(offset, offset + 65_536), { stream: true }) + yield decodeText(chunk.subarray(offset, offset + 65_536)) } } if (bytes !== size) throw new SimApiError(`${field}: input changed during staging.`, 0) - yield decoder.decode() + yield decodeText() } const definition = CSV_PROVIDERS[provider][field] const header = `${definition.header.join(',')}\n` @@ -182,11 +186,9 @@ export async function stagePermissionCsvs( } catch (error) { if (signal?.aborted || snapshot?.signal?.aborted) throw new SimApiError('Permission CSV upload cancelled.', 0) - if (error instanceof SimApiError) throw error - throw new SimApiError( - `${field}: could not read valid UTF-8 CSV. Check the file, quoting, and record lengths.`, - 0 - ) + if (error instanceof CsvError) + throw new SimApiError(`${field}: invalid CSV quoting or record length.`, 0) + throw error } finally { stream?.destroy() if (snapshotStream && !snapshotStream.locked) await snapshotStream.cancel() From b49cd8596bd0aa7e0f69d29b7ccc43fa7339c17a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 18 Nov 2026 18:02:07 -0800 Subject: [PATCH 4/4] fix(cli): retain structured upload errors and retry guidance --- .../src/commands/source-permissions.test.ts | 1 + packages/sim-cli/src/http/client.test.ts | 24 +++++++++++++ packages/sim-cli/src/http/client.ts | 4 ++- packages/sim-cli/src/terminal.test.ts | 34 +++++++++++++++++++ .../sim-cli/src/transfer/permission-csv.ts | 8 ++++- 5 files changed, 69 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/source-permissions.test.ts b/packages/sim-cli/src/commands/source-permissions.test.ts index 17856bbf2c2..224f21dc14c 100644 --- a/packages/sim-cli/src/commands/source-permissions.test.ts +++ b/packages/sim-cli/src/commands/source-permissions.test.ts @@ -69,6 +69,7 @@ describe('Search permission CSV upload', () => { expect(result.stderr).toContain('cancelled') } finally { if (originalAny) Object.defineProperty(AbortSignal, 'any', originalAny) + else Reflect.deleteProperty(AbortSignal, 'any') } }) diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index 0110810f69a..ad14ac058d8 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -103,6 +103,30 @@ describe('redirects', () => { }) describe('non-JSON responses', () => { + it.each([200, 429, 503])( + 'retains Retry-After when the HTTP %i response body is lost', + async (status) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.error(new Error('Connection closed')) + }, + }), + { status, headers: { 'retry-after': '10' } } + ) + ) + ) + await expect(client().request('/api/v2/workflows')).rejects.toMatchObject({ + code: 'RESPONSE_READ_FAILED', + status, + retryAfterMs: 10_000, + }) + } + ) + it('turns a 200 that is not JSON into an explained error, not a SyntaxError', async () => { vi.stubGlobal( 'fetch', diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 0db293d4231..8d5c771b71d 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -250,7 +250,7 @@ async function readResponseText(response: Response): Promise { try { return await response.text() } catch (error) { - throw new SimApiError( + const failure = new SimApiError( `Unable to read the response: ${transportErrorMessage(error)}`, response.status, 'RESPONSE_READ_FAILED', @@ -258,6 +258,8 @@ async function readResponseText(response: Response): Promise { 1, responseRequestId(response) ) + failure.retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), 300_000) + throw failure } } diff --git a/packages/sim-cli/src/terminal.test.ts b/packages/sim-cli/src/terminal.test.ts index bbf412d8a1f..a6d4a0dd50d 100644 --- a/packages/sim-cli/src/terminal.test.ts +++ b/packages/sim-cli/src/terminal.test.ts @@ -54,6 +54,40 @@ class ExitCalled extends Error { } describe('API errors at the terminal', () => { + it('reports CSV file failures as structured JSON instead of crashing', async () => { + const directory = mkdtempSync(join(tmpdir(), 'sim-cli-missing-csv-')) + try { + const { stderr, exitCode } = await runAgainst( + [ + '--output', + 'json', + 'organizations', + 'search', + 'sources', + 'permissions', + 'upload', + 'source-1', + '--organization', + 'org_test', + '--provider', + 'gitlab', + '--expected-revision', + '1', + '--user-mapping', + join(directory, 'missing.csv'), + '--project-permissions', + join(directory, 'projects.csv'), + '--yes', + ], + Response.json({}) + ) + expect(exitCode).toBe(1) + expect(JSON.parse(stderr).error.message).toContain('ENOENT') + } finally { + rmSync(directory, { recursive: true, force: true }) + } + }) + it('names the server request id in JSON output', async () => { const { stderr, exitCode } = await runAgainst( ['--output', 'json', 'workflows', 'get', 'wf-missing'], diff --git a/packages/sim-cli/src/transfer/permission-csv.ts b/packages/sim-cli/src/transfer/permission-csv.ts index 8c1798634c5..6c9c22aa3fe 100644 --- a/packages/sim-cli/src/transfer/permission-csv.ts +++ b/packages/sim-cli/src/transfer/permission-csv.ts @@ -3,6 +3,7 @@ import { mkdtemp, open, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { addAbortSignal, Readable } from 'node:stream' +import { getErrorMessage } from '@sim/utils/errors' import { CsvError, parse } from 'csv-parse' import { embedStore } from '#sim-cli/embed-context' import { combineSignals, SimApiError } from '#sim-cli/http/client' @@ -56,7 +57,9 @@ export async function stagePermissionCsvs( paths: Record, signal?: AbortSignal ) { - const directory = await mkdtemp(join(tmpdir(), 'sim-permissions-')) + const directory = await mkdtemp(join(tmpdir(), 'sim-permissions-')).catch((error: unknown) => { + throw new SimApiError(`Cannot stage permission CSVs: ${getErrorMessage(error)}`, 0) + }) const parts: { field: CsvField; path: string }[] = [] const manifest = {} as Record let totalBytes = 0 @@ -199,6 +202,9 @@ export async function stagePermissionCsvs( return { manifest, parts, dispose } } catch (error) { await dispose() + if (error instanceof SimApiError) throw error + if (error instanceof Error && 'code' in error && typeof error.code === 'string') + throw new SimApiError(`Cannot stage permission CSVs: ${error.message}`, 0) throw error } }