feat(features): roll out features by deployment and organization, with a kill switch (#5702)

* feat(den): declare features once in a registry stored per organization

Adds packages/types/src/den/features.ts as the single place a feature is
declared. Each entry decides, separately for OpenWork Cloud and self-hosted,
whether the feature exists (unavailable / off / on) or is controlled per
organization by platform admins, with a default.

- Storage moves from organization.metadata.capabilities to a new
  organization_feature table (migration 0129 copies existing overrides and
  the old Connect aliases). Better Auth never writes it, so creating an
  organization can no longer turn features on; metadata.capabilities is
  stripped at creation and no longer sent to members. Writes are mirrored
  into metadata for one release so a rollback keeps working.
- den-api reads features only through features.ts (getOrganizationFeatures,
  organizationFeatureEnabled, requireFeature). The three hand-written
  capability helper modules are deleted.
- DEN_DEPLOYMENT (default self_hosted) and DEN_FEATURE_* locks, rendered
  from a generated Helm config.features block with a values schema. A lock
  outranks a stored override.
- /admin schemas and the Den admin panel are generated from the registry,
  with Default / override / locked states and "Use default".
- GET /v1/org adds features; capabilities stays frozen for published clients.
- pnpm features:sync / features:check plus a CI job keep the chart in step
  and reject new DEN_*_ENABLED switches or metadata.capabilities reads.
- add-a-feature skill and an AGENTS.md line: flag first, before feature code.

No behavior change: every existing feature keeps its current default and
stays platform-controlled on both deployments.

* refactor(features): move the registry into its own @openwork/features package

The registry and resolver were runtime logic living in @openwork/types.
They now live in packages/features:

- src/registry.ts: the one file you edit to declare a feature
- src/resolve.ts: precedence rules, env parsing, key schema (pure, no I/O)
- src/resolve.test.ts: node:test coverage of the precedence rules, env
  parsing, key schema and DEN_FEATURE_* names, run in features-check CI

Files import each other through package self-references, so the TypeScript
source runs as-is under Node (verified in the node:22 production image) and
typechecks in every consumer without a build step.

Also adds the package to the den, gateway and den-web Docker images and to
the den-contract CI path filters, and pins azure/setup-helm to a commit SHA
(Warden finding).

* ci(features): check that Dockerfiles copy every workspace package they need

The den, gateway, den-web and den-gateway images copy workspace packages one
by one for layer caching, and only publish-ee-images builds them, so a missed
COPY line surfaced at release time. scripts/check-docker-workspace-packages.mjs
reads the manifests and Dockerfiles (about 10 ms) and fails when a copied
package.json depends on a workspace package whose package.json is not copied
(pnpm install fails) or a copied source folder imports one at runtime that is
not copied. It runs inside pnpm features:check, and the workflow now also
triggers on Dockerfile, workspace and package.json changes.

* ci(features): name the exact setup-helm version in its pin comment

* feat(features): roll features out by deployment, percentage, organization and kill switch

A feature is no longer "per organization". Each registry entry declares only
what is fixed in code: its subject (organization, or person so signed-out
desktop users are included), the deployments it exists on, and its starting
percentage. Everything else is runtime state, resolved by one function in
@openwork/features, in this order: not part of this deployment, kill switch,
operator lock (DEN_FEATURE_*), organization override, percentage of the
subject (stable FNV-1a bucket; raising it only adds subjects).

- feature_rollout table (migration 0129 now creates it alongside
  organization_feature) holds percentage and kill switch per feature.
- /admin › Features page and GET/PUT /v1/admin/features change them without
  a deploy; organization rows show why a feature is on or off.
- Admin MCP tools den_list_features and den_set_feature_rollout.
- Public GET /v1/features/rollouts for clients that resolve person features
  themselves, including signed-out desktops.
- /v1/org resolves person features for the signed-in member.
- The nine existing features keep today's behaviour: organization subject,
  starting at 100% (install links, Connect) or 0% (the rest).
- Skill, AGENTS.md, Helm comments and README describe the one model;
  features:check asks for a decision on rollouts older than six months
  unless marked permanent.

* refactor(features): drop percentage rollouts; on or off for everyone, per organization, or killed

Removes percentage rollouts and the organization/person subject they needed.
A feature is now rolled out by deployment (fixed in code), on or off for
everyone (/admin, starting from the registry default), per-organization
overrides, operator locks, and the kill switch. feature_rollout stores
enabled and killed; GET /v1/features gives people without an organization
the deployment-wide answer.
This commit is contained in:
ben authored and GitHub committed 2026-10-06 07:38:34 -07:00
1 parent f9298faa56
commit 94359f1439
85 files changed
+20611 -690

No files matched your search

+1
View File
@@ -16,6 +16,7 @@ on:
- "ee/apps/den-api/**"
- "ee/packages/**"
- "packages/types/**"
- "packages/features/**"
permissions:
contents: read
+1 -1
View File
@@ -62,7 +62,7 @@ jobs:
// Route, schema, or contract changes must ship the regenerated
// packages/docs/openapi.json and packages/sdk/src/gen.
const denContractPrefixes = ["ee/apps/den-api/", "ee/packages/", "packages/types/", "packages/sdk/"]
const denContractPrefixes = ["ee/apps/den-api/", "ee/packages/", "packages/types/", "packages/features/", "packages/sdk/"]
// The workflow itself is listed so changes to this check exercise it.
const denContractFiles = new Set(["packages/docs/openapi.json", ".spectral.yaml", ".spectral-baseline.json", "scripts/api-lint.mjs", "scripts/den-contract.mjs", ".github/workflows/ci-tests.yml"])
const touchesDenContract = (name) => Boolean(name) && (denContractFiles.has(name) || denContractPrefixes.some((prefix) => name.startsWith(prefix)))
+65
View File
@@ -0,0 +1,65 @@
name: Feature registry check
# The feature registry (packages/features/src/registry.ts) generates the Helm
# chart's config.features block, values schema and README table. This job
# fails when those are stale, when the chart renders DEN_FEATURE_* names that
# den-api does not read, when a Dockerfile misses a workspace package its
# service needs, or when code adds a DEN_*_ENABLED switch or reads
# organization metadata.capabilities instead of the registry.
# See .opencode/skills/add-a-feature/SKILL.md.
on:
pull_request:
paths:
- "packages/features/**"
- "packaging/helm/openwork-ee/**"
- "scripts/features-sync.mjs"
- "scripts/check-docker-workspace-packages.mjs"
- "packaging/docker/**"
- "pnpm-workspace.yaml"
- "apps/*/package.json"
- "packages/*/package.json"
- "ee/apps/*/package.json"
- "ee/packages/*/package.json"
- "ee/apps/den-api/src/**"
- "ee/apps/den-web/app/**"
- "ee/apps/den-web/components/**"
- "ee/apps/gateway/src/**"
- "ee/packages/**"
- "apps/app/src/**"
- "apps/server/src/**"
workflow_dispatch:
permissions:
contents: read
jobs:
features:
name: Feature registry, Helm chart and guard rules
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: Setup Node
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
with:
version: 11.4.0
- name: Install the registry's dependencies
run: pnpm install --frozen-lockfile --filter "@openwork/features"
- name: Set up Helm
uses: azure/setup-helm@1a275c3b69536ee54be43f2070a358922e12c8d4 # v4.3.1
- name: Test the resolver
run: pnpm --filter @openwork/features test
- name: Check the feature registry
run: pnpm features:check
+112
View File
@@ -0,0 +1,112 @@
---
name: add-a-feature
description: Add a new feature, put work behind a feature flag, roll something out (per organization, for everyone, cloud or self-hosted), revert or kill a feature, or make a big change to existing behavior such as a new engine. Use BEFORE writing the feature code, and when finishing or removing a rollout.
---
# Skill: Add a feature
Every new user-visible feature, and every change existing users would notice,
is a **feature** in the registry, declared **before any feature code**, off.
Nothing big ships ungated.
Registry: `packages/features/src/registry.ts` (package `@openwork/features`).
That file is the only one you edit to declare a feature. The rules live in
`resolve.ts` and are tested in `resolve.test.ts`
(`pnpm --filter @openwork/features test`).
## The model: one rollout, several dimensions
A feature is rolled out, and reverted, along these dimensions, resolved in
this order by one function (`resolveFeature`) everywhere it is checked:
1. **Deployments**: products it exists on (`cloud`, `self_hosted`). Fixed in code.
2. **Kill switch**: off everywhere at once, outranking everything below. This is the revert; no deploy.
3. **Operator lock**: a self-hosted operator forces it on or off for the whole install (Helm `config.features.<key>`).
4. **Organization override**: platform admins turn it on or off for one organization in `/admin`.
5. **Everyone**: on or off for everyone on the deployment, changed in `/admin` without a deploy.
Steps 2, 4 and 5 are set per deployment in `/admin` (Features page and each
organization's row) or with the admin MCP tools `den_list_features`,
`den_set_feature_rollout` and `den_set_org_capability`.
## Does this need a feature?
Yes, if any of these is true:
- People get a new screen, tab, button, tool, route family, worker, or engine.
- Existing users would notice the change (a flow works differently, something moves or disappears).
- It should roll out gradually, be revertable, or might not belong on self-hosted installs.
No for bug fixes, copy changes, refactors and internal tooling.
Not a feature either: something that only keeps older clients working
(compat shim with a removal condition), something worked out from what is
configured (derive it in code), or a setting that changes *how* something
works rather than *whether* people get it (put it in `env.ts` / Helm `config.<area>`).
## 1. Declare it, off
```ts
newThing: {
label: "New thing",
description: "What a person gets, in words they see in the product.",
since: "2026-10",
deployments: ["cloud", "self_hosted"],
default: false,
},
```
- **Key**: lowerCamelCase, no consecutive capitals. Permanent: also the Helm key, `DEN_FEATURE_NEW_THING`, the API field and stored rows.
- **Deployments**: leave one out on purpose (e.g. `["cloud"]` for a cloud-only feature).
- **default**: false for new work. A fresh deployment, and a client that cannot reach Den, uses it, so never ship half-done work as `true`.
- **permanent: true** only when the switch itself is part of the product (e.g. turning Connect off for one organization). Rollouts are temporary.
Then run `pnpm features:sync` and commit the regenerated Helm files.
## 2. Make it safe to turn off at any moment
Before shipping, answer: **what happens when the kill switch is used?**
In-flight work, stored data, and what the person sees must survive a revert.
For example, a new engine switches only when nothing is running, falls back
on failure, and keeps history readable after a revert.
## 3. Gate the code
Only through the registry. Never read organization metadata or an
environment variable to decide whether a feature is on.
- den-api, one check: `await organizationFeatureEnabled(orgId, "newThing", { userId })`
- den-api, several checks: `const features = await getOrganizationFeatures(orgId, { userId })`
- den-api route guard: `requireFeature("newThing")` after `orgMemberRoute()`; answers 404 `feature_disabled`
- Inside a transaction that must stay consistent: pass `{ database: tx, lock: "share" }`
- Den web: `orgFeatureEnabled(orgContext, "newThing")` (from `app/(den)/_lib/den-org.ts`), backed by `GET /v1/org` `features`
- People without an organization (signed-out desktop): read `GET /v1/features`; a missing key means off
Gated UI follows DESIGN.md P4: show a locked entry point with a plain reason
rather than silently removing it, when the person could act on it.
## 4. Roll it out
1. Turn it on for our own organization (override in `/admin`).
2. Turn it on for more organizations, one override at a time, checking errors as you go.
3. Turn it on for everyone in `/admin` › Features. Organizations can still be turned off one by one.
4. Anything wrong: **Turn off everywhere** (kill switch). Fix, restore, continue.
5. Once it is on everywhere: set `default: true`, then delete the entry and every check. `pnpm features:check` asks for a decision six months after `since` unless the entry is `permanent`.
Evals turn features on per organization through the admin API:
`enableOrganizationCapabilities(seed, admin, { newThing: true })` in
`evals/worlds/dashboards.ts`.
## Never
- Add a `DEN_*_ENABLED` env var for a product surface (CI rejects new ones).
- Read or write `organization.metadata.capabilities` (CI rejects it).
- Hand-write an `/admin` control, a `/v1/org` field, or a Helm line for a feature.
- Ship something on self-hosted by accident: choose `deployments` on purpose.
## In the PR
Name the feature and its deployments under "How is this implemented?", e.g.
"Behind `newThing` (cloud and self-hosted, off), safe to kill: falls back to
the old flow." Run `pnpm features:check` before
pushing.
+2 -2
View File
@@ -1,7 +1,7 @@
{
"warnings": 39,
"warnings": 38,
"byRule": {
"ow-list-pagination": 23,
"ow-list-pagination": 22,
"ow-timestamps-date-time": 16
}
}
+4
View File
@@ -48,6 +48,10 @@ Hooks never commit, push, or change CI/Warden policy; CI remains authoritative.
100% necessary or instructed.
* Prefer Tailwind, React, shadcn/ui (Base UI), TanStack Query, Zustand, Zod,
Drizzle, Better-Auth. Reuse `@/components`; end users are non-technical.
* New feature or a change users would notice? Declare it, off, in
`packages/features/src/registry.ts` before writing the code, make it safe
to turn off, then roll it out from `/admin`. Follow
`.opencode/skills/add-a-feature`.
* Any user-facing UI (desktop app, Den web, MCP Apps, artifact views) follows
`DESIGN.md`: read it before designing, cite its rule ids in PRs, and attach
screenshots of new UI. The optional
+9 -15
View File
@@ -200,20 +200,14 @@ Scope note: these are `mcp:read`-class operations; nothing on this path writes;
## 7. Org kill switch
Marketplace capability search/execute uses the same effective Connect rail check
as External MCP connections: `memberFacingMcpConnectionsEnabled(metadata)`
in `ee/apps/den-api/src/capability-sources/external-mcp-rollout.ts`. There is
no deployment-level gate; org metadata is authoritative.
Org metadata kill-switch key:
```json
{ "capabilities": { "mcpConnections": false } }
```
as External MCP connections: the `mcpConnections` feature, read with
`getOrganizationFeatures(organizationId)` from `ee/apps/den-api/src/features.ts`
and declared in `packages/features/src/registry.ts`.
Connect is default-on, so local dev, self-hosted, evals, and hosted production
get the feature immediately unless an org explicitly opts out. The backoffice
capability value outranks legacy flat aliases (`connectEnabled` and
`mcpConnectionsEnabled`).
get the feature immediately unless a platform admin turns it off for an
organization in /admin (stored in the `organization_feature` table), or an
operator locks it with `config.features.mcpConnections` / `DEN_FEATURE_MCP_CONNECTIONS`.
Check the kill switch in both paths: disabled orgs get an empty marketplace
merge; execute returns `unknown_capability`. Opted-out is byte-identical to
@@ -229,9 +223,9 @@ nonexistence.
6. No schema changes, no migrations, no new tables in Phase 1; everything derives from existing plugin-arch tables in `ee/packages/den-db/src/schema/sharables/plugin-arch.ts`.
7. No prompt changes and no tool-description changes in Phase 1; results are self-describing via `summary`, `status`, and `hint`.
Kill switch uses the same layer as connections: flip org metadata in /admin (or
an ops script) by setting `metadata.capabilities.mcpConnections` to `false`.
The old deployment-level env gate is deprecated and inert.
Kill switch uses the same layer as connections: turn the `mcpConnections`
feature off for the organization in /admin (or with the `den_set_org_capability`
admin tool).
---
+1 -1
View File
@@ -117,7 +117,7 @@ DEN_OPENWORK_WEB_ENABLED=false
# This does NOT grant the per-org auditLogs feature flag or initialize a policy.
DEN_AUDIT_SELF_HOSTED_ENABLED=false
# Default-on deployment switches; explicit false is a global kill switch.
# Platform admins must opt in each org with metadata.capabilities.auditLogs=true.
# Platform admins must turn on the auditLogs feature for each org in /admin.
# Ready orgs automatically get a temporary 6,000,000 retained-operation policy.
# Capture starts ON; existing policies/OFF choices are preserved. No cap enforcement.
# Existing capture OFF preferences remain OFF. Flag disable hides history without deletion.
+1
View File
@@ -53,6 +53,7 @@
"@openwork/connect-link": "workspace:*",
"@openwork/email": "workspace:*",
"@openwork/enterprise-mcp-client": "workspace:*",
"@openwork/features": "workspace:*",
"@openwork/free-auto": "workspace:*",
"@openwork/headless-threads": "workspace:*",
"@openwork/install-config": "workspace:*",
+6 -6
View File
@@ -4,7 +4,7 @@ import { registerWorkbotRoutes } from "./workbot/routes.js"
import { createDenTypeId, normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { swaggerUI } from "@hono/swagger-ui"
import { and, eq, isNull, sql } from "@openwork-ee/den-db/drizzle"
import { MemberTable, OrganizationTable } from "@openwork-ee/den-db/schema"
import { MemberTable } from "@openwork-ee/den-db/schema"
import { cors } from "hono/cors"
import { Hono } from "hono"
import type { RequestIdVariables } from "hono/request-id"
@@ -13,6 +13,7 @@ import { describeRoute, generateSpecs, resolver } from "hono-openapi"
import { z } from "zod"
import { db } from "./db.js"
import { env } from "./env.js"
import { getOrganizationFeatures } from "./features.js"
import { publicRoute } from "./middleware/index.js"
import { registerAdminMcpRoutes } from "./mcp/admin.js"
import { registerAgentMcpRoutes } from "./mcp/agent.js"
@@ -44,6 +45,7 @@ import { DEN_MCP_REQUESTED_SCOPES } from "./mcp/scopes.js"
import { registerMeRoutes } from "./routes/me/index.js"
import { registerOrgRoutes } from "./routes/org/index.js"
import { registerVersionRoutes } from "./routes/version/index.js"
import { registerFeatureRoutes } from "./routes/features/index.js"
import { registerWebhookRoutes } from "./routes/webhooks/index.js"
import { registerWorkerRoutes } from "./routes/workers/index.js"
import { registerCloudWorkerCompatibilityPreflightRoute } from "./routes/workers/compatibility.js"
@@ -282,6 +284,7 @@ registerOrgRoutes(app)
registerSlackAssistantRoutes(app)
registerWorkbotRoutes(app)
registerVersionRoutes(app)
registerFeatureRoutes(app)
registerWebhookRoutes(app)
registerWorkerRoutes(app)
registerMcpTokenRoutes(app)
@@ -303,10 +306,7 @@ configureCloudWorkflowExecutor(async ({ organizationId, ownerMemberId, automatio
)).limit(1)
const userId = members[0]?.userId
if (!userId) return { ok: false, message: "The Automation owner is no longer active.", retryable: false }
const organizations = await db.select({ metadata: OrganizationTable.metadata }).from(OrganizationTable).where(
eq(OrganizationTable.id, normalizedOrganizationId),
).limit(1)
const organizationMetadata = organizations[0]?.metadata
const organizationFeatures = await getOrganizationFeatures(normalizedOrganizationId)
const member = await resolveMcpMemberIdentity({ userId, organizationId })
if (!member) return { ok: false, message: "The Automation owner is no longer active.", retryable: false }
const catalog = await getCatalog(app as unknown as Hono, undefined)
@@ -320,7 +320,7 @@ configureCloudWorkflowExecutor(async ({ organizationId, ownerMemberId, automatio
member,
redirectUriBase: env.apiPublicUrl ?? "http://127.0.0.1",
generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,
organizationMetadata,
organizationFeatures,
})
const result = await executeMarketplaceCapability({
organizationId,
+5 -5
View File
@@ -3,7 +3,7 @@ import { ArtifactViewRevisionTable, ArtifactViewTable, DashboardAppTable } from
import { createDenTypeId, normalizeDenTypeId, type DenTypeId } from "@openwork-ee/utils/typeid"
import type { GeneratedArtifactView, GeneratedArtifactViewRevision } from "@openwork/types/workflows"
import { db } from "./db.js"
import { appMcpServersEnabled } from "./mcp-app-rollout.js"
import { organizationBuildsMcpApps } from "./mcp-app-rollout.js"
import { getWorkflowAccess, getWorkflowDetail } from "./workflows.js"
import { buildGeneratedArtifactView } from "./generated-artifact-view-builder.js"
import type { PluginArchActorContext } from "./routes/org/plugin-system/access.js"
@@ -14,8 +14,8 @@ import { artifactViewResourceUri } from "./artifact-view-resource.js"
* Apps as MCP servers (see appMcpServersEnabled). They keep rendering, running
* live data, and can be retired, but are not created, edited, or re-activated.
*/
export function legacyArtifactViewsReadOnly(context: PluginArchActorContext): boolean {
return appMcpServersEnabled(context.organizationContext.organization.metadata)
export async function legacyArtifactViewsReadOnly(context: PluginArchActorContext): Promise<boolean> {
return organizationBuildsMcpApps(context.organizationContext.organization.id)
}
const ARTIFACT_VIEW_LIST_LIMIT = 50
@@ -243,7 +243,7 @@ export async function saveArtifactViewRevision(input: {
cssSource?: string
dataMode?: "live" | "snapshot"
}): Promise<GeneratedArtifactView> {
if (legacyArtifactViewsReadOnly(input.context)) throw new Error("legacy_view_read_only")
if (await legacyArtifactViewsReadOnly(input.context)) throw new Error("legacy_view_read_only")
const script = await getWorkflowDetail({ context: input.context, configObjectId: input.configObjectId })
if (!script.canManage) throw new Error("artifact_view_not_found")
if (!script.currentVersion.outputSchema || !script.currentVersion.outputSchemaDigest) {
@@ -332,7 +332,7 @@ export async function activateArtifactViewRevision(input: {
revisionId: string
save?: { title: string; useInWorkflow: boolean; expectedActiveRevisionId: string | null }
}): Promise<GeneratedArtifactView> {
if (legacyArtifactViewsReadOnly(input.context)) throw new Error("legacy_view_read_only")
if (await legacyArtifactViewsReadOnly(input.context)) throw new Error("legacy_view_read_only")
const view = await accessibleView({ context: input.context, artifactViewId: input.artifactViewId, role: "manager" })
const revisionId = parseRevisionId(input.revisionId)
const revisions = await db.select().from(ArtifactViewRevisionTable).where(and(
+5 -2
View File
@@ -3,7 +3,7 @@ import { eq, sql } from "@openwork-ee/den-db/drizzle"
import { AuditPolicyTable, AuditStateTable, OrganizationTable } from "@openwork-ee/den-db/schema"
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { auditPolicySchema, type AuditEntitlement } from "@openwork/types/den/audit"
import { organizationHasCapability } from "../organization-capabilities.js"
import { organizationFeatureEnabled } from "../features.js"
import { AuditReadError } from "./cursors.js"
import { PILOT_DEFAULT_CATEGORIES } from "./pilot-policy.js"
@@ -33,7 +33,10 @@ export async function readAuditAvailability(database: AuditDatabase | AuditTx, o
const [organization] = await (lock ? query.for("share") : query)
if (!organization) throw new AuditLogError("audit_storage_inconsistent")
const { getAuditEntitlement } = await import("../entitlements.js")
return { featureEnabled: organizationHasCapability(organization.metadata, "auditLogs"), entitlement: getAuditEntitlement(organization.metadata) }
// Read after the organization fence, with the same share lock, so a concurrent
// /admin change cannot flip the flag between this check and commit.
const featureEnabled = await organizationFeatureEnabled(organizationId, "auditLogs", { database, lock: lock ? "share" : undefined })
return { featureEnabled, entitlement: getAuditEntitlement(organization.metadata) }
}
export async function readAuditEntitlement(database: AuditDatabase | AuditTx, organizationId: string, lock = false): Promise<AuditEntitlement> {
+1 -1
View File
@@ -59,7 +59,7 @@ export const providerCoverage: AuditCoverageDeclaration = {
...[...new Set([...providerCoveredRoutes.map(({ step }) => step), ...providerBackgroundSteps])].flatMap((step) => ["committed", "attempted"].map((outcome) => `provider.configuration.${step}.${outcome}`)),
],
categories: ["change", "request", "security", "execution"],
capturePolicy: "Fresh literal metadata.capabilities.auditLogs=true AND (Enterprise plan OR explicit self-hosted installation entitlement) AND default-on deployment capture switch AND enabled stored policy AND selected category; missing policies initialize with temporary server defaults before snapshot reads. Organization share lock before snapshot reads, state/policy revision recheck before commit. Existing OFF stays OFF. Generic DB writer semantics are unchanged.",
capturePolicy: "auditLogs feature on for the organization (read fresh) AND (Enterprise plan OR explicit self-hosted installation entitlement) AND default-on deployment capture switch AND enabled stored policy AND selected category; missing policies initialize with temporary server defaults before snapshot reads. Organization share lock before snapshot reads, state/policy revision recheck before commit. Existing OFF stays OFF. Generic DB writer semantics are unchanged.",
resources: [...providerCoveredResources.map(({ type }) => type), "organization", "member", "team"],
snapshotPolicy: "Per-resource allowlisted before/after and changed fields; secret/configuration changes use markers, never secret values or comparison hashes; oversize rejects.",
emitter: "src/audit/provider.ts:providerAuditMutation; recordProviderAttempt; src/llm/gateway-matrix.ts:refreshGatewayCatalog",
+2 -2
View File
@@ -116,8 +116,8 @@ Coverage is limited to implemented provider configuration and audit-read emitter
category names do not promise all security, execution or read activity is captured.
Global DEN_AUDIT_CAPTURE_ENABLED and DEN_AUDIT_VISIBILITY_ENABLED default true;
explicit false is a kill switch. This initializer never changes them.
Traffic and API access require metadata.capabilities.auditLogs=true (literal true),
managed only by platform admins; absent/false means hidden and no traffic capture.
Traffic and API access require the auditLogs feature to be on for the organization,
set only by platform admins in /admin; off means hidden and no traffic capture.
Disabling the feature hides history without deleting data or changing captureOn.
Ready organizations now lazily initialize missing policies ON during capture or
GET usage, with a system audit.policy.initialized event. Temporary server defaults:
+6 -13
View File
@@ -1224,19 +1224,12 @@ export const auth = betterAuth({
if ("plan" in metadata) {
throw new APIError("FORBIDDEN", { message: "plan is reserved for internal platform administration." });
}
const capabilities = metadata.capabilities;
if (capabilities && typeof capabilities === "object" && "auditLogs" in capabilities) {
throw new APIError("FORBIDDEN", { message: "capabilities.auditLogs is reserved for internal platform administration." });
}
for (const key of ["slackAssistant", "slackAssistantHeadless", "headlessAutomations", "workbot"]) {
if (capabilities && typeof capabilities === "object" && key in capabilities) {
throw new APIError("FORBIDDEN", { message: `capabilities.${key} is reserved for internal platform administration.` });
}
}
if (capabilities && typeof capabilities === "object" && "gatewayDashboard" in capabilities) {
const retainedCapabilities = { ...capabilities };
delete retainedCapabilities.gatewayDashboard;
return { data: { metadata: { ...metadata, capabilities: retainedCapabilities } } };
// Features live in the organization_feature table and only platform
// admins write them. Organization metadata never turns a feature on,
// so a client-supplied capabilities object is dropped, not stored.
if ("capabilities" in metadata) {
const { capabilities: _ignored, ...retained } = metadata;
return { data: { metadata: retained } };
}
},
beforeUpdateOrganization: async ({ organization }) => {
@@ -4,7 +4,7 @@ import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { db } from "../db.js"
import { planIncludesHeadlessAutomations } from "../entitlements.js"
import { headlessRunnerConfig } from "../headless-runner/client.js"
import { organizationHasCapability } from "../organization-capabilities.js"
import { getOrganizationFeatures, type FeatureMap } from "../features.js"
/** Engine kind recorded on cloud agent runs that executed on the headless runner. */
export const HEADLESS_AGENT_ENGINE_KIND = "openwork-headless-agent-v1"
@@ -19,11 +19,11 @@ export const HEADLESS_AGENT_ENGINE_KIND = "openwork-headless-agent-v1"
export type CloudAutomationRuntime = "headless" | "web"
export function cloudAutomationRuntimeForOrganization(
metadata: Parameters<typeof organizationHasCapability>[0],
input: { features: Pick<FeatureMap, "headlessAutomations">; metadata: Parameters<typeof planIncludesHeadlessAutomations>[0] },
options: { env?: Record<string, string | undefined>; gatingEnabled?: boolean } = {},
): CloudAutomationRuntime {
if (!organizationHasCapability(metadata, "headlessAutomations")) return "web"
if (!planIncludesHeadlessAutomations(metadata, { gatingEnabled: options.gatingEnabled })) return "web"
if (!input.features.headlessAutomations) return "web"
if (!planIncludesHeadlessAutomations(input.metadata, { gatingEnabled: options.gatingEnabled })) return "web"
return headlessRunnerConfig(options.env ?? process.env) ? "headless" : "web"
}
@@ -36,5 +36,6 @@ export async function cloudAutomationRuntime(organizationId: string): Promise<Cl
.from(OrganizationTable)
.where(eq(OrganizationTable.id, normalizeDenTypeId("organization", organizationId)))
.limit(1)
return organization ? cloudAutomationRuntimeForOrganization(organization.metadata) : "web"
if (!organization) return "web"
return cloudAutomationRuntimeForOrganization({ features: await getOrganizationFeatures(organizationId), metadata: organization.metadata })
}
@@ -1,52 +0,0 @@
/**
* Kill switch for member-facing org MCP connections.
*
* Connect is default-on for every org. Platform admins can explicitly disable
* the member-facing rail with `metadata.capabilities.mcpConnections: false`;
* that backoffice capability outranks the historical flat aliases
* (`metadata.mcpConnectionsEnabled` and `metadata.connectEnabled`). Admin
* management (scope=manageable, create, access grants) stays available so orgs
* can stage or repair connections while members see an empty list.
*/
type MetadataInput = Record<string, unknown> | string | null | undefined
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function parseMetadata(input: MetadataInput): Record<string, unknown> {
if (!input) {
return {}
}
if (typeof input === "string") {
try {
const parsed: unknown = JSON.parse(input)
return isRecord(parsed) ? parsed : {}
} catch {
return {}
}
}
return isRecord(input) ? input : {}
}
export function memberFacingMcpConnectionsEnabled(metadata: MetadataInput): boolean {
const parsed = parseMetadata(metadata)
const capabilities = isRecord(parsed.capabilities) ? parsed.capabilities : {}
if (capabilities.mcpConnections === true) {
return true
}
if (capabilities.mcpConnections === false) {
return false
}
if (parsed.connectEnabled === true || parsed.mcpConnectionsEnabled === true) {
return true
}
if (parsed.connectEnabled === false || parsed.mcpConnectionsEnabled === false) {
return false
}
return true
}
@@ -1,44 +0,0 @@
/**
* Kill switch for organization install links.
*
* Install links are default-on for every org. Platform admins can explicitly
* disable workspace-admin minting with `metadata.capabilities.installLinks: false`.
* A literal `true` keeps the org enabled; absent and non-boolean values fall
* through to the default-on posture.
*/
type MetadataInput = Record<string, unknown> | string | null | undefined
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function parseMetadata(input: MetadataInput): Record<string, unknown> {
if (!input) {
return {}
}
if (typeof input === "string") {
try {
const parsed: unknown = JSON.parse(input)
return isRecord(parsed) ? parsed : {}
} catch {
return {}
}
}
return isRecord(input) ? input : {}
}
export function organizationInstallLinksEnabled(metadata: MetadataInput): boolean {
const parsed = parseMetadata(metadata)
const capabilities = isRecord(parsed.capabilities) ? parsed.capabilities : {}
if (capabilities.installLinks === true) {
return true
}
if (capabilities.installLinks === false) {
return false
}
return true
}
@@ -13,7 +13,7 @@ import {
import { getConnectedAccount, getOrgOAuthClient } from "./oauth-credentials.js"
import { readProviderTenantId } from "./oauth-tenant.js"
import { listExternalMcpConnections, listUsableNativeProviderConnections } from "./external-mcp-connections.js"
import { memberFacingMcpConnectionsEnabled } from "./external-mcp-rollout.js"
import { organizationFeatureEnabled } from "../features.js"
/**
* Native providers (google-workspace, ...) surface in the SAME member-facing
@@ -114,11 +114,11 @@ export type NativeProviderPolicyError = { kind: "policy_blocked"; message: strin
export async function nativeProviderConnectionPolicyError(organizationId: DenTypeId<"organization">): Promise<NativeProviderPolicyError | null> {
const [organization] = await db
.select({ metadata: OrganizationTable.metadata })
.select({ id: OrganizationTable.id })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, organizationId))
.limit(1)
if (organization && memberFacingMcpConnectionsEnabled(organization.metadata)) return null
if (organization && await organizationFeatureEnabled(organization.id, "mcpConnections")) return null
return {
kind: "policy_blocked",
message: organization
+16
View File
@@ -9,6 +9,7 @@ import { resolveDenServiceVersion } from "./service-version.js"
import { denApiAppVersion } from "./version.js"
import { z } from "zod"
import { readFreeInferenceConfig } from "@openwork/types/den/inference"
import { parseFeatureEnvironment } from "@openwork/features"
export const DEFAULT_DEN_DIAGNOSTICS_ORIGIN = "https://diagnostic.openworklabs.com"
@@ -541,6 +542,20 @@ const automationsRuntimeEnabled = parseBooleanFlag(
const automationsEnabled = automationsRuntimeEnabled
&& parseBooleanFlag(parsed.DEN_AUTOMATIONS_ENABLED ?? "false")
const dashboardsEnabled = parseBooleanFlag(parsed.DEN_DASHBOARDS_ENABLED ?? "false")
// Which product this install is (DEN_DEPLOYMENT, default self_hosted so a
// misconfigured customer install never picks up cloud-only features) and the
// operator's feature locks (DEN_FEATURE_*, rendered from Helm config.features).
// See packages/features/src/registry.ts.
const featureEnvironment = parseFeatureEnvironment(process.env)
const fatalFeatureProblems = featureEnvironment.problems.filter((problem) => problem.fatal)
if (fatalFeatureProblems.length > 0) {
throw new Error(fatalFeatureProblems.map((problem) => `${problem.variable} ${problem.message}`).join(" "))
}
for (const problem of featureEnvironment.problems) {
console.warn(`[features] ${problem.variable} ${problem.message}`)
}
// An edge that already answers CORS (reflecting the caller's origin) in front
// of den-api makes den-api's own headers duplicates, which browsers reject.
// The allowlist still feeds proxy-trust decisions; only header emission stops.
@@ -827,6 +842,7 @@ export const env = {
runnerClaimDeadlineMs: automationTuning(parsed.DEN_AUTOMATIONS_RUNNER_CLAIM_DEADLINE_MS, 900_000),
},
dashboardsEnabled,
features: { deployment: featureEnvironment.deployment, locks: featureEnvironment.locks },
auditCaptureEnabled: parsed.DEN_AUDIT_CAPTURE_ENABLED === "true",
auditVisibilityEnabled: parsed.DEN_AUDIT_VISIBILITY_ENABLED === "true",
auditSelfHostedEnabled: parsed.DEN_AUDIT_SELF_HOSTED_ENABLED === "true",
+49
View File
@@ -0,0 +1,49 @@
import { readFeatures, type FeatureDatabase } from "@openwork-ee/den-db/organization-features"
import type { FeatureKey, FeatureMap } from "@openwork/features"
import type { MiddlewareHandler } from "hono"
import { db } from "./db.js"
import { env } from "./env.js"
import type { OrganizationContextVariables } from "./middleware/organization-context.js"
/**
* The only way den-api asks whether a feature is on.
*
* Features are declared in packages/features/src/registry.ts (read
* .opencode/skills/add-a-feature first). Never read organization metadata or
* environment variables to decide whether a feature is on.
*/
export type { FeatureKey, FeatureMap }
type ReadOptions = {
database?: FeatureDatabase
lock?: "share"
}
/**
* Effective on/off for every feature, for one organization. Read fresh on
* every call, so an /admin change applies to the next request. Pass the
* transaction (and `lock: "share"`) when the answer must stay stable until commit.
*/
export function getOrganizationFeatures(organizationId: string, options: ReadOptions = {}): Promise<FeatureMap> {
return readFeatures(options.database ?? db, organizationId, env.features, { lock: options.lock })
}
export async function organizationFeatureEnabled(organizationId: string, key: FeatureKey, options: ReadOptions = {}): Promise<boolean> {
return (await getOrganizationFeatures(organizationId, options))[key]
}
/**
* Route guard for organization routes: answers 404 `feature_disabled` as if the
* route did not exist when the feature is off for the caller's organization. Use after
* orgMemberRoute()/orgRoleRoute().
*/
export function requireFeature(key: FeatureKey): MiddlewareHandler<{ Variables: Partial<OrganizationContextVariables> }> {
return async (c, next) => {
const payload = c.get("organizationContext")
if (!payload) return c.json({ error: "organization_not_found" }, 404)
const enabled = await organizationFeatureEnabled(payload.organization.id, key)
if (!enabled) return c.json({ error: "feature_disabled", feature: key }, 404)
await next()
}
}
+3 -5
View File
@@ -3,20 +3,19 @@ import { InstallLinkTable } from "@openwork-ee/den-db/schema"
import { createDenTypeId, normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { createHash, randomBytes } from "node:crypto"
import { OPENWORK_DOWNLOAD_URL } from "./CONSTS.js"
import { organizationInstallLinksEnabled } from "./capability-sources/install-links-rollout.js"
import { db } from "./db.js"
import { env } from "./env.js"
import { organizationFeatureEnabled } from "./features.js"
import { appLogger } from "./observability/logger.js"
type InstallLinkInsert = typeof InstallLinkTable.$inferInsert
const logger = appLogger.child({ component: "install_links" })
type MintOrganizationInstallLinkInput = Pick<InstallLinkInsert, "organizationId" | "createdByUserId"> & {
metadata: Record<string, unknown> | string | null | undefined
rotate?: boolean
}
type InvitationDownloadUrlInput = Pick<MintOrganizationInstallLinkInput, "metadata"> & {
type InvitationDownloadUrlInput = {
organizationId: string
createdByUserId: string
}
@@ -30,7 +29,7 @@ function installPageUrl(token: string) {
}
export async function mintOrganizationInstallLink(input: MintOrganizationInstallLinkInput) {
if (!organizationInstallLinksEnabled(input.metadata)) {
if (!(await organizationFeatureEnabled(input.organizationId, "installLinks"))) {
return null
}
@@ -68,7 +67,6 @@ export async function resolveInvitationDownloadUrl(input: InvitationDownloadUrlI
const installLink = await mintOrganizationInstallLink({
organizationId: normalizeDenTypeId("organization", input.organizationId),
createdByUserId: normalizeDenTypeId("user", input.createdByUserId),
metadata: input.metadata,
})
return installLink?.installPageUrl ?? OPENWORK_DOWNLOAD_URL
} catch (error) {
+5 -11
View File
@@ -1,9 +1,5 @@
import { eq } from "@openwork-ee/den-db/drizzle"
import { OrganizationTable } from "@openwork-ee/den-db/schema"
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { memberFacingMcpConnectionsEnabled } from "./capability-sources/external-mcp-rollout.js"
import { db } from "./db.js"
import { env } from "./env.js"
import { getOrganizationFeatures, type FeatureMap } from "./features.js"
/**
* Whether members of this organization can build their own Apps, each served
@@ -14,13 +10,11 @@ import { env } from "./env.js"
* It gates only Apps built in OpenWork. MCP Apps from connected MCP servers
* work either way, and where it is off, Workflow-bound views stay writable.
*/
export function appMcpServersEnabled(metadata: Parameters<typeof memberFacingMcpConnectionsEnabled>[0]): boolean {
return env.appMcpServersEnabled && memberFacingMcpConnectionsEnabled(metadata)
export function appMcpServersEnabled(features: Pick<FeatureMap, "mcpConnections">): boolean {
return env.appMcpServersEnabled && features.mcpConnections
}
/** The same check by organization id, for callers that do not hold its metadata. */
/** The same check by organization id, for callers that do not hold its features. */
export async function organizationBuildsMcpApps(organizationId: string): Promise<boolean> {
const [organization] = await db.select({ metadata: OrganizationTable.metadata }).from(OrganizationTable)
.where(eq(OrganizationTable.id, normalizeDenTypeId("organization", organizationId))).limit(1)
return appMcpServersEnabled(organization?.metadata)
return appMcpServersEnabled(await getOrganizationFeatures(organizationId))
}
+64 -10
View File
@@ -5,9 +5,11 @@ import { readOrganizationMetadata } from "@openwork/types/den/managed-models-pol
import { z } from "zod"
import { db } from "../db.js"
import { getDesktopReleaseMetadata } from "../desktop-releases.js"
import { env } from "../env.js"
import { parseOrganizationPlan, type PlanTier } from "../entitlements.js"
import { normalizeOrganizationMetadata } from "../organization-limits.js"
import { organizationCapabilityKeySchema, organizationHasCapability } from "../organization-capabilities.js"
import { readFeatureRollouts, setFeatureRollout, setOrganizationFeatureOverrides } from "@openwork-ee/den-db/organization-features"
import { FEATURE_KEYS, featureAvailableOn, featureDefinition, featureKeySchema, featureRollout, resolveFeature } from "@openwork/features"
import { updateOrganizationMetadata } from "../organization-metadata.js"
/**
@@ -485,10 +487,10 @@ export function registerAdminMcpTools(server: McpServer) {
"den_set_org_capability",
{
description:
"Admin write tool: turn one organization capability on or off (the same switches as the admin panel), e.g. capability='workbot'. enabled=null removes the override and restores the default.",
"Admin write tool: turn one feature on or off for one organization (an organization override, the same switch as the admin panel), e.g. capability='workbot'. enabled=null removes the override so the feature follows the deployment-wide on/off state again. The kill switch (den_set_feature_rollout) still outranks it.",
inputSchema: z.object({
organizationId: z.string().min(1).describe("Organization id, e.g. org_..."),
capability: organizationCapabilityKeySchema.describe("Capability to set"),
capability: featureKeySchema.describe("Feature to set (see packages/features/src/registry.ts)"),
enabled: z.boolean().nullable().describe("true or false, or null to restore the default"),
}),
},
@@ -506,22 +508,74 @@ export function registerAdminMcpTools(server: McpServer) {
if (!organization) {
throw new Error(`No organization found for ${organizationId}`)
}
const metadata = await updateOrganizationMetadata(organizationId, (current) => {
// Other capability keys (and unmanaged ones) are kept as they are.
const capabilities = { ...readOrganizationMetadata(current.capabilities) }
if (enabled === null) delete capabilities[capability]
else capabilities[capability] = enabled
return { ...current, capabilities }
if (!featureAvailableOn(capability, env.features.deployment)) {
throw new Error(`${capability} is not part of this deployment.`)
}
const overrides = await setOrganizationFeatureOverrides(db, {
organizationId,
changes: { [capability]: enabled },
source: "platform",
})
return {
ok: true,
organization: { id: organization.id, name: organization.name, slug: organization.slug },
capability,
enabled: organizationHasCapability(metadata, capability),
enabled: resolveFeature(capability, {
...env.features,
rollouts: await readFeatureRollouts(db),
overrides,
}).enabled,
}
}),
)
server.registerTool(
"den_list_features",
{
description:
"Admin read tool: every feature in the registry with the deployments it exists on and this deployment's state (on or off for everyone, kill switch, operator lock).",
inputSchema: z.object({}),
},
async () =>
run(async () => {
const rollouts = await readFeatureRollouts(db)
return {
deployment: env.features.deployment,
features: FEATURE_KEYS.map((key) => {
const definition = featureDefinition(key)
return {
key,
label: definition.label,
deployments: definition.deployments,
available: featureAvailableOn(key, env.features.deployment),
...featureRollout(key, rollouts),
lock: env.features.locks[key] ?? null,
}
}),
}
}),
)
server.registerTool(
"den_set_feature_rollout",
{
description:
"Admin write tool: change a feature for this whole deployment. enabled turns it on or off for everyone (organization overrides still apply); killed=true turns it off everywhere at once (the revert), outranking operator locks and organization overrides.",
inputSchema: z.object({
feature: featureKeySchema.describe("Feature key (see den_list_features)"),
enabled: z.boolean().optional().describe("true for on for everyone, false for off"),
killed: z.boolean().optional().describe("true to turn it off everywhere, false to clear the kill switch"),
}),
},
async ({ feature, enabled, killed }) =>
run(async () => {
if (enabled === undefined && killed === undefined) throw new Error("Set enabled, killed, or both.")
if (!featureAvailableOn(feature, env.features.deployment)) throw new Error(`${feature} is not part of this deployment.`)
const rollouts = await setFeatureRollout(db, { key: feature, enabled, killed, defaultEnabled: featureDefinition(feature).default })
return { ok: true, feature, ...featureRollout(feature, rollouts) }
}),
)
server.registerTool(
"den_growth",
{
+4 -9
View File
@@ -9,7 +9,6 @@ import {
type ToolAnnotations,
} from "@modelcontextprotocol/server"
import { eq } from "@openwork-ee/den-db/drizzle"
import { OrganizationTable } from "@openwork-ee/den-db/schema"
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import { openworkCloudMcpConnectionActionSchema } from "@openwork/types/den/mcp-connection-action"
import type { Hono } from "hono"
@@ -39,6 +38,7 @@ import { resolvePublicOrigin } from "../capability-sources/generic-oauth.js"
import { automationService } from "../automations/service.js"
import { AGENT_AUTOMATION_INDEX_LIMIT, registerAgentAutomationResources } from "./automation-index.js"
import { env } from "../env.js"
import { getOrganizationFeatures } from "../features.js"
import { getOrganizationContextForUser, listTeamsForMember } from "../orgs.js"
import { executeLiveArtifactWorkflow, getWorkflowDetail, getWorkflowSnapshot } from "../workflows.js"
import { artifactFreshness } from "../workflow-artifacts.js"
@@ -477,12 +477,7 @@ export function registerAgentMcpRoutes<T extends { Variables: RequestIdVariables
})
const notificationScope = `${principal.organizationId}\0${principal.userId}`
const organizationId = normalizeDenTypeId("organization", principal.organizationId)
const organizationRows = await db
.select({ metadata: OrganizationTable.metadata })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, organizationId))
.limit(1)
const organizationMetadata = organizationRows[0]?.metadata
const organizationFeatures = await getOrganizationFeatures(organizationId)
const connectMcpAppHostSupported = supportsConnectMcpAppHost(
c.req.header(CONNECT_MCP_APP_HOST_CAPABILITY_HEADER),
) && principal.scopes.has(DEN_MCP_APP_HOST_SCOPE)
@@ -498,12 +493,12 @@ export function registerAgentMcpRoutes<T extends { Variables: RequestIdVariables
member: memberIdentity,
redirectUriBase,
generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,
organizationMetadata,
organizationFeatures,
})
const { externalMcpConnectionsEnabled } = capabilityContext
// Building your own Apps is per-organization and default-off; MCP Apps
// from connected MCP servers work either way.
const appServersEnabled = appMcpServersEnabled(organizationMetadata)
const appServersEnabled = appMcpServersEnabled(organizationFeatures)
// Resolved once per request, and only by the methods that need it: the
// skill resources at discovery time, and list_skills / get_skill on call.
let remoteSkillsPromise: Promise<RemoteSkillDescriptor[]> | null = null
+5 -5
View File
@@ -26,6 +26,7 @@ import type { Context, Hono } from "hono"
import { resolvePublicOrigin } from "../capability-sources/generic-oauth.js"
import { db } from "../db.js"
import { env } from "../env.js"
import { getOrganizationFeatures } from "../features.js"
import { appMcpServersEnabled } from "../mcp-app-rollout.js"
import {
loadMcpAppResource,
@@ -246,18 +247,17 @@ async function handleMcpAppServerRequestUntimed(input: {
const organizationId = normalizeDenTypeId("organization", principal.organizationId)
const refuse = (reason: AppRefusal, organizationName?: string) =>
refuseAppRequest(context.req.raw, { reason, organizationId, appId: input.appId, organizationName })
const [member, home, organization, catalog] = await Promise.all([
const [member, home, organizationFeatures, catalog] = await Promise.all([
resolveMcpMemberIdentity({ userId: principal.userId, organizationId }),
appOrganizationForMember(input.appId, principal.userId),
db.select({ metadata: OrganizationTable.metadata }).from(OrganizationTable)
.where(eq(OrganizationTable.id, organizationId)).limit(1),
getOrganizationFeatures(organizationId),
getCatalog(input.app, context.env),
])
if (!member) return refuse("not_a_member")
// A client authorized for one organization cannot reach an App built in another.
if (home && home.id !== organizationId) return refuse("other_organization", home.name)
// Building your own Apps is per-organization and default-off.
if (!appMcpServersEnabled(organization[0]?.metadata)) return refuse("apps_off")
if (!appMcpServersEnabled(organizationFeatures)) return refuse("apps_off")
const capabilityContext = createCapabilityRegistryContext({
app: input.app,
env: context.env,
@@ -267,7 +267,7 @@ async function handleMcpAppServerRequestUntimed(input: {
member,
redirectUriBase: resolvePublicOrigin(context.req.raw, env.apiPublicUrl),
generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,
organizationMetadata: organization[0]?.metadata,
organizationFeatures,
})
const access = { organizationId, member, enabled: capabilityContext.externalMcpConnectionsEnabled, requestScope: {} }
let definition: McpAppServerDefinition
@@ -4,7 +4,7 @@ import type { DenTypeId } from "@openwork-ee/utils/typeid"
import { Effect } from "effect"
import type { Hono } from "hono"
import { z } from "zod"
import { memberFacingMcpConnectionsEnabled } from "../capability-sources/external-mcp-rollout.js"
import type { FeatureMap } from "../features.js"
import { isPlatformAdminUserId } from "../middleware/admin.js"
import type { McpPrincipal } from "./auth.js"
import type { McpToolOperation } from "./catalog.js"
@@ -137,11 +137,12 @@ export type CapabilityRegistryContextInput = {
member: McpMemberIdentity | null
redirectUriBase: string
generatedArtifactViewsEnabled: boolean
organizationMetadata: Parameters<typeof memberFacingMcpConnectionsEnabled>[0]
/** Effective features of the organization (see features.ts). */
organizationFeatures: Pick<FeatureMap, "mcpConnections">
}
export function createCapabilityRegistryContext(input: CapabilityRegistryContextInput): CapabilityRegistryContext {
const externalMcpConnectionsEnabled = memberFacingMcpConnectionsEnabled(input.organizationMetadata)
const externalMcpConnectionsEnabled = input.organizationFeatures.mcpConnections
let platformAdmin: Promise<boolean> | undefined
const resolvePlatformAdmin = () => {
platformAdmin ??= isPlatformAdminUserId(input.principal.userId)
@@ -166,7 +167,7 @@ export function createCapabilityRegistryContext(input: CapabilityRegistryContext
redirectUriBase: input.redirectUriBase,
generatedArtifactViewsEnabled: input.generatedArtifactViewsEnabled,
externalMcpConnectionsEnabled,
remoteSessionsEnabled: remoteSessionCapabilitiesEnabled(input.organizationMetadata),
remoteSessionsEnabled: remoteSessionCapabilitiesEnabled(),
resolvePlatformAdmin,
resolveNamespaceContext,
}
@@ -10,8 +10,6 @@ import {
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js"
import { StreamableHTTPTransport } from "@hono/mcp"
import { eq } from "@openwork-ee/den-db/drizzle"
import { OrganizationTable } from "@openwork-ee/den-db/schema"
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import type { Context, Hono } from "hono"
import type { RequestIdVariables } from "hono/request-id"
@@ -31,9 +29,8 @@ import {
readExternalMcpResource,
} from "../capability-sources/external-mcp-client-runtime.js"
import { externalMcpDiagnosticForResponse } from "../capability-sources/external-mcp-diagnostics.js"
import { memberFacingMcpConnectionsEnabled } from "../capability-sources/external-mcp-rollout.js"
import { organizationFeatureEnabled } from "../features.js"
import { evaluateToolPolicy } from "../capability-sources/external-mcp-tool-policy.js"
import { db } from "../db.js"
import { env } from "../env.js"
import { tokenRoute } from "../middleware/index.js"
import { resolvePublicOrigin } from "../capability-sources/generic-oauth.js"
@@ -487,7 +484,7 @@ export function registerExternalConnectionProxyRoutes<T extends { Variables: Req
// The direct provider catalog is a member-facing MCP surface, so it obeys
// the same organization flag as the member-facing connection list.
const directExposureEnabled = connection.exposeDirectly
&& await memberFacingMcpConnectionsEnabledForOrganization(organizationId)
&& await organizationFeatureEnabled(organizationId, "mcpConnections")
const redirectUriBase = resolvePublicOrigin(c.req.raw, env.apiPublicUrl)
const redirectUri = `${redirectUriBase}/v1/mcp-connections/${encodeURIComponent(connection.id)}/connect/callback`
@@ -508,17 +505,6 @@ export function registerExternalConnectionProxyRoutes<T extends { Variables: Req
})
}
async function memberFacingMcpConnectionsEnabledForOrganization(
organizationId: ExternalMcpConnectionRow["organizationId"],
): Promise<boolean> {
const rows = await db
.select({ metadata: OrganizationTable.metadata })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, organizationId))
.limit(1)
return memberFacingMcpConnectionsEnabled(rows[0]?.metadata)
}
export const STANDARD_MCP_APP_EXTENSION = {
extensionId: EXTENSION_ID,
mimeType: RESOURCE_MIME_TYPE,
@@ -1,101 +0,0 @@
import { z } from "zod"
/**
* Per-organization capability flags ("org capabilities").
*
* Capabilities let platform admins manage feature switches org-by-org from the
* /admin backoffice. The helpers here expose the raw stored booleans;
* feature-specific rollout helpers can layer effective default-on kill-switch
* semantics for member-facing surfaces.
*
* Storage rides the existing organization metadata JSON column — the same
* home as `limits`, `plan`, and `requireSso` — so no schema change is needed.
*/
export const ORGANIZATION_CAPABILITY_KEYS = ["installLinks", "mcpConnections", "modelsAnalytics", "auditLogs", "orgManagedDashboards", "slackAssistant", "slackAssistantHeadless", "headlessAutomations", "workbot"] as const
export const organizationCapabilityKeySchema = z.enum(ORGANIZATION_CAPABILITY_KEYS)
export type OrganizationCapabilityKey = z.infer<typeof organizationCapabilityKeySchema>
export type OrganizationCapabilities = Record<OrganizationCapabilityKey, boolean>
type MetadataInput = Record<string, unknown> | string | null | undefined
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function parseMetadata(input: MetadataInput): Record<string, unknown> {
if (!input) {
return {}
}
if (typeof input === "string") {
try {
const parsed = JSON.parse(input) as unknown
return isRecord(parsed) ? parsed : {}
} catch {
return {}
}
}
return isRecord(input) ? input : {}
}
/** Every capability key resolved to a boolean, defaulting to false. */
export function normalizeOrganizationCapabilities(metadata: MetadataInput): OrganizationCapabilities {
const parsed = parseMetadata(metadata)
const raw = isRecord(parsed.capabilities) ? parsed.capabilities : {}
return {
installLinks: raw.installLinks === true,
mcpConnections: raw.mcpConnections === true,
modelsAnalytics: raw.modelsAnalytics === true,
auditLogs: raw.auditLogs === true,
orgManagedDashboards: raw.orgManagedDashboards === true,
slackAssistant: raw.slackAssistant === true,
slackAssistantHeadless: raw.slackAssistantHeadless === true,
headlessAutomations: raw.headlessAutomations === true,
workbot: raw.workbot === true,
}
}
/** Only raw, literal org capability overrides that are explicitly stored. */
export function readOrganizationCapabilityOverrides(metadata: MetadataInput): Partial<OrganizationCapabilities> {
const parsed = parseMetadata(metadata)
const raw = isRecord(parsed.capabilities) ? parsed.capabilities : {}
const capabilities: Partial<OrganizationCapabilities> = {}
if (typeof raw.installLinks === "boolean") {
capabilities.installLinks = raw.installLinks
}
if (typeof raw.mcpConnections === "boolean") {
capabilities.mcpConnections = raw.mcpConnections
}
if (typeof raw.modelsAnalytics === "boolean") capabilities.modelsAnalytics = raw.modelsAnalytics
if (typeof raw.auditLogs === "boolean") capabilities.auditLogs = raw.auditLogs
if (typeof raw.orgManagedDashboards === "boolean") capabilities.orgManagedDashboards = raw.orgManagedDashboards
if (typeof raw.slackAssistant === "boolean") capabilities.slackAssistant = raw.slackAssistant
if (typeof raw.slackAssistantHeadless === "boolean") capabilities.slackAssistantHeadless = raw.slackAssistantHeadless
if (typeof raw.headlessAutomations === "boolean") capabilities.headlessAutomations = raw.headlessAutomations
if (typeof raw.workbot === "boolean") capabilities.workbot = raw.workbot
return capabilities
}
/**
* Org-managed Dashboards are default-off per organization. Only an explicit
* `metadata.capabilities.orgManagedDashboards: true` enables the Den admin
* surface, the /v1/dashboards routes, and granted dashboards in Desktop.
* Workflows, saved apps, and every other capability are unaffected.
*/
export function organizationManagedDashboardsEnabled(metadata: MetadataInput): boolean {
return normalizeOrganizationCapabilities(metadata).orgManagedDashboards
}
/** Whether the organization stores an explicit literal true for the capability. */
export function organizationHasCapability(metadata: MetadataInput, key: OrganizationCapabilityKey): boolean {
return normalizeOrganizationCapabilities(metadata)[key]
}
+9 -13
View File
@@ -389,23 +389,19 @@ function serializeMetadataRecord(metadata: Record<string, unknown>) {
return Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : null
}
/**
* Organization metadata as members see it. Feature overrides are platform
* administration data (still mirrored into metadata.capabilities for one
* release, for rollback) and are never sent; clients read the effective
* `features` from GET /v1/org instead.
*/
export function serializeMemberFacingOrganizationMetadata(input: OrganizationMetadataInput) {
const metadata = parseMetadataRecord(input)
const capabilities = isRecord(metadata.capabilities) ? metadata.capabilities : null
if (!capabilities || !("cloud" in capabilities)) {
if (!("capabilities" in metadata)) {
return serializeOrganizationMetadata(input)
}
const nextCapabilities = { ...capabilities }
delete nextCapabilities.cloud
const nextMetadata = { ...metadata }
if (Object.keys(nextCapabilities).length > 0) {
nextMetadata.capabilities = nextCapabilities
} else {
delete nextMetadata.capabilities
}
return serializeMetadataRecord(nextMetadata)
const { capabilities: _platformOnly, ...memberFacing } = metadata
return serializeMetadataRecord(memberFacing)
}
export function parsePermissionRecord(value: string | null) {
+168 -116
View File
@@ -41,9 +41,27 @@ import { adminRoute, jsonValidator, queryValidator } from "../../middleware/inde
import { registerAdminFreeAutoUsageRoutes } from "./free-auto-usage.js"
import { denTypeIdSchema, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
import { appLogger } from "../../observability/logger.js"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { organizationInstallLinksEnabled } from "../../capability-sources/install-links-rollout.js"
import { normalizeOrganizationCapabilities, readOrganizationCapabilityOverrides } from "../../organization-capabilities.js"
import {
describeFeatures,
readFeatureRollouts,
readOrganizationFeatureOverrides,
readOrganizationFeatureOverridesForMany,
setFeatureRollout,
setOrganizationFeatureOverrides,
type FeatureOverrideChanges,
} from "@openwork-ee/den-db/organization-features"
import {
FEATURE_KEYS,
featureAvailableOn,
featureDefinition,
featureKeySchema,
featureRollout,
mapFeatures,
type FeatureKey,
type FeatureOverrides,
type FeatureRollouts,
type ResolvedFeature,
} from "@openwork/features"
import { DEFAULT_ORGANIZATION_LIMITS, normalizeOrganizationMetadata } from "../../organization-limits.js"
import { updateOrganizationMetadata } from "../../organization-metadata.js"
import { env } from "../../env.js"
@@ -103,17 +121,11 @@ const updateOrganizationDpaSchema = z.object({
reason: z.string().trim().min(3).max(500),
}).strict()
// Generated from the feature registry (packages/features/src/registry.ts):
// every registry key is accepted; unknown and retired keys are ignored.
const updateOrganizationCapabilitiesSchema = z.object({
capabilities: z.object({
installLinks: z.boolean().nullable().optional(),
mcpConnections: z.boolean().nullable().optional(),
modelsAnalytics: z.boolean().nullable().optional(),
auditLogs: z.boolean().nullable().optional(),
orgManagedDashboards: z.boolean().nullable().optional(),
slackAssistant: z.boolean().nullable().optional(),
slackAssistantHeadless: z.boolean().nullable().optional(),
headlessAutomations: z.boolean().nullable().optional(),
workbot: z.boolean().nullable().optional(),
...mapFeatures(() => z.boolean().nullable().optional()),
gatewayDashboard: z.boolean().nullable().optional().meta({
deprecated: true,
description: "Accepted for compatibility only and ignored; AI Gateway no longer has an organization rollout override.",
@@ -122,21 +134,45 @@ const updateOrganizationCapabilitiesSchema = z.object({
})
const adminOrganizationCapabilitiesSchema = z.object({
installLinks: z.boolean(),
mcpConnections: z.boolean(),
modelsAnalytics: z.boolean(),
auditLogs: z.boolean(),
orgManagedDashboards: z.boolean(),
slackAssistant: z.boolean(),
slackAssistantHeadless: z.boolean(),
headlessAutomations: z.boolean(),
workbot: z.boolean(),
...mapFeatures(() => z.boolean()),
gatewayDashboard: z.literal(true).meta({
deprecated: true,
description: "Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply.",
}),
})
const adminFeatureStateSchema = z.object({
enabled: z.boolean(),
source: z.enum(["unavailable", "killed", "lock", "override", "everyone"]),
everyone: z.boolean(),
killed: z.boolean(),
lock: z.boolean().nullable(),
override: z.boolean().nullable(),
overrideApplies: z.boolean(),
})
const adminFeatureStatesSchema = z.object(mapFeatures(() => adminFeatureStateSchema)).meta({
description: "Per feature for this organization: whether it is on and why (not part of this deployment, kill switch, operator lock, organization override, or the deployment-wide on/off state), and whether an organization override would take effect.",
})
const adminFeatureSchema = z.object({
key: featureKeySchema,
label: z.string(),
description: z.string(),
since: z.string(),
deployments: z.array(z.enum(["cloud", "self_hosted"])),
default: z.boolean(),
available: z.boolean(),
enabled: z.boolean(),
killed: z.boolean(),
lock: z.boolean().nullable(),
}).meta({ ref: "AdminFeature" })
const updateFeatureRolloutSchema = z.object({
enabled: z.boolean().optional(),
killed: z.boolean().optional(),
}).strict().refine((value) => value.enabled !== undefined || value.killed !== undefined, { message: "Set enabled, killed, or both." })
const createAdminSchema = z.object({
email: z.string().trim().max(255).email().transform((email) => email.toLowerCase()),
note: z.string().max(255).nullable().optional(),
@@ -205,7 +241,7 @@ const adminOverviewResponseSchema = z.object({
admins: z.array(z.object({}).passthrough()),
summary: adminSummarySchema,
users: z.array(z.object({}).passthrough()),
organizations: z.array(z.object({ capabilities: adminOrganizationCapabilitiesSchema }).passthrough()),
organizations: z.array(z.object({ capabilities: adminOrganizationCapabilitiesSchema, featureStates: adminFeatureStatesSchema }).passthrough()),
userPage: adminPageInfoSchema,
organizationPage: adminPageInfoSchema,
generatedAt: z.string().datetime(),
@@ -219,7 +255,7 @@ const adminUsersPageResponseSchema = z.object({
}).meta({ ref: "AdminUsersPageResponse" })
const adminOrganizationsPageResponseSchema = z.object({
organizations: z.array(z.object({ capabilities: adminOrganizationCapabilitiesSchema }).passthrough()),
organizations: z.array(z.object({ capabilities: adminOrganizationCapabilitiesSchema, featureStates: adminFeatureStatesSchema }).passthrough()),
page: adminPageInfoSchema,
generatedAt: z.string().datetime(),
}).meta({ ref: "AdminOrganizationsPageResponse" })
@@ -297,22 +333,37 @@ function parseBooleanQuery(value: string | undefined): boolean {
return normalized === "1" || normalized === "true" || normalized === "yes"
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
type DescribedFeatures = Record<FeatureKey, ResolvedFeature>
function describeOrganization(rollouts: FeatureRollouts, overrides: FeatureOverrides): DescribedFeatures {
return describeFeatures({ rollouts, overrides, environment: env.features })
}
function readAdminVisibleOrganizationCapabilities(metadata: Record<string, unknown> | string | null | undefined): z.infer<typeof adminOrganizationCapabilitiesSchema> {
function readAdminFeatureStates(described: DescribedFeatures): z.infer<typeof adminFeatureStatesSchema> {
return mapFeatures((key) => {
const { enabled, source, everyone, killed, lock, override, overrideApplies } = described[key]
return { enabled, source, everyone, killed, lock, override, overrideApplies }
})
}
function readAdminVisibleOrganizationCapabilities(described: DescribedFeatures): z.infer<typeof adminOrganizationCapabilitiesSchema> {
return { ...mapFeatures((key) => described[key].enabled), gatewayDashboard: true }
}
function readAdminFeature(key: FeatureKey, rollouts: FeatureRollouts): z.infer<typeof adminFeatureSchema> {
const definition = featureDefinition(key)
const { enabled, killed } = featureRollout(key, rollouts)
return {
installLinks: organizationInstallLinksEnabled(metadata),
mcpConnections: memberFacingMcpConnectionsEnabled(metadata),
modelsAnalytics: normalizeOrganizationCapabilities(metadata).modelsAnalytics,
auditLogs: normalizeOrganizationCapabilities(metadata).auditLogs,
orgManagedDashboards: normalizeOrganizationCapabilities(metadata).orgManagedDashboards,
slackAssistant: normalizeOrganizationCapabilities(metadata).slackAssistant,
slackAssistantHeadless: normalizeOrganizationCapabilities(metadata).slackAssistantHeadless,
headlessAutomations: normalizeOrganizationCapabilities(metadata).headlessAutomations,
workbot: normalizeOrganizationCapabilities(metadata).workbot,
gatewayDashboard: true,
key,
label: definition.label,
description: definition.description,
since: definition.since,
deployments: [...definition.deployments],
default: definition.default,
available: featureAvailableOn(key, env.features.deployment),
enabled,
killed,
lock: env.features.locks[key] ?? null,
}
}
@@ -341,24 +392,6 @@ function readAdminOpenWorkWebAccess(
}
}
function readUnmanagedCapabilityMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
const raw = isRecord(metadata.capabilities) ? metadata.capabilities : {}
const capabilities: Record<string, unknown> = {}
for (const [key, value] of Object.entries(raw)) {
// "workflows", "codemodeScripts", "remoteMcpApps", "appMcpServers", and
// "cloud" are retired rollout keys: those features are now always on (Cloud
// is entitled by OpenWork Web access instead), so stale stored overrides
// stay managed (dropped on the next capabilities write) instead of passing
// through as unmanaged metadata.
if (key !== "gatewayDashboard" && key !== "modelsAnalytics" && key !== "auditLogs" && key !== "orgManagedDashboards" && key !== "appMcpServers" && key !== "slackAssistant" && key !== "slackAssistantHeadless" && key !== "headlessAutomations" && key !== "workbot" && key !== "installLinks" && key !== "mcpConnections" && key !== "workflows" && key !== "codemodeScripts" && key !== "remoteMcpApps" && key !== "cloud") {
capabilities[key] = value
}
}
return capabilities
}
function getManualPlanMetadata(tier: PlanTier): { tier: PlanTier; source: "manual"; grantedAt?: string } {
return {
tier,
@@ -475,6 +508,7 @@ type AdminOrganizationRow = {
seatsFreeAdditional: number
billableSeatCount: number
capabilities: ReturnType<typeof readAdminVisibleOrganizationCapabilities>
featureStates: ReturnType<typeof readAdminFeatureStates>
openworkWebAccess: AdminOpenWorkWebAccess
}
@@ -935,7 +969,7 @@ async function shapeAdminOrganizationRows(rows: Array<Pick<typeof OrganizationTa
}
const organizationIds = rows.map((row) => row.id)
const [memberRows, webSubscriptionRows] = await Promise.all([
const [memberRows, webSubscriptionRows, featureOverridesByOrg, featureRollouts] = await Promise.all([
db
.select({ organizationId: MemberTable.organizationId, memberCount: sql<number>`count(*)` })
.from(MemberTable)
@@ -953,6 +987,8 @@ async function shapeAdminOrganizationRows(rows: Array<Pick<typeof OrganizationTa
inArray(OrgSubscriptionTable.organization_id, organizationIds),
eq(OrgSubscriptionTable.type, "web"),
)),
readOrganizationFeatureOverridesForMany(db, organizationIds),
readFeatureRollouts(db),
])
const memberCountByOrg = new Map<string, number>()
for (const row of memberRows) {
@@ -961,6 +997,7 @@ async function shapeAdminOrganizationRows(rows: Array<Pick<typeof OrganizationTa
const webSubscriptionByOrg = new Map(webSubscriptionRows.map((row) => [row.organizationId, row]))
return rows.map((entry) => {
const described = describeOrganization(featureRollouts, featureOverridesByOrg.get(entry.id) ?? {})
const metadata = normalizeOrganizationMetadata(entry.metadata).metadata
const seatLimit = metadata.limits.members ?? DEFAULT_ORGANIZATION_LIMITS.members
const seatCounts = calculateOrganizationSeatBillingCounts({ memberCount: memberCountByOrg.get(entry.id) ?? 0, metadata })
@@ -976,7 +1013,8 @@ async function shapeAdminOrganizationRows(rows: Array<Pick<typeof OrganizationTa
freeSeatCount: seatCounts.free,
seatsFreeAdditional: seatCounts.additionalFree,
billableSeatCount: seatCounts.chargeable,
capabilities: readAdminVisibleOrganizationCapabilities(metadata),
capabilities: readAdminVisibleOrganizationCapabilities(described),
featureStates: readAdminFeatureStates(described),
openworkWebAccess: readAdminOpenWorkWebAccess(metadata, webSubscriptionByOrg.get(entry.id) ?? null),
}
})
@@ -1955,9 +1993,9 @@ export function registerAdminRoutes<T extends { Variables: AuthContextVariables
describeRoute({
tags: ["Admin"],
summary: "Get an organization's capability overrides",
description: "Returns admin-visible capabilities. The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.",
description: "Returns the effective value of every registry feature (capabilities) and, per feature, its source and whether /admin can change it (featureStates). The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.",
responses: {
200: jsonResponse("Capability overrides returned.", z.object({ capabilities: adminOrganizationCapabilitiesSchema })),
200: jsonResponse("Capability overrides returned.", z.object({ capabilities: adminOrganizationCapabilitiesSchema, featureStates: adminFeatureStatesSchema })),
400: jsonResponse("The organization id was invalid.", adminRequestErrorSchema),
...adminRouteErrors,
404: jsonResponse("The organization does not exist.", notFoundSchema),
@@ -1981,7 +2019,9 @@ export function registerAdminRoutes<T extends { Variables: AuthContextVariables
return c.json({ error: "not_found", message: "Organization not found." }, 404)
}
return c.json({ capabilities: readAdminVisibleOrganizationCapabilities(organization.metadata) })
const [overrides, rollouts] = await Promise.all([readOrganizationFeatureOverrides(db, organization.id), readFeatureRollouts(db)])
const described = describeOrganization(rollouts, overrides)
return c.json({ capabilities: readAdminVisibleOrganizationCapabilities(described), featureStates: readAdminFeatureStates(described) })
},
)
@@ -1990,9 +2030,9 @@ export function registerAdminRoutes<T extends { Variables: AuthContextVariables
describeRoute({
tags: ["Admin"],
summary: "Set an organization's capability overrides",
description: "Enables, disables or clears (null) the install-links, MCP-connections, Models analytics, auditLogs and orgManagedDashboards overrides. Audit logs and org-managed Dashboards require literal true (absent/false is disabled); this flag neither grants capture entitlement nor initializes capacity or changes capture preferences. The deprecated gatewayDashboard boolean or null input is validated but ignored and never persisted; its response field is always true. Stale retired overrides are removed on capability writes.",
description: "Enables, disables or clears (null) per-organization feature overrides. Every key in the feature registry (packages/features/src/registry.ts) is accepted; a feature that is fixed on this deployment (unavailable, off or on for everyone) returns 400, and unknown or retired keys are ignored. A deployment lock (DEN_FEATURE_*) outranks a stored override; featureStates shows the effective value and its source. The auditLogs feature neither grants capture entitlement nor initializes capacity or changes capture preferences. The deprecated gatewayDashboard boolean or null input is validated but ignored and never persisted; its response field is always true.",
responses: {
200: jsonResponse("Capability overrides were updated.", z.object({ ok: z.literal(true), organization: z.object({ id: z.string() }), capabilities: adminOrganizationCapabilitiesSchema })),
200: jsonResponse("Capability overrides were updated.", z.object({ ok: z.literal(true), organization: z.object({ id: z.string() }), capabilities: adminOrganizationCapabilitiesSchema, featureStates: adminFeatureStatesSchema })),
400: jsonResponse("The request body or organization id was invalid.", adminRequestErrorSchema),
...adminRouteErrors,
404: jsonResponse("The organization does not exist.", notFoundSchema),
@@ -2021,64 +2061,76 @@ export function registerAdminRoutes<T extends { Variables: AuthContextVariables
return c.json({ error: "not_found", message: "Organization not found." }, 404)
}
const metadata = await updateOrganizationMetadata(organizationId, (current) => {
const capabilities = readOrganizationCapabilityOverrides(current)
const installLinks = body.data.capabilities.installLinks
if (installLinks !== undefined) {
if (installLinks === null) {
delete capabilities.installLinks
} else {
capabilities.installLinks = installLinks
}
}
const mcpConnections = body.data.capabilities.mcpConnections
if (mcpConnections !== undefined) {
if (mcpConnections === null) {
delete capabilities.mcpConnections
} else {
capabilities.mcpConnections = mcpConnections
}
}
const modelsAnalytics = body.data.capabilities.modelsAnalytics
if (modelsAnalytics === null) delete capabilities.modelsAnalytics
else if (modelsAnalytics !== undefined) capabilities.modelsAnalytics = modelsAnalytics
const auditLogs = body.data.capabilities.auditLogs
if (auditLogs === null) delete capabilities.auditLogs
else if (auditLogs !== undefined) capabilities.auditLogs = auditLogs
const orgManagedDashboards = body.data.capabilities.orgManagedDashboards
if (orgManagedDashboards === null) delete capabilities.orgManagedDashboards
else if (orgManagedDashboards !== undefined) capabilities.orgManagedDashboards = orgManagedDashboards
const slackAssistant = body.data.capabilities.slackAssistant
if (slackAssistant === null) delete capabilities.slackAssistant
else if (slackAssistant !== undefined) capabilities.slackAssistant = slackAssistant
const slackAssistantHeadless = body.data.capabilities.slackAssistantHeadless
if (slackAssistantHeadless === null) delete capabilities.slackAssistantHeadless
else if (slackAssistantHeadless !== undefined) capabilities.slackAssistantHeadless = slackAssistantHeadless
const headlessAutomations = body.data.capabilities.headlessAutomations
if (headlessAutomations === null) delete capabilities.headlessAutomations
else if (headlessAutomations !== undefined) capabilities.headlessAutomations = headlessAutomations
const workbot = body.data.capabilities.workbot
if (workbot === null) delete capabilities.workbot
else if (workbot !== undefined) capabilities.workbot = workbot
return {
...current,
capabilities: {
...readUnmanagedCapabilityMetadata(current),
...capabilities,
},
const changes: FeatureOverrideChanges = {}
for (const key of FEATURE_KEYS) {
const value = body.data.capabilities[key]
if (value === undefined) continue
if (!featureAvailableOn(key, env.features.deployment)) {
return c.json({ error: "invalid_request", message: `${key} is not part of this deployment.` }, 400)
}
changes[key] = value
}
const overrides = await setOrganizationFeatureOverrides(db, {
organizationId,
changes,
source: "platform",
setByUserId: c.get("user")?.id ?? null,
})
return c.json({ ok: true, organization: { id: organizationId }, capabilities: readAdminVisibleOrganizationCapabilities(metadata) })
const described = describeOrganization(await readFeatureRollouts(db), overrides)
return c.json({ ok: true, organization: { id: organizationId }, capabilities: readAdminVisibleOrganizationCapabilities(described), featureStates: readAdminFeatureStates(described) })
},
)
app.get(
"/v1/admin/features",
describeRoute({
tags: ["Admin"],
summary: "List features and their state",
description: "Every feature in the registry (packages/features/src/registry.ts) with what is fixed in code (deployments, default) and this deployment's state: on or off for everyone, kill switch, and any operator lock.",
responses: {
200: jsonResponse("Features returned.", z.object({ deployment: z.enum(["cloud", "self_hosted"]), features: z.array(adminFeatureSchema) })),
...adminRouteErrors,
},
}),
adminRoute(),
async (c) => {
const rollouts = await readFeatureRollouts(db)
return c.json({ deployment: env.features.deployment, features: FEATURE_KEYS.map((key) => readAdminFeature(key, rollouts)) })
},
)
app.put(
"/v1/admin/features/:key",
describeRoute({
tags: ["Admin"],
summary: "Change a feature's state",
description: "Turns the feature on or off for everyone on this deployment (organization overrides still apply), and/or sets the kill switch. The kill switch turns the feature off everywhere, outranking operator locks and organization overrides; it is the way to revert.",
responses: {
200: jsonResponse("Feature updated.", z.object({ ok: z.literal(true), feature: adminFeatureSchema })),
400: jsonResponse("The feature or body was invalid.", adminRequestErrorSchema),
...adminRouteErrors,
},
}),
adminRoute(),
async (c) => {
const key = featureKeySchema.safeParse(c.req.param("key"))
if (!key.success) return c.json({ error: "invalid_request", message: "Unknown feature." }, 400)
const body = updateFeatureRolloutSchema.safeParse(await c.req.json().catch(() => null))
if (!body.success) {
return c.json({ error: "invalid_request", message: body.error.issues[0]?.message ?? "Invalid feature request." }, 400)
}
if (!featureAvailableOn(key.data, env.features.deployment)) {
return c.json({ error: "invalid_request", message: `${key.data} is not part of this deployment.` }, 400)
}
const rollouts = await setFeatureRollout(db, {
key: key.data,
enabled: body.data.enabled,
killed: body.data.killed,
defaultEnabled: featureDefinition(key.data).default,
updatedByUserId: c.get("user")?.id ?? null,
})
return c.json({ ok: true, feature: readAdminFeature(key.data, rollouts) })
},
)
@@ -5,7 +5,7 @@ import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import type { Hono } from "hono"
import { describeRoute } from "hono-openapi"
import { z } from "zod"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { organizationFeatureEnabled } from "../../features.js"
import { jsonValidator, publicRoute, userSessionRoute } from "../../middleware/index.js"
import { db } from "../../db.js"
import { env, type DenOrgMode } from "../../env.js"
@@ -648,7 +648,6 @@ export function registerDesktopAuthRoutes<T extends { Variables: AuthContextVari
// back to null when the session has no resolvable organization; the app
// then repairs through its normal org-resolution path.
let organization: { id: string; slug: string; name: string } | null = null
let organizationMetadata: string | null = null
try {
const userId = normalizeDenTypeId("user", exchange.user.id)
let resolved = await resolveUserOrganizations({
@@ -666,7 +665,6 @@ export function registerDesktopAuthRoutes<T extends { Variables: AuthContextVari
}
const activeOrg = resolved.orgs.find((org) => org.id === resolved.activeOrgId) ?? null
organization = activeOrg ? { id: activeOrg.id, slug: activeOrg.slug, name: activeOrg.name } : null
organizationMetadata = activeOrg?.metadata ?? null
} catch {
organization = null
}
@@ -674,7 +672,7 @@ export function registerDesktopAuthRoutes<T extends { Variables: AuthContextVari
let connectEnabled: boolean | null = null
if (organization) {
try {
connectEnabled = memberFacingMcpConnectionsEnabled(organizationMetadata)
connectEnabled = await organizationFeatureEnabled(organization.id, "mcpConnections")
} catch {
connectEnabled = null
}
@@ -0,0 +1,47 @@
import { readFeatureRollouts } from "@openwork-ee/den-db/organization-features"
import { FEATURE_KEYS, featureAvailableOn, resolveFeature } from "@openwork/features"
import type { Env, Hono } from "hono"
import { describeRoute } from "hono-openapi"
import { z } from "zod"
import { db } from "../../db.js"
import { env } from "../../env.js"
import { publicRoute } from "../../middleware/index.js"
import { jsonResponse } from "../../openapi.js"
const publicFeaturesResponseSchema = z.object({
version: z.literal(1),
deployment: z.enum(["cloud", "self_hosted"]),
features: z.record(z.string(), z.boolean()),
}).meta({ ref: "PublicFeatures" })
/**
* Which features are on for someone without an organization (for example a
* desktop that is not signed in): the deployment-wide state after the kill
* switch and operator locks. Signed-in clients read `features` from GET /v1/org,
* which also applies their organization's overrides.
*/
export function registerFeatureRoutes<T extends Env>(app: Hono<T>) {
app.get(
"/v1/features",
describeRoute({
tags: ["System"],
security: [],
summary: "Get features for people without an organization",
description: "On or off for every feature that is part of this deployment, for someone who is not signed in: the deployment-wide state after the kill switch and operator locks, with no organization overrides. A feature missing here is off.",
responses: {
200: jsonResponse("Features returned.", publicFeaturesResponseSchema),
},
}),
publicRoute,
async (c) => {
c.header("Cache-Control", "public, max-age=60, stale-if-error=86400")
const rollouts = await readFeatureRollouts(db)
const features: Record<string, boolean> = {}
for (const key of FEATURE_KEYS) {
if (!featureAvailableOn(key, env.features.deployment)) continue
features[key] = resolveFeature(key, { ...env.features, rollouts, overrides: {} }).enabled
}
return c.json({ version: 1 as const, deployment: env.features.deployment, features })
},
)
}
+2 -2
View File
@@ -15,8 +15,8 @@ import { normalizeOrganizationMetadata } from "../../organization-limits.js"
import { resolveUserOrganizations, setSessionActiveOrganization, type UserOrgSummary } from "../../orgs.js"
import type { AuthContextVariables } from "../../session.js"
import { calculateDesktopPolicyForOrgMember } from "../../desktop-policies.js"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { DenEmailSendError, sendEmail } from "../../utils/email/send-email.js"
import { organizationFeatureEnabled } from "../../features.js"
const DOWNLOAD_LINK_RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000
const DOWNLOAD_LINK_RATE_LIMIT_MAX = 5
@@ -376,7 +376,7 @@ export function registerMeRoutes<T extends { Variables: AuthContextVariables & P
...desktopPolicy,
automationsEnabled: env.automations.enabled,
dashboardEnabled: env.dashboardsEnabled,
connectEnabled: memberFacingMcpConnectionsEnabled(organization.metadata),
connectEnabled: await organizationFeatureEnabled(organization.id, "mcpConnections"),
...(Array.isArray(metadata.allowedDesktopVersions)
? { allowedDesktopVersions: metadata.allowedDesktopVersions }
: {}),
+3 -3
View File
@@ -25,7 +25,7 @@ type AuditRouteContext = Pick<Context, "req" | "header" | "json"> & {
get: <K extends "organizationContext" | "apiKey" | "requestId">(key: K) => Variables[K]
}
const describeAuditRoute = (options: AuditRouteDescription) => describeRoute({ security: [{ bearerAuth: [] }, { denApiKey: [] }], ...options })
const coverage = "Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made."
const coverage = "Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made."
const pagination = "Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees."
const filterDescription = "Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values."
const errors = {
@@ -104,7 +104,7 @@ async function serveAudit(c: AuditRouteContext, action: "event_types" | "operati
export function registerOrgAuditRoutes<T extends { Variables: Variables }>(app: Hono<T>) {
app.patch("/v1/audit/settings", describeAuditRoute({
operationId: "updateAuditCapture", tags: ["Organizations"], "x-mcp": false, summary: "Set organization audit capture",
description: "Fresh organization administrator authorization, literal metadata.capabilities.auditLogs=true and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.",
description: "Fresh organization administrator authorization, the auditLogs feature on for the organization and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.",
responses: { ...errors,
200: jsonResponse("Latest audit policy, entitlement and retained usage.", auditUsageResponseSchema),
400: jsonResponse("Only captureOn and a nonnegative safe expectedRevision are accepted.", invalidRequestSchema),
@@ -154,7 +154,7 @@ export function registerOrgAuditRoutes<T extends { Variables: Variables }>(app:
app.get("/v1/audit/event-types", describeAuditRoute({
operationId: "getAuditEventTypes", tags: ["Organizations"], "x-mcp": false, summary: "List supported audit event types",
description: "Organization administrator, fresh literal metadata.capabilities.auditLogs=true and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.",
description: "Organization administrator, the auditLogs feature on for the organization (read fresh) and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.",
responses: { ...errors, 200: jsonResponse("The full static supported action catalog, not observed tenant event counts.", auditEventTypesResponseSchema) },
} satisfies AuditRouteDescription), orgMemberRoute(), (c) => serveAudit(c, "event_types", async () => {
parseQuery(z.object({}).strict(), c)
@@ -29,6 +29,7 @@ import { orgMemberRoute, jsonValidator, queryValidator } from "../../middleware/
import { forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
import { listTeamsForMember } from "../../orgs.js"
import { env } from "../../env.js"
import { getOrganizationFeatures } from "../../features.js"
import { getCatalog } from "../../mcp/index.js"
import { buildCapabilityToolTree, createCapabilityRegistryContext } from "../../mcp/capability-registry.js"
import {
@@ -256,7 +257,7 @@ export function registerOrgWorkflowRoutes<T extends { Variables: OrgRouteVariabl
member,
redirectUriBase: env.apiPublicUrl ?? "http://127.0.0.1",
generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,
organizationMetadata: context.organization.metadata,
organizationFeatures: await getOrganizationFeatures(context.organization.id),
})
const buildTools = () => buildCapabilityToolTree(capabilityContext)
const actorContext = { organizationContext: context, memberTeams: teams, session: c.get("session") }
+17 -11
View File
@@ -10,8 +10,6 @@ import { auth } from "../../auth.js"
import { verifyBotProtection } from "../../bot-protection.js"
import { validateBrandIconUrl } from "../../brand-icon-validation.js"
import { cloudHostingAvailable } from "../../capability-sources/cloud-hosting.js"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { organizationInstallLinksEnabled } from "../../capability-sources/install-links-rollout.js"
import { db } from "../../db.js"
import { checkEntitlement, getOrganizationEntitlements, parseOrganizationPlan } from "../../entitlements.js"
import { env } from "../../env.js"
@@ -21,7 +19,7 @@ import { jsonValidator, orgMemberRoute, orgRoleRoute, publicRoute, queryValidato
import { denTypeIdSchema, enterprisePlanRequiredSchema, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
import { validateInvitationAcceptVerification } from "../../organization-join-verification.js"
import { normalizeOrganizationMetadata } from "../../organization-limits.js"
import { organizationHasCapability, organizationManagedDashboardsEnabled } from "../../organization-capabilities.js"
import { getOrganizationFeatures } from "../../features.js"
import { appMcpServersEnabled } from "../../mcp-app-rollout.js"
import { workbotOrigin } from "../../workbot/config.js"
import { isOpenWorkWebAvailableForOrganization } from "../../openwork-web-availability.js"
@@ -181,6 +179,12 @@ const organizationContextResponseSchema = z.object({
description: "Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply.",
}),
}).passthrough(),
/**
* Effective on/off for every registry feature (packages/features/src/registry.ts).
* New clients read this; `capabilities` is frozen for published clients.
* A key missing here means an older server: treat it as off.
*/
features: z.record(z.string(), z.boolean()).meta({ description: "Effective on/off for every OpenWork feature in this organization. Treat a missing key as off." }),
deploymentCapabilities: deploymentCapabilitiesSchema,
entitlements: z.object({ sso: z.boolean(), desktopPolicies: z.boolean(), orgControls: z.boolean(), auditLogs: z.boolean() }),
}).passthrough().meta({ ref: "OrganizationContextResponse" })
@@ -682,6 +686,7 @@ export function registerOrgCoreRoutes<T extends { Variables: OrgRouteVariables }
const [currentOrganization] = await db.select({ metadata: OrganizationTable.metadata }).from(OrganizationTable).where(eq(OrganizationTable.id, payload.organization.id)).limit(1)
if (!currentOrganization) return c.json({ error: "organization_not_found" }, 404)
const features = await getOrganizationFeatures(payload.organization.id)
const owner = payload.members.find((member: typeof payload.members[number]) => member.isOwner) ?? null
// Cloud is entitled by OpenWork Web access (paid subscription or the
// platform-admin complimentary grant) on hosted deployments; there is no
@@ -720,32 +725,33 @@ export function registerOrgCoreRoutes<T extends { Variables: OrgRouteVariables }
deploymentCapabilities: deploymentCapabilities(),
plan: parseOrganizationPlan(currentOrganization.metadata),
entitlements: getOrganizationEntitlements(currentOrganization.metadata),
features,
// Frozen for published clients; new clients read `features`.
capabilities: {
auditLogs: organizationHasCapability(currentOrganization.metadata, "auditLogs") && env.auditVisibilityEnabled,
auditLogs: features.auditLogs && env.auditVisibilityEnabled,
gatewayDashboard: true,
// Protocol capability: clients must see this explicit signal before
// calling the dashboard routes. Older Den versions omit the field,
// allowing newer Desktop builds to fail closed during a staggered
// rollout instead of calling an endpoint that does not exist yet.
// Per-organization and default-off: platform admins enable it with
// metadata.capabilities.orgManagedDashboards = true.
orgManagedDashboards: organizationManagedDashboardsEnabled(payload.organization.metadata),
// Per-organization and default-off: platform admins enable it in /admin.
orgManagedDashboards: features.orgManagedDashboards,
// Expose the effective value, not the raw stored flag: Connect is
// member-facing default-on unless an explicit org kill switch says no.
mcpConnections: memberFacingMcpConnectionsEnabled(payload.organization.metadata),
mcpConnections: features.mcpConnections,
// Building your own Apps is on for every organization unless the
// deployment or the org's member-facing MCP connections turn it off.
appMcpServers: appMcpServersEnabled(payload.organization.metadata),
appMcpServers: appMcpServersEnabled(features),
// Workflows/Code Mode are enabled for every organization; the field
// remains for published clients that still read it.
workflows: true,
installLinks: organizationInstallLinksEnabled(payload.organization.metadata),
installLinks: features.installLinks,
// Effective offer: the deployment switch enables Web generally,
// while the platform-admin complimentary grant enables only this
// organization when the deployment switch is off.
openworkWeb: isOpenWorkWebAvailableForOrganization(payload.organization.metadata),
// Workbot is its own app (DEN_WORKBOT_URL), per-organization and default-off.
workbot: organizationHasCapability(payload.organization.metadata, "workbot") && workbotOrigin() !== null,
workbot: features.workbot && workbotOrigin() !== null,
...(cloudEnabled ? { cloud: true } : {}),
},
authMethods: {
+9 -9
View File
@@ -13,9 +13,8 @@ import type { Hono, MiddlewareHandler } from "hono"
import { describeRoute } from "hono-openapi"
import { z } from "zod"
import { db } from "../../db.js"
import { appMcpServersEnabled } from "../../mcp-app-rollout.js"
import { organizationBuildsMcpApps } from "../../mcp-app-rollout.js"
import { currentMcpAppRevisionIds } from "../../mcp-apps.js"
import { organizationManagedDashboardsEnabled } from "../../organization-capabilities.js"
import {
jsonValidator,
orgMemberRoute,
@@ -27,6 +26,7 @@ import { denTypeIdSchema, emptyResponse, forbiddenSchema, invalidRequestSchema,
import type { MemberTeamSummary } from "../../orgs.js"
import type { OrgRouteVariables } from "./shared.js"
import { idParamSchema } from "./shared.js"
import { organizationFeatureEnabled } from "../../features.js"
/**
* Organization-managed Dashboards: an org-owned, ordered list of MCP App
@@ -255,7 +255,7 @@ async function grantTargetsInOrganization(
const requireOrgManagedDashboards: MiddlewareHandler<{ Variables: OrgRouteVariables }> = async (c, next) => {
const payload = c.get("organizationContext")
if (!payload) return c.json({ error: "organization_not_found" }, 404)
if (!organizationManagedDashboardsEnabled(payload.organization.metadata)) {
if (!(await organizationFeatureEnabled(payload.organization.id, "orgManagedDashboards"))) {
return c.json({ error: "dashboards_not_enabled" }, 404)
}
await next()
@@ -283,7 +283,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
.from(DashboardTable)
.where(and(eq(DashboardTable.organizationId, payload.organization.id), isNull(DashboardTable.deletedAt)))
.orderBy(asc(DashboardTable.name), asc(DashboardTable.id))
return c.json({ items: (await withCurrentAppRevisions(payload.organization.id, rows, appMcpServersEnabled(payload.organization.metadata))).map(serializeDashboard) })
return c.json({ items: (await withCurrentAppRevisions(payload.organization.id, rows, await organizationBuildsMcpApps(payload.organization.id))).map(serializeDashboard) })
},
)
@@ -318,7 +318,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
deletedAt: null,
}
await db.insert(DashboardTable).values(row)
const [current] = await withCurrentAppRevisions(payload.organization.id, [row], appMcpServersEnabled(payload.organization.metadata))
const [current] = await withCurrentAppRevisions(payload.organization.id, [row], await organizationBuildsMcpApps(payload.organization.id))
return c.json({ item: serializeDashboard(current ?? row) }, 201)
},
)
@@ -346,7 +346,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
normalizeDenTypeId("dashboard", c.req.valid("param").dashboardId),
)
if (!row) return c.json({ error: "dashboard_not_found" }, 404)
const [current] = await withCurrentAppRevisions(payload.organization.id, [row], appMcpServersEnabled(payload.organization.metadata))
const [current] = await withCurrentAppRevisions(payload.organization.id, [row], await organizationBuildsMcpApps(payload.organization.id))
return c.json({ item: serializeDashboard(current ?? row) })
},
)
@@ -388,7 +388,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
.update(DashboardTable)
.set({ name: next.name, elementsJson: next.elementsJson, updatedAt })
.where(eq(DashboardTable.id, existing.id))
const [current] = await withCurrentAppRevisions(payload.organization.id, [next], appMcpServersEnabled(payload.organization.metadata))
const [current] = await withCurrentAppRevisions(payload.organization.id, [next], await organizationBuildsMcpApps(payload.organization.id))
return c.json({ item: serializeDashboard(current ?? next) })
},
)
@@ -608,7 +608,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
async (c) => {
const payload = c.get("organizationContext")
// Desktop polls this route; a disabled org sees no granted dashboards.
if (!organizationManagedDashboardsEnabled(payload.organization.metadata)) {
if (!(await organizationFeatureEnabled(payload.organization.id, "orgManagedDashboards"))) {
return c.json({ items: [] })
}
const memberId = payload.currentMember.id
@@ -642,7 +642,7 @@ export function registerOrgDashboardRoutes<T extends { Variables: OrgRouteVariab
))
.orderBy(asc(DashboardTable.name), asc(DashboardTable.id))
const seen = new Set<string>()
const items = (await withCurrentAppRevisions(payload.organization.id, rows, appMcpServersEnabled(payload.organization.metadata))).flatMap((row) => {
const items = (await withCurrentAppRevisions(payload.organization.id, rows, await organizationBuildsMcpApps(payload.organization.id))).flatMap((row) => {
if (seen.has(row.id)) return []
seen.add(row.id)
return [{
@@ -11,7 +11,7 @@ import { describeRoute } from "hono-openapi"
import { z } from "zod"
import { OPENWORK_DOWNLOAD_URL } from "../../CONSTS.js"
import { resolvePublicOrigin } from "../../capability-sources/generic-oauth.js"
import { organizationInstallLinksEnabled } from "../../capability-sources/install-links-rollout.js"
import { organizationFeatureEnabled } from "../../features.js"
import { db } from "../../db.js"
import { mintDesktopConnectLink } from "../../desktop-connect-link.js"
import { resolveInstallerReleaseTag } from "../../desktop-releases.js"
@@ -25,7 +25,7 @@ import { env } from "../../env.js"
import { hashInstallLinkToken, mintOrganizationInstallLink } from "../../install-links.js"
import { jsonValidator, orgMemberRoute, orgRoleRoute, publicRoute, queryValidator } from "../../middleware/index.js"
import { denTypeIdSchema, emptyResponse, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, textResponse, unauthorizedSchema } from "../../openapi.js"
import { organizationCapabilityKeySchema } from "../../organization-capabilities.js"
import { featureKeySchema } from "@openwork/features"
import { normalizeOrganizationMetadata } from "../../organization-limits.js"
import {
cloudDesktopReleaseAssetName,
@@ -95,7 +95,7 @@ const installLinkNotFoundSchema = z.object({
const capabilityDisabledSchema = z.object({
error: z.literal("capability_disabled"),
capability: organizationCapabilityKeySchema,
capability: featureKeySchema,
}).meta({ ref: "CapabilityDisabledError" })
const rateLimitedSchema = z.object({
@@ -391,7 +391,7 @@ export function registerOrgInstallLinkRoutes<T extends { Variables: OrgRouteVari
const input = c.req.valid("json")
const payload = c.get("organizationContext")
if (!organizationInstallLinksEnabled(payload.organization.metadata)) {
if (!(await organizationFeatureEnabled(payload.organization.id, "installLinks"))) {
return c.json({ error: "capability_disabled", capability: "installLinks" }, 403)
}
@@ -416,7 +416,6 @@ export function registerOrgInstallLinkRoutes<T extends { Variables: OrgRouteVari
const installLink = await mintOrganizationInstallLink({
organizationId: payload.organization.id,
createdByUserId: payload.currentMember.userId,
metadata: payload.organization.metadata,
rotate: input.rotate,
})
@@ -6,7 +6,7 @@ import type { Hono } from "hono"
import { describeRoute } from "hono-openapi"
import { z } from "zod"
import { db } from "../../db.js"
import { appMcpServersEnabled } from "../../mcp-app-rollout.js"
import { organizationBuildsMcpApps } from "../../mcp-app-rollout.js"
import { listAccessibleMcpApps } from "../../mcp-apps.js"
import { orgRoleRoute, resolveMemberTeamsMiddleware } from "../../middleware/index.js"
import { forbiddenSchema, jsonResponse, unauthorizedSchema } from "../../openapi.js"
@@ -55,7 +55,7 @@ export function registerOrgMcpAppCatalogRoutes<T extends { Variables: OrgRouteVa
resolveMemberTeamsMiddleware,
async (c) => {
const payload = c.get("organizationContext")
if (!appMcpServersEnabled(payload.organization.metadata)) return c.json({ apps: [] })
if (!(await organizationBuildsMcpApps(payload.organization.id))) return c.json({ apps: [] })
const memberTeams: MemberTeamSummary[] = c.get("memberTeams") ?? []
const apps = await listAccessibleMcpApps({
organizationId: payload.organization.id,
@@ -78,7 +78,6 @@ import {
} from "../../capability-sources/external-mcp-connections.js"
import { evaluateToolPolicy } from "../../capability-sources/external-mcp-tool-policy.js"
import { memberApiKeyUsable, usesMemberApiKey, validMemberApiKey } from "../../capability-sources/member-api-key.js"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { externalMcpAppResourceUri } from "../../mcp/external-capabilities.js"
import { EXECUTE_CAPABILITY_TOOL_NAME, SEARCH_CAPABILITIES_TOOL_NAME } from "../../mcp/search.js"
import { listNativeProviderUsableEntries } from "../../capability-sources/native-provider-connections.js"
@@ -136,6 +135,7 @@ import {
} from "./shared.js"
import type { OrgRouteVariables } from "./shared.js"
import { beginNativeProviderConnect } from "./oauth-providers.js"
import { organizationFeatureEnabled } from "../../features.js"
const connectionParamsSchema = idParamSchema("connectionId", "externalMcpConnection")
const logger = appLogger.child({ component: "mcp_connections" })
@@ -1262,7 +1262,7 @@ export async function listMemberUsableConnectionFacts(input: {
context: PluginArchActorContext
}): Promise<MemberUsableConnectionFacts[]> {
const organization = input.context.organizationContext.organization
if (!memberFacingMcpConnectionsEnabled(organization.metadata)) {
if (!(await organizationFeatureEnabled(organization.id, "mcpConnections"))) {
return []
}
@@ -2391,7 +2391,7 @@ export function registerMcpConnectionRoutes<T extends { Variables: OrgRouteVaria
const isAdmin = verifyOrgRole({ roles: ["admin"], userContext: payload.currentMember })
if (!isAdmin) {
const memberTeams: MemberTeamSummary[] = c.get("memberTeams") ?? []
const canUse = memberFacingMcpConnectionsEnabled(payload.organization.metadata)
const canUse = await organizationFeatureEnabled(payload.organization.id, "mcpConnections")
&& await memberCanUseExternalMcpConnection({
connectionId: connection.id,
orgMembershipId: payload.currentMember.id,
@@ -2582,7 +2582,7 @@ export function registerMcpConnectionRoutes<T extends { Variables: OrgRouteVaria
}
const memberTeams: MemberTeamSummary[] = c.get("memberTeams") ?? []
const canUse = memberFacingMcpConnectionsEnabled(payload.organization.metadata)
const canUse = await organizationFeatureEnabled(payload.organization.id, "mcpConnections")
&& await memberCanUseExternalMcpConnection({
connectionId: connection.id,
orgMembershipId: payload.currentMember.id,
@@ -2686,7 +2686,7 @@ export function registerMcpConnectionRoutes<T extends { Variables: OrgRouteVaria
const parsedBody = c.req.valid("json")
let body = parsedBody
if (!isOrganizationAdmin(payload)) {
const denial = !memberFacingMcpConnectionsEnabled(payload.organization.metadata)
const denial = !(await organizationFeatureEnabled(payload.organization.id, "mcpConnections"))
? "Connections are not enabled for this organization."
: memberConnectionCreateDenial(parsedBody)
if (denial || parsedBody.kind === "native_provider") {
@@ -81,7 +81,6 @@ import { env } from "../../../env.js"
import { appLogger } from "../../../observability/logger.js"
import { roleIncludesOwner } from "../../../orgs.js"
import { redactWorkflowNormalizedPayloadAuthoringDetails } from "../../../workflow-projections.js"
import { memberFacingMcpConnectionsEnabled } from "../../../capability-sources/external-mcp-rollout.js"
import { comparablePluginMcpRequirementUrl, marketplaceMcpServerEntries, resolveMarketplacePluginCloudReadiness } from "../../../mcp/marketplace-capabilities.js"
import { assertPublicUrl, PrivateUrlError } from "../../../capability-sources/url-guard.js"
import {
@@ -118,6 +117,7 @@ import {
import { resolveImportedConnectorTarget } from "../../../capability-sources/claude-connector-aliases.js"
import { NATIVE_OAUTH_PROVIDERS } from "../../../capability-sources/provider-registry.js"
import type { MemberUsableConnectionFacts } from "../mcp-connections.js"
import { organizationFeatureEnabled } from "../../../features.js"
type OrganizationId = PluginArchActorContext["organizationContext"]["organization"]["id"]
const logger = appLogger.child({ component: "plugin_system_store" })
@@ -3757,7 +3757,7 @@ export async function getMarketplaceResolved(input: { context: PluginArchActorCo
counts.set(objectType, (counts.get(objectType) ?? 0) + 1)
}
const cloudReadinessByPlugin = memberFacingMcpConnectionsEnabled(input.context.organizationContext.organization.metadata)
const cloudReadinessByPlugin = (await organizationFeatureEnabled(input.context.organizationContext.organization.id, "mcpConnections"))
? await resolveMarketplacePluginCloudReadiness({
organizationId,
member: {
+2 -2
View File
@@ -15,7 +15,6 @@ import { z } from "zod"
import { db } from "../../db.js"
import { env } from "../../env.js"
import { organizationAllowsManagedModels } from "../../inference.js"
import { memberFacingMcpConnectionsEnabled } from "../../capability-sources/external-mcp-rollout.js"
import { listAccessibleMarketplaceCapabilityReferences } from "../../mcp/marketplace-capabilities.js"
import {
type MemberTeamsContext,
@@ -26,6 +25,7 @@ import { jsonResponse, unauthorizedSchema } from "../../openapi.js"
import { listAccessibleLlmProviderAccess } from "./llm-provider-access.js"
import { resolvePluginArchResourceRole, type PluginArchActorContext } from "./plugin-system/access.js"
import type { OrgRouteVariables } from "./shared.js"
import { organizationFeatureEnabled } from "../../features.js"
type OrganizationId = typeof LlmProviderTable.$inferSelect.organizationId
type MemberId = NonNullable<typeof LlmProviderAccessTable.$inferSelect.orgMembershipId>
@@ -281,7 +281,7 @@ export function registerOrgResourceRoutes<T extends { Variables: OrgRouteVariabl
orgMembershipId: organizationContext.currentMember.id,
teamIds,
},
enabled: memberFacingMcpConnectionsEnabled(organizationContext.organization.metadata),
enabled: await organizationFeatureEnabled(organizationContext.organization.id, "mcpConnections"),
})
return c.json({
items: items.map((item) => ({
@@ -1,5 +1,5 @@
import type { RemoteSessionAction } from "../mcp/remote-session-capabilities.js"
import { organizationHasCapability } from "../organization-capabilities.js"
import type { FeatureMap } from "../features.js"
import { stepLabel } from "../headless-runner/client.js"
import {
createHeadlessRunnerClient,
@@ -29,11 +29,10 @@ export type SlackRuntime = "headless" | "web"
/** An organization uses the headless runner only when it is switched on for it and the deployment has one. */
export function slackRuntimeForOrganization(
metadata: Parameters<typeof organizationHasCapability>[0],
features: Pick<FeatureMap, "slackAssistantHeadless">,
env: Record<string, string | undefined> = process.env,
): SlackRuntime {
const enabled = organizationHasCapability(metadata, "slackAssistantHeadless")
return enabled && headlessRunnerConfig(env) !== null ? "headless" : "web"
return features.slackAssistantHeadless && headlessRunnerConfig(env) !== null ? "headless" : "web"
}
export { stepLabel }
@@ -20,8 +20,7 @@ import {
readConnectedAccountForExternalMcpIdentity,
type ExternalMcpConnectionRow,
} from "../capability-sources/external-mcp-connections.js"
import { memberFacingMcpConnectionsEnabled } from "../capability-sources/external-mcp-rollout.js"
import { organizationHasCapability } from "../organization-capabilities.js"
import { getOrganizationFeatures, organizationFeatureEnabled } from "../features.js"
import { getOpenWorkWebRuntimeAccess } from "../openwork-web-runtime-access.js"
import { listTeamsForMember } from "../orgs.js"
import { canUseSlackAssistant, scopeKey, slackClient, type SlackEvent } from "./protocol.js"
@@ -34,20 +33,10 @@ export async function getInstallation(connectionId: DenTypeId<"externalMcpConnec
return (await db.select().from(Installation).where(eq(Installation.connectionId, connectionId)).limit(1))[0] ?? null
}
export async function slackAssistantEnabledForInstallation(installation: InstallationRow) {
const [organization] = await db
.select({ metadata: OrganizationTable.metadata })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, installation.organizationId))
.limit(1)
return organizationHasCapability(organization?.metadata, "slackAssistant")
return organizationFeatureEnabled(installation.organizationId, "slackAssistant")
}
export async function slackRuntimeForInstallation(installation: InstallationRow): Promise<SlackRuntime> {
const [organization] = await db
.select({ metadata: OrganizationTable.metadata })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, installation.organizationId))
.limit(1)
return slackRuntimeForOrganization(organization?.metadata)
return slackRuntimeForOrganization(await getOrganizationFeatures(installation.organizationId))
}
export function isSlackConnection(connection: ExternalMcpConnectionRow) {
return (
@@ -204,15 +193,16 @@ export async function resolveSlackActor(installation: InstallationRow, slackUser
.limit(1)
const member = members[0]
if (!member?.userId) return null
const [organizations, teams, account, access] = await Promise.all([
const [organizations, teams, account, access, features] = await Promise.all([
db.select().from(OrganizationTable).where(eq(OrganizationTable.id, installation.organizationId)).limit(1),
listTeamsForMember({ organizationId: installation.organizationId, memberId: member.id }),
readConnectedAccountForExternalMcpIdentity({ connection, orgMembershipId: member.id }),
getOpenWorkWebRuntimeAccess(installation.organizationId),
getOrganizationFeatures(installation.organizationId),
])
const organization = organizations[0]
// The headless runner needs no per-member OpenWork Web computer.
const runtime = slackRuntimeForOrganization(organization?.metadata)
const runtime = slackRuntimeForOrganization(features)
const granted = await memberCanUseExternalMcpConnection({
connectionId: connection.id,
orgMembershipId: member.id,
@@ -221,10 +211,10 @@ export async function resolveSlackActor(installation: InstallationRow, slackUser
if (
!organization ||
!canUseSlackAssistant({
capabilityEnabled: organizationHasCapability(organization.metadata, "slackAssistant"),
capabilityEnabled: features.slackAssistant,
enabled: installation.enabled,
individualAccounts: true,
mcpEnabled: memberFacingMcpConnectionsEnabled(organization.metadata),
mcpEnabled: features.mcpConnections,
webAccess: runtime === "headless" || access.hasAccess,
activeMember: true,
granted,
@@ -35,7 +35,7 @@ import { getExternalMcpConnection } from "../capability-sources/external-mcp-con
import { getOrgOAuthClient } from "../capability-sources/oauth-credentials.js"
import { getOpenWorkWebRuntimeAccess } from "../openwork-web-runtime-access.js"
import { listHeadlessModels, slackRuntimeForOrganization } from "./headless.js"
import { organizationHasCapability } from "../organization-capabilities.js"
import { getOrganizationFeatures } from "../features.js"
import { publicRequestUrl } from "../request-url.js"
import { getOrganizationContextForUser } from "../orgs.js"
import { openworkYourConnectionsUrl } from "../mcp/connection-navigation.js"
@@ -162,16 +162,17 @@ export function registerSlackAssistantRoutes<T extends { Variables: OrgRouteVari
if (!connection) return c.json({ error: "not_found" }, 404)
const installation = await getInstallation(connectionId)
const web = await getOpenWorkWebRuntimeAccess(org.organization.id)
const features = await getOrganizationFeatures(org.organization.id)
const catalog =
slackRuntimeForOrganization(org.organization.metadata) === "headless" ? await listHeadlessModels() : null
slackRuntimeForOrganization(features) === "headless" ? await listHeadlessModels() : null
return c.json({
enabled: installation?.enabled ?? false,
installed: Boolean(installation?.botToken),
teamId: installation?.teamId ?? null,
rolloutEnabled: organizationHasCapability(org.organization.metadata, "slackAssistant"),
rolloutEnabled: features.slackAssistant,
hasSigningSecret: Boolean(installation?.signingSecret),
eligible: isSlackConnection(connection),
webAccess: slackRuntimeForOrganization(org.organization.metadata) === "headless" || web.hasAccess,
webAccess: slackRuntimeForOrganization(features) === "headless" || web.hasAccess,
channelIds: installation?.channelIds ?? [],
shadowMode: installation?.shadowMode ?? false,
dailyLimit: installation?.dailyLimit ?? 100,
@@ -213,7 +214,8 @@ export function registerSlackAssistantRoutes<T extends { Variables: OrgRouteVari
400,
)
const body = c.req.valid("json")
if (body.enabled && !organizationHasCapability(org.organization.metadata, "slackAssistant")) {
const features = await getOrganizationFeatures(org.organization.id)
if (body.enabled && !features.slackAssistant) {
return c.json(
{
error: "slack_assistant_not_enabled",
@@ -224,7 +226,7 @@ export function registerSlackAssistantRoutes<T extends { Variables: OrgRouteVari
}
if (
body.enabled &&
slackRuntimeForOrganization(org.organization.metadata) !== "headless" &&
slackRuntimeForOrganization(features) !== "headless" &&
!(await getOpenWorkWebRuntimeAccess(org.organization.id)).hasAccess
)
return c.json({ error: "openwork_web_access_required" }, 403)
+3 -3
View File
@@ -11,7 +11,7 @@ import { verifyMcpRequest } from "../mcp/auth.js"
import { DEN_MCP_HEADLESS_RUN_TOKEN_MAX_TTL_MS } from "../mcp/headless-run-token.js"
import { mintHeadlessRunMcpToken } from "../mcp/headless-run-token-mint.js"
import { jsonResponse, unauthorizedSchema } from "../openapi.js"
import { organizationHasCapability } from "../organization-capabilities.js"
import { organizationFeatureEnabled } from "../features.js"
import { jsonValidator, tokenRoute } from "../middleware/index.js"
import { checkRateLimit } from "../utils/rate-limit.js"
@@ -121,7 +121,7 @@ export function registerWorkbotRoutes<T extends { Variables: object }>(app: Hono
user,
organization: { id: organization.id, name: organization.name, brandAppName: readBrandAppName(organization.metadata) },
memberId,
enabled: organizationHasCapability(organization.metadata, "workbot"),
enabled: await organizationFeatureEnabled(organization.id, "workbot"),
canSchedule,
})
},
@@ -149,7 +149,7 @@ export function registerWorkbotRoutes<T extends { Variables: object }>(app: Hono
const resolved = await resolve(c.req.raw.headers)
if (resolved instanceof Response) return resolved
const { principal, organization } = resolved
if (!organizationHasCapability(organization.metadata, "workbot")) {
if (!(await organizationFeatureEnabled(organization.id, "workbot"))) {
return c.json({ error: "workbot_not_enabled", message: "Workbot is off for this workspace." }, 403)
}
const retryAfter = await checkRateLimit(`workbot-run-token:${principal.organizationId}:${principal.userId}`, RUN_TOKENS_PER_WINDOW, RUN_TOKEN_WINDOW_MS, Date.now())
+16
View File
@@ -1,4 +1,5 @@
import { parseDeploymentCapabilities, type DeploymentCapabilities } from "@openwork/types/den/deployment-capabilities";
import { mapFeatures, type FeatureMap } from "@openwork/features";
export type DenOrgSummary = {
id: string;
@@ -232,7 +233,10 @@ export type DenOrgContext = {
currentMemberTeams: DenCurrentMemberTeam[];
entitlements: DenOrgEntitlements;
authMethods: DenOrgAuthMethods;
/** Frozen for published screens; new code reads `features` through orgFeatureEnabled(). */
capabilities: DenOrgCapabilities;
/** Effective on/off per registry feature (packages/features/src/registry.ts). Missing from older servers means off. */
features: FeatureMap;
deploymentCapabilities: DeploymentCapabilities;
};
@@ -1051,6 +1055,7 @@ export function parseOrgContextPayload(payload: unknown): DenOrgContext | null {
entitlements: parseOrgEntitlements(payload.entitlements),
authMethods: parseOrgAuthMethods(payload.authMethods),
capabilities: parseOrgCapabilities(payload.capabilities),
features: parseOrgFeatures(payload.features),
deploymentCapabilities: parseDeploymentCapabilities(payload.deploymentCapabilities),
};
}
@@ -1066,6 +1071,17 @@ function parseOrgAuthMethods(value: unknown): DenOrgAuthMethods {
};
}
/** Fail closed: a feature the server did not report (older server) is off. */
function parseOrgFeatures(value: unknown): FeatureMap {
const reported = isRecord(value) ? value : {};
return mapFeatures((key) => reported[key] === true);
}
/** Whether a registry feature is on for the active organization. Use this for every new feature gate. */
export function orgFeatureEnabled(orgContext: Pick<DenOrgContext, "features"> | null | undefined, key: keyof FeatureMap): boolean {
return orgContext?.features[key] === true;
}
function parseOrgCapabilities(value: unknown): DenOrgCapabilities {
if (!isRecord(value)) {
return { auditLogs: false, orgManagedDashboards: false, installLinks: false, mcpConnections: false, appMcpServers: false, workflows: true, openworkWeb: false, cloud: false, workbot: false };
@@ -0,0 +1,10 @@
import { AdminShell } from "../../../components/admin/admin-shell";
import { FeatureRolloutsPage } from "../../../components/admin/features/feature-rollouts-page";
export default function AdminFeaturesPage() {
return (
<AdminShell active="features">
<FeatureRolloutsPage />
</AdminShell>
);
}
@@ -44,3 +44,19 @@ export async function requestAdmin<T>(path: string, parse: (payload: unknown) =>
const data = parse(payload);
return data === null ? { access: "error", message: "The server returned data this page does not understand." } : { access: "ready", data };
}
/** PUT/POST JSON to an admin endpoint; returns the parsed payload or the server's error message. */
export async function sendAdmin(path: string, method: "PUT" | "POST", body: unknown): Promise<{ ok: true; payload: unknown } | { ok: false; message: string }> {
const endpoint = denBrowserEndpoint(path);
const response = await fetch(endpoint, {
method,
credentials: denApiCredentials(endpoint),
headers: withStoredBearer({ Accept: "application/json", "Content-Type": "application/json" }),
body: JSON.stringify(body),
});
const text = await response.text();
let payload: unknown = null;
try { payload = text ? JSON.parse(text) : null; } catch { payload = text; }
if (!response.ok) return { ok: false, message: errorMessage(payload, `The request failed with status ${response.status}.`) };
return { ok: true, payload };
}
@@ -1,10 +1,11 @@
import Link from "next/link";
import type { ReactNode } from "react";
export type AdminSection = "overview" | "free-auto";
export type AdminSection = "overview" | "features" | "free-auto";
const SECTIONS: Array<{ id: AdminSection; label: string; href: string }> = [
{ id: "overview", label: "Overview", href: "/admin" },
{ id: "features", label: "Features", href: "/admin/features" },
{ id: "free-auto", label: "Free Auto usage", href: "/admin/free-auto" },
];
@@ -0,0 +1,185 @@
"use client";
import { RefreshCw } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { DenBadge } from "../../../app/(den)/_components/ui/badge";
import { DenButton } from "../../../app/(den)/_components/ui/button";
import { DenCard } from "../../../app/(den)/_components/ui/card";
import { DenNotice } from "../../../app/(den)/_components/ui/notice";
import { DenPageHeader } from "../../../app/(den)/_components/ui/page-header";
import { DenSegmented } from "../../../app/(den)/_components/ui/segmented";
import { requestAdmin, sendAdmin } from "../admin-request";
/**
* Deployment-wide state of every feature in packages/features/src/registry.ts:
* on or off for everyone, and the kill switch. Per-organization overrides stay
* on each organization's row in the Overview.
*/
type AdminFeature = {
key: string;
label: string;
description: string;
deployments: Array<"cloud" | "self_hosted">;
available: boolean;
enabled: boolean;
killed: boolean;
lock: boolean | null;
};
type FeaturesReport = { deployment: "cloud" | "self_hosted"; features: AdminFeature[] };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function parseFeature(value: unknown): AdminFeature | null {
if (!isRecord(value) || typeof value.key !== "string" || typeof value.label !== "string") return null;
const deployments = Array.isArray(value.deployments)
? value.deployments.filter((entry): entry is "cloud" | "self_hosted" => entry === "cloud" || entry === "self_hosted")
: [];
return {
key: value.key,
label: value.label,
description: typeof value.description === "string" ? value.description : "",
deployments,
available: value.available === true,
enabled: value.enabled === true,
killed: value.killed === true,
lock: typeof value.lock === "boolean" ? value.lock : null,
};
}
function parseReport(payload: unknown): FeaturesReport | null {
if (!isRecord(payload) || !Array.isArray(payload.features)) return null;
return {
deployment: payload.deployment === "cloud" ? "cloud" : "self_hosted",
features: payload.features.map(parseFeature).filter((feature): feature is AdminFeature => feature !== null),
};
}
/** One state line per feature (DESIGN.md P1). */
function rolloutState(feature: AdminFeature): string {
if (!feature.available) return "Not part of this deployment";
if (feature.killed) return "Turned off everywhere";
if (feature.lock !== null) return feature.lock ? "On for everyone · set by deployment config" : "Off for everyone · set by deployment config";
return feature.enabled ? "On for everyone · organization overrides apply" : "Off · organization overrides only";
}
const ON_OFF = [{ value: "on", label: "On" }, { value: "off", label: "Off" }] as const;
function FeatureRow({ feature, onChange }: { feature: AdminFeature; onChange: (next: AdminFeature) => void }) {
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const save = useCallback(async (body: { enabled?: boolean; killed?: boolean }) => {
setSaving(true);
setError(null);
const result = await sendAdmin(`/v1/admin/features/${encodeURIComponent(feature.key)}`, "PUT", body);
setSaving(false);
if (!result.ok) {
setError(result.message);
return;
}
const next = isRecord(result.payload) ? parseFeature(result.payload.feature) : null;
if (next) onChange(next);
}, [feature.key, onChange]);
const controlsDisabled = !feature.available || saving;
return (
<li data-testid={`admin-feature-${feature.key}`} className="flex flex-col gap-3 border-t border-gray-100 py-4 first:border-t-0 sm:flex-row sm:items-center">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<p className="text-[14px] font-medium text-gray-900" title={feature.description}>{feature.label}</p>
{feature.deployments.length === 1 ? <DenBadge>{feature.deployments[0] === "cloud" ? "Cloud only" : "Self-hosted only"}</DenBadge> : null}
</div>
<p data-testid={`admin-feature-state-${feature.key}`} className={`mt-1 text-[13px] ${feature.killed ? "text-red-700" : "text-gray-500"}`}>
{rolloutState(feature)}
</p>
{error ? <p className="mt-1 text-[13px] text-red-700">{error}</p> : null}
</div>
<div className="flex shrink-0 items-center gap-3">
<DenSegmented
aria-label={`${feature.label} for everyone`}
options={ON_OFF.map((option) => ({ ...option, disabled: controlsDisabled }))}
value={feature.enabled ? "on" : "off"}
onChange={(value) => {
const enabled = value === "on";
if (enabled !== feature.enabled) void save({ enabled });
}}
/>
{/* Fixed-width slot so rows stay aligned whichever button shows. */}
<div className="flex w-40 justify-end">
{feature.killed ? (
<DenButton type="button" variant="secondary" size="sm" data-testid={`admin-feature-restore-${feature.key}`} disabled={controlsDisabled} onClick={() => void save({ killed: false })}>
Restore
</DenButton>
) : (
<DenButton
type="button"
variant="destructive"
size="sm"
data-testid={`admin-feature-kill-${feature.key}`}
disabled={controlsDisabled}
onClick={() => {
// Turning a feature off for everyone, overrides included, is the one destructive action here (DESIGN.md P8).
if (window.confirm(`Turn off ${feature.label} for everyone on this deployment? Organization overrides and deployment locks are ignored until you restore it.`)) {
void save({ killed: true });
}
}}
>
Turn off everywhere
</DenButton>
)}
</div>
</div>
</li>
);
}
export function FeatureRolloutsPage() {
const [state, setState] = useState<
| { status: "loading" }
| { status: "ready"; report: FeaturesReport }
| { status: "signed-out" | "forbidden" | "error"; message: string }
>({ status: "loading" });
const load = useCallback(async (signal?: AbortSignal) => {
const result = await requestAdmin("/v1/admin/features", parseReport, signal);
setState(result.access === "ready" ? { status: "ready", report: result.data } : { status: result.access, message: result.message });
}, []);
useEffect(() => {
const controller = new AbortController();
void load(controller.signal).catch(() => undefined);
return () => controller.abort();
}, [load]);
const replaceFeature = useCallback((next: AdminFeature) => {
setState((current) => current.status === "ready"
? { status: "ready", report: { ...current.report, features: current.report.features.map((feature) => feature.key === next.key ? next : feature) } }
: current);
}, []);
return (
<div className="flex flex-col gap-6">
<DenPageHeader
title="Features"
caption={state.status === "ready" ? (state.report.deployment === "cloud" ? "OpenWork Cloud" : "Self-hosted") : undefined}
action={<DenButton variant="secondary" size="sm" icon={RefreshCw} onClick={() => void load()}>Refresh</DenButton>}
/>
{state.status === "signed-out" || state.status === "forbidden" ? <DenNotice tone="warning" message={state.message} /> : null}
{state.status === "error" ? <DenNotice message={state.message} /> : null}
{state.status === "ready" ? (
<DenCard className="!py-1">
<ul>
{state.report.features.map((feature) => (
<FeatureRow key={feature.key} feature={feature} onChange={replaceFeature} />
))}
</ul>
</DenCard>
) : null}
</div>
);
}
+127 -146
View File
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Copy, Pencil, Trash2 } from "lucide-react";
import { FEATURE_KEYS, FEATURES, mapFeatures, type FeatureKey } from "@openwork/features";
import { denApiCredentials, denBrowserEndpoint } from "../app/(den)/_lib/den-api-origin";
import { withStoredBearer } from "./admin/admin-request";
@@ -129,18 +130,62 @@ type AdminUser = {
organizations: AdminUserOrganization[];
};
type AdminOrganizationCapabilities = {
auditLogs: boolean;
orgManagedDashboards: boolean;
slackAssistant: boolean;
slackAssistantHeadless: boolean;
headlessAutomations: boolean;
workbot: boolean;
modelsAnalytics: boolean;
installLinks: boolean;
mcpConnections: boolean;
const ADMIN_FEATURE_SOURCES = ["unavailable", "killed", "lock", "override", "everyone"] as const;
/** One registry feature for one organization, as /v1/admin reports it (featureStates). */
type AdminFeatureState = {
enabled: boolean;
source: (typeof ADMIN_FEATURE_SOURCES)[number];
/** The deployment-wide on/off state. */
everyone: boolean;
killed: boolean;
override: boolean | null;
/** An organization override would take effect (not killed or locked). */
overrideApplies: boolean;
};
type AdminOrganizationFeatures = Record<FeatureKey, AdminFeatureState>;
function parseAdminFeatureSource(value: unknown): AdminFeatureState["source"] {
return ADMIN_FEATURE_SOURCES.find((source) => source === value) ?? "everyone";
}
/** Server featureStates, falling back to the effective capabilities map from older servers. */
function parseAdminOrganizationFeatures(featureStates: unknown, capabilities: unknown): AdminOrganizationFeatures {
const states = isRecord(featureStates) ? featureStates : {};
const effective = isRecord(capabilities) ? capabilities : {};
return mapFeatures((key) => {
const state = states[key];
if (!isRecord(state)) {
const enabled = effective[key] === true;
return { enabled, source: "everyone", everyone: enabled, killed: false, override: null, overrideApplies: true };
}
return {
enabled: state.enabled === true,
source: parseAdminFeatureSource(state.source),
everyone: state.everyone === true,
killed: state.killed === true,
override: typeof state.override === "boolean" ? state.override : null,
overrideApplies: state.overrideApplies === true,
};
});
}
function describeAdminFeatureSource(state: AdminFeatureState): string {
switch (state.source) {
case "everyone":
return state.everyone ? "On for everyone" : "Off for everyone";
case "override":
return "Set for this organization";
case "lock":
return "Set by deployment config";
case "killed":
return "Turned off everywhere";
case "unavailable":
return "Not part of this deployment";
}
}
type AdminOpenWorkWebAccess = {
hasAccess: boolean;
accessSource: "subscription" | "complimentary" | null;
@@ -165,7 +210,7 @@ type AdminOrganization = {
freeSeatCount: number;
seatsFreeAdditional: number;
billableSeatCount: number;
capabilities: AdminOrganizationCapabilities;
features: AdminOrganizationFeatures;
openworkWebAccess: AdminOpenWorkWebAccess;
};
@@ -440,7 +485,6 @@ function parseAdminPayload(payload: unknown): AdminPayload | null {
const plan = isRecord(value.plan) ? value.plan : {};
const tier = plan.tier === "team" || plan.tier === "enterprise" ? plan.tier : "free";
const capabilities = isRecord(value.capabilities) ? value.capabilities : {};
return {
id: value.id,
@@ -457,17 +501,7 @@ function parseAdminPayload(payload: unknown): AdminPayload | null {
freeSeatCount: toNumberValue(value.freeSeatCount) || DEFAULT_FREE_SEAT_COUNT,
seatsFreeAdditional: toNumberValue(value.seatsFreeAdditional),
billableSeatCount: toNumberValue(value.billableSeatCount),
capabilities: {
auditLogs: capabilities.auditLogs === true,
orgManagedDashboards: capabilities.orgManagedDashboards === true,
slackAssistant: capabilities.slackAssistant === true,
slackAssistantHeadless: capabilities.slackAssistantHeadless === true,
headlessAutomations: capabilities.headlessAutomations === true,
workbot: capabilities.workbot === true,
modelsAnalytics: capabilities.modelsAnalytics === true,
installLinks: capabilities.installLinks === true,
mcpConnections: capabilities.mcpConnections === true
},
features: parseAdminOrganizationFeatures(value.featureStates, value.capabilities),
openworkWebAccess: parseAdminOpenWorkWebAccess(value.openworkWebAccess)
};
})
@@ -837,7 +871,10 @@ function buildFixtureOrganization(index: number): AdminOrganization {
freeSeatCount: target ? 25 : DEFAULT_FREE_SEAT_COUNT,
seatsFreeAdditional: target ? 20 : 0,
billableSeatCount: target ? 103 : 0,
capabilities: { auditLogs: false, orgManagedDashboards: false, slackAssistant: false, slackAssistantHeadless: false, headlessAutomations: false, workbot: false, installLinks: target, mcpConnections: target, modelsAnalytics: false },
features: mapFeatures((key) => {
const enabled = target && (key === "installLinks" || key === "mcpConnections");
return { enabled, source: "everyone", everyone: enabled, killed: false, override: null, overrideApplies: true };
}),
openworkWebAccess: {
hasAccess: target,
accessSource: target ? "complimentary" : null,
@@ -2114,7 +2151,7 @@ export function DenAdminPanel() {
}
}, [freeSeatsDialog]);
const setOrganizationCapabilityLocally = useCallback((orgId: string, key: keyof AdminOrganizationCapabilities, enabled: boolean) => {
const setOrganizationFeaturesLocally = useCallback((orgId: string, update: (features: AdminOrganizationFeatures) => AdminOrganizationFeatures) => {
setPayload((current) => {
if (!current) {
return current;
@@ -2123,39 +2160,55 @@ export function DenAdminPanel() {
return {
...current,
organizations: current.organizations.map((org) =>
org.id === orgId ? { ...org, capabilities: { ...org.capabilities, [key]: enabled } } : org
org.id === orgId ? { ...org, features: update(org.features) } : org
)
};
});
}, []);
const saveOrganizationCapability = useCallback(async (org: AdminOrganization, key: keyof AdminOrganizationCapabilities, enabled: boolean) => {
// value: true/false sets an override for this organization; null makes it follow the deployment-wide state again.
const saveOrganizationFeature = useCallback(async (org: AdminOrganization, key: FeatureKey, value: boolean | null) => {
const previous = org.features;
setSavingCapabilityOrgId(org.id);
setError(null);
setCapabilityError(null);
// Optimistic: flip the toggle immediately, roll back if the PUT fails.
setOrganizationCapabilityLocally(org.id, key, enabled);
// Optimistic: show the change immediately, roll back if the PUT fails.
setOrganizationFeaturesLocally(org.id, (features) => ({
...features,
[key]: {
...features[key],
enabled: value ?? features[key].everyone,
override: value,
source: value === null ? "everyone" : "override",
},
}));
try {
const { response, payload: nextPayload } = await putJson(`/v1/admin/organizations/${org.id}/capabilities`, {
capabilities: { [key]: enabled }
capabilities: { [key]: value }
});
if (!response.ok) {
setOrganizationCapabilityLocally(org.id, key, !enabled);
const message = getErrorMessage(nextPayload, `Could not update capabilities for ${org.name}.`);
setOrganizationFeaturesLocally(org.id, () => previous);
const message = getErrorMessage(nextPayload, `Could not update features for ${org.name}.`);
setError(message);
setCapabilityError({ orgId: org.id, message });
return;
}
// The server's answer is the truth (locks, defaults), not the optimistic guess.
if (isRecord(nextPayload) && isRecord(nextPayload.featureStates)) {
const features = parseAdminOrganizationFeatures(nextPayload.featureStates, nextPayload.capabilities);
setOrganizationFeaturesLocally(org.id, () => features);
}
} catch (nextError) {
setOrganizationCapabilityLocally(org.id, key, !enabled);
setOrganizationFeaturesLocally(org.id, () => previous);
const message = nextError instanceof Error ? nextError.message : "Unknown network error";
setError(message);
setCapabilityError({ orgId: org.id, message });
} finally {
setSavingCapabilityOrgId(null);
}
}, [setOrganizationCapabilityLocally]);
}, [setOrganizationFeaturesLocally]);
const saveOpenWorkWebAccess = useCallback(async () => {
if (!openworkWebAccessDialog) {
@@ -2712,124 +2765,52 @@ export function DenAdminPanel() {
</div>
<div className="mt-4 border-t border-slate-200 pt-4">
<p className="text-[0.68rem] font-semibold uppercase tracking-[0.14em] text-slate-500">Capabilities</p>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-2">
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-installLinks"
checked={org.capabilities.installLinks}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "installLinks", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Install links
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-mcpConnections"
checked={org.capabilities.mcpConnections}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "mcpConnections", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
OpenWork Connect (alpha)
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-auditLogs"
checked={org.capabilities.auditLogs}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => void saveOrganizationCapability(org, "auditLogs", event.target.checked)}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Audit logs
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-orgManagedDashboards"
checked={org.capabilities.orgManagedDashboards}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => void saveOrganizationCapability(org, "orgManagedDashboards", event.target.checked)}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Dashboards
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-slackAssistant"
checked={org.capabilities.slackAssistant}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "slackAssistant", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Slack Assistant
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-slackAssistantHeadless"
checked={org.capabilities.slackAssistantHeadless}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "slackAssistantHeadless", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Slack Assistant: headless runtime
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-headlessAutomations"
checked={org.capabilities.headlessAutomations}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "headlessAutomations", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Cloud Automations: headless runtime
</label>
<label className="inline-flex items-center gap-2 text-sm text-slate-700">
<input
type="checkbox"
data-testid="admin-capability-workbot"
checked={org.capabilities.workbot}
disabled={savingCapabilityOrgId === org.id}
onChange={(event) => {
void saveOrganizationCapability(org, "workbot", event.target.checked);
}}
className="h-4 w-4 rounded-sm border-slate-300"
/>
Workbot
</label>
<div className="flex items-baseline justify-between gap-3">
<p className="text-[0.68rem] font-semibold uppercase tracking-[0.14em] text-slate-500">Features</p>
<a href="/admin/features" className="text-xs font-medium text-slate-500 underline-offset-2 hover:underline">All features</a>
</div>
<label className="mt-3 inline-flex items-center gap-2 text-sm text-slate-700">
<input type="checkbox" checked={org.capabilities.modelsAnalytics} disabled={savingCapabilityOrgId === org.id}
onChange={(event) => void saveOrganizationCapability(org, "modelsAnalytics", event.target.checked)} />
OpenWork Models task analytics (requires admin opt-in)
</label>
{/* Generated from packages/features/src/registry.ts; add features there, not here. */}
<ul className="mt-2 grid gap-2">
{FEATURE_KEYS.filter((key) => org.features[key].source !== "unavailable").map((key) => {
const state = org.features[key];
const definition = FEATURES[key];
return (
<li key={key} className="flex items-start gap-3">
<label className="flex min-w-0 flex-1 items-start gap-2">
<input
type="checkbox"
data-testid={`admin-capability-${key}`}
checked={state.enabled}
disabled={!state.overrideApplies || savingCapabilityOrgId === org.id}
onChange={(event) => void saveOrganizationFeature(org, key, event.target.checked)}
className="mt-0.5 h-4 w-4 shrink-0 rounded-sm border-slate-300"
/>
<span className="min-w-0">
<span className="text-sm text-slate-700">{definition.label}</span>
<span className="ml-2 text-xs text-slate-400" data-testid={`admin-capability-source-${key}`}>{describeAdminFeatureSource(state)}</span>
<span className="block text-xs leading-5 text-slate-400">{definition.description}</span>
</span>
</label>
{state.source === "override" && state.overrideApplies ? (
<button
type="button"
data-testid={`admin-capability-reset-${key}`}
disabled={savingCapabilityOrgId === org.id}
onClick={() => void saveOrganizationFeature(org, key, null)}
className="shrink-0 text-xs font-medium text-slate-500 underline-offset-2 hover:underline disabled:opacity-50"
>
Use everyone&apos;s setting
</button>
) : null}
</li>
);
})}
</ul>
{capabilityError?.orgId === org.id ? (
<p data-testid="admin-capability-error" className="mt-2 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs leading-5 text-red-700">
Save failed — the change was reverted. {capabilityError.message}
</p>
) : null}
<p className="mt-1 text-xs text-slate-400">On by default. Turn off to stop workspace admins from minting desktop install links for this organization.</p>
<p className="mt-1 text-xs text-slate-400">On by default. Turn off to hide member-facing org connections, marketplace capabilities on the agent rail, and the desktop Connect tab.</p>
<p className="mt-1 text-xs text-slate-400">Slack Assistant is off by default. Enables Slack mentions and DMs for this organization after Slack connector setup. Turn off to stop new requests and further replies; no redeploy is needed.</p>
<p className="mt-1 text-xs text-slate-400">Slack Assistant: headless runtime is off by default. Answers Slack requests on the shared headless runner instead of each member&apos;s OpenWork Web computer, so no Web seat is needed. Requires the deployment&apos;s headless runner to be configured.</p>
<p className="mt-1 text-xs text-slate-400">Confined multi-tool scripts run server-side for this organization.</p>
</div>
<div className="mt-4 border-t border-slate-200 pt-4" data-testid="admin-openwork-web-access">
+1
View File
@@ -26,6 +26,7 @@
"@opentelemetry/sdk-trace-base": "2.9.0",
"@opentelemetry/semantic-conventions": "1.42.0",
"@openwork-ee/utils": "workspace:*",
"@openwork/features": "workspace:*",
"@openwork/types": "workspace:*",
"@openwork/ui": "workspace:*",
"@paper-design/shaders-react": "0.0.72",
@@ -0,0 +1,67 @@
CREATE TABLE `feature_rollout` (
`feature_key` varchar(64) NOT NULL,
`enabled` boolean NOT NULL,
`killed` boolean NOT NULL DEFAULT false,
`updated_by_user_id` varchar(64),
`created_at` timestamp(3) NOT NULL DEFAULT (now()),
`updated_at` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
CONSTRAINT `feature_rollout_feature_key` PRIMARY KEY(`feature_key`)
);
--> statement-breakpoint
CREATE TABLE `organization_feature` (
`organization_id` varchar(64) NOT NULL,
`feature_key` varchar(64) NOT NULL,
`enabled` boolean NOT NULL,
`source` varchar(16) NOT NULL,
`set_by_user_id` varchar(64),
`created_at` timestamp(3) NOT NULL DEFAULT (now()),
`updated_at` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
CONSTRAINT `organization_feature_pk` PRIMARY KEY(`organization_id`,`feature_key`)
);
--> statement-breakpoint
-- Copy per-organization feature overrides out of organization.metadata.capabilities.
-- Only literal booleans were ever honored; anything else meant "use the default".
-- Some rows hold metadata double-encoded as a JSON string, so unwrap those first.
-- Idempotent: INSERT IGNORE never replaces a row that already exists.
INSERT IGNORE INTO `organization_feature` (`organization_id`, `feature_key`, `enabled`, `source`)
SELECT `o`.`id`, `k`.`feature_key`,
JSON_EXTRACT(`o`.`doc`, CONCAT('$.capabilities.', `k`.`feature_key`)) = CAST('true' AS JSON),
'migration'
FROM (
SELECT `id`,
CASE
WHEN JSON_TYPE(`metadata`) = 'STRING' AND JSON_VALID(JSON_UNQUOTE(`metadata`)) THEN CAST(JSON_UNQUOTE(`metadata`) AS JSON)
ELSE `metadata`
END AS `doc`
FROM `organization`
) AS `o`
JOIN (
SELECT 'installLinks' AS `feature_key`
UNION ALL SELECT 'mcpConnections'
UNION ALL SELECT 'modelsAnalytics'
UNION ALL SELECT 'auditLogs'
UNION ALL SELECT 'orgManagedDashboards'
UNION ALL SELECT 'slackAssistant'
UNION ALL SELECT 'slackAssistantHeadless'
UNION ALL SELECT 'headlessAutomations'
UNION ALL SELECT 'workbot'
) AS `k`
WHERE JSON_TYPE(JSON_EXTRACT(`o`.`doc`, CONCAT('$.capabilities.', `k`.`feature_key`))) = 'BOOLEAN';
--> statement-breakpoint
-- Connect also honored two older flat aliases when capabilities.mcpConnections
-- was not a boolean: any literal true enabled it, otherwise a literal false disabled it.
INSERT IGNORE INTO `organization_feature` (`organization_id`, `feature_key`, `enabled`, `source`)
SELECT `o`.`id`, 'mcpConnections',
JSON_EXTRACT(`o`.`doc`, '$.connectEnabled') <=> CAST('true' AS JSON)
OR JSON_EXTRACT(`o`.`doc`, '$.mcpConnectionsEnabled') <=> CAST('true' AS JSON),
'migration'
FROM (
SELECT `id`,
CASE
WHEN JSON_TYPE(`metadata`) = 'STRING' AND JSON_VALID(JSON_UNQUOTE(`metadata`)) THEN CAST(JSON_UNQUOTE(`metadata`) AS JSON)
ELSE `metadata`
END AS `doc`
FROM `organization`
) AS `o`
WHERE JSON_TYPE(JSON_EXTRACT(`o`.`doc`, '$.connectEnabled')) = 'BOOLEAN'
OR JSON_TYPE(JSON_EXTRACT(`o`.`doc`, '$.mcpConnectionsEnabled')) = 'BOOLEAN';
File diff suppressed because it is too large. Load diff
@@ -897,6 +897,13 @@
"when": 1791246307322,
"tag": "0128_remove_legacy_analytics",
"breakpoints": true
},
{
"idx": 129,
"version": "5",
"when": 1791266169752,
"tag": "0129_organization_features",
"breakpoints": true
}
]
}
+7 -1
View File
@@ -66,6 +66,11 @@
"development": "./src/audit-accounting.ts",
"default": "./dist/audit-accounting.js"
},
"./organization-features": {
"types": "./src/organization-features.ts",
"development": "./src/organization-features.ts",
"default": "./dist/organization-features.js"
},
"./audit-log": {
"types": "./src/audit-log.ts",
"development": "./src/audit-log.ts",
@@ -95,8 +100,9 @@
"benchmark:admin-scale:mysql": "node --import tsx scripts/admin-scale-benchmark.ts"
},
"dependencies": {
"@openwork/types": "workspace:*",
"@openwork-ee/utils": "workspace:*",
"@openwork/features": "workspace:*",
"@openwork/types": "workspace:*",
"@planetscale/database": "^1.19.0",
"drizzle-orm": "^0.45.2",
"mysql2": "^3.23.1"
@@ -0,0 +1,194 @@
import { and, eq, inArray } from "drizzle-orm"
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
import {
isFeatureKey,
mapFeatures,
resolveFeature,
resolveFeatures,
type FeatureEnvironment,
type FeatureKey,
type FeatureMap,
type FeatureOverrides,
type FeatureRollouts,
type ResolvedFeature,
} from "@openwork/features"
import type { createDenDb } from "./client"
import { OrganizationTable } from "./schema/org"
import { FeatureRolloutTable, OrganizationFeatureTable } from "./schema/organization-features"
/**
* Storage for feature state (on/off for everyone and kill switch per feature) and
* per-organization overrides. The registry and resolution rules live in
* @openwork/features; this module only reads and writes the rows. Read
* features through here, never from organization metadata.
*/
type Db = ReturnType<typeof createDenDb>["db"]
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0]
export type FeatureDatabase = Db | Tx
export type FeatureOverrideChanges = Partial<Record<FeatureKey, boolean | null>>
function toOverrides(rows: Array<{ feature_key: string; enabled: boolean }>): FeatureOverrides {
const overrides: FeatureOverrides = {}
for (const row of rows) {
if (isFeatureKey(row.feature_key)) overrides[row.feature_key] = row.enabled
}
return overrides
}
/** Stored overrides for one organization. `lock: "share"` keeps them stable until the transaction commits. */
export async function readOrganizationFeatureOverrides(
database: FeatureDatabase,
organizationId: string,
options: { lock?: "share" } = {},
): Promise<FeatureOverrides> {
const query = database
.select({ feature_key: OrganizationFeatureTable.feature_key, enabled: OrganizationFeatureTable.enabled })
.from(OrganizationFeatureTable)
.where(eq(OrganizationFeatureTable.organization_id, normalizeDenTypeId("organization", organizationId)))
return toOverrides(await (options.lock ? query.for(options.lock) : query))
}
/** Stored overrides for many organizations in one query, keyed by organization id. */
export async function readOrganizationFeatureOverridesForMany(
database: FeatureDatabase,
organizationIds: string[],
): Promise<Map<string, FeatureOverrides>> {
const result = new Map<string, FeatureOverrides>()
if (organizationIds.length === 0) return result
const rows = await database
.select({
organization_id: OrganizationFeatureTable.organization_id,
feature_key: OrganizationFeatureTable.feature_key,
enabled: OrganizationFeatureTable.enabled,
})
.from(OrganizationFeatureTable)
.where(inArray(OrganizationFeatureTable.organization_id, organizationIds.map((id) => normalizeDenTypeId("organization", id))))
for (const row of rows) {
if (!isFeatureKey(row.feature_key)) continue
const overrides = result.get(row.organization_id) ?? {}
overrides[row.feature_key] = row.enabled
result.set(row.organization_id, overrides)
}
return result
}
/** Deployment-wide rollout state for every feature that has a stored row. */
export async function readFeatureRollouts(database: FeatureDatabase): Promise<FeatureRollouts> {
const rows = await database
.select({ feature_key: FeatureRolloutTable.feature_key, enabled: FeatureRolloutTable.enabled, killed: FeatureRolloutTable.killed })
.from(FeatureRolloutTable)
const rollouts: FeatureRollouts = {}
for (const row of rows) {
if (isFeatureKey(row.feature_key)) rollouts[row.feature_key] = { enabled: row.enabled, killed: row.killed }
}
return rollouts
}
/**
* Effective on/off for every feature, for one organization, or for someone
* without one (pass null: only the deployment-wide state applies).
*/
export async function readFeatures(
database: FeatureDatabase,
organizationId: string | null,
environment: FeatureEnvironment,
options: { lock?: "share" } = {},
): Promise<FeatureMap> {
const [rollouts, overrides] = await Promise.all([
readFeatureRollouts(database),
organizationId ? readOrganizationFeatureOverrides(database, organizationId, options) : Promise.resolve({}),
])
return resolveFeatures({ ...environment, rollouts, overrides })
}
/** Effective state with its source, for /admin. */
export function describeFeatures(input: {
rollouts: FeatureRollouts
overrides: FeatureOverrides
environment: FeatureEnvironment
}): Record<FeatureKey, ResolvedFeature> {
return mapFeatures((key) => resolveFeature(key, { ...input.environment, rollouts: input.rollouts, overrides: input.overrides }))
}
/** Turns one feature on or off for everyone and/or sets its kill switch, for this deployment. */
export async function setFeatureRollout(
database: Db,
input: { key: FeatureKey; enabled?: boolean; killed?: boolean; updatedByUserId?: string | null; defaultEnabled: boolean },
): Promise<FeatureRollouts> {
const updatedByUserId = input.updatedByUserId ? normalizeDenTypeId("user", input.updatedByUserId) : null
const current = (await readFeatureRollouts(database))[input.key]
const enabled = input.enabled ?? current?.enabled ?? input.defaultEnabled
const killed = input.killed ?? current?.killed ?? false
await database.insert(FeatureRolloutTable)
.values({ feature_key: input.key, enabled, killed, updated_by_user_id: updatedByUserId })
.onDuplicateKeyUpdate({ set: { enabled, killed, updated_by_user_id: updatedByUserId } })
return readFeatureRollouts(database)
}
function parseMetadata(value: unknown): Record<string, unknown> {
let parsed = value
if (typeof parsed === "string") {
try {
parsed = JSON.parse(parsed)
} catch {
return {}
}
}
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? { ...parsed } : {}
}
/**
* Sets (true/false) or clears (null) overrides. Keys missing from `changes` are
* left alone. Returns every override stored afterwards.
*
* Rollback safety for one release: the result is also copied into
* `organization.metadata.capabilities`, which the previous release reads.
* The next release stops copying and a migration removes that key.
*/
export async function setOrganizationFeatureOverrides(
database: Db,
input: {
organizationId: string
changes: FeatureOverrideChanges
source: "platform"
setByUserId?: string | null
},
): Promise<FeatureOverrides> {
const organizationId = normalizeDenTypeId("organization", input.organizationId)
const setByUserId = input.setByUserId ? normalizeDenTypeId("user", input.setByUserId) : null
return database.transaction(async (tx) => {
const [organization] = await tx
.select({ metadata: OrganizationTable.metadata })
.from(OrganizationTable)
.where(eq(OrganizationTable.id, organizationId))
.limit(1)
.for("update")
if (!organization) throw new Error("organization_not_found")
for (const [key, value] of Object.entries(input.changes)) {
if (!isFeatureKey(key) || value === undefined) continue
if (value === null) {
await tx.delete(OrganizationFeatureTable).where(and(
eq(OrganizationFeatureTable.organization_id, organizationId),
eq(OrganizationFeatureTable.feature_key, key),
))
continue
}
await tx.insert(OrganizationFeatureTable)
.values({ organization_id: organizationId, feature_key: key, enabled: value, source: input.source, set_by_user_id: setByUserId })
.onDuplicateKeyUpdate({ set: { enabled: value, source: input.source, set_by_user_id: setByUserId } })
}
const overrides = await readOrganizationFeatureOverrides(tx, organizationId)
const metadata = parseMetadata(organization.metadata)
// The previous release also honored these flat aliases for Connect.
delete metadata.connectEnabled
delete metadata.mcpConnectionsEnabled
if (Object.keys(overrides).length > 0) metadata.capabilities = { ...overrides }
else delete metadata.capabilities
await tx.update(OrganizationTable).set({ metadata }).where(eq(OrganizationTable.id, organizationId))
return overrides
})
}
+1
View File
@@ -7,6 +7,7 @@ export * from "./inference"
export * from "./gateway-usage-limits"
export * from "./inference-providers"
export * from "./org"
export * from "./organization-features"
export * from "./remote-mcp-apps"
export * from "./remote-session-commands"
export * from "./scim-groups"
@@ -0,0 +1,35 @@
import { sql } from "drizzle-orm"
import { boolean, mysqlTable, primaryKey, timestamp, varchar } from "drizzle-orm/mysql-core"
import { denTypeIdColumn } from "../columns"
/**
* Per-organization feature overrides. A row exists only when someone set an
* override; no row means the registry default (packages/features/src/registry.ts).
* Better Auth never writes this table, so organization creation cannot turn
* features on.
*/
export const OrganizationFeatureTable = mysqlTable("organization_feature", {
organization_id: denTypeIdColumn("organization", "organization_id").notNull(),
feature_key: varchar("feature_key", { length: 64 }).notNull(),
enabled: boolean("enabled").notNull(),
/** "platform" for /admin and the admin MCP tool, "migration" for the backfill. */
source: varchar("source", { length: 16 }).notNull(),
set_by_user_id: denTypeIdColumn("user", "set_by_user_id"),
created_at: timestamp("created_at", { fsp: 3 }).notNull().defaultNow(),
updated_at: timestamp("updated_at", { fsp: 3 }).notNull().default(sql`CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)`),
}, (table) => [primaryKey({ name: "organization_feature_pk", columns: [table.organization_id, table.feature_key] })])
/**
* Deployment-wide state per feature, changed in /admin. No row means the
* registry default and no kill switch.
*/
export const FeatureRolloutTable = mysqlTable("feature_rollout", {
feature_key: varchar("feature_key", { length: 64 }).notNull().primaryKey(),
/** On or off for everyone on this deployment (organization overrides still apply). */
enabled: boolean("enabled").notNull(),
/** Off everywhere, outranking locks, overrides and the percentage. */
killed: boolean("killed").notNull().default(false),
updated_by_user_id: denTypeIdColumn("user", "updated_by_user_id"),
created_at: timestamp("created_at", { fsp: 3 }).notNull().defaultNow(),
updated_at: timestamp("updated_at", { fsp: 3 }).notNull().default(sql`CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)`),
})
+1
View File
@@ -16,6 +16,7 @@ export default defineConfig({
drizzle: "src/drizzle.ts",
"gateway-usage-limits": "src/gateway-usage-limits.ts",
"audit-log": "src/audit-log.ts",
"organization-features": "src/organization-features.ts",
"audit-accounting": "src/audit-accounting.ts",
},
format: ["esm"],
+2 -1
View File
@@ -19,7 +19,8 @@
"dependencies": {
"@openwork-ee/den-db": "workspace:*",
"@openwork-ee/telemetry-contracts": "workspace:*",
"@openwork-ee/utils": "workspace:*"
"@openwork-ee/utils": "workspace:*",
"@openwork/features": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.11.30",
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto"
import type { createDenDb } from "@openwork-ee/den-db"
import { and, eq, sql } from "@openwork-ee/den-db/drizzle"
import { readFeatures } from "@openwork-ee/den-db/organization-features"
import { parseFeatureEnvironment } from "@openwork/features"
import { ModelsAnalyticsEventTable, ModelsAnalyticsSettingsTable, OrganizationTable, OrgSubscriptionTable } from "@openwork-ee/den-db/schema"
import { modelsAnalyticsEventSchema, type ModelsAnalyticsEvent } from "@openwork-ee/telemetry-contracts"
@@ -18,7 +20,9 @@ export async function readModelsAnalyticsSettings(db: Db, orgId: ModelsAnalytics
const [subscription] = await db.select({ status: OrgSubscriptionTable.status })
.from(OrgSubscriptionTable).where(and(eq(OrgSubscriptionTable.organization_id, orgId), eq(OrgSubscriptionTable.type, "inference"))).limit(1)
const metadata = record(org?.metadata)
const available = record(metadata.capabilities).modelsAnalytics === true
// Shared by den-api and the gateway, which receive the same DEN_DEPLOYMENT /
// DEN_FEATURE_* configuration; den-api validates it at boot.
const available = org ? (await readFeatures(db, orgId, parseFeatureEnvironment(process.env))).modelsAnalytics : false
const subscribed = subscription?.status === "active" || subscription?.status === "trialing"
const modelsEnabled = record(metadata.inference).enabled === true
// Unreleased organizations do not touch the new tables. This also keeps
+2 -2
View File
@@ -102,10 +102,10 @@ export async function auditLogs(seed: Seed, { place }: { place: Place }) {
const providerId = identifier(record(record(created.body).inferenceProvider).id);
const warmed = await seed.api(den.admin, `/v1/inference-providers/${encodeURIComponent(providerId)}/models`);
if (!warmed.response.ok) throw new Error(`Synthetic model setup failed: ${warmed.response.status}`);
// Seed only the release flag, preserving all existing metadata and sibling capabilities.
// Seed only the auditLogs feature override, leaving every other feature alone.
// Provider setup predates the grant; browser/API traffic initializes the real
// default policy and records access events before the user's provider save.
await seedAuditDatabase(den, "UPDATE organization SET metadata = JSON_SET(JSON_SET(COALESCE(metadata, JSON_OBJECT()), '$.capabilities', COALESCE(JSON_EXTRACT(metadata, '$.capabilities'), JSON_OBJECT())), '$.capabilities.auditLogs', CAST('true' AS JSON)) WHERE id = ?", [orgId]);
await seedAuditDatabase(den, "INSERT INTO organization_feature (organization_id, feature_key, enabled, source) VALUES (?, 'auditLogs', TRUE, 'platform') ON DUPLICATE KEY UPDATE enabled = TRUE", [orgId]);
const viewport = { width: 1440, height: 1100 };
const web = await seed.web({ den, signedInAs: den.admin, startPath: "/dashboard/audit-logs", headless: true, viewport });
const memberWeb = await seed.web({ den, signedInAs: teammate, startPath: "/dashboard/audit-logs", headless: true, viewport });
+2
View File
@@ -53,6 +53,8 @@
"test:fs-engine": "pnpm --filter @openwork/app test:fs-engine",
"warden:check": "PI_CODING_AGENT_DIR=.warden/pi pnpm dlx @sentry/warden@0.43.0 --runtime pi --config-path warden.toml --log",
"check:outbound-access": "node scripts/check-outbound-access.mjs",
"features:sync": "node scripts/features-sync.mjs",
"features:check": "node scripts/features-sync.mjs --check",
"test:e2e": "pnpm --filter @openwork/app test:e2e",
"benchmark:admin-scale:mysql": "pnpm --filter @openwork-ee/den-db benchmark:admin-scale:mysql",
"evals:e2e": "node evals/bin/evals.mjs",
+15 -10
View File
@@ -21,12 +21,13 @@
"UnauthorizedError": {"type":"object","properties":{"error":{"type":"string","const":"unauthorized"}},"required":["error"]},
"ForbiddenError": {"type":"object","properties":{"error":{"type":"string","enum":["forbidden","reauth"]},"reason":{"type":"string"},"message":{"type":"string"}},"required":["error"]},
"NotFoundError": {"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}},"required":["error"]},
"AdminFeature": {"type":"object","properties":{"key":{"type":"string","enum":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot"]},"label":{"type":"string"},"description":{"type":"string"},"since":{"type":"string"},"deployments":{"type":"array","items":{"type":"string","enum":["cloud","self_hosted"]}},"default":{"type":"boolean"},"available":{"type":"boolean"},"enabled":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]}},"required":["key","label","description","since","deployments","default","available","enabled","killed","lock"]},
"AdminPageInfo": {"type":"object","properties":{"total":{"type":"number"},"limit":{"type":"number"},"offset":{"type":"number"},"returned":{"type":"number"},"hasMore":{"type":"boolean"},"search":{"type":"string"},"durationMs":{"type":"number"}},"required":["total","limit","offset","returned","hasMore","search","durationMs"]},
"AdminUsersPageResponse": {"type":"object","properties":{"users":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"page":{"$ref":"#/components/schemas/AdminPageInfo"},"billing":{"type":"object","properties":{"loaded":{"type":"boolean"},"paidUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"unpaidUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"billingUnavailableUsers":{"anyOf":[{"type":"number"},{"type":"null"}]}},"required":["loaded","paidUsers","unpaidUsers","billingUnavailableUsers"]},"generatedAt":{"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))$"}},"required":["users","page","billing","generatedAt"]},
"AdminOrganizationsPageResponse": {"type":"object","properties":{"organizations":{"type":"array","items":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]}},"required":["capabilities"],"additionalProperties":{}}},"page":{"$ref":"#/components/schemas/AdminPageInfo"},"generatedAt":{"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))$"}},"required":["organizations","page","generatedAt"]},
"AdminOrganizationsPageResponse": {"type":"object","properties":{"organizations":{"type":"array","items":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]},"featureStates":{"type":"object","properties":{"installLinks":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"mcpConnections":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"modelsAnalytics":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"auditLogs":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"orgManagedDashboards":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistant":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistantHeadless":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"headlessAutomations":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"workbot":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},Line truncated
"AdminSummary": {"type":"object","properties":{"totalUsers":{"type":"number"},"totalOrganizations":{"type":"number"},"verifiedUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"recentUsers7d":{"anyOf":[{"type":"number"},{"type":"null"}]},"recentUsers30d":{"anyOf":[{"type":"number"},{"type":"null"}]},"totalWorkers":{"anyOf":[{"type":"number"},{"type":"null"}]},"cloudWorkers":{"anyOf":[{"type":"number"},{"type":"null"}]},"localWorkers":{"anyOf":[{"type":"number"},{"type":"null"}]},"usersWithWorkers":{"anyOf":[{"type":"number"},{"type":"null"}]},"usersWithoutWorkers":{"anyOf":[{"type":"number"},{"type":"null"}]},"paidUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"unpaidUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"billingUnavailableUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"adminCount":{"type":"number"},"billingLoaded":{"type":"boolean"},"activeUsers1d":{"anyOf":[{"type":"number"},{"type":"null"}]},"activeUsers7d":{"anyOf":[{"type":"number"},{"type":"null"}]},"activeUsers30d":{"anyOf":[{"type":"number"},{"type":"null"}]},"realActiveUsers1d":{"anyOf":[{"type":"number"},{"type":"null"}]},"realActiveUsers7d":{"anyOf":[{"type":"number"},{"type":"null"}]},"realActiveUsers30d":{"anyOf":[{"type":"number"},{"type":"null"}]},"recurringUsers":{"anyOf":[{"type":"number"},{"type":"null"}]},"inviters":{"anyOf":[{"type":"number"},{"type":"null"}]},"medianHoursToFirstInvite":{"anyOf":[{"type":"number"},{"type":"null"}]},"activitySeries":{"type":"array","items":{"type":"object","properties":{"day":{"type":"string"},"activeUsers":{"type":"number"},"realActiveUsers":{"type":"number"},"signups":{"type":"number"}},"required":["day","activeUsers","realActiveUsers","signups"]}}},"required":["totalUsers","totalOrganizations","verifiedUsers","recentUsers7d","recentUsers30d","totalWorkers","cloudWorkers","localWorkers","usersWithWorkers","usersWithoutWorkers","paidUsers","unpaidUsers","billingUnavailableUsers","adminCount","billingLoaded","activeUsers1d","activeUsers7d","activeUsers30d","realActiveUsers1d","realActiveUsers7d","realActiveUsers30d","recurringUsers","inviters","medianHoursToFirstInvite","activitySeries"]},
"AdminMetricsResponse": {"type":"object","properties":{"summary":{"$ref":"#/components/schemas/AdminSummary"},"generatedAt":{"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))$"}},"required":["summary","generatedAt"]},
"AdminOverviewResponse": {"type":"object","properties":{"viewer":{"type":"object","properties":{"id":{"description":"Den TypeID with 'usr_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"email":{"type":"string"},"name":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","email","name"]},"admins":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"summary":{"$ref":"#/components/schemas/AdminSummary"},"users":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"organizations":{"type":"array","items":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]}},"required":["capabilities"],"additionalProperties":{}}},"userPage":{"$ref":"#/components/schemas/AdminPageInfo"},"organizationPage":{"$ref":"#/components/schemas/AdminPageInfo"},"generatedAt":{"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))$"}},"required":["viewer","admins","summary","users","organizations","userPage","organizationPage","generatedAt"]},
"AdminOverviewResponse": {"type":"object","properties":{"viewer":{"type":"object","properties":{"id":{"description":"Den TypeID with 'usr_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"email":{"type":"string"},"name":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","email","name"]},"admins":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"summary":{"$ref":"#/components/schemas/AdminSummary"},"users":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"organizations":{"type":"array","items":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]},"featureStates":{"type":"object","properties":{"installLinks":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"mcpConnections":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"modelsAnalytics":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"auditLogs":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"orgManagedDashboards":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistant":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistantHeadless":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"headlessAutomations":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anLine truncated
"OpaqueObject": {"type":"object","properties":{},"additionalProperties":{}},
"ScimAuthRouteError": {"type":"object","properties":{"detail":{"type":"string"}},"required":["detail"]},
"AuthLoginOptionsResponse": {"type":"object","properties":{"email":{"type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"nextStep":{"anyOf":[{"type":"string","const":"sso"},{"type":"string","const":"google"},{"type":"string","const":"github"},{"type":"string","const":"password"},{"type":"string","const":"new_account"}]},"allowPublicSignup":{"type":"boolean"},"allowInvitationSignup":{"type":"boolean"},"organizationSlug":{"type":"string"},"signInPath":{"type":"string"},"signInUrl":{"type":"string","format":"uri"}},"required":["email","nextStep"]},
@@ -83,7 +84,7 @@
"EnterprisePlanRequiredError": {"type":"object","properties":{"error":{"type":"string","const":"enterprise_plan_required"},"feature":{"type":"string"},"message":{"type":"string"}},"required":["error","feature","message"]},
"RateLimitedError": {"type":"object","properties":{"error":{"type":"string","const":"rate_limited"},"message":{"type":"string"}},"required":["error","message"]},
"OrganizationOwner": {"type":"object","properties":{"memberId":{"description":"Den TypeID with 'om_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":29,"maxLength":29},"userId":{"description":"Den TypeID with 'usr_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"name":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"anyOf":[{"type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},{"type":"null"}]},"image":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["memberId","userId","name","email"]},
"OrganizationContextResponse": {"type":"object","properties":{"organization":{"type":"object","properties":{"owner":{"anyOf":[{"$ref":"#/components/schemas/OrganizationOwner"},{"type":"null"}]}},"additionalProperties":{}},"currentMember":{"type":"object","properties":{},"additionalProperties":{}},"currentMemberTeams":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"capabilities":{"type":"object","properties":{"auditLogs":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["auditLogs","gatewayDashboard"],"additionalProperties":{}},"deploymentCapabilities":{"type":"object","properties":{"version":{"type":"number","const":1},"aiGateway":{"type":"boolean"}},"required":["version","aiGateway"]},"entitlements":{"type":"object","properties":{"sso":{"type":"boolean"},"desktopPolicies":{"type":"boolean"},"orgControls":{"type":"boolean"},"auditLogs":{"type":"boolean"}},"required":["sso","desktopPolicies","orgControls","auditLogs"]}},"required":["organization","currentMember","currentMemberTeams","capabilities","deploymentCapabilities","entitlements"],"additionalProperties":{}},
"OrganizationContextResponse": {"type":"object","properties":{"organization":{"type":"object","properties":{"owner":{"anyOf":[{"$ref":"#/components/schemas/OrganizationOwner"},{"type":"null"}]}},"additionalProperties":{}},"currentMember":{"type":"object","properties":{},"additionalProperties":{}},"currentMemberTeams":{"type":"array","items":{"type":"object","properties":{},"additionalProperties":{}}},"capabilities":{"type":"object","properties":{"auditLogs":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["auditLogs","gatewayDashboard"],"additionalProperties":{}},"features":{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"boolean"},"description":"Effective on/off for every OpenWork feature in this organization. Treat a missing key as off."},"deploymentCapabilities":{"type":"object","properties":{"version":{"type":"number","const":1},"aiGateway":{"type":"boolean"}},"required":["version","aiGateway"]},"entitlements":{"type":"object","properties":{"sso":{"type":"boolean"},"desktopPolicies":{"type":"boolean"},"orgControls":{"type":"boolean"},"auditLogs":{"type":"boolean"}},"required":["sso","desktopPolicies","orgControls","auditLogs"]}},"required":["organization","currentMember","currentMemberTeams","capabilities","features","deploymentCapabilities","entitlements"],"additionalProperties":{}},
"DeleteOrganizationResponse": {"type":"object","properties":{"ok":{"type":"boolean","const":true},"organization":{"type":"object","properties":{"id":{"description":"Den TypeID with 'org_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"name":{"type":"string"}},"required":["id","name"]}},"required":["ok","organization"]},
"OrganizationApiKeyOwner": {"type":"object","properties":{"userId":{"description":"Den TypeID with 'usr_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"memberId":{"description":"Den TypeID with 'om_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":29,"maxLength":29},"name":{"type":"string"},"email":{"type":"string","format":"email","pattern":"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"},"image":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["userId","memberId","name","email","image"]},
"OrganizationApiKey": {"type":"object","properties":{"id":{"type":"string"},"configId":{"type":"string"},"name":{"anyOf":[{"type":"string"},{"type":"null"}]},"start":{"anyOf":[{"type":"string"},{"type":"null"}]},"prefix":{"anyOf":[{"type":"string"},{"type":"null"}]},"enabled":{"type":"boolean"},"rateLimitEnabled":{"type":"boolean"},"rateLimitMax":{"anyOf":[{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},{"type":"null"}]},"rateLimitTimeWindow":{"anyOf":[{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},{"type":"null"}]},"lastRequest":{"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"}]},"expiresAt":{"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"}]},"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))$"},"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))$"},"owner":{"$ref":"#/components/schemas/OrganizationApiKeyOwner"}},"required":["id","configId","name","start","prefix","enabled","rateLimitEnabled","rateLimitMax","rateLimitTimeWindow","lastRequest","expiresAt","createdAt","updatedAt","owner"]},
@@ -378,6 +379,7 @@
"WorkbotSession": {"type":"object","properties":{"user":{"type":"object","properties":{"id":{"type":"string"},"name":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"type":"string"}},"required":["id","name","email"]},"organization":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"brandAppName":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","brandAppName"]},"memberId":{"type":"string"},"enabled":{"type":"boolean"},"canSchedule":{"type":"boolean"}},"required":["user","organization","memberId","enabled","canSchedule"]},
"WorkbotRunToken": {"type":"object","properties":{"token":{"type":"string"},"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))$"}},"required":["token","expiresAt"]},
"DenAppVersionResponse": {"type":"object","properties":{"minAppVersion":{"type":"string"},"latestAppVersion":{"type":"string","minLength":1},"publishedDesktopVersions":{"type":"array","items":{"type":"string","minLength":1}},"webUrl":{"type":"string","minLength":1}},"required":["minAppVersion","latestAppVersion","publishedDesktopVersions"]},
"PublicFeatures": {"type":"object","properties":{"version":{"type":"number","const":1},"deployment":{"type":"string","enum":["cloud","self_hosted"]},"features":{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"boolean"}}},"required":["version","deployment","features"]},
"PluginArchGithubWebhookIgnoredResponse": {"type":"object","properties":{"ok":{"type":"boolean","const":true},"accepted":{"type":"boolean","const":false},"reason":{"type":"string","minLength":1}},"required":["ok","accepted","reason"]},
"PluginArchGithubWebhookAcceptedResponse": {"type":"object","properties":{"ok":{"type":"boolean","const":true},"accepted":{"type":"boolean","const":true},"event":{"type":"string","enum":["push","installation","installation_repositories","repository"]},"deliveryId":{"type":"string","minLength":1},"queued":{"type":"boolean"}},"required":["ok","accepted","event","deliveryId","queued"]},
"PluginArchGithubWebhookUnauthorizedResponse": {"type":"object","properties":{"ok":{"type":"boolean","const":false},"error":{"type":"string","const":"invalid signature"}},"required":["ok","error"]},
@@ -415,7 +417,9 @@
"/v1/admin/organizations/{organizationId}/free-seats": {"patch":{"operationId":"patchV1AdminOrganizationsByOrganizationIdFreeSeats","tags":["Admin"],"summary":"Set an organization's free seats","description":"Sets the total number of free seats for the organization and resynchronizes its seat subscription quantity. Body: { totalFreeSeats: integer }.","responses":{"200":{"description":"Free seats were updated.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean","const":true},"organization":{"type":"object","properties":{},"additionalProperties":{}}},"required":["ok","organization"]}}}},"400":{"description":"The request body or organization id was invalid.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"The organization does not exist.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/organizations/{organizationId}/dpa": {"patch":{"operationId":"patchV1AdminOrganizationsByOrganizationIdDpa","tags":["Admin"],"summary":"Record an organization DPA decision","description":"Allowlisted platform administrators only. Atomically updates the reserved metadata flag and records the authenticated actor and reason in the audit trail.","responses":{"200":{"description":"DPA decision recorded.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean","const":true},"organization":{"type":"object","properties":{"id":{"description":"Den TypeID with 'org_' prefix and a 26-character base32 suffix.","format":"typeid","type":"string","minLength":30,"maxLength":30},"dpaSigned":{"type":"boolean"}},"required":["id","dpaSigned"]}},"required":["ok","organization"]}}}},"400":{"description":"Invalid DPA decision or organization identifier.","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/InvalidRequestError"},{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}]}}}},"401":{"description":"Authentication is required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Platform administrator access is required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Organization not found.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"not_found"},"message":{"type":"string"}},"required":["error","message"]}}}},"503":{"description":"Organization metadata could not be read.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"managed_models_policy_unavailable"},"message":{"type":"string"}},"required":["error","message"]}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"dpaSigned":{"type":"boolean"},"reason":{"type":"string","minLength":3,"maxLength":500}},"required":["dpaSigned","reason"],"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/organizations/{organizationId}/openwork-web-access": {"put":{"operationId":"putV1AdminOrganizationsByOrganizationIdOpenworkWebAccess","tags":["Admin"],"summary":"Grant or revoke complimentary OpenWork Web access","description":"Toggles complimentary OpenWork Web access for the organization and records an audit event. Access cannot be granted while a paid OpenWork Web subscription is ongoing. Body: { enabled: boolean, reason: string }.","responses":{"200":{"description":"OpenWork Web access was updated.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean","const":true},"organization":{"type":"object","properties":{},"additionalProperties":{}}},"required":["ok","organization"]}}}},"400":{"description":"The request body or organization id was invalid.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"The organization does not exist.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}},"409":{"description":"The organization has an ongoing paid OpenWork Web subscription.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}},"required":["error","message"]}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/organizations/{organizationId}/capabilities": {"get":{"operationId":"getV1AdminOrganizationsByOrganizationIdCapabilities","tags":["Admin"],"summary":"Get an organization's capability overrides","description":"Returns admin-visible capabilities. The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.","responses":{"200":{"description":"Capability overrides returned.","content":{"application/json":{"schema":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]}},"required":["capabilities"]}}}},"400":{"description":"The organization id was invalid.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"The organization does not exist.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]},"put":{"operationId":"putV1AdminOrganizationsByOrganizationIdCapabilities","tags":["Admin"],"summary":"Set an organization's capability overrides","description":"Enables, disables or clears (null) the install-links, MCP-connections, Models analytics, auditLogs and orgManagedDashboards overrides. Audit logs and org-managed Dashboards require literal true (absent/false is disabled); this flag neither grants capture entitlement nor initializes capacity or changes capture preferences. The deprecated gatewayDashboard boolean or null input is validated but ignored and never persisted; its response field is always true. Stale retired overrides are removed on capability writes.","responses":{"200":{"description":"Capability overrides were updated.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean","const":true},"organization":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]}},"required":["ok","organization","capabilities"]}}}},"400":{"description":"The request body or organization id was invalid.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"The organization does not exist.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/organizations/{organizationId}/capabilities": {"get":{"operationId":"getV1AdminOrganizationsByOrganizationIdCapabilities","tags":["Admin"],"summary":"Get an organization's capability overrides","description":"Returns the effective value of every registry feature (capabilities) and, per feature, its source and whether /admin can change it (featureStates). The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.","responses":{"200":{"description":"Capability overrides returned.","content":{"application/json":{"schema":{"type":"object","properties":{"capabilities":{"type":"object","properties":{"installLinks":{"type":"boolean"},"mcpConnections":{"type":"boolean"},"modelsAnalytics":{"type":"boolean"},"auditLogs":{"type":"boolean"},"orgManagedDashboards":{"type":"boolean"},"slackAssistant":{"type":"boolean"},"slackAssistantHeadless":{"type":"boolean"},"headlessAutomations":{"type":"boolean"},"workbot":{"type":"boolean"},"gatewayDashboard":{"type":"boolean","const":true,"deprecated":true,"description":"Compatibility field, always true. AI Gateway is available to every organization; deployment configuration and authorization still apply."}},"required":["installLinks","mcpConnections","modelsAnalytics","auditLogs","orgManagedDashboards","slackAssistant","slackAssistantHeadless","headlessAutomations","workbot","gatewayDashboard"]},"featureStates":{"type":"object","properties":{"installLinks":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"mcpConnections":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"modelsAnalytics":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"auditLogs":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"orgManagedDashboards":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistant":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"slackAssistantHeadless":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"override":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"overrideApplies":{"type":"boolean"}},"required":["enabled","source","everyone","killed","lock","override","overrideApplies"]},"headlessAutomations":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["unavailable","killed","lock","override","everyone"]},"everyone":{"type":"boolean"},"killed":{"type":"boolean"},"lock":{"anyOf":[{"typeLine truncated
"/v1/admin/features": {"get":{"operationId":"getV1AdminFeatures","tags":["Admin"],"summary":"List features and their state","description":"Every feature in the registry (packages/features/src/registry.ts) with what is fixed in code (deployments, default) and this deployment's state: on or off for everyone, kill switch, and any operator lock.","responses":{"200":{"description":"Features returned.","content":{"application/json":{"schema":{"type":"object","properties":{"deployment":{"type":"string","enum":["cloud","self_hosted"]},"features":{"type":"array","items":{"$ref":"#/components/schemas/AdminFeature"}}},"required":["deployment","features"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/features/{key}": {"put":{"operationId":"putV1AdminFeaturesByKey","tags":["Admin"],"summary":"Change a feature's state","description":"Turns the feature on or off for everyone on this deployment (organization overrides still apply), and/or sets the kill switch. The kill switch turns the feature off everywhere, outranking operator locks and organization overrides; it is the way to revert.","responses":{"200":{"description":"Feature updated.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean","const":true},"feature":{"$ref":"#/components/schemas/AdminFeature"}},"required":["ok","feature"]}}}},"400":{"description":"The feature or body was invalid.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"invalid_request"},"message":{"type":"string"}},"required":["error","message"]}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"key","required":true}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/users": {"get":{"operationId":"getV1AdminUsers","tags":["Admin"],"summary":"Get a bounded admin user page","description":"Returns one bounded page of users plus required pagination metadata. Search runs across the global user set and optional billing enrichment stays page-scoped.","responses":{"200":{"description":"Admin user page returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdminUsersPageResponse"}}}},"400":{"description":"The admin user page query parameters were invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}},"parameters":[{"in":"query","name":"includeBilling","schema":{"type":"string"}},{"in":"query","name":"limit","schema":{"type":"string"}},{"in":"query","name":"offset","schema":{"type":"string"}},{"in":"query","name":"search","schema":{"type":"string"}}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/organizations": {"get":{"operationId":"getV1AdminOrganizations","tags":["Admin"],"summary":"Get a bounded admin organization page","description":"Returns one bounded page of organizations plus required pagination metadata. Search runs across the global organization set without changing the global overview totals.","responses":{"200":{"description":"Admin organization page returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdminOrganizationsPageResponse"}}}},"400":{"description":"The admin organization page query parameters were invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}},"parameters":[{"in":"query","name":"includeBilling","schema":{"type":"string"}},{"in":"query","name":"limit","schema":{"type":"string"}},{"in":"query","name":"offset","schema":{"type":"string"}},{"in":"query","name":"search","schema":{"type":"string"}}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/admin/metrics": {"get":{"operationId":"getV1AdminMetrics","tags":["Admin"],"summary":"Load deferred admin analytics","description":"Calculates analytics that are intentionally deferred from the initial admin page: verified users, worker totals, activity, recurrence, invites, and chart series.","responses":{"200":{"description":"Deferred admin analytics returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdminMetricsResponse"}}}},"401":{"description":"The caller must be authenticated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"The authenticated user is not an admin.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
@@ -476,12 +480,12 @@
"/v1/orgs/invitations/preview": {"get":{"operationId":"getV1OrgsInvitationsPreview","tags":["Invitations"],"security":[],"summary":"Preview organization invitation","description":"Returns invitation preview details so a user can inspect an organization invite before accepting it.","responses":{"200":{"description":"Invitation preview returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvitationPreviewResponse"}}}},"400":{"description":"The invitation preview query parameters were invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"404":{"description":"The invitation could not be found.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"in":"query","name":"id","schema":{"type":"string","minLength":1,"maxLength":255},"required":true}]}},
"/v1/orgs/invitations/accept": {"post":{"operationId":"postV1OrgsInvitationsAccept","tags":["Invitations"],"security":[{"bearerAuth":[]}],"summary":"Accept organization invitation","description":"Accepts an organization invitation for the current signed-in user and switches their active organization to the accepted workspace.","responses":{"200":{"description":"Invitation accepted successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvitationAcceptedResponse"}}}},"400":{"description":"The invitation acceptance request body was invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"The caller must be signed in to accept an invitation.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"API keys cannot accept invitations, or the deployment requires a verified account email.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"The invitation could not be found.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}},"409":{"description":"The account cannot join this organization.","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/AccountEmailDomainNotAllowedError"},{"$ref":"#/components/schemas/ScimDeprovisionedError"}]}}}},"410":{"description":"The user previously accepted this invitation, but their workspace access was removed.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MembershipRemovedError"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","minLength":1,"maxLength":255}},"required":["id"]}}}}}},
"/v1/api-keys": {"get":{"operationId":"getV1ApiKeys","tags":["API Keys"],"summary":"List organization API keys","description":"Returns the API keys that belong to the selected organization.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Organization API keys","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrganizationApiKeyListResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Only workspace owners and admins can list API keys.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrganizationApiKeyForbiddenError"}}}},"404":{"description":"Organization not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrganizationNotFoundError"}}}}}},"post":{"operationId":"postV1ApiKeys","tags":["API Keys"],"summary":"Create an organization API key","description":"Creates a new API key for the selected organization.","security":[{"bearerAuth":[]}],"responses":{"201":{"description":"Organization API key created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrganizationApiKeyResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Only workspace owners and super-admins can create API keys.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrganizationApiKeyForbiddenError"}}}},"404":{"description":"Organization not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrganizationNotFoundError"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrganizationApiKeyRequest"}}}}}},
"/v1/audit/settings": {"patch":{"operationId":"updateAuditCapture","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Set organization audit capture","description":"Fresh organization administrator authorization, literal metadata.capabilities.auditLogs=true and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.","responses":{"200":{"description":"Latest audit policy, entitlement and retained usage.","content":{"application/json":{"schema":{"type":"object","properties":{"entitlement":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["enterprise_plan","self_hosted","none"]}},"required":["enabled","source"],"additionalProperties":false},"captureOn":{"type":"boolean"},"captureAvailable":{"type":"boolean"},"policy":{"anyOf":[{"type":"object","properties":{"organizationId":{"type":"string"},"revision":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"source":{"type":"string","enum":["cloud","operator"]},"enabled":{"type":"boolean"},"categories":{"type":"array","items":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]}},"allowance":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"excessMode":{"type":"string","enum":["delete_oldest","paid_overage","keep_all"]},"effectiveAt":{"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))$"},"captureStartedAt":{"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"}]},"attachmentWindowSeconds":{"type":"integer","minimum":1,"maximum":86400}},"required":["organizationId","revision","source","enabled","categories","allowance","excessMode","effectiveAt","captureStartedAt","attachmentWindowSeconds"],"additionalProperties":false},{"type":"null"}]},"captureEnabled":{"type":"boolean"},"retainedOperations":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"eventCount":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"logicalBytes":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"oldestAvailableAt":{"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"}]},"measuredAt":{"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"}]},"billing":{"type":"string","const":"disabled"},"cleanup":{"type":"string","const":"dry_run"},"drains":{"type":"string","const":"not_configured"}},"required":["entitlement","captureOn","captureAvailable","policy","captureEnabled","retainedOperations","eventCount","logicalBytes","oldestAvailableAt","measuredAt","billing","cleanup","drains"],"additionalProperties":false}}}},"400":{"description":"Only captureOn and a nonnegative safe expectedRevision are accepted.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"Authentication required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"402":{"description":"Enabling capture requires audit availability.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EnterprisePlanRequiredError"}}}},"403":{"description":"Administrator permission, fresh authentication, audit feature and visibility requiLine truncated
"/v1/audit/event-types": {"get":{"operationId":"getAuditEventTypes","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List supported audit event types","description":"Organization administrator, fresh literal metadata.capabilities.auditLogs=true and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.","responses":{"200":{"description":"The full static supported action catalog, not observed tenant event counts.","content":{"application/json":{"schema":{"type":"object","properties":{"eventTypes":{"type":"array","items":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"}}},"required":["eventTypes"],"additionalProperties":false}}}},"400":{"description":"Malformed query, cursor, mismatched filters, operation scope or export format.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_invalid_query","audit_invalid_cursor"]}},"required":["error"]}}}},"401":{"description":"Authentication required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Organization administrator permission, audit feature and visibility required.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["forbidden","audit_feature_disabled","audit_visibility_disabled"]},"message":{"type":"string"}},"required":["error"]}}}},"404":{"description":"Organization or retained operation not found, including foreign-tenant targets.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["organization_not_found","audit_operation_not_found"]}},"required":["error"]}}}},"410":{"description":"Cursor expired or retained snapshot anchors/history are no longer available.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_cursor_expired","audit_history_unavailable"]}},"required":["error"]}}}},"503":{"description":"Audit storage or required access capture unavailable; no audit content is released.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_unavailable","audit_storage_inconsistent"]}},"required":["error"]}}}}}}},
"/v1/audit/operations": {"get":{"operationId":"getAuditOperations","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List retained audit operations","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Newest operations first, ordered by server first-recorded time then ID. Summary action and resources describe the FIRST event only (at most 256 stored references), not all affected resources. Expand events for complete evidence; X-Audit-Resource-Scope is first_event.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"query","name":"from","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"to","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"actorId","schema":{"type":"string","pattern":"^usr_[0-7][0-9a-hjkmnp-tv-z]{25}$"},"description":"Initiating user ID, not a delegated event actor or membership ID."},{"in":"query","name":"action","schema":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Exact stable action of any child event within the snapshot watermark."},{"in":"query","name":"outcome","schema":{"type":"string","enum":["running","succeeded","failed","partial","unknown"]},"description":"Current operation outcome; not an individual event outcome."},{"in":"query","name":"origin","schema":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"description":"Stored operation origin."},{"in":"query","name":"searchId","schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[^\\u0000-\\u001f\\u007f-\\u009f]+$"},"description":"Exact case-sensitive operation, child event, child request or stored child resource reference ID within the snapshot watermark; OR across ID kinds, AND with other filters. Not free-text or legacy payload search."},{"in":"query","name":"resourceId","schema":{"type":"string","minLength":1,"maxLength":255},"description":"Exact case-sensitive stored reference ID from any child within the watermark."},{"in":"query","name":"resourceType","schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Optional stored reference type; requires resourceId."}],"responses":{"200":{"description":"One bounded summary per operation.","content":{"application/json":{"schema":{"type":"object","properties":{"operations":{"type":"array","items":{"type":"object","propertLine truncated
"/v1/audit/operations/{operationId}/events": {"get":{"operationId":"getAuditOperationEvents","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List retained operation events","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Events are in ascending tenant sequence order and carry complete versioned envelopes. Missing or foreign retained operations return the same 404.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"path","name":"operationId","required":true,"schema":{"type":"string","pattern":"^aop_[0-7][0-9a-hjkmnp-tv-z]{25}$"}}],"responses":{"200":{"description":"A bounded ascending page of event envelopes.","content":{"application/json":{"schema":{"type":"object","properties":{"events":{"type":"array","items":{"type":"object","properties":{"schemaVersion":{"type":"number","const":1},"id":{"type":"string"},"organizationId":{"type":"string"},"operationId":{"type":"string"},"sequence":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"operation":{"type":"object","properties":{"kind":{"type":"string"},"scope":{"type":"string"},"origin":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"originTrust":{"type":"string","enum":["authenticated","reported"]},"initiatingActor":{"type":"object","properties":{"type":{"type":"string","enum":["user","service","system","unknown"]},"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"memberId":{"type":"string"},"credentialId":{"type":"string"}},"required":["type","id"],"additionalProperties":false},"startedAt":{"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))$"}},"required":["kind","scope","origin","originTrust","initiatingActor","startedAt"],"additionalProperties":false},"actor":{"type":"object","properties":{"type":{"type":"string","enum":["user","service","system","unknown"]},"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"memberId":{"type":"string"},"credentialId":{"type":"string"}},"required":["type","id"],"additionalProperties":false},"action":{"type":"string"},"category":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]},"outcome":{"type":"string","enum":["succeeded","failed","denied","unknown"]},"occurredAt":{"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))$"},"recordedAt":{"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))$"},"requestId":{"anyOf":[{"type":"string"},{"type":"null"}]},"jobRunId":{"type":"string"},"causedByEventId":{"type":"string"},"resources":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"id":{"type":"string"},"relationship":{"type":"string","enum":["target","parent","related"]},"label":{"type":"string"}},"required":["type","id","relationship"],"additionalProperties":false}},"changes":{"type":"object","proLine truncated
"/v1/audit/usage": {"get":{"operationId":"getAuditUsage","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Read audit retention usage","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Reads stored policy and tenant counters, plus the oldest retained operation. Capture requires audit entitlement, organization captureOn and the deployment capture flag. A ready organization without a policy is lazily initialized ON, including on this GET, with one system lifecycle event. Temporary defaults: 6,000,000 retained OPERATIONS (not child events), 300-second grouping window, change/security/execution/access/request/lifecycle categories, cloud/delete_oldest for Enterprise or operator/keep_all for explicit self-hosted entitlement. Existing OFF and custom policies are preserved. These are provisional declarations, not enforced caps: no billing, cleanup or deletion is activated. Drains are not configured. Logical bytes are not physical database size; access capture may itself add one operation.","responses":{"200":{"description":"Current stored audit policy and usage, without a history scan.","content":{"application/json":{"schema":{"type":"object","properties":{"entitlement":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["enterprise_plan","self_hosted","none"]}},"required":["enabled","source"],"additionalProperties":false},"captureOn":{"type":"boolean"},"captureAvailable":{"type":"boolean"},"policy":{"anyOf":[{"type":"object","properties":{"organizationId":{"type":"string"},"revision":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"source":{"type":"string","enum":["cloud","operator"]},"enabled":{"type":"boolean"},"categories":{"type":"array","items":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]}},"allowance":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"excessMode":{"type":"string","enum":["delete_oldest","paid_overage","keep_all"]},"effectiveAt":{"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))$"},"captureStartedAt":{"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"}]},"attachmentWindowSeconds":{"type":"integer","minimum":1,"maximum":86400}},"required":["organizationId","revision","source","enabled","categories","allowance","excessMode","effectiveAt","captureStartedAt","attachmentWindowSeconds"],"additionalProperties":false},{"type":"null"}]},"captureEnabled":{"type":"boolean"},"retainedOperations":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"eventCount":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"logicalBytes":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"oldestAvailableAt":{"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"}]},"measuredAt":{"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"}]},"billing":{"type":"string","const":"disabled"},"cleanup":{"type":"string","const":"dry_run"},"drains":{"type":"string","const":"not_configured"}},"required":["entitlement","captureOn","captureAvailable","policy","captureEnabled","retainedOperations","eventCount","logicalBytes","oldestAvailableAt","measuredAt","billing","cleanup","drains"],"additionalPropertieLine truncated
"/v1/audit/export": {"get":{"operationId":"getAuditExport","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Export one audit snapshot page","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Exports ALL matching operations' children within the watermark in ascending tenant sequence, not date/ID order. Each response is one bounded attachment, not a continuous drain. Follow X-Audit-Next-Cursor with the same format and filters until that header is absent. X-Audit-Snapshot-Sequence stays fixed. NDJSON has one full envelope per line. CSV has a header on every page and summary fields only: references and changed-field names are JSON cells, no before/after content. Every cell is quoted; formula-leading whitespace/control and =+-@ are prefixed with an apostrophe, backslashes are doubled, controls/multiline characters are encoded as literal backslash-u escapes.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"query","name":"from","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"to","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"actorId","schema":{"type":"string","pattern":"^usr_[0-7][0-9a-hjkmnp-tv-z]{25}$"},"description":"Initiating user ID, not a delegated event actor or membership ID."},{"in":"query","name":"action","schema":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Exact stable action of any child event within the snapshot watermark."},{"in":"query","name":"outcome","schema":{"type":"string","enum":["running","succeeded","failed","partial","unknown"]},"description":"Current operation outcome; not an individual event outcome."},{"in":"query","name":"origin","schema":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"description":"Stored operation origin."},{"in":"query","name":"searchId","schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[^\\u0000-\\u001f\\u007f-\\u009f]+$"},"description":"Exact case-sensitive operation, child event, child request or stored child resource reference ID within the snapshot watermark; OR across ID kinds, AND with other filters. Not free-text or legacy payload search."},{"in":"query","name":"resourceId","schema":{"type":"string","minLength":1,"maxLength":255},"description":"Exact case-sensitive stored reference ID from any child within the watermark."},{Line truncated
"/v1/audit/settings": {"patch":{"operationId":"updateAuditCapture","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Set organization audit capture","description":"Fresh organization administrator authorization, the auditLogs feature on for the organization and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.","responses":{"200":{"description":"Latest audit policy, entitlement and retained usage.","content":{"application/json":{"schema":{"type":"object","properties":{"entitlement":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["enterprise_plan","self_hosted","none"]}},"required":["enabled","source"],"additionalProperties":false},"captureOn":{"type":"boolean"},"captureAvailable":{"type":"boolean"},"policy":{"anyOf":[{"type":"object","properties":{"organizationId":{"type":"string"},"revision":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"source":{"type":"string","enum":["cloud","operator"]},"enabled":{"type":"boolean"},"categories":{"type":"array","items":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]}},"allowance":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"excessMode":{"type":"string","enum":["delete_oldest","paid_overage","keep_all"]},"effectiveAt":{"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))$"},"captureStartedAt":{"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"}]},"attachmentWindowSeconds":{"type":"integer","minimum":1,"maximum":86400}},"required":["organizationId","revision","source","enabled","categories","allowance","excessMode","effectiveAt","captureStartedAt","attachmentWindowSeconds"],"additionalProperties":false},{"type":"null"}]},"captureEnabled":{"type":"boolean"},"retainedOperations":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"eventCount":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"logicalBytes":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"oldestAvailableAt":{"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"}]},"measuredAt":{"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"}]},"billing":{"type":"string","const":"disabled"},"cleanup":{"type":"string","const":"dry_run"},"drains":{"type":"string","const":"not_configured"}},"required":["entitlement","captureOn","captureAvailable","policy","captureEnabled","retainedOperations","eventCount","logicalBytes","oldestAvailableAt","measuredAt","billing","cleanup","drains"],"additionalProperties":false}}}},"400":{"description":"Only captureOn and a nonnegative safe expectedRevision are accepted.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"Authentication required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"402":{"description":"Enabling capture requires audit availability.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EnterprisePlanRequiredError"}}}},"403":{"description":"Administrator permission, fresh authentication, audit feature and visibility requLine truncated
"/v1/audit/event-types": {"get":{"operationId":"getAuditEventTypes","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List supported audit event types","description":"Organization administrator, the auditLogs feature on for the organization (read fresh) and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.","responses":{"200":{"description":"The full static supported action catalog, not observed tenant event counts.","content":{"application/json":{"schema":{"type":"object","properties":{"eventTypes":{"type":"array","items":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"}}},"required":["eventTypes"],"additionalProperties":false}}}},"400":{"description":"Malformed query, cursor, mismatched filters, operation scope or export format.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_invalid_query","audit_invalid_cursor"]}},"required":["error"]}}}},"401":{"description":"Authentication required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Organization administrator permission, audit feature and visibility required.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["forbidden","audit_feature_disabled","audit_visibility_disabled"]},"message":{"type":"string"}},"required":["error"]}}}},"404":{"description":"Organization or retained operation not found, including foreign-tenant targets.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["organization_not_found","audit_operation_not_found"]}},"required":["error"]}}}},"410":{"description":"Cursor expired or retained snapshot anchors/history are no longer available.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_cursor_expired","audit_history_unavailable"]}},"required":["error"]}}}},"503":{"description":"Audit storage or required access capture unavailable; no audit content is released.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","enum":["audit_unavailable","audit_storage_inconsistent"]}},"required":["error"]}}}}}}},
"/v1/audit/operations": {"get":{"operationId":"getAuditOperations","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List retained audit operations","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Newest operations first, ordered by server first-recorded time then ID. Summary action and resources describe the FIRST event only (at most 256 stored references), not all affected resources. Expand events for complete evidence; X-Audit-Resource-Scope is first_event.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"query","name":"from","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"to","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"actorId","schema":{"type":"string","pattern":"^usr_[0-7][0-9a-hjkmnp-tv-z]{25}$"},"description":"Initiating user ID, not a delegated event actor or membership ID."},{"in":"query","name":"action","schema":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Exact stable action of any child event within the snapshot watermark."},{"in":"query","name":"outcome","schema":{"type":"string","enum":["running","succeeded","failed","partial","unknown"]},"description":"Current operation outcome; not an individual event outcome."},{"in":"query","name":"origin","schema":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"description":"Stored operation origin."},{"in":"query","name":"searchId","schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[^\\u0000-\\u001f\\u007f-\\u009f]+$"},"description":"Exact case-sensitive operation, child event, child request or stored child resource reference ID within the snapshot watermark; OR across ID kinds, AND with other filters. Not free-text or legacy payload search."},{"in":"query","name":"resourceId","schema":{"type":"string","minLength":1,"maxLength":255},"description":"Exact case-sensitive stored reference ID from any child within the watermark."},{"in":"query","name":"resourceType","schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Optional stored reference type; requires resourceId."}],"responses":{"200":{"description":"One bounded summary per operation.","content":{"application/json":{"schema":{"type":"object","properties":{"operations":{"type":"array","items":{"type":"object"Line truncated
"/v1/audit/operations/{operationId}/events": {"get":{"operationId":"getAuditOperationEvents","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"List retained operation events","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Events are in ascending tenant sequence order and carry complete versioned envelopes. Missing or foreign retained operations return the same 404.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"path","name":"operationId","required":true,"schema":{"type":"string","pattern":"^aop_[0-7][0-9a-hjkmnp-tv-z]{25}$"}}],"responses":{"200":{"description":"A bounded ascending page of event envelopes.","content":{"application/json":{"schema":{"type":"object","properties":{"events":{"type":"array","items":{"type":"object","properties":{"schemaVersion":{"type":"number","const":1},"id":{"type":"string"},"organizationId":{"type":"string"},"operationId":{"type":"string"},"sequence":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"operation":{"type":"object","properties":{"kind":{"type":"string"},"scope":{"type":"string"},"origin":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"originTrust":{"type":"string","enum":["authenticated","reported"]},"initiatingActor":{"type":"object","properties":{"type":{"type":"string","enum":["user","service","system","unknown"]},"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"memberId":{"type":"string"},"credentialId":{"type":"string"}},"required":["type","id"],"additionalProperties":false},"startedAt":{"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))$"}},"required":["kind","scope","origin","originTrust","initiatingActor","startedAt"],"additionalProperties":false},"actor":{"type":"object","properties":{"type":{"type":"string","enum":["user","service","system","unknown"]},"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"memberId":{"type":"string"},"credentialId":{"type":"string"}},"required":["type","id"],"additionalProperties":false},"action":{"type":"string"},"category":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]},"outcome":{"type":"string","enum":["succeeded","failed","denied","unknown"]},"occurredAt":{"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))$"},"recordedAt":{"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))$"},"requestId":{"anyOf":[{"type":"string"},{"type":"null"}]},"jobRunId":{"type":"string"},"causedByEventId":{"type":"string"},"resources":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"id":{"type":"string"},"relationship":{"type":"string","enum":["target","parent","related"]},"label":{"type":"string"}},"required":["type","id","relationship"],"additionalProperties":false}},"changes":{"type":"objLine truncated
"/v1/audit/usage": {"get":{"operationId":"getAuditUsage","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Read audit retention usage","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Reads stored policy and tenant counters, plus the oldest retained operation. Capture requires audit entitlement, organization captureOn and the deployment capture flag. A ready organization without a policy is lazily initialized ON, including on this GET, with one system lifecycle event. Temporary defaults: 6,000,000 retained OPERATIONS (not child events), 300-second grouping window, change/security/execution/access/request/lifecycle categories, cloud/delete_oldest for Enterprise or operator/keep_all for explicit self-hosted entitlement. Existing OFF and custom policies are preserved. These are provisional declarations, not enforced caps: no billing, cleanup or deletion is activated. Drains are not configured. Logical bytes are not physical database size; access capture may itself add one operation.","responses":{"200":{"description":"Current stored audit policy and usage, without a history scan.","content":{"application/json":{"schema":{"type":"object","properties":{"entitlement":{"type":"object","properties":{"enabled":{"type":"boolean"},"source":{"type":"string","enum":["enterprise_plan","self_hosted","none"]}},"required":["enabled","source"],"additionalProperties":false},"captureOn":{"type":"boolean"},"captureAvailable":{"type":"boolean"},"policy":{"anyOf":[{"type":"object","properties":{"organizationId":{"type":"string"},"revision":{"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991},"source":{"type":"string","enum":["cloud","operator"]},"enabled":{"type":"boolean"},"categories":{"type":"array","items":{"type":"string","enum":["change","security","execution","access","read","request","lifecycle"]}},"allowance":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"excessMode":{"type":"string","enum":["delete_oldest","paid_overage","keep_all"]},"effectiveAt":{"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))$"},"captureStartedAt":{"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"}]},"attachmentWindowSeconds":{"type":"integer","minimum":1,"maximum":86400}},"required":["organizationId","revision","source","enabled","categories","allowance","excessMode","effectiveAt","captureStartedAt","attachmentWindowSeconds"],"additionalProperties":false},{"type":"null"}]},"captureEnabled":{"type":"boolean"},"retainedOperations":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"eventCount":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"logicalBytes":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991},"oldestAvailableAt":{"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"}]},"measuredAt":{"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"}]},"billing":{"type":"string","const":"disabled"},"cleanup":{"type":"string","const":"dry_run"},"drains":{"type":"string","const":"not_configured"}},"required":["entitlement","captureOn","captureAvailable","policy","captureEnabled","retainedOperations","eventCount","logicalBytes","oldestAvailableAt","measuredAt","billing","cleanup","drains"],"additionalLine truncated
"/v1/audit/export": {"get":{"operationId":"getAuditExport","security":[{"bearerAuth":[]},{"denApiKey":[]}],"tags":["Organizations"],"x-mcp":false,"summary":"Export one audit snapshot page","description":"Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Exports ALL matching operations' children within the watermark in ascending tenant sequence, not date/ID order. Each response is one bounded attachment, not a continuous drain. Follow X-Audit-Next-Cursor with the same format and filters until that header is absent. X-Audit-Snapshot-Sequence stays fixed. NDJSON has one full envelope per line. CSV has a header on every page and summary fields only: references and changed-field names are JSON cells, no before/after content. Every cell is quoted; formula-leading whitespace/control and =+-@ are prefixed with an apostrophe, backslashes are doubled, controls/multiline characters are encoded as literal backslash-u escapes.","parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Maximum rows in this page."},{"in":"query","name":"cursor","schema":{"type":"string","maxLength":4096},"description":"Opaque nextCursor from the prior page of the same query and mode."},{"in":"query","name":"from","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"to","schema":{"anyOf":[{"type":"string","format":"date"},{"type":"string","format":"date-time","maxLength":40}]},"description":"Inclusive operation-start bound; date-only is UTC midnight. from must not exceed to."},{"in":"query","name":"actorId","schema":{"type":"string","pattern":"^usr_[0-7][0-9a-hjkmnp-tv-z]{25}$"},"description":"Initiating user ID, not a delegated event actor or membership ID."},{"in":"query","name":"action","schema":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[a-z][a-z0-9_.-]*$"},"description":"Exact stable action of any child event within the snapshot watermark."},{"in":"query","name":"outcome","schema":{"type":"string","enum":["running","succeeded","failed","partial","unknown"]},"description":"Current operation outcome; not an individual event outcome."},{"in":"query","name":"origin","schema":{"type":"string","enum":["api","cloud_ui","mcp","scheduler","webhook","platform_admin"]},"description":"Stored operation origin."},{"in":"query","name":"searchId","schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[^\\u0000-\\u001f\\u007f-\\u009f]+$"},"description":"Exact case-sensitive operation, child event, child request or stored child resource reference ID within the snapshot watermark; OR across ID kinds, AND with other filters. Not free-text or legacy payload search."},{"in":"query","name":"resourceId","schema":{"type":"string","minLength":1,"maxLength":255},"description":"Exact case-sensitive stored reference ID from any child within the waterLine truncated
"/v1/brand-assets/{organizationId}/{kind}/{version}": {"get":{"operationId":"getV1BrandAssetsByOrganizationIdByKindByVersion","tags":["Organizations"],"security":[],"summary":"Read an immutable organization brand asset","description":"Serves a capability-signed, content-addressed organization logo or app icon from this Den deployment.","responses":{"200":{"description":"Immutable brand image bytes. The media type follows the `{version}` extension (`.png` -> `image/png`, `.jpg` -> `image/jpeg`); served with `Cache-Control: public, max-age=31536000, immutable` and an `ETag` equal to the content hash.","content":{"image/png":{"schema":{"type":"string","format":"binary"}},"image/jpeg":{"schema":{"type":"string","format":"binary"}}}},"404":{"description":"The managed brand asset could not be found.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"organizationId","required":true},{"schema":{"type":"string"},"in":"path","name":"kind","required":true},{"schema":{"type":"string"},"in":"path","name":"version","required":true}]}},
"/v1/org/brand-assets": {"post":{"operationId":"postV1OrgBrandAssets","tags":["Organizations"],"summary":"Upload organization brand assets","description":"Validates and stores owner-supplied wordmark and app icon files inside the Den deployment.","responses":{"200":{"description":"Managed brand assets were saved.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ManagedBrandAssetUploadResponse"}}}},"400":{"description":"A supplied brand asset was invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidManagedBrandAssetError"}}}},"401":{"description":"The caller must be signed in.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Only workspace owners and super-admins can upload brand assets.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"413":{"description":"The upload exceeded the request size limit.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidManagedBrandAssetError"}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/workflows": {"get":{"operationId":"getV1Workflows","tags":["Workflows"],"summary":"List accessible Workflows","description":"Lists every Workflow the calling member can reach through Plugin or direct grants, each with the Plugin it executes under, its latest immutable version id, declared inputSchema and outputSchema, and the capabilities it calls. Workflows whose latest version cannot be parsed are omitted. Use the returned configObjectVersionId to run an exact version.","responses":{"200":{"description":"Workflows returned.","content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"pluginId":{"type":"string"},"configObjectId":{"type":"string"},"configObjectVersionId":{"type":"string"},"title":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"inputSchema":{"anyOf":[{},{"type":"null"}]},"outputSchema":{"anyOf":[{},{"type":"null"}]},"requiredCapabilities":{"type":"array","items":{"type":"object","properties":{"capabilityName":{"type":"string"},"scriptPath":{"type":"string"}},"required":["capabilityName","scriptPath"]}}},"required":["pluginId","configObjectId","configObjectVersionId","title","description","inputSchema","outputSchema","requiredCapabilities"]}}},"required":["items"]}}}},"401":{"description":"Sign-in required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]},"post":{"operationId":"saveWorkflow","tags":["Workflows"],"summary":"Save a successful Code Mode run as a Workflow inside an OpenWork Connect Plugin","description":"Saves a successful authoring run as a reusable Workflow. Supply code or receiptId, or both with byte-identical source. Explicit receiptId requires a successful run from this caller in this organization within 15 minutes, retained source (encrypted shared storage when Redis is configured; process-local otherwise), and exactly matching tested input and schema digests; missing retention fails closed (400 workflow_authoring_receipt_required). Live receipts forbid currentInput, validate with their server-generated runtime, and never save runtime day bounds as example input. Without receiptId, the existing byte-exact recent successful code lookup applies (400 workflow_recent_receipt_required). Literal credentials in source are rejected, not sanitized. The run's tool calls become requiredCapabilities and must still be available. Saving creates no artifact snapshot linkage. Omit pluginId for the private My Workflows Plugin; a chosen Plugin requires editor access. Replacing a same-name Workflow requires manager access.","responses":{"201":{"description":"Workflow saved.","content":{"application/json":{"schema":{"type":"object","properties":{"pluginId":{"type":"string"},"configObjectId":{"type":"string"},"configObjectVersionId":{"type":"string"},"graph":{"type":"object","properties":{"nodes":{"type":"array","items":{"oneOf":[{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"input"},"label":{"type":"string"},"fields":{"type":"array","items":{"type":"string"}}},"required":["id","kind","label","fields"]},{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"tool"},"label":{"type":"string"},"namespace":{"type":"string"},"tool":{"type":"string"},"scriptPath":{"type":"string"},"assignsTo":{"anyOf":[{"type":"string"},{"type":"null"}]},"parallelGroup":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","kind","label","namespace","tool","scriptPath","assignsTo","parallelGroup"]},{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"search"},"label":{"type":"string"}},"required":["id","kind","label"]},{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"branch"},"label":{"type":"string"}},"required":["id","kind","label"]},{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"loop"},"label":{"type":"string"}},"required":["id","kind","label"]},{"type":"object","properties":{"id":{"type":"string"},"kind":{"type":"string","const":"return"},"label":{"type":"string"}},"required":["id","kind","label"]}]}},"edges":{"type":"array","items":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"},"label":{"anyOf":[{"type":"string"},{"type":"null"}]},"kind":{"type":"string","enum":["flow","data"]}},"required":["from","to","label","kind"]}},"parseError":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["nodes","edges","parseError"]},"mermaid":{"type":"string"}},"required":["pluginId","configObjectId","configObjectVersionId","graph","mermaid"]}}}},"400":{"description":"Invalid request.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"403":{"description":"The caller cannot add Workflows to this Plugin.","content":{"application/json":{"schema":{"$ref":Line truncated
@@ -746,6 +750,7 @@
"/v1/workbot/session": {"get":{"operationId":"getWorkbotSession","tags":["Workbot"],"x-mcp":false,"summary":"Who is signed in to Workbot","description":"For the Workbot app only. With the access token a person got by signing in to Workbot through Den, returns who they are, the workspace they chose, and whether Workbot is on for it.","responses":{"200":{"description":"The signed-in person and their workspace.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkbotSession"}}}},"401":{"description":"The token is missing, expired or revoked, or the membership ended.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/workbot/run-token": {"post":{"operationId":"createWorkbotRunToken","tags":["Workbot"],"x-mcp":false,"summary":"A short-lived token for one Workbot turn","description":"For the Workbot app only. Mints the member-scoped MCP token a Workbot turn uses to reach the person's connected apps on the headless runner, for at most an hour. Refused when Workbot is off for the workspace.","responses":{"200":{"description":"The token.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkbotRunToken"}}}},"401":{"description":"The token is missing, expired or revoked, or the membership ended.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Workbot is off for this workspace.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}},"required":["error"]}}}},"429":{"description":"Too many tokens requested.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","const":"rate_limited"},"retryAfter":{"type":"number"}},"required":["error","retryAfter"]}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"ttlMs":{"type":"integer","minimum":60000,"maximum":3600000}}}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
"/v1/app-version": {"get":{"operationId":"getV1AppVersion","tags":["System"],"security":[],"summary":"Get desktop app version metadata","description":"Returns the supported desktop app range, stable published desktop releases from GitHub, and, when available, this deployment's web app base URL so desktop clients only need to be configured with the API URL.","responses":{"200":{"description":"Desktop app version metadata returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DenAppVersionResponse"}}}}}}},
"/v1/features": {"get":{"operationId":"getV1Features","tags":["System"],"security":[],"summary":"Get features for people without an organization","description":"On or off for every feature that is part of this deployment, for someone who is not signed in: the deployment-wide state after the kill switch and operator locks, with no organization overrides. A feature missing here is off.","responses":{"200":{"description":"Features returned.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PublicFeatures"}}}}}}},
"/v1/webhooks/connectors/github": {"post":{"operationId":"postV1WebhooksConnectorsGithub","tags":["Webhooks"],"security":[],"summary":"GitHub webhook ingress","description":"Verifies a GitHub App webhook signature against the raw request body, then records any relevant sync work.","responses":{"200":{"description":"Ignored but valid GitHub webhook delivery.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PluginArchGithubWebhookIgnoredResponse"}}}},"202":{"description":"Accepted GitHub webhook delivery.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PluginArchGithubWebhookAcceptedResponse"}}}},"401":{"description":"Invalid GitHub webhook signature.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PluginArchGithubWebhookUnauthorizedResponse"}}}},"503":{"description":"GitHub webhook secret is not configured."}}}},
"/v1/workers/{id}/activity-heartbeat": {"post":{"operationId":"postV1WorkersByIdActivityHeartbeat","tags":["Workers","Worker Activity"],"security":[{"workerHeartbeatToken":[]}],"summary":"Record worker heartbeat","description":"Accepts signed heartbeat and recent-activity updates from a worker so Den can track worker health and recent usage.","responses":{"200":{"description":"Worker heartbeat accepted successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerHeartbeatResponse"}}}},"400":{"description":"The heartbeat payload or worker path parameters were invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"The worker heartbeat token was missing or invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"The worker could not be found.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}},"parameters":[{"in":"path","name":"id","schema":{"format":"typeid","type":"string","minLength":30,"maxLength":30},"required":true,"description":"Den TypeID with 'wrk_' prefix and a 26-character base32 suffix."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"sentAt":{"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))$"},"isActiveRecently":{"type":"boolean"},"lastActivityAt":{"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"}]},"openSessionCount":{"type":"integer","minimum":0,"maximum":9007199254740991}},"required":["isActiveRecently"]}}}}}},
"/v1/workers": {"get":{"operationId":"getV1Workers","tags":["Workers"],"summary":"List workers","description":"Lists the workers that belong to the caller's active organization, newest first, including each worker's latest known instance state. Pass nextCursor from the previous page as cursor to continue; nextCursor is null on the last page.","responses":{"200":{"description":"Workers returned successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerListResponse"}}}},"400":{"description":"The worker list query parameters were invalid.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvalidRequestError"}}}},"401":{"description":"The caller must be signed in to list workers.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}},"parameters":[{"in":"query","name":"cursor","schema":{"type":"string","minLength":1,"maxLength":200},"description":"Opaque cursor returned as nextCursor by the previous page. Omit for the first page."},{"in":"query","name":"limit","schema":{"default":20,"type":"integer","minimum":1,"maximum":50}}],"security":[{"bearerAuth":[]},{"denApiKey":[]}]},"post":{"operationId":"postV1Workers","tags":["Workers"],"summary":"Create worker","description":"Creates a local worker or cloud worker for the active organization and returns the initial tokens needed to connect to it.","responses":{"201":{"description":"Local worker created successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerCreateResponse"}}}},"202":{"description":"Cloud worker creation started successfully.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerCreateResponse"}}}},"400":{"description":"The worker creation payload was invalid.","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/InvalidRequestError"},{"$ref":"#/components/schemas/OrganizationUnavailableError"},{"$ref":"#/components/schemas/WorkspacePathRequiredError"},{"$ref":"#/components/schemas/WorkerUserEmailRequiredError"}]}}}},"401":{"description":"The caller must be signed in to create workers.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"OpenWork Web access is required to launch a cloud worker.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerOpenWorkWebAccessRequiredError"}}}},"409":{"description":"The organization has reached its worker limit.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkerOrgLimitReachedError"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1},"description":{"type":"string"},"destination":{"type":"string","enum":["local","cloud"]},"workspacePath":{"type":"string"},"sandboxBackend":{"type":"string"},"imageVersion":{"type":"string"}},"required":["name","destination"]}}}},"security":[{"bearerAuth":[]},{"denApiKey":[]}]}},
+35
View File
@@ -0,0 +1,35 @@
{
"name": "@openwork/features",
"version": "0.0.0",
"private": true,
"type": "module",
"description": "OpenWork feature registry: declare a feature once, resolve it per deployment and organization.",
"exports": {
".": {
"types": "./src/index.ts",
"development": "./src/index.ts",
"default": "./src/index.ts"
},
"./registry": {
"types": "./src/registry.ts",
"development": "./src/registry.ts",
"default": "./src/registry.ts"
},
"./resolve": {
"types": "./src/resolve.ts",
"development": "./src/resolve.ts",
"default": "./src/resolve.ts"
}
},
"scripts": {
"test": "node --test src/*.test.ts",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^20.11.30",
"typescript": "^5.6.3"
}
}
+4
View File
@@ -0,0 +1,4 @@
// Self-references (not relative paths) so this TypeScript source runs as-is
// under Node and typechecks in every consumer without a build step.
export * from "@openwork/features/registry"
export * from "@openwork/features/resolve"
+125
View File
@@ -0,0 +1,125 @@
/**
* OpenWork feature registry: the one place a feature is declared.
*
* This is the file you edit to add a feature. Read
* .opencode/skills/add-a-feature/SKILL.md first. Every new user-visible
* feature, or a change existing users would notice, starts here, off, before
* any feature code is written.
*
* A feature is rolled out, and reverted, along several dimensions:
*
* deployments which products it exists on (OpenWork Cloud, self-hosted)
* everyone on or off for everyone on the deployment, changed in /admin
* without a deploy
* organization platform admins turn it on or off for one organization in /admin
* operator a self-hosted operator locks it on or off for the whole install (Helm)
* kill switch turns it off everywhere at once, outranking everything above
*
* The entry only declares what is fixed in code. The on/off state, kill
* switches and per-organization overrides live in the database of each
* deployment, and start from `default`. Run `pnpm features:sync` after
* editing this file.
*
* Keys are permanent: the same name is the Helm values key, the
* DEN_FEATURE_<KEY> environment variable, the API field, and the stored rows.
* Use lowerCamelCase with no consecutive capitals.
*/
export type FeatureDeployment = "cloud" | "self_hosted"
export type FeatureDefinition = {
/** Short name shown to platform admins and operators. */
label: string
/** One sentence: what a person gets, in words they see in the product. */
description: string
/** Year and month the entry was added or last changed, e.g. "2026-10". */
since: `${number}-${number}`
/** Products it exists on. Leave one out on purpose, e.g. ["cloud"] for cloud-only. */
deployments: readonly FeatureDeployment[]
/** On or off for everyone on a fresh deployment: false for new work, true once everyone has it. */
default: boolean
/**
* The switch is part of the product (e.g. platform admins turn Connect off for
* one organization), not a temporary rollout. Rollouts are deleted once done;
* `pnpm features:check` asks for a decision six months after `since`.
*/
permanent?: boolean
}
function defineFeatures<const T extends Record<string, FeatureDefinition>>(features: T): T {
return features
}
const everywhere = ["cloud", "self_hosted"] as const
export const FEATURES = defineFeatures({
installLinks: {
label: "Install links",
description: "Workspace admins can create desktop install links for their organization.",
since: "2026-10",
deployments: everywhere,
default: true,
},
mcpConnections: {
label: "OpenWork Connect",
description: "Members see the organization's connections, marketplace capabilities on the agent rail, and the desktop Connect tab.",
since: "2026-10",
deployments: everywhere,
default: true,
},
modelsAnalytics: {
label: "OpenWork Models task analytics",
description: "Organization admins can opt in to task analytics for OpenWork Models.",
since: "2026-10",
deployments: everywhere,
default: false,
},
auditLogs: {
label: "Audit logs",
description: "Organization admins can read and configure audit logs. Capture still needs an audit entitlement.",
since: "2026-10",
deployments: everywhere,
default: false,
},
orgManagedDashboards: {
label: "Dashboards",
description: "Organization admins publish dashboards to members in Den and the desktop app.",
since: "2026-10",
deployments: everywhere,
default: false,
},
slackAssistant: {
label: "Slack Assistant",
description: "Answers Slack mentions and DMs for the organization after the Slack connector is set up.",
since: "2026-10",
deployments: everywhere,
default: false,
},
slackAssistantHeadless: {
label: "Slack Assistant: headless runtime",
description: "Answers Slack on the shared headless runner instead of each member's OpenWork Web computer. Needs the deployment's headless runner.",
since: "2026-10",
deployments: everywhere,
default: false,
},
headlessAutomations: {
label: "Cloud Automations: headless runtime",
description: "Runs the organization's cloud Automations on the shared headless runner. Needs the deployment's headless runner and a plan that includes it.",
since: "2026-10",
deployments: everywhere,
default: false,
},
workbot: {
label: "Workbot",
description: "Members can use Workbot. Needs the deployment's Workbot app.",
since: "2026-10",
deployments: everywhere,
default: false,
},
})
export type FeatureKey = keyof typeof FEATURES
export type FeatureMap = Record<FeatureKey, boolean>
export type FeatureOverrides = Partial<FeatureMap>
+80
View File
@@ -0,0 +1,80 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import {
FEATURE_KEYS,
FEATURES,
featureKeySchema,
featureLockEnvName,
mapFeatures,
parseFeatureEnvironment,
resolveFeature,
resolveFeatures,
type FeatureContext,
} from "@openwork/features"
const base: FeatureContext = { deployment: "cloud", locks: {}, rollouts: {}, overrides: {} }
test("without stored state, every feature follows its registry default", () => {
for (const key of FEATURE_KEYS) {
const resolved = resolveFeature(key, base)
assert.equal(resolved.enabled, FEATURES[key].default)
assert.equal(resolved.source, "everyone")
assert.equal(resolved.overrideApplies, true)
}
})
test("precedence: unavailable, kill switch, lock, override, everyone", () => {
const key = "orgManagedDashboards"
assert.equal(resolveFeature(key, { ...base, rollouts: { [key]: { enabled: true, killed: false } } }).enabled, true)
const overridden = resolveFeature(key, { ...base, overrides: { [key]: true } })
assert.equal(overridden.enabled, true)
assert.equal(overridden.source, "override")
assert.equal(resolveFeature(key, { ...base, overrides: { [key]: true }, locks: { [key]: false } }).enabled, false)
const killed = resolveFeature(key, { ...base, overrides: { [key]: true }, locks: { [key]: true }, rollouts: { [key]: { enabled: true, killed: true } } })
assert.equal(killed.enabled, false)
assert.equal(killed.source, "killed")
assert.equal(killed.overrideApplies, false)
})
test("an organization override can turn a feature off while it is on for everyone", () => {
const key = "installLinks"
const resolved = resolveFeature(key, { ...base, overrides: { [key]: false } })
assert.equal(resolved.everyone, true)
assert.equal(resolved.enabled, false)
})
test("mapFeatures and the key schema cover exactly the registry", () => {
assert.deepEqual(Object.keys(mapFeatures(() => 0)).sort(), [...FEATURE_KEYS].sort())
for (const key of FEATURE_KEYS) assert.equal(featureKeySchema.parse(key), key)
assert.equal(featureKeySchema.safeParse("notAFeature").success, false)
assert.equal(featureKeySchema.safeParse("appMcpServers").success, false)
assert.deepEqual(Object.keys(resolveFeatures(base)).sort(), [...FEATURE_KEYS].sort())
})
test("every key maps to a unique DEN_FEATURE_ name", () => {
const names = FEATURE_KEYS.map(featureLockEnvName)
for (const name of names) assert.match(name, /^DEN_FEATURE_[A-Z0-9]+(?:_[A-Z0-9]+)*$/)
assert.equal(new Set(names).size, names.length)
assert.equal(featureLockEnvName("orgManagedDashboards"), "DEN_FEATURE_ORG_MANAGED_DASHBOARDS")
})
test("environment: self_hosted by default, strict values, unknown keys warn", () => {
const empty = parseFeatureEnvironment({})
assert.equal(empty.deployment, "self_hosted")
assert.deepEqual(empty.locks, {})
assert.deepEqual(empty.problems, [])
const parsed = parseFeatureEnvironment({
DEN_DEPLOYMENT: "cloud",
DEN_FEATURE_WORKBOT: "true",
DEN_FEATURE_INSTALL_LINKS: "false",
DEN_FEATURE_ORG_MANAGED_DASHBOARDS: "",
DEN_FEATURE_NOT_A_THING: "true",
})
assert.equal(parsed.deployment, "cloud")
assert.deepEqual(parsed.locks, { workbot: true, installLinks: false })
assert.deepEqual(parsed.problems.map((problem) => [problem.variable, problem.fatal]), [["DEN_FEATURE_NOT_A_THING", false]])
const fatal = parseFeatureEnvironment({ DEN_DEPLOYMENT: "prod", DEN_FEATURE_WORKBOT: "yes" })
assert.deepEqual(fatal.problems.map((problem) => [problem.variable, problem.fatal]), [["DEN_DEPLOYMENT", true], ["DEN_FEATURE_WORKBOT", true]])
})
+163
View File
@@ -0,0 +1,163 @@
/**
* How a feature from ./registry.ts resolves. One function for
* every feature and every place it is checked (den-api, Den web, the desktop):
*
* 1. not part of this deployment → off ("unavailable")
* 2. kill switch → off ("killed") the revert, no deploy
* 3. operator lock (DEN_FEATURE_*) → as set ("lock")
* 4. organization override (/admin) → as set ("override")
* 5. on or off for everyone (/admin) → as set ("everyone")
*
* Pure functions with no I/O, safe in browsers.
*/
import { z } from "zod"
import {
FEATURES,
type FeatureDefinition,
type FeatureDeployment,
type FeatureKey,
type FeatureMap,
type FeatureOverrides,
} from "@openwork/features/registry"
/**
* Retired keys. Older clients and stored overrides may still send or hold them;
* inputs accept and ignore them, and they are never stored again.
*/
export const RETIRED_FEATURE_KEYS = ["gatewayDashboard", "workflows", "codemodeScripts", "remoteMcpApps", "appMcpServers", "cloud"] as const
export function isFeatureKey(value: string): value is FeatureKey {
return Object.hasOwn(FEATURES, value)
}
export const FEATURE_KEYS: readonly FeatureKey[] = Object.keys(FEATURES).filter(isFeatureKey)
export function featureDefinition(key: FeatureKey): FeatureDefinition {
return FEATURES[key]
}
export function featureAvailableOn(key: FeatureKey, deployment: FeatureDeployment): boolean {
return featureDefinition(key).deployments.includes(deployment)
}
/** Features that exist on this deployment; the only ones with a Helm key there. */
export function availableFeatureKeys(deployment: FeatureDeployment): FeatureKey[] {
return FEATURE_KEYS.filter((key) => featureAvailableOn(key, deployment))
}
/**
* `newThing` → `DEN_FEATURE_NEW_THING`. Must match the Helm chart's
* `snakecase | upper`; `pnpm features:check` renders the chart to prove it.
*/
export function featureLockEnvName(key: FeatureKey): string {
return `DEN_FEATURE_${key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase()}`
}
/** Builds a value for every registry key, so adding an entry never means editing a literal. */
export function mapFeatures<V>(fn: (key: FeatureKey) => V): Record<FeatureKey, V> {
const result: Partial<Record<FeatureKey, V>> = {}
for (const key of FEATURE_KEYS) result[key] = fn(key)
// Every key in FEATURE_KEYS was assigned above; TypeScript cannot follow the loop.
return result as Record<FeatureKey, V>
}
/** Accepts exactly the registry keys. */
export const featureKeySchema = z.enum(mapFeatures((key) => key))
/** Deployment-wide state of one feature, stored per deployment and changed in /admin. */
export type FeatureRollout = { enabled: boolean; killed: boolean }
export type FeatureRollouts = Partial<Record<FeatureKey, FeatureRollout>>
/** The stored state, or the registry default when nothing is stored. */
export function featureRollout(key: FeatureKey, rollouts: FeatureRollouts): FeatureRollout {
return rollouts[key] ?? { enabled: featureDefinition(key).default, killed: false }
}
export type FeatureEnvironment = {
deployment: FeatureDeployment
/** Operator locks from DEN_FEATURE_* (Helm `config.features`). */
locks: FeatureOverrides
}
export type FeatureContext = FeatureEnvironment & {
rollouts: FeatureRollouts
/** Stored overrides for the organization being resolved; empty when there is none (signed out). */
overrides: FeatureOverrides
}
export type FeatureSource = "unavailable" | "killed" | "lock" | "override" | "everyone"
export type ResolvedFeature = {
key: FeatureKey
enabled: boolean
source: FeatureSource
/** The deployment-wide on/off state. */
everyone: boolean
killed: boolean
lock: boolean | null
override: boolean | null
/** A per-organization override would take effect (available, not killed, not locked). */
overrideApplies: boolean
}
export function resolveFeature(key: FeatureKey, context: FeatureContext): ResolvedFeature {
const { enabled: everyone, killed } = featureRollout(key, context.rollouts)
const lock = context.locks[key] ?? null
const override = context.overrides[key] ?? null
const base = { key, everyone, killed, lock, override }
if (!featureAvailableOn(key, context.deployment)) {
return { ...base, enabled: false, source: "unavailable", overrideApplies: false }
}
if (killed) return { ...base, enabled: false, source: "killed", overrideApplies: false }
if (lock !== null) return { ...base, enabled: lock, source: "lock", overrideApplies: false }
if (override !== null) return { ...base, enabled: override, source: "override", overrideApplies: true }
return { ...base, enabled: everyone, source: "everyone", overrideApplies: true }
}
export function resolveFeatures(context: FeatureContext): FeatureMap {
return mapFeatures((key) => resolveFeature(key, context).enabled)
}
export type FeatureEnvironmentProblem = { variable: string; message: string; fatal: boolean }
/**
* Reads DEN_DEPLOYMENT and DEN_FEATURE_* from an environment record. Fatal
* problems (unknown deployment, a value other than "true"/"false") should stop
* the server at boot; the others are warnings about ignored variables.
*/
export function parseFeatureEnvironment(env: Record<string, string | undefined>): FeatureEnvironment & { problems: FeatureEnvironmentProblem[] } {
const problems: FeatureEnvironmentProblem[] = []
const rawDeployment = env.DEN_DEPLOYMENT?.trim() ?? ""
let deployment: FeatureDeployment = "self_hosted"
if (rawDeployment === "cloud" || rawDeployment === "self_hosted") {
deployment = rawDeployment
} else if (rawDeployment !== "") {
problems.push({ variable: "DEN_DEPLOYMENT", message: `must be "cloud" or "self_hosted", got "${rawDeployment}".`, fatal: true })
}
const locks: FeatureOverrides = {}
const known = new Map<string, FeatureKey>(FEATURE_KEYS.map((key) => [featureLockEnvName(key), key]))
for (const [variable, rawValue] of Object.entries(env)) {
if (!variable.startsWith("DEN_FEATURE_")) continue
const value = rawValue?.trim() ?? ""
if (value === "") continue
const key = known.get(variable)
if (!key) {
problems.push({ variable, message: "is not a known feature and is ignored.", fatal: false })
continue
}
if (value !== "true" && value !== "false") {
problems.push({ variable, message: `must be "true", "false" or empty, got "${value}".`, fatal: true })
continue
}
if (!featureAvailableOn(key, deployment)) {
problems.push({ variable, message: `is ignored: ${key} is not part of this deployment.`, fatal: false })
continue
}
locks[key] = value === "true"
}
return { deployment, locks, problems }
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"rootDir": "src",
"noEmit": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"types": ["node"]
},
"include": ["src/**/*"]
}
+60 -8
View File
@@ -175,6 +175,8 @@ import type {
GetMcpWellKnownOauthProtectedResourceResponses,
GetReadyErrors,
GetReadyResponses,
GetV1AdminFeaturesErrors,
GetV1AdminFeaturesResponses,
GetV1AdminFreeAutoUsageErrors,
GetV1AdminFreeAutoUsageResponses,
GetV1AdminMetricsErrors,
@@ -287,6 +289,7 @@ import type {
GetV1DesktopPoliciesResponses,
GetV1DiagnosticsEgressErrors,
GetV1DiagnosticsEgressResponses,
GetV1FeaturesResponses,
GetV1GatewayUsageLimitPoliciesByPolicyIdAssignmentsErrors,
GetV1GatewayUsageLimitPoliciesByPolicyIdAssignmentsResponses,
GetV1GatewayUsageLimitPoliciesErrors,
@@ -853,6 +856,8 @@ import type {
PutApiAuthScimV2GroupsByGroupIdResponses,
PutApiAuthScimV2UsersByUserIdErrors,
PutApiAuthScimV2UsersByUserIdResponses,
PutV1AdminFeaturesByKeyErrors,
PutV1AdminFeaturesByKeyResponses,
PutV1AdminOrganizationsByOrganizationIdCapabilitiesErrors,
PutV1AdminOrganizationsByOrganizationIdCapabilitiesResponses,
PutV1AdminOrganizationsByOrganizationIdOpenworkWebAccessErrors,
@@ -1235,7 +1240,7 @@ export class DenClient extends HeyApiClient {
/**
* Get an organization's capability overrides
*
* Returns admin-visible capabilities. The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.
* Returns the effective value of every registry feature (capabilities) and, per feature, its source and whether /admin can change it (featureStates). The deprecated gatewayDashboard compatibility field is always true, not a mutable organization flag; deployment configuration and authorization still apply.
*/
public getV1AdminOrganizationsByOrganizationIdCapabilities<ThrowOnError extends boolean = false>(
parameters: {
@@ -1258,7 +1263,7 @@ export class DenClient extends HeyApiClient {
/**
* Set an organization's capability overrides
*
* Enables, disables or clears (null) the install-links, MCP-connections, Models analytics, auditLogs and orgManagedDashboards overrides. Audit logs and org-managed Dashboards require literal true (absent/false is disabled); this flag neither grants capture entitlement nor initializes capacity or changes capture preferences. The deprecated gatewayDashboard boolean or null input is validated but ignored and never persisted; its response field is always true. Stale retired overrides are removed on capability writes.
* Enables, disables or clears (null) per-organization feature overrides. Every key in the feature registry (packages/features/src/registry.ts) is accepted; a feature that is fixed on this deployment (unavailable, off or on for everyone) returns 400, and unknown or retired keys are ignored. A deployment lock (DEN_FEATURE_*) outranks a stored override; featureStates shows the effective value and its source. The auditLogs feature neither grants capture entitlement nor initializes capacity or changes capture preferences. The deprecated gatewayDashboard boolean or null input is validated but ignored and never persisted; its response field is always true.
*/
public putV1AdminOrganizationsByOrganizationIdCapabilities<ThrowOnError extends boolean = false>(
parameters: {
@@ -1278,6 +1283,41 @@ export class DenClient extends HeyApiClient {
});
}
/**
* List features and their state
*
* Every feature in the registry (packages/features/src/registry.ts) with what is fixed in code (deployments, default) and this deployment's state: on or off for everyone, kill switch, and any operator lock.
*/
public getV1AdminFeatures<ThrowOnError extends boolean = false>(options?: Options<never, ThrowOnError>) {
return (options?.client ?? this.client).get<GetV1AdminFeaturesResponses, GetV1AdminFeaturesErrors, ThrowOnError>({
url: "/v1/admin/features",
...options,
});
}
/**
* Change a feature's state
*
* Turns the feature on or off for everyone on this deployment (organization overrides still apply), and/or sets the kill switch. The kill switch turns the feature off everywhere, outranking operator locks and organization overrides; it is the way to revert.
*/
public putV1AdminFeaturesByKey<ThrowOnError extends boolean = false>(
parameters: {
key: string;
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams([parameters], [{ args: [{ in: "path", key: "key" }] }]);
return (options?.client ?? this.client).put<
PutV1AdminFeaturesByKeyResponses,
PutV1AdminFeaturesByKeyErrors,
ThrowOnError
>({
url: "/v1/admin/features/{key}",
...options,
...params,
});
}
/**
* Get a bounded admin user page
*
@@ -3010,7 +3050,7 @@ export class DenClient extends HeyApiClient {
/**
* Set organization audit capture
*
* Fresh organization administrator authorization, literal metadata.capabilities.auditLogs=true and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.
* Fresh organization administrator authorization, the auditLogs feature on for the organization and visibility required. Only captureOn and expectedRevision are accepted. Enabling requires Enterprise or explicit installation entitlement and capture rollout availability. A missing policy is initialized with server-owned temporary defaults; expectedRevision=0 is accepted only by the initializing request. Explicit OFF initializes and disables atomically, never publishing intermediate ON. Disabling remains available after entitlement loss while flagged. Revision conflicts require refresh; matching no-ops do not record duplicate events. Changes and immutable lifecycle evidence commit atomically. Existing capacity configuration and retained history are unchanged.
*/
public updateAuditCapture<ThrowOnError extends boolean = false>(
parameters: {
@@ -3045,7 +3085,7 @@ export class DenClient extends HeyApiClient {
/**
* List supported audit event types
*
* Organization administrator, fresh literal metadata.capabilities.auditLogs=true and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.
* Organization administrator, the auditLogs feature on for the organization (read fresh) and audit visibility required. Returns the static supported semantic action catalog from the executable provider, audit-read, capture-settings, default-policy and pilot-policy coverage registries, including hidden child actions and this endpoint's access events. Unique deterministic lexicographic order. This fixed bounded catalog needs no pagination or observed full-history DISTINCT scan. It is independent of loaded rows, time/filter selection and capture category enablement, including empty history; support does not imply this organization has events of every type or that every cloud action is captured. Legacy event types are excluded. Access capture uses the same content-free requested/served policy as other audit reads.
*/
public getAuditEventTypes<ThrowOnError extends boolean = false>(options?: Options<never, ThrowOnError>) {
return (options?.client ?? this.client).get<GetAuditEventTypesResponses, GetAuditEventTypesErrors, ThrowOnError>({
@@ -3057,7 +3097,7 @@ export class DenClient extends HeyApiClient {
/**
* List retained audit operations
*
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Newest operations first, ordered by server first-recorded time then ID. Summary action and resources describe the FIRST event only (at most 256 stored references), not all affected resources. Expand events for complete evidence; X-Audit-Resource-Scope is first_event.
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Newest operations first, ordered by server first-recorded time then ID. Summary action and resources describe the FIRST event only (at most 256 stored references), not all affected resources. Expand events for complete evidence; X-Audit-Resource-Scope is first_event.
*/
public getAuditOperations<ThrowOnError extends boolean = false>(
parameters?: {
@@ -3105,7 +3145,7 @@ export class DenClient extends HeyApiClient {
/**
* List retained operation events
*
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Events are in ascending tenant sequence order and carry complete versioned envelopes. Missing or foreign retained operations return the same 404.
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Events are in ascending tenant sequence order and carry complete versioned envelopes. Missing or foreign retained operations return the same 404.
*/
public getAuditOperationEvents<ThrowOnError extends boolean = false>(
parameters: {
@@ -3141,7 +3181,7 @@ export class DenClient extends HeyApiClient {
/**
* Read audit retention usage
*
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Reads stored policy and tenant counters, plus the oldest retained operation. Capture requires audit entitlement, organization captureOn and the deployment capture flag. A ready organization without a policy is lazily initialized ON, including on this GET, with one system lifecycle event. Temporary defaults: 6,000,000 retained OPERATIONS (not child events), 300-second grouping window, change/security/execution/access/request/lifecycle categories, cloud/delete_oldest for Enterprise or operator/keep_all for explicit self-hosted entitlement. Existing OFF and custom policies are preserved. These are provisional declarations, not enforced caps: no billing, cleanup or deletion is activated. Drains are not configured. Logical bytes are not physical database size; access capture may itself add one operation.
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Reads stored policy and tenant counters, plus the oldest retained operation. Capture requires audit entitlement, organization captureOn and the deployment capture flag. A ready organization without a policy is lazily initialized ON, including on this GET, with one system lifecycle event. Temporary defaults: 6,000,000 retained OPERATIONS (not child events), 300-second grouping window, change/security/execution/access/request/lifecycle categories, cloud/delete_oldest for Enterprise or operator/keep_all for explicit self-hosted entitlement. Existing OFF and custom policies are preserved. These are provisional declarations, not enforced caps: no billing, cleanup or deletion is activated. Drains are not configured. Logical bytes are not physical database size; access capture may itself add one operation.
*/
public getAuditUsage<ThrowOnError extends boolean = false>(options?: Options<never, ThrowOnError>) {
return (options?.client ?? this.client).get<GetAuditUsageResponses, GetAuditUsageErrors, ThrowOnError>({
@@ -3153,7 +3193,7 @@ export class DenClient extends HeyApiClient {
/**
* Export one audit snapshot page
*
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the latest literal metadata.capabilities.auditLogs=true and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Exports ALL matching operations' children within the watermark in ascending tenant sequence, not date/ID order. Each response is one bounded attachment, not a continuous drain. Follow X-Audit-Next-Cursor with the same format and filters until that header is absent. X-Audit-Snapshot-Sequence stays fixed. NDJSON has one full envelope per line. CSV has a header on every page and summary fields only: references and changed-field names are JSON cells, no before/after content. Every cell is quoted; formula-leading whitespace/control and =+-@ are prefixed with an apostrophe, backslashes are doubled, controls/multiline characters are encoded as literal backslash-u escapes.
* Organization administrator access to currently captured, retained audit history only; this is not coverage of every cloud action. Requires the auditLogs feature to be on for the organization (read fresh) and deployment visibility; feature disable returns 403 audit_feature_disabled without deleting history or changing capture preference. Legacy arbitrary payloads are preserved separately and are not backfilled or returned. One operation may contain multiple child events. Visibility is independent of capture entitlement. No duration, charge or continuous-drain guarantee is made. Default limit 50, maximum 100. Cursors are signed, organization/filter/mode scoped and expire 24 hours after the first page (not renewed). Repeat the same filters; limit may change. The snapshotSequence is the committed tenant publication watermark, not a timestamp or auto-increment allocation. Events above it are excluded, including later children of an existing operation. Missing retained anchors or changed removal counters return 410 audit_history_unavailable; start a new snapshot. These checks are not lossless-drain or retention protection guarantees. Time filters are inclusive operation-start bounds (ISO date or offset date-time; date-only means UTC midnight). actorId is the initiating user ID; outcome is the current OPERATION outcome, not an event outcome. action matches an exact stable action of any child event within the watermark. searchId is an exact case-sensitive ID match (1..255 characters, no controls), not free-text search: operation ID OR any canonical retained child event ID, child envelope requestId or child resource reference ID, scoped to this organization and operation within the watermark. Legacy payloads are not searched. All other filters are AND combined with searchId. Resource filters match stored references within the watermark, without live-resource joins; resourceType requires resourceId. Operation outcome/count/byte projections remain current rather than historical as-of-watermark values. Exports ALL matching operations' children within the watermark in ascending tenant sequence, not date/ID order. Each response is one bounded attachment, not a continuous drain. Follow X-Audit-Next-Cursor with the same format and filters until that header is absent. X-Audit-Snapshot-Sequence stays fixed. NDJSON has one full envelope per line. CSV has a header on every page and summary fields only: references and changed-field names are JSON cells, no before/after content. Every cell is quoted; formula-leading whitespace/control and =+-@ are prefixed with an apostrophe, backslashes are doubled, controls/multiline characters are encoded as literal backslash-u escapes.
*/
public getAuditExport<ThrowOnError extends boolean = false>(
parameters?: {
@@ -14133,6 +14173,18 @@ export class DenClient extends HeyApiClient {
});
}
/**
* Get features for people without an organization
*
* On or off for every feature that is part of this deployment, for someone who is not signed in: the deployment-wide state after the kill switch and operator locks, with no organization overrides. A feature missing here is off.
*/
public getV1Features<ThrowOnError extends boolean = false>(options?: Options<never, ThrowOnError>) {
return (options?.client ?? this.client).get<GetV1FeaturesResponses, unknown, ThrowOnError>({
url: "/v1/features",
...options,
});
}
/**
* GitHub webhook ingress
*
+469
View File
@@ -141,6 +141,28 @@ export type NotFoundError = {
message?: string;
};
export type AdminFeature = {
key:
| "installLinks"
| "mcpConnections"
| "modelsAnalytics"
| "auditLogs"
| "orgManagedDashboards"
| "slackAssistant"
| "slackAssistantHeadless"
| "headlessAutomations"
| "workbot";
label: string;
description: string;
since: string;
deployments: Array<"cloud" | "self_hosted">;
default: boolean;
available: boolean;
enabled: boolean;
killed: boolean;
lock: boolean | null;
};
export type AdminPageInfo = {
total: number;
limit: number;
@@ -184,6 +206,92 @@ export type AdminOrganizationsPageResponse = {
*/
gatewayDashboard: true;
};
/**
* Per feature for this organization: whether it is on and why (not part of this deployment, kill switch, operator lock, organization override, or the deployment-wide on/off state), and whether an organization override would take effect.
*/
featureStates: {
installLinks: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
mcpConnections: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
modelsAnalytics: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
auditLogs: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
orgManagedDashboards: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistant: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistantHeadless: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
headlessAutomations: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
workbot: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
};
[key: string]: unknown;
}>;
page: AdminPageInfo;
@@ -262,6 +370,92 @@ export type AdminOverviewResponse = {
*/
gatewayDashboard: true;
};
/**
* Per feature for this organization: whether it is on and why (not part of this deployment, kill switch, operator lock, organization override, or the deployment-wide on/off state), and whether an organization override would take effect.
*/
featureStates: {
installLinks: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
mcpConnections: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
modelsAnalytics: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
auditLogs: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
orgManagedDashboards: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistant: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistantHeadless: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
headlessAutomations: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
workbot: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
};
[key: string]: unknown;
}>;
userPage: AdminPageInfo;
@@ -823,6 +1017,12 @@ export type OrganizationContextResponse = {
gatewayDashboard: true;
[key: string]: unknown;
};
/**
* Effective on/off for every OpenWork feature in this organization. Treat a missing key as off.
*/
features: {
[key: string]: boolean;
};
deploymentCapabilities: {
version: 1;
aiGateway: boolean;
@@ -4522,6 +4722,14 @@ export type DenAppVersionResponse = {
webUrl?: string;
};
export type PublicFeatures = {
version: 1;
deployment: "cloud" | "self_hosted";
features: {
[key: string]: boolean;
};
};
export type PluginArchGithubWebhookIgnoredResponse = {
ok: true;
accepted: false;
@@ -5324,6 +5532,92 @@ export type GetV1AdminOrganizationsByOrganizationIdCapabilitiesResponses = {
*/
gatewayDashboard: true;
};
/**
* Per feature for this organization: whether it is on and why (not part of this deployment, kill switch, operator lock, organization override, or the deployment-wide on/off state), and whether an organization override would take effect.
*/
featureStates: {
installLinks: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
mcpConnections: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
modelsAnalytics: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
auditLogs: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
orgManagedDashboards: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistant: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistantHeadless: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
headlessAutomations: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
workbot: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
};
};
};
@@ -5390,12 +5684,171 @@ export type PutV1AdminOrganizationsByOrganizationIdCapabilitiesResponses = {
*/
gatewayDashboard: true;
};
/**
* Per feature for this organization: whether it is on and why (not part of this deployment, kill switch, operator lock, organization override, or the deployment-wide on/off state), and whether an organization override would take effect.
*/
featureStates: {
installLinks: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
mcpConnections: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
modelsAnalytics: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
auditLogs: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
orgManagedDashboards: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistant: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
slackAssistantHeadless: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
headlessAutomations: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
workbot: {
enabled: boolean;
source: "unavailable" | "killed" | "lock" | "override" | "everyone";
everyone: boolean;
killed: boolean;
lock: boolean | null;
override: boolean | null;
overrideApplies: boolean;
};
};
};
};
export type PutV1AdminOrganizationsByOrganizationIdCapabilitiesResponse =
PutV1AdminOrganizationsByOrganizationIdCapabilitiesResponses[keyof PutV1AdminOrganizationsByOrganizationIdCapabilitiesResponses];
export type GetV1AdminFeaturesData = {
body?: never;
path?: never;
query?: never;
url: "/v1/admin/features";
};
export type GetV1AdminFeaturesErrors = {
/**
* The caller must be authenticated.
*/
401: UnauthorizedError;
/**
* The authenticated user is not an admin.
*/
403: ForbiddenError;
};
export type GetV1AdminFeaturesError = GetV1AdminFeaturesErrors[keyof GetV1AdminFeaturesErrors];
export type GetV1AdminFeaturesResponses = {
/**
* Features returned.
*/
200: {
deployment: "cloud" | "self_hosted";
features: Array<AdminFeature>;
};
};
export type GetV1AdminFeaturesResponse = GetV1AdminFeaturesResponses[keyof GetV1AdminFeaturesResponses];
export type PutV1AdminFeaturesByKeyData = {
body?: never;
path: {
key: string;
};
query?: never;
url: "/v1/admin/features/{key}";
};
export type PutV1AdminFeaturesByKeyErrors = {
/**
* The feature or body was invalid.
*/
400: {
error: "invalid_request";
message: string;
};
/**
* The caller must be authenticated.
*/
401: UnauthorizedError;
/**
* The authenticated user is not an admin.
*/
403: ForbiddenError;
};
export type PutV1AdminFeaturesByKeyError = PutV1AdminFeaturesByKeyErrors[keyof PutV1AdminFeaturesByKeyErrors];
export type PutV1AdminFeaturesByKeyResponses = {
/**
* Feature updated.
*/
200: {
ok: true;
feature: AdminFeature;
};
};
export type PutV1AdminFeaturesByKeyResponse = PutV1AdminFeaturesByKeyResponses[keyof PutV1AdminFeaturesByKeyResponses];
export type GetV1AdminUsersData = {
body?: never;
path?: never;
@@ -27007,6 +27460,22 @@ export type GetV1AppVersionResponses = {
export type GetV1AppVersionResponse = GetV1AppVersionResponses[keyof GetV1AppVersionResponses];
export type GetV1FeaturesData = {
body?: never;
path?: never;
query?: never;
url: "/v1/features";
};
export type GetV1FeaturesResponses = {
/**
* Features returned.
*/
200: PublicFeatures;
};
export type GetV1FeaturesResponse = GetV1FeaturesResponses[keyof GetV1FeaturesResponses];
export type PostV1WebhooksConnectorsGithubData = {
body?: never;
path?: never;
+2
View File
@@ -16,6 +16,7 @@ ENV PORT=8788
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml /app/
COPY patches /app/patches
COPY packages/types/package.json /app/packages/types/package.json
COPY packages/features/package.json /app/packages/features/package.json
COPY packages/free-auto/package.json /app/packages/free-auto/package.json
COPY packages/automations/package.json /app/packages/automations/package.json
COPY packages/codemode/package.json /app/packages/codemode/package.json
@@ -49,6 +50,7 @@ COPY ee/apps/den-api/package.json /app/ee/apps/den-api/package.json
RUN pnpm install --frozen-lockfile --trust-lockfile
COPY packages/types /app/packages/types
COPY packages/features /app/packages/features
COPY packages/free-auto /app/packages/free-auto
COPY packages/automations /app/packages/automations
COPY packages/codemode /app/packages/codemode
+2
View File
@@ -8,6 +8,7 @@ WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml /app/
COPY patches /app/patches
COPY packages/types/package.json /app/packages/types/package.json
COPY packages/features/package.json /app/packages/features/package.json
COPY packages/ui/package.json /app/packages/ui/package.json
COPY ee/packages/utils/package.json /app/ee/packages/utils/package.json
# Client-safe telemetry contracts: source-only package (no build step) that
@@ -19,6 +20,7 @@ COPY ee/apps/den-web/package.json /app/ee/apps/den-web/package.json
RUN pnpm install --frozen-lockfile --trust-lockfile --filter @openwork-ee/den-web...
COPY packages/types /app/packages/types
COPY packages/features /app/packages/features
COPY packages/ui /app/packages/ui
COPY ee/packages/utils /app/ee/packages/utils
COPY ee/packages/telemetry-contracts /app/ee/packages/telemetry-contracts
+2
View File
@@ -14,6 +14,7 @@ ENV PORT=8791
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml /app/
COPY patches /app/patches
COPY packages/types/package.json /app/packages/types/package.json
COPY packages/features/package.json /app/packages/features/package.json
COPY packages/free-auto/package.json /app/packages/free-auto/package.json
COPY ee/packages/utils/package.json /app/ee/packages/utils/package.json
COPY ee/packages/den-db/package.json /app/ee/packages/den-db/package.json
@@ -24,6 +25,7 @@ COPY ee/apps/gateway/package.json /app/ee/apps/gateway/package.json
RUN pnpm install --frozen-lockfile --trust-lockfile
COPY packages/types /app/packages/types
COPY packages/features /app/packages/features
COPY packages/free-auto /app/packages/free-auto
COPY ee/packages/utils /app/ee/packages/utils
COPY ee/packages/den-db /app/ee/packages/den-db
+44
View File
@@ -299,6 +299,50 @@ helm upgrade --install openwork-ee ./packaging/helm/openwork-ee \
-f values.prod.yaml
```
### Features
OpenWork features are declared once, in `packages/features/src/registry.ts`,
and rolled out along several dimensions: which products a feature exists on,
on or off for everyone, per-organization overrides, and a kill switch.
Platform admins change these in `/admin` without a redeploy. As the operator,
you can also lock a feature for the whole install under `config.features`:
```yaml
config:
features:
orgManagedDashboards: "true" # on for everyone on this install
installLinks: "false" # off for everyone on this install
```
- `""` (the default) follows `/admin`, which starts from the default listed
below.
- `"true"` or `"false"` locks the feature for everyone. `/admin` shows "Set by
deployment config" for it. The `/admin` kill switch still turns it off.
Each key renders `DEN_FEATURE_<KEY>` for den-api. Features that are not part
of self-hosted installs have no key, so they can't be turned on here. A key
that isn't listed below fails `helm install` through `values.schema.json`.
`config.deployment` (`DEN_DEPLOYMENT`) is `self_hosted` unless this is
OpenWork Cloud. Don't change it on a customer install.
<!-- BEGIN GENERATED features (pnpm features:sync) -->
| `config.features.*` | Environment variable | Default | What it does |
| --- | --- | --- | --- |
| `installLinks` | `DEN_FEATURE_INSTALL_LINKS` | default on | Workspace admins can create desktop install links for their organization. |
| `mcpConnections` | `DEN_FEATURE_MCP_CONNECTIONS` | default on | Members see the organization's connections, marketplace capabilities on the agent rail, and the desktop Connect tab. |
| `modelsAnalytics` | `DEN_FEATURE_MODELS_ANALYTICS` | default off | Organization admins can opt in to task analytics for OpenWork Models. |
| `auditLogs` | `DEN_FEATURE_AUDIT_LOGS` | default off | Organization admins can read and configure audit logs. Capture still needs an audit entitlement. |
| `orgManagedDashboards` | `DEN_FEATURE_ORG_MANAGED_DASHBOARDS` | default off | Organization admins publish dashboards to members in Den and the desktop app. |
| `slackAssistant` | `DEN_FEATURE_SLACK_ASSISTANT` | default off | Answers Slack mentions and DMs for the organization after the Slack connector is set up. |
| `slackAssistantHeadless` | `DEN_FEATURE_SLACK_ASSISTANT_HEADLESS` | default off | Answers Slack on the shared headless runner instead of each member's OpenWork Web computer. Needs the deployment's headless runner. |
| `headlessAutomations` | `DEN_FEATURE_HEADLESS_AUTOMATIONS` | default off | Runs the organization's cloud Automations on the shared headless runner. Needs the deployment's headless runner and a plan that includes it. |
| `workbot` | `DEN_FEATURE_WORKBOT` | default off | Members can use Workbot. Needs the deployment's Workbot app. |
<!-- END GENERATED features -->
The table and the `config.features` block are generated: run `pnpm features:sync`
after changing the registry.
### Automations rollout
The Helm chart advertises Automations as unavailable by default for self-hosted
@@ -16,6 +16,14 @@ data:
# prefer rediss:// whenever the provider supports TLS.
DATABASE_REDIS_ALLOW_INSECURE_INTERNAL: {{ ternary "1" "0" .Values.redis.allowInsecureInternal | quote }}
DB_MODE: {{ .Values.config.databaseMode | quote }}
# Feature registry: packages/features/src/registry.ts. Keys come from the
# generated config.features block; never add per-feature lines here.
DEN_DEPLOYMENT: {{ .Values.config.deployment | default "self_hosted" | quote }}
{{- range $key, $value := .Values.config.features }}
{{- if ne (toString $value) "" }}
DEN_FEATURE_{{ $key | snakecase | upper }}: {{ toString $value | quote }}
{{- end }}
{{- end }}
DEN_ORG_MODE: {{ .Values.config.tenancy.mode | quote }}
DEN_SINGLE_ORG_NAME: {{ .Values.config.tenancy.singleOrgName | quote }}
DEN_SINGLE_ORG_SLUG: {{ .Values.config.tenancy.singleOrgSlug | quote }}
@@ -0,0 +1,116 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$comment": "Generated by pnpm features:sync from packages/features/src/registry.ts. Only config.deployment and config.features are constrained.",
"type": "object",
"properties": {
"config": {
"type": "object",
"properties": {
"deployment": {
"type": "string",
"enum": [
"cloud",
"self_hosted"
],
"description": "Which product this install is. Only OpenWork Cloud sets \"cloud\". Renders DEN_DEPLOYMENT."
},
"features": {
"type": "object",
"additionalProperties": false,
"properties": {
"installLinks": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Install links: Workspace admins can create desktop install links for their organization. Renders DEN_FEATURE_INSTALL_LINKS."
},
"mcpConnections": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "OpenWork Connect: Members see the organization's connections, marketplace capabilities on the agent rail, and the desktop Connect tab. Renders DEN_FEATURE_MCP_CONNECTIONS."
},
"modelsAnalytics": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "OpenWork Models task analytics: Organization admins can opt in to task analytics for OpenWork Models. Renders DEN_FEATURE_MODELS_ANALYTICS."
},
"auditLogs": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Audit logs: Organization admins can read and configure audit logs. Capture still needs an audit entitlement. Renders DEN_FEATURE_AUDIT_LOGS."
},
"orgManagedDashboards": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Dashboards: Organization admins publish dashboards to members in Den and the desktop app. Renders DEN_FEATURE_ORG_MANAGED_DASHBOARDS."
},
"slackAssistant": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Slack Assistant: Answers Slack mentions and DMs for the organization after the Slack connector is set up. Renders DEN_FEATURE_SLACK_ASSISTANT."
},
"slackAssistantHeadless": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Slack Assistant: headless runtime: Answers Slack on the shared headless runner instead of each member's OpenWork Web computer. Needs the deployment's headless runner. Renders DEN_FEATURE_SLACK_ASSISTANT_HEADLESS."
},
"headlessAutomations": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Cloud Automations: headless runtime: Runs the organization's cloud Automations on the shared headless runner. Needs the deployment's headless runner and a plan that includes it. Renders DEN_FEATURE_HEADLESS_AUTOMATIONS."
},
"workbot": {
"enum": [
"",
"true",
"false",
true,
false
],
"description": "Workbot: Members can use Workbot. Needs the deployment's Workbot app. Renders DEN_FEATURE_WORKBOT."
}
}
}
}
}
}
}
+21 -1
View File
@@ -16,6 +16,26 @@ config:
openworkDevMode: "0"
# Passed to the den-api Node.js process as NODE_OPTIONS at container startup.
denApiNodeOptions: ""
# Which product this install is. Only OpenWork Cloud sets "cloud"; features
# declared unavailable for self-hosted cannot be turned on here. Renders DEN_DEPLOYMENT.
deployment: self_hosted
# BEGIN GENERATED features (pnpm features:sync; source: packages/features/src/registry.ts)
# Operator locks for this install. Each key renders DEN_FEATURE_<KEY>.
# "" follow /admin: on or off for everyone, plus per-organization overrides
# "true" on for everyone; /admin shows "Set by deployment config"
# "false" off for everyone; /admin shows "Set by deployment config"
# The /admin kill switch still turns a feature off, even when locked on.
features:
installLinks: "" # default on · Workspace admins can create desktop install links for their organization.
mcpConnections: "" # default on · Members see the organization's connections, marketplace capabilities on the agent rail, and the desktop Connect tab.
modelsAnalytics: "" # default off · Organization admins can opt in to task analytics for OpenWork Models.
auditLogs: "" # default off · Organization admins can read and configure audit logs. Capture still needs an audit entitlement.
orgManagedDashboards: "" # default off · Organization admins publish dashboards to members in Den and the desktop app.
slackAssistant: "" # default off · Answers Slack mentions and DMs for the organization after the Slack connector is set up.
slackAssistantHeadless: "" # default off · Answers Slack on the shared headless runner instead of each member's OpenWork Web computer. Needs the deployment's headless runner.
headlessAutomations: "" # default off · Runs the organization's cloud Automations on the shared headless runner. Needs the deployment's headless runner and a plan that includes it.
workbot: "" # default off · Members can use Workbot. Needs the deployment's Workbot app.
# END GENERATED features
tenancy:
mode: single_org
singleOrgName: OpenWork
@@ -28,7 +48,7 @@ config:
selfHostedEnabled: "false"
# Rollout gates; org admins separately control capture on their initialized policy.
# Default-on deployment switches; explicit false disables globally.
# Also requires metadata.capabilities.auditLogs=true per org plus entitlement.
# Also requires the auditLogs feature per org (/admin or config.features) plus entitlement.
# Ready orgs auto-provision 6M retained operations, capture ON, no cap enforcement.
# Existing policy values and explicit capture OFF choices are preserved.
captureEnabled: "true"
+25
View File
@@ -608,6 +608,9 @@ importers:
'@openwork/enterprise-mcp-client':
specifier: workspace:*
version: link:../../../packages/enterprise-mcp-client
'@openwork/features':
specifier: workspace:*
version: link:../../../packages/features
'@openwork/free-auto':
specifier: workspace:*
version: link:../../../packages/free-auto
@@ -805,6 +808,9 @@ importers:
'@openwork-ee/utils':
specifier: workspace:*
version: link:../../packages/utils
'@openwork/features':
specifier: workspace:*
version: link:../../../packages/features
'@openwork/types':
specifier: workspace:*
version: link:../../../packages/types
@@ -1179,6 +1185,9 @@ importers:
'@openwork-ee/utils':
specifier: workspace:*
version: link:../utils
'@openwork/features':
specifier: workspace:*
version: link:../../../packages/features
'@openwork/types':
specifier: workspace:*
version: link:../../../packages/types
@@ -1254,6 +1263,9 @@ importers:
'@openwork-ee/utils':
specifier: workspace:*
version: link:../utils
'@openwork/features':
specifier: workspace:*
version: link:../../../packages/features
devDependencies:
'@types/node':
specifier: ^20.11.30
@@ -1500,6 +1512,19 @@ importers:
specifier: ^5.6.3
version: 5.9.3
packages/features:
dependencies:
zod:
specifier: ^4.3.6
version: 4.3.6
devDependencies:
'@types/node':
specifier: ^20.11.30
version: 20.12.12
typescript:
specifier: ^5.6.3
version: 5.9.3
packages/free-auto:
dependencies:
'@openwork/types':
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env node
// Fast guard (file reads only, no Docker or pnpm) for the Dockerfiles in
// packaging/docker that copy workspace packages one by one for layer caching.
// A package that gains a dependency on another workspace package must have
// that package copied too:
//
// 1. Every workspace dependency of a copied package.json must have its own
// package.json copied, or `pnpm install` in the image fails.
// 2. Every runtime workspace dependency (`dependencies`) of a copied source
// folder must be copied as source too, or the import fails at runtime.
//
// Run directly or through `pnpm features:check`.
import { existsSync, readdirSync, readFileSync } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]
function readJson(file) {
return JSON.parse(readFileSync(file, "utf8"))
}
/** name -> repo-relative directory, from the simple "dir/*" globs in pnpm-workspace.yaml. */
function workspacePackages(root) {
const yaml = readFileSync(path.join(root, "pnpm-workspace.yaml"), "utf8")
const block = /^packages:\n((?:\s+-\s+.+\n)+)/m.exec(yaml)
if (!block) throw new Error("pnpm-workspace.yaml has no packages list")
const globs = [...block[1].matchAll(/-\s+["']?([^"'\n]+?)["']?\s*$/gm)].map((match) => match[1])
const byName = new Map()
for (const glob of globs) {
if (!glob.endsWith("/*")) throw new Error(`Unsupported workspace glob "${glob}"; extend scripts/check-docker-workspace-packages.mjs`)
const parent = glob.slice(0, -2)
const absolute = path.join(root, parent)
if (!existsSync(absolute)) continue
for (const entry of readdirSync(absolute)) {
const manifest = path.join(absolute, entry, "package.json")
if (!existsSync(manifest)) continue
const name = readJson(manifest).name
if (typeof name === "string") byName.set(name, `${parent}/${entry}`)
}
}
return byName
}
function workspaceDependencies(root, dir, fields) {
const manifest = readJson(path.join(root, dir, "package.json"))
const names = []
for (const field of fields) {
for (const [name, version] of Object.entries(manifest[field] ?? {})) {
if (typeof version === "string" && version.startsWith("workspace:")) names.push(name)
}
}
return names
}
export function checkDockerWorkspacePackages(root) {
const problems = []
const packages = workspacePackages(root)
const dirs = new Set(packages.values())
const dockerDir = path.join(root, "packaging/docker")
for (const file of readdirSync(dockerDir).filter((entry) => entry.startsWith("Dockerfile")).sort()) {
const text = readFileSync(path.join(dockerDir, file), "utf8")
const manifests = new Set()
const sources = new Set()
for (const match of text.matchAll(/^COPY\s+(\S+)\s+\/app\/(\S+)\s*$/gm)) {
const [, from, to] = match
if (from !== to) continue
if (from.endsWith("/package.json")) manifests.add(from.slice(0, -"/package.json".length))
else if (dirs.has(from)) sources.add(from)
}
if (manifests.size === 0) continue // builds from the whole repository
const label = `packaging/docker/${file}`
for (const dir of manifests) {
if (!dirs.has(dir)) continue
for (const name of workspaceDependencies(root, dir, DEPENDENCY_FIELDS)) {
const needed = packages.get(name)
if (needed && !manifests.has(needed)) {
problems.push(`${label}: ${dir} depends on ${name}; add \`COPY ${needed}/package.json /app/${needed}/package.json\` before \`pnpm install\`.`)
}
}
}
for (const dir of sources) {
for (const name of workspaceDependencies(root, dir, ["dependencies"])) {
const needed = packages.get(name)
if (needed && !sources.has(needed)) {
problems.push(`${label}: ${dir} imports ${name} at runtime; add \`COPY ${needed} /app/${needed}\`.`)
}
}
}
}
return problems
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
const started = performance.now()
const problems = checkDockerWorkspacePackages(root)
for (const problem of problems) console.error(`[docker] ${problem}`)
console.log(`[docker] ${problems.length === 0 ? "Dockerfiles copy every workspace package they need" : `${problems.length} problem(s)`} (${Math.round(performance.now() - started)} ms)`)
process.exit(problems.length === 0 ? 0 : 1)
}
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env node
// Keeps everything derived from the feature registry in step with it.
//
// pnpm features:sync regenerate the Helm chart's feature block, values
// schema and README table from
// packages/features/src/registry.ts
// pnpm features:check fail if those files are stale, if the chart renders
// different DEN_FEATURE_* names than den-api reads, if
// a Dockerfile misses a workspace package its service
// needs, or if code bypasses the registry (see below)
//
// Read .opencode/skills/add-a-feature/SKILL.md before adding a feature.
import { execFileSync } from "node:child_process"
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import {
FEATURES,
FEATURE_KEYS,
featureAvailableOn,
featureLockEnvName,
} from "../packages/features/src/index.ts"
import { checkDockerWorkspacePackages } from "./check-docker-workspace-packages.mjs"
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
const chartDir = path.join(root, "packaging/helm/openwork-ee")
const valuesPath = path.join(chartDir, "values.yaml")
const schemaPath = path.join(chartDir, "values.schema.json")
const readmePath = path.join(chartDir, "README.md")
const check = process.argv.includes("--check")
const BEGIN = "# BEGIN GENERATED features (pnpm features:sync; source: packages/features/src/registry.ts)"
const END = "# END GENERATED features"
const README_BEGIN = "<!-- BEGIN GENERATED features (pnpm features:sync) -->"
const README_END = "<!-- END GENERATED features -->"
/** Keys an operator can lock: every feature that exists on at least one deployment. */
const helmKeys = FEATURE_KEYS.filter((key) => featureAvailableOn(key, "self_hosted") || featureAvailableOn(key, "cloud"))
function defaultLabel(key) {
const scope = featureAvailableOn(key, "self_hosted") ? "" : " (cloud only)"
return `default ${FEATURES[key].default ? "on" : "off"}${scope}`
}
function valuesBlock() {
const width = Math.max(...helmKeys.map((key) => key.length)) + 5
const lines = [
` ${BEGIN}`,
" # Operator locks for this install. Each key renders DEN_FEATURE_<KEY>.",
" # \"\" follow /admin: on or off for everyone, plus per-organization overrides",
" # \"true\" on for everyone; /admin shows \"Set by deployment config\"",
" # \"false\" off for everyone; /admin shows \"Set by deployment config\"",
" # The /admin kill switch still turns a feature off, even when locked on.",
" features:",
...helmKeys.map((key) => ` ${`${key}: ""`.padEnd(width)}# ${defaultLabel(key)} · ${FEATURES[key].description}`),
` ${END}`,
]
return lines.join("\n")
}
function renderValues(current) {
const start = current.indexOf(` ${BEGIN}`)
const end = current.indexOf(` ${END}`)
if (start === -1 || end === -1) {
throw new Error(`${path.relative(root, valuesPath)} is missing the generated features markers.`)
}
return current.slice(0, start) + valuesBlock() + current.slice(end + ` ${END}`.length)
}
function renderSchema() {
const schema = {
$schema: "http://json-schema.org/draft-07/schema#",
$comment: "Generated by pnpm features:sync from packages/features/src/registry.ts. Only config.deployment and config.features are constrained.",
type: "object",
properties: {
config: {
type: "object",
properties: {
deployment: {
type: "string",
enum: ["cloud", "self_hosted"],
description: "Which product this install is. Only OpenWork Cloud sets \"cloud\". Renders DEN_DEPLOYMENT.",
},
features: {
type: "object",
additionalProperties: false,
properties: Object.fromEntries(helmKeys.map((key) => [key, {
// --set turns "true" into a boolean, so accept both spellings.
enum: ["", "true", "false", true, false],
description: `${FEATURES[key].label}: ${FEATURES[key].description} Renders ${featureLockEnvName(key)}.`,
}])),
},
},
},
},
}
return `${JSON.stringify(schema, null, 2)}\n`
}
function renderReadme(current) {
const start = current.indexOf(README_BEGIN)
const end = current.indexOf(README_END)
if (start === -1 || end === -1) {
throw new Error(`${path.relative(root, readmePath)} is missing the generated features markers.`)
}
const rows = helmKeys.map((key) => `| \`${key}\` | \`${featureLockEnvName(key)}\` | ${defaultLabel(key)} | ${FEATURES[key].description} |`)
const table = [
README_BEGIN,
"| `config.features.*` | Environment variable | Default | What it does |",
"| --- | --- | --- | --- |",
...rows,
README_END,
].join("\n")
return current.slice(0, start) + table + current.slice(end + README_END.length)
}
const problems = []
function compareOrWrite(filePath, next) {
const current = readFileSync(filePath, "utf8").toString()
if (current === next) return
if (check) problems.push(`${path.relative(root, filePath)} is out of date. Run \`pnpm features:sync\` and commit the result.`)
else writeFileSync(filePath, next)
}
compareOrWrite(valuesPath, renderValues(readFileSync(valuesPath, "utf8")))
compareOrWrite(readmePath, renderReadme(readFileSync(readmePath, "utf8")))
let schemaCurrent = ""
try {
schemaCurrent = readFileSync(schemaPath, "utf8")
} catch {
schemaCurrent = ""
}
if (schemaCurrent !== renderSchema()) {
if (check) problems.push(`${path.relative(root, schemaPath)} is out of date. Run \`pnpm features:sync\` and commit the result.`)
else writeFileSync(schemaPath, renderSchema())
}
if (check) {
// Registry rules.
const now = new Date()
for (const key of FEATURE_KEYS) {
const definition = FEATURES[key]
if (!/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/.test(key)) {
problems.push(`Feature key "${key}" must be lowerCamelCase with no consecutive capitals (it becomes ${featureLockEnvName(key)}).`)
}
if (!definition.label.trim() || !definition.description.trim()) problems.push(`Feature "${key}" needs a label and a description.`)
const since = /^(\d{4})-(\d{2})$/.exec(definition.since)
if (!since) {
problems.push(`Feature "${key}" since must be "YYYY-MM".`)
continue
}
if (definition.deployments.length === 0) problems.push(`Feature "${key}" must exist on at least one deployment.`)
const ageMonths = (now.getUTCFullYear() - Number(since[1])) * 12 + (now.getUTCMonth() + 1 - Number(since[2]))
if (!definition.permanent && ageMonths > 6) {
problems.push(`Feature "${key}" has been a rollout since ${definition.since}. Finish it and delete the flag and its checks, or mark it permanent: true if the switch is part of the product (see .opencode/skills/add-a-feature).`)
}
}
// The chart must render exactly the variable names den-api reads.
let helmAvailable = true
try {
execFileSync("helm", ["version", "--short"], { stdio: "ignore" })
} catch {
helmAvailable = false
}
const chartStale = problems.some((problem) => problem.includes("out of date"))
if (helmAvailable && !chartStale) {
const setArgs = helmKeys.flatMap((key) => ["--set-string", `config.features.${key}=true`])
let rendered = ""
try {
rendered = execFileSync("helm", ["template", "features-check", chartDir, "--show-only", "templates/configmap.yaml", ...setArgs], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] })
} catch (error) {
const stderr = error && typeof error === "object" && "stderr" in error ? String(error.stderr) : String(error)
problems.push(`helm template failed with every feature key set: ${stderr.trim()}`)
}
const renderedNames = new Set([...rendered.matchAll(/^\s+(DEN_FEATURE_[A-Z0-9_]+):/gm)].map((match) => match[1]))
for (const key of helmKeys) {
if (!renderedNames.has(featureLockEnvName(key))) {
problems.push(`Helm renders no ${featureLockEnvName(key)} for config.features.${key}; den-api would never see it.`)
}
}
for (const name of renderedNames) {
if (!helmKeys.some((key) => featureLockEnvName(key) === name)) problems.push(`Helm renders ${name}, which den-api does not read.`)
}
if (!/^\s+DEN_DEPLOYMENT: "self_hosted"$/m.test(rendered)) problems.push("Helm must render DEN_DEPLOYMENT, defaulting to self_hosted.")
} else if (!helmAvailable) {
console.warn("[features] helm is not installed; skipped the chart render check.")
}
// Images that copy workspace packages one by one must copy every one they need.
problems.push(...checkDockerWorkspacePackages(root))
// No new deployment-wide feature switches: declare a feature instead.
const allowedEnableFlags = new Set([
"DEN_APP_MCP_SERVERS_ENABLED", "DEN_AUDIT_CAPTURE_ENABLED", "DEN_AUDIT_SELF_HOSTED_ENABLED", "DEN_AUDIT_VISIBILITY_ENABLED",
"DEN_AUTOMATIONS_ENABLED", "DEN_AUTOMATIONS_RUNTIME_ENABLED", "DEN_BOTID_PROTECTION_ENABLED", "DEN_DASHBOARDS_ENABLED",
"DEN_GENERATED_ARTIFACT_VIEWS_ENABLED", "DEN_OPENWORK_WEB_ENABLED", "DEN_PASSWORD_BREACH_SCREENING_ENABLED",
"DEN_PLAN_GATING_ENABLED", "DEN_SLACK_ASSISTANT_WORKER_ENABLED",
])
function* sourceFiles(dir) {
for (const entry of readdirSync(dir)) {
if (entry === "node_modules" || entry === "dist" || entry === ".next" || entry === "drizzle" || entry === "gen") continue
const full = path.join(dir, entry)
if (statSync(full).isDirectory()) yield* sourceFiles(full)
else if (/\.(ts|tsx|mjs)$/.test(entry)) yield full
}
}
// Feature overrides live in the organization_feature table; only the store
// (and the one-release rollback copy) may touch metadata.capabilities.
const metadataCapabilitiesAllowed = new Set([
"ee/packages/den-db/src/organization-features.ts",
"ee/apps/den-api/src/orgs.ts",
])
for (const dir of ["ee/apps/den-api/src", "ee/apps/den-web/app", "ee/apps/den-web/components", "ee/apps/gateway/src", "ee/packages", "apps/app/src", "apps/server/src"]) {
const absolute = path.join(root, dir)
try {
statSync(absolute)
} catch {
continue
}
for (const file of sourceFiles(absolute)) {
const relative = path.relative(root, file)
const text = readFileSync(file, "utf8")
if (relative.startsWith("ee/apps/den-api/src")) {
for (const match of text.matchAll(/\bDEN_[A-Z0-9_]+_ENABLED\b/g)) {
if (!allowedEnableFlags.has(match[0])) {
problems.push(`${relative}: new switch ${match[0]}. Declare a feature in packages/features/src/registry.ts instead (see .opencode/skills/add-a-feature).`)
}
}
}
if (!metadataCapabilitiesAllowed.has(relative) && /metadata\)?\??\.capabilities\b|\$\.capabilities/.test(text)) {
problems.push(`${relative}: reads organization metadata.capabilities. Use getOrganizationFeatures() / orgFeatureEnabled() instead.`)
}
}
}
}
if (problems.length > 0) {
for (const problem of [...new Set(problems)]) console.error(`[features] ${problem}`)
process.exit(1)
}
console.log(check ? "[features] Registry, Helm chart and guard rules are in sync." : "[features] Helm chart files regenerated.")