Skip to content

Commit 4882bcf

Browse files
author
ben
authored
feat(den): let admins choose the default model for cloud agents (#5845)
* feat(den): let admins choose the default model for cloud agents Adds Manage › Workbot in Den with one organization default model, behind workbotDefaultModel (cloud and self-hosted, off). Workbot sends it on every turn, the Slack assistant uses it instead of its installation model, and cloud Automations on the cloud default run on it; Automations with their own model keep it. A saved model the runner no longer serves falls back to the runner default. With the feature off everything behaves as before. * fix(den-web): show the full saved model name in Workbot settings
1 parent c39bbb5 commit 4882bcf

36 files changed

Lines changed: 1692 additions & 16 deletions

File tree

‎.github/workflows/ci-tests.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ jobs:
107107
pnpm --filter @openwork-ee/utils test
108108
pnpm --filter @openwork/automations test
109109
pnpm --filter @openwork-ee/den-api test
110+
pnpm --filter @openwork-ee/workbot test:model
110111
- name: Check sandbox contracts and adapters (no cloud resources)
111112
run: |
112113
pnpm --filter @openwork/sandbox build

‎ee/apps/den-api/src/audit/COVERAGE.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Generated by `pnpm --filter @openwork-ee/den-api audit:coverage --write` from `src/audit/routes`. Do not edit by hand; CI fails when this file is stale.
44

5-
- 569 den-api route keys (`app.routes`), 143 HTTP-reachable better-auth endpoints, 694 declarations.
5+
- 571 den-api route keys (`app.routes`), 143 HTTP-reachable better-auth endpoints, 696 declarations.
66
- Tenant capture requires the trusted organization's `auditLogs` feature (features registry, read fresh), `DEN_AUDIT_CAPTURE_ENABLED`, an enabled policy and the class category; with capture off no audit database work happens.
77
- Request evidence: declared resource type, validated path-parameter id (`unparseable` otherwise) or `collection:<type>`, parent organization, method, route template and status. Never bodies, query strings, headers, IPs or secrets.
88
- One operation per request: intent, outcome and domain change events (`appendAuditChanges`) share it. Requests without trustworthy tenant attribution go to `platform_audit_event` (no organization column, not tenant-visible) with a target: the declared resource type plus validated path id, else the first handler-named resource; an organization target only when it is the authenticated context's organization.
@@ -14,9 +14,9 @@ Generated by `pnpm --filter @openwork-ee/den-api audit:coverage --write` from `s
1414

1515
| Class | Declarations | Capture policy | Event types | Failure behaviour |
1616
|---|---|---|---|---|
17-
| tenant_read | 133 | served before release (category read, off by default) | .served .attempted | capture-start failure: served without capture; served append after capture started: up to 3 attempts on transient database errors, then 503, no content |
17+
| tenant_read | 134 | served before release (category read, off by default) | .served .attempted | capture-start failure: served without capture; served append after capture started: up to 3 attempts on transient database errors, then 503, no content |
1818
| tenant_access | 48 | requested before handler; served before release (access) | .requested .served .attempted | intent or served: up to 3 attempts on transient database errors, then 503, no content |
19-
| tenant_change | 211 | requested before handler; succeeded/attempted after (request) | .requested .succeeded .attempted | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] |
19+
| tenant_change | 212 | requested before handler; succeeded/attempted after (request) | .requested .succeeded .attempted | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] |
2020
| tenant_external | 83 | requested before handler; confirmed/attempted, 5xx unknown (request) | .requested .confirmed .attempted .unknown | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] |
2121
| tenant_job | 10 | requested before handler; accepted/attempted after (execution) | .requested .accepted .attempted | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] |
2222
| tenant_signal | 11 | one outcome after handler: observed/attempted (category read, off by default; denials use security when selected); no intent | .observed .attempted | never fail-closed: capture-start failure served without capture; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] |
@@ -777,6 +777,8 @@ When tenant capture is active the domain emitter appends the new change event in
777777
| GET | `/v1/org/web-origins` | tenant_read | `web_origin.list` | web_origin.management | web_origin | org_context | served before release (category read, off by default) | request evidence only | capture-start failure: served without capture; served append after capture started: up to 3 attempts on transient database errors, then 503, no content | |
778778
| POST | `/v1/org/web-origins` | tenant_change | `web_origin.approve` | web_origin.management | web_origin | org_context | requested before handler; succeeded/attempted after (request) | audit/domain/web-origins.ts | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] | Legacy organization.web_origin.approved. |
779779
| DELETE | `/v1/org/web-origins/:webOriginId` | tenant_change | `web_origin.remove` | web_origin.management | web_origin (:webOriginId) | org_context | requested before handler; succeeded/attempted after (request) | audit/domain/web-origins.ts | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] | Legacy organization.web_origin.removed. |
780+
| GET | `/v1/org/workbot-settings` | tenant_read | `workbot.settings.read` | organization.settings | organization | org_context | served before release (category read, off by default) | request evidence only | capture-start failure: served without capture; served append after capture started: up to 3 attempts on transient database errors, then 503, no content | |
781+
| PUT | `/v1/org/workbot-settings` | tenant_change | `workbot.settings.update` | organization.settings | organization | org_context | requested before handler; succeeded/attempted after (request) | request evidence only | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] | Sets organization metadata workbot.model (the default model for Workbot, the Slack assistant and cloud-default Automations); the headless runner model catalog read is incidental. |
780782
| POST | `/v1/orgs/:organizationId/install-links` | tenant_change | `install_link.create` | install.distribution | install_link | org_context | requested before handler; succeeded/attempted after (request) | request evidence only | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] | Path organizationId only seeds context; attribute to organizationContext. Returns the install token; rotate revokes older links. |
781783
| ALL | `/v1/orgs/:orgId/*` | proxy | `legacy_org.proxy` | request.proxy | organization (:orgId) | none | destination route records | | none | delegatedRoute legacy org proxy re-dispatches through app.fetch; the destination route records. |
782784
| POST | `/v1/orgs/invitations/accept` | tenant_external | `invitation.accept` | invitation.management | invitation | handler | requested before handler; confirmed/attempted, 5xx unknown (request) | request evidence only | intent: up to 3 attempts on transient database errors, then 503, handler not run; outcome: up to 3 attempts on transient database errors, then logged [audit-outcome-lost] | external: stripe (seat/web/inference quantity sync via runPostOrganizationMemberChangeHooks); Org proof: pending invitation row whose email matches the verified session user -> invitation.organizationId; attributed through acceptInvitationForUser beforeEffect (before any write). Actor = invitee user without a member id (not yet a member). |

‎ee/apps/den-api/src/audit/coverage.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ export const orgAuditCoverage: Readonly<Record<string, AuditCoverageDeclaration>
199199
"sso.ts": bridged(["organization.sso.connection_registered", "organization.sso.connection_enabled", "organization.sso.connection_disabled", "organization.sso.connection_deleted"], ["sso_connection"]),
200200
"teams.ts": routes("Team and membership management."),
201201
"web-origins.ts": bridged(["organization.web_origin.approved", "organization.web_origin.removed"], ["web_origin"]),
202+
"workbot-settings.ts": routes("Workbot default model setting (organization metadata)."),
202203
}
203204

204205
function boundary(limitations: string): AuditCoverageDeclaration {

‎ee/apps/den-api/src/audit/routes/org.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ export const orgAuditRoutes: readonly AuditRouteDeclaration[] = [
111111
member("GET", "/v1/org/web-origins", "tenant_read", "web_origin.list", "web_origin.management", "web_origin", null),
112112
member("POST", "/v1/org/web-origins", "tenant_change", "web_origin.approve", "web_origin.management", "web_origin", null, { changeEvidence: DOMAIN("web-origins"), notes: "Legacy organization.web_origin.approved." }),
113113
member("DELETE", "/v1/org/web-origins/:webOriginId", "tenant_change", "web_origin.remove", "web_origin.management", "web_origin", "webOriginId", { changeEvidence: DOMAIN("web-origins"), notes: "Legacy organization.web_origin.removed." }),
114+
member("GET", "/v1/org/workbot-settings", "tenant_read", "workbot.settings.read", "organization.settings", "organization", null),
115+
member("PUT", "/v1/org/workbot-settings", "tenant_change", "workbot.settings.update", "organization.settings", "organization", null, { notes: "Sets organization metadata workbot.model (the default model for Workbot, the Slack assistant and cloud-default Automations); the headless runner model catalog read is incidental." }),
114116

115117
// SCIM management
116118
member("GET", "/v1/scim", "tenant_read", "scim.connection.read", "scim.configuration", "scim_connection", null),

‎ee/apps/den-api/src/automations/headless-agent-executor.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import { DEN_MCP_HEADLESS_RUN_TOKEN_MAX_TTL_MS } from "../mcp/headless-run-token.js"
1717
import type { CloudAgentEvent, CloudAgentExecution, CloudAgentExecutorInput } from "./cloud-agent-executor.js"
1818
import { cloudAutomationRuntime } from "./headless-runtime.js"
19+
import { organizationDefaultModel } from "../workbot/model.js"
1920

2021
/**
2122
* Runs one cloud agent Automation on the shared headless runner.
@@ -56,6 +57,8 @@ export type HeadlessAgentExecutorDeps = {
5657
ownerUserId: (scope: OwnerScope) => Promise<string | null>
5758
/** Live check that the organization still runs Automations headless. */
5859
stillHeadless: (organizationId: string) => Promise<boolean>
60+
/** The organization's default model for runs on the cloud default (workbotDefaultModel); null: the runner's. */
61+
defaultModel: (organizationId: string) => Promise<string | null>
5962
sleep: (ms: number, signal: AbortSignal) => Promise<void>
6063
pollIntervalMs: number
6164
}
@@ -105,6 +108,7 @@ function defaultDeps(): HeadlessAgentExecutorDeps {
105108
client: runner ? createHeadlessRunnerClient(runner) : null,
106109
ownerUserId,
107110
stillHeadless: async (organizationId) => (await cloudAutomationRuntime(organizationId)) === "headless",
111+
defaultModel: (organizationId) => organizationDefaultModel(organizationId),
108112
sleep: abortableSleep,
109113
pollIntervalMs: POLL_INTERVAL_MS,
110114
}
@@ -186,10 +190,16 @@ function turnFailure(turn: RunnerTurn, messages: RunnerMessage[]): CloudAgentExe
186190

187191
/**
188192
* The member's own selection when the runner can serve it, otherwise the
189-
* runner's default model. Either way the run records which model it used.
193+
* runner's default model. An Automation on the cloud default runs on the
194+
* organization's default model when admins chose one, else the runner's
195+
* default. Either way the run records which model it used.
190196
*/
191-
async function chooseModel(client: HeadlessRunnerClient, model: { providerId: string; modelId: string }) {
192-
if (isAutomationCloudDefaultModel(model)) return { model: undefined, warning: null }
197+
export async function chooseModel(
198+
client: Pick<HeadlessRunnerClient, "listModels">,
199+
model: { providerId: string; modelId: string },
200+
organizationModel: string | null = null,
201+
) {
202+
if (isAutomationCloudDefaultModel(model)) return { model: organizationModel ?? undefined, warning: null }
193203
const modelId = model.modelId
194204
const catalog = await client.listModels()
195205
if (!catalog) return { model: undefined, warning: null }
@@ -245,7 +255,11 @@ export async function executeHeadlessAgent(
245255
await input.onAdmitted({ runtime: "headless", sessionId, messageId })
246256
}
247257

248-
const { model, warning } = await chooseModel(client, input.action.model)
258+
// Read only for runs on the cloud default; a failed read keeps the runner's default for this run.
259+
const organizationModel = isAutomationCloudDefaultModel(input.action.model)
260+
? await deps.defaultModel(input.organizationId).catch(() => null)
261+
: null
262+
const { model, warning } = await chooseModel(client, input.action.model, organizationModel)
249263
const ttlMs = Math.min(input.maximumRuntimeMs + TOKEN_GRACE_MS, DEN_MCP_HEADLESS_RUN_TOKEN_MAX_TTL_MS)
250264
const runSessionId = sessionId
251265
const sendTurn = () => client.sendTurn(actor, { sessionId: runSessionId, messageId, prompt: input.action.instructions, model, ttlMs })

‎ee/apps/den-api/src/routes/org/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ This folder owns organization-facing Den API routes.
1212
- `scim.ts`: active-organization SCIM connector metadata and token rotation
1313
- `templates.ts`: shared template CRUD
1414
- `web-origins.ts`: approved exact HTTPS web origins for sign-in handoff and Den API CORS
15+
- `workbot-settings.ts`: the organization default model for Workbot, the Slack assistant and cloud-default Automations (`workbotDefaultModel`)
1516
- `shared.ts`: shared route-local helpers, param schemas, and guard helpers
1617

1718
## Active organization model

‎ee/apps/den-api/src/routes/org/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { registerOrgSsoRoutes } from "./sso.js"
3636
import { registerOrgResourceRoutes } from "./resources.js"
3737
import { registerOrgTeamRoutes } from "./teams.js"
3838
import { registerOrgWebOriginRoutes } from "./web-origins.js"
39+
import { registerOrgWorkbotSettingsRoutes } from "./workbot-settings.js"
3940

4041
const LEGACY_ORG_PATH_PREFIX = "/v1/orgs/"
4142

@@ -97,6 +98,7 @@ export function registerOrgRoutes<T extends { Variables: OrgRouteVariables & Req
9798
registerOrgResourceRoutes(app)
9899
registerOrgTeamRoutes(app)
99100
registerOrgWebOriginRoutes(app)
101+
registerOrgWorkbotSettingsRoutes(app)
100102

101103
app.all("/v1/orgs/:orgId/*", delegatedRoute, async (c) => {
102104
const url = new URL(c.req.raw.url)
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { readWorkbotModel, withWorkbotModel, workbotSettingsInputSchema, workbotSettingsSchema } from "@openwork/types/den/workbot-settings"
2+
import type { Hono } from "hono"
3+
import { describeRoute } from "hono-openapi"
4+
import { z } from "zod"
5+
import { requireFeature } from "../../features.js"
6+
import { jsonValidator, orgMemberRoute, requireOrgPermission } from "../../middleware/index.js"
7+
import { forbiddenSchema, invalidRequestSchema, jsonResponse, unauthorizedSchema } from "../../openapi.js"
8+
import { updateOrganizationMetadata } from "../../organization-metadata.js"
9+
import {
10+
checkWorkbotModelChoice,
11+
forgetHeadlessModelCatalog,
12+
headlessModelCatalog,
13+
readOrganizationDefaultModel,
14+
workbotSettingsView,
15+
} from "../../workbot/model.js"
16+
import type { OrgRouteVariables } from "./shared.js"
17+
18+
const workbotSettingsDocumentSchema = workbotSettingsSchema.meta({ ref: "WorkbotSettings" })
19+
const workbotSettingsInputDocumentSchema = workbotSettingsInputSchema.meta({ ref: "WorkbotSettingsInput" })
20+
const featureDisabledSchema = z.object({ error: z.literal("feature_disabled"), feature: z.string() })
21+
const unknownModelSchema = z.object({ error: z.literal("unknown_model"), message: z.string() }).meta({ ref: "WorkbotUnknownModelError" })
22+
const runnerUnavailableSchema = z
23+
.object({ error: z.literal("workbot_runner_unavailable"), message: z.string() })
24+
.meta({ ref: "WorkbotRunnerUnavailableError" })
25+
26+
export const UNKNOWN_MODEL_MESSAGE = "Workbot can't use that model. Choose one from the list."
27+
export const RUNNER_UNAVAILABLE_MESSAGE = "Workbot's models can't be checked right now. Try again in a minute."
28+
29+
const notFound = jsonResponse("The organization was not found, or Workbot or its workbotDefaultModel feature is off.", featureDisabledSchema)
30+
31+
/**
32+
* Manage › Workbot: the organization's default model for its cloud agents (Workbot, the Slack assistant, and cloud
33+
* Automations set to the cloud default). Admins choose it from the models the headless runner serves.
34+
*/
35+
export function registerOrgWorkbotSettingsRoutes<T extends { Variables: OrgRouteVariables }>(app: Hono<T>) {
36+
app.get(
37+
"/v1/org/workbot-settings",
38+
describeRoute({
39+
tags: ["Organizations"],
40+
summary: "Get Workbot settings",
41+
description:
42+
"Returns the organization's default model for Workbot, the Slack assistant and cloud Automations set to the cloud default (null means the headless runner's default), and the models the runner can serve. Requires the View OpenWork Models settings permission, Workbot and the workbotDefaultModel feature.",
43+
responses: {
44+
200: jsonResponse("Workbot settings returned.", workbotSettingsDocumentSchema),
45+
401: jsonResponse("Authentication required.", unauthorizedSchema),
46+
403: jsonResponse("The caller lacks the View OpenWork Models settings permission.", forbiddenSchema),
47+
404: notFound,
48+
},
49+
}),
50+
orgMemberRoute(),
51+
requireFeature("workbot"),
52+
requireFeature("workbotDefaultModel"),
53+
requireOrgPermission("inference.view"),
54+
async (c) => {
55+
c.header("Cache-Control", "no-store")
56+
const organizationId = c.get("organizationContext").organization.id
57+
const chosen = await readOrganizationDefaultModel(organizationId)
58+
return c.json(workbotSettingsView(chosen, await headlessModelCatalog()))
59+
},
60+
)
61+
62+
app.put(
63+
"/v1/org/workbot-settings",
64+
describeRoute({
65+
tags: ["Organizations"],
66+
summary: "Set Workbot's default model",
67+
description:
68+
"Sets the organization's default model for Workbot, the Slack assistant and cloud Automations set to the cloud default, from their next message or run; null uses the headless runner's default. Automations with their own model keep it. Only models the runner serves are accepted. Requires the Manage OpenWork Models permission, a recent sign-in, Workbot and the workbotDefaultModel feature.",
69+
responses: {
70+
200: jsonResponse("Workbot settings saved.", workbotSettingsDocumentSchema),
71+
400: jsonResponse("The model is not one the runner serves, or the request was invalid.", z.union([unknownModelSchema, invalidRequestSchema])),
72+
401: jsonResponse("Authentication required.", unauthorizedSchema),
73+
403: jsonResponse("The caller lacks the Manage OpenWork Models permission or needs to sign in again.", forbiddenSchema),
74+
404: notFound,
75+
503: jsonResponse("The headless runner could not be reached to check the model.", runnerUnavailableSchema),
76+
},
77+
}),
78+
orgMemberRoute(),
79+
requireFeature("workbot"),
80+
requireFeature("workbotDefaultModel"),
81+
requireOrgPermission("inference.manage"),
82+
jsonValidator(workbotSettingsInputDocumentSchema),
83+
async (c) => {
84+
c.header("Cache-Control", "no-store")
85+
const organizationId = c.get("organizationContext").organization.id
86+
const { model } = c.req.valid("json")
87+
// Checked against a fresh catalog, so a model added to the runner a moment ago can be chosen.
88+
if (model !== null) forgetHeadlessModelCatalog()
89+
const catalog = await headlessModelCatalog()
90+
const choice = checkWorkbotModelChoice(model, catalog)
91+
if (choice === "runner_unavailable") return c.json({ error: "workbot_runner_unavailable" as const, message: RUNNER_UNAVAILABLE_MESSAGE }, 503)
92+
if (choice === "unknown_model") return c.json({ error: "unknown_model" as const, message: UNKNOWN_MODEL_MESSAGE }, 400)
93+
const metadata = await updateOrganizationMetadata(organizationId, (current) => withWorkbotModel(current, model))
94+
return c.json(workbotSettingsView(readWorkbotModel(metadata), catalog))
95+
},
96+
)
97+
}

0 commit comments

Comments
 (0)