Multiplayer agent harness for work.
Give drifted lists one source of truth (#2428)
Regan Bell15c846484bc3
diff --git a/.github/workflows/pgbouncer.yml b/.github/workflows/pgbouncer.ymlindex 4d3835aca..9f57c8ad4 100644--- a/.github/workflows/pgbouncer.yml+++ b/.github/workflows/pgbouncer.yml@@ -13,7 +13,7 @@ jobs:- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444with:- node-version: "24.18.1"+ node-version-file: .node-versioncache: npm- run: npm ci- run: bash scripts/test-pgbouncer.shdiff --git a/cli/src/config.ts b/cli/src/config.tsindex e53775179..976e9b98a 100644--- a/cli/src/config.ts+++ b/cli/src/config.ts@@ -15,11 +15,15 @@ import {} from "./services.ts";import {hostingProviderChoices,+ isSandboxBackendId,isTarget,+ type SandboxBackendId,type Target,SANDBOX_BACKEND_POLICY,+ SANDBOX_BACKENDS,targetsAllowingSandboxBackend,} from "./providers.ts";+import { TARGET_ENV_DEFAULTS } from "./target-env-defaults.ts";import { envNum, isEnvVarName, isMissingOrPlaceholder } from "./util.ts";export const CONFIG_FILENAME = "qm.config.jsonc";@@ -46,7 +50,7 @@ export interface PluginEntry {}export interface SandboxConfig {- backend?: "local" | "sprites" | "aws" | "agent37" | "superserve" | "e2b";+ backend?: SandboxBackendId;app?: string;image?: string;baseImage?: string;@@ -816,7 +820,7 @@ function validate(raw: unknown, path: string): QmConfig {}function configuredHarness(config: QmConfig): string {- return config.env.core?.HARNESS?.trim() || (config.target === "fly" ? "pi" : "mock");+ return config.env.core?.HARNESS?.trim() || TARGET_ENV_DEFAULTS[config.target](config, "core", "HARNESS") || "mock";}export function mockHarnessWarning(config: QmConfig): string | undefined {@@ -1024,7 +1028,7 @@ function validateAwsFrontDoor(config: QmConfig, path: string): void {if (hasPortal && protocol !== "https:") {throw new CliError(`${path}: AWS portal requires an HTTPS publicUrl and ACM certificate`);}- const harness = config.env.core?.HARNESS?.trim() || "mock";+ const harness = configuredHarness(config);if (protocol !== "https:" && harness !== "mock") {throw new CliError(`${path}: AWS HARNESS=${harness} requires an HTTPS publicUrl so sandbox capabilities never cross the Internet in cleartext`,@@ -1507,17 +1511,9 @@ function validateSandbox(raw: unknown, path: string, target: Target): SandboxCon};const out: SandboxConfig = {};if (o["backend"] !== undefined) {- if (- o["backend"] !== "local" &&- o["backend"] !== "sprites" &&- o["backend"] !== "aws" &&- o["backend"] !== "agent37" &&- o["backend"] !== "superserve" &&- o["backend"] !== "e2b"- ) {- throw new CliError(- `${path}: "sandbox.backend" must be "local" (Docker containers on the deployment host), "sprites" (Fly Sprites), "aws" (Lambda MicroVM sandboxes), "agent37", "superserve" (Superserve sandboxes), or "e2b" (E2B sandboxes)`,- );+ if (!isSandboxBackendId(o["backend"])) {+ const choices = Object.entries(SANDBOX_BACKENDS).map(([id, label]) => (label ? `"${id}" (${label})` : `"${id}"`));+ throw new CliError(`${path}: "sandbox.backend" must be ${choices.slice(0, -1).join(", ")}, or ${choices.at(-1)}`);}out.backend = o["backend"];}diff --git a/cli/src/providers.ts b/cli/src/providers.tsindex e70a0f62c..914f9597a 100644--- a/cli/src/providers.ts+++ b/cli/src/providers.ts@@ -5,7 +5,19 @@ export type Target = (typeof HOSTING_PROVIDER_IDS)[number];export const isTarget = (value: unknown): value is Target =>typeof value === "string" && (HOSTING_PROVIDER_IDS as readonly string[]).includes(value);-export type SandboxBackendId = "local" | "sprites" | "aws" | "agent37" | "superserve" | "e2b";+export const SANDBOX_BACKENDS = {+ local: "Docker containers on the deployment host",+ sprites: "Fly Sprites",+ aws: "Lambda MicroVM sandboxes",+ agent37: "",+ superserve: "Superserve sandboxes",+ e2b: "E2B sandboxes",+} as const;++export type SandboxBackendId = keyof typeof SANDBOX_BACKENDS;++export const isSandboxBackendId = (value: unknown): value is SandboxBackendId =>+ typeof value === "string" && Object.hasOwn(SANDBOX_BACKENDS, value);export interface SandboxBackendPolicy {/** Sandbox backends this hosting target can run. */diff --git a/plugins/admin/test/settings-lit.test.ts b/plugins/admin/test/settings-lit.test.tsindex 33c44279b..8fd34a2ee 100644--- a/plugins/admin/test/settings-lit.test.ts+++ b/plugins/admin/test/settings-lit.test.ts@@ -70,6 +70,40 @@ test("feature flag entries use a compact row that cannot inherit the card grid",}});+test("feature flag picker offers every server feature and limits personal-only features to people", async () => {+ const dom = setup();+ try {+ dom.window.eval(`settingsUI.configureFlags({+ loadChoices: async () => [{ scopeId: "personal:ada" }, { scopeId: "channel:C1" }],+ buildSelector: (choices) => Object.assign(document.createElement("ul"), { id: "offered", textContent: choices.map((c) => c.scopeId).join() }),+ save: async () => ({ ok: true }),+ })`);+ await dom.window.eval(`settingsUI.loadFlags(+ { featureFlags: [+ { featureName: "persistent_subagents", label: "Persistent subagents", personalOnly: true, hint: "People only.", enabledScopes: [] },+ { featureName: "swarms", label: "Swarms", personalOnly: true, enabledScopes: [] },+ { featureName: "team_scopes", label: "Team scopes", enabledScopes: [] },+ ] },+ "org:test",+ )`);+ await new Promise((resolve) => dom.window.setTimeout(resolve, 0));+ const doc = dom.window.document;+ const select = doc.getElementById("feature-flag-name") as HTMLSelectElement;+ assert.deepEqual(+ [...select.options].map((option) => option.textContent),+ ["Persistent subagents", "Swarms", "Team scopes"],+ );+ assert.equal(select.value, "persistent_subagents");+ assert.equal(doc.getElementById("offered")!.textContent, "personal:ada");+ assert.equal(doc.querySelector("#card-feature-flags .hint:not(#feature-flag-list)")!.textContent, "People only.");+ select.value = "team_scopes";+ select.dispatchEvent(new dom.window.Event("change"));+ assert.equal(doc.getElementById("offered")!.textContent, "personal:ada,channel:C1");+ } finally {+ dom.window.close();+ }+});+test("SOUL conflict keeps draft while replacing saved revision and version", () => {const dom = setup();try {diff --git a/plugins/admin/ui/settings-flags.ts b/plugins/admin/ui/settings-flags.tsindex 9b39200f8..c8c8c398b 100644--- a/plugins/admin/ui/settings-flags.ts+++ b/plugins/admin/ui/settings-flags.ts@@ -18,12 +18,11 @@ let redraw = () => {};export function configureFlags(options: any) {config = options;}+function feature() {+ return state.rows.find((row) => row.featureName === state.feature);+}function selector() {- const choices = state.choices.filter(- (row) =>- !["persistent_subagents", "app_annotations", "ui_canvas"].includes(state.feature) ||- row.scopeId.startsWith("personal:"),- );+ const choices = state.choices.filter((row) => !feature()?.personalOnly || row.scopeId.startsWith("personal:"));for (const id of state.selected) if (!choices.some((row) => row.scopeId === id)) state.selected.delete(id);state.selector = config.buildSelector(choices, state.selected, redraw);redraw();@@ -128,20 +127,13 @@ function template() {<label>Feature<selectid="feature-flag-name"- .value=${state.feature}?disabled=${state.saving}@change=${(e: Event) => {state.feature = (e.target as HTMLSelectElement).value;selector();}}>- <option value="persistent_subagents">Persistent subagents</option>- <option value="app_annotations">App annotations</option>- <option value="inbox_loops">Inbox Loops</option>- <option value="slack_loading_indicator">Slack loading indicator (experimental)</option>- <option value="external_app_sharing">External app sharing (public links, outside emails)</option>- <option value="loop_triage">Loop triage (prioritize and consolidate)</option>- <option value="ui_canvas">UI canvas and UI state (agent code runs in the page)</option>+ ${state.rows.map((row) => html`<option value=${row.featureName} .selected=${row.featureName === state.feature}>${row.label}</option>`)}</select></label><div>@@ -149,18 +141,7 @@ function template() {<div id="feature-flag-scopes" aria-labelledby="feature-flag-scope-label" ?inert=${state.saving}>${state.selector || "Loading people and scopes…"}</div>- <span class="hint"- >${- {- app_annotations:- "Enables app text comments and annotation tools for the selected people. Applies on the next app page load; app management permission is still required.",- ui_canvas:- "Lets the agent read the selected people's whole web UI and place live HTML/CSS/JS panels in their conversations. Canvas code runs unsandboxed in their page with their full session: it can do anything they can, including answering approvals. Personal scopes only. Turning it off stops canvases from loading on the next page load.",- slack_loading_indicator:- "Shows an activity card in Slack threads, including background work and monitors. After five minutes, the card links to the web conversation. Everyone in a shared thread can see it. Top-level DMs stay unchanged. Turning this off leaves existing cards.",- }[state.feature] ?? "Persistent subagents are available for personal scopes only."- }</span- >+ <span class="hint">${feature()?.hint ?? ""}</span></div></div></div>diff --git a/plugins/portal/src/proxy.ts b/plugins/portal/src/proxy.tsindex 2d5f81442..9ece144ac 100644--- a/plugins/portal/src/proxy.ts+++ b/plugins/portal/src/proxy.ts@@ -151,6 +151,7 @@ export const FORWARD_WEBHOOK_HEADERS = ["x-slack-signature","x-slack-request-timestamp","stripe-signature",+ "linear-signature","x-signature","x-delivery-id",];diff --git a/plugins/portal/test/router.test.ts b/plugins/portal/test/router.test.tsindex 7053e222d..902fd0846 100644--- a/plugins/portal/test/router.test.ts+++ b/plugins/portal/test/router.test.ts@@ -305,6 +305,17 @@ test("inbound webhooks pass through to the core with NO session, signature headeassert.equal(body.headers["x-github-delivery"], "d-1");});+test("inbound Linear webhooks reach the core with their signature header", async () => {+ const r = await fetch(`${base}/v1/webhooks/incoming/wh_linear`, {+ method: "POST",+ headers: { "content-type": "application/json", "linear-signature": "abc123" },+ body: JSON.stringify({ webhookTimestamp: 1 }),+ });+ assert.equal(r.status, 200);+ const body = (await r.json()) as { headers: Record<string, string> };+ assert.equal(body.headers["linear-signature"], "abc123");+});+test("the webhook passthrough is exact-shape + POST-only (no widening of /v1)", async () => {assert.equal((await fetch(`${base}/v1/webhooks/incoming/abc`)).status, 404);assert.equal((await fetch(`${base}/v1/webhooks/incoming/a/b`, { method: "POST" })).status, 404);diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex ab0e97a05..aa4a76c18 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -3016,7 +3016,7 @@ const apiRoutes: readonly WebRoute[] = [) {return json(res, 400, {error: "unsupported_verification",- message: "verification requires a scheme (HMAC-SHA256, GitHub, Slack, or Stripe)",+ message: "verification requires a scheme",});}verification = {@@ -3060,12 +3060,6 @@ const apiRoutes: readonly WebRoute[] = [error: "action_required",message: "an action (the agent's instructions) is required",});- if (!["hmac-sha256", "github", "slack", "stripe"].includes(verification.scheme)) {- return json(res, 400, {- error: "unsupported_verification",- message: "choose HMAC-SHA256, GitHub, Slack, or Stripe signature verification",- });- }if (!verification.secret) {verification = { ...verification, secret: randomBytes(32).toString("hex") };}diff --git a/plugins/web-ui/src/connector-link.ts b/plugins/web-ui/src/connector-link.tsindex a5e7409bd..330598376 100644--- a/plugins/web-ui/src/connector-link.ts+++ b/plugins/web-ui/src/connector-link.ts@@ -1,13 +1,34 @@const LINK_RE = /https?:\/\/[^\s<>()[\]]+/gi;-export const CONNECTOR_NAMES: Record<string, string> = {- google: "Google Workspace",- slack: "Slack",- notion: "Notion",- linear: "Linear",- github: "GitHub",- dropbox: "Dropbox",- x: "X",+export const CONNECTOR_LABELS: Record<string, { name: string; hosts: string }> = {+ google: {+ name: "Google Workspace",+ hosts: "Gmail, Calendar, Drive, Sheets",+ },+ slack: {+ name: "Slack",+ hosts: "Channels & messages",+ },+ notion: {+ name: "Notion",+ hosts: "Pages & databases",+ },+ linear: {+ name: "Linear",+ hosts: "Issues & projects",+ },+ github: {+ name: "GitHub",+ hosts: "Repos, issues & PRs",+ },+ dropbox: {+ name: "Dropbox",+ hosts: "Files & folders",+ },+ x: {+ name: "X (Twitter)",+ hosts: "Posts & profile",+ },};export interface ConnectorLink {@@ -49,7 +70,7 @@ export function connectorLinksIn(text: string, trustedOrigin?: string): Connectoif (trustedOrigin && parsed.origin !== trustedOrigin) continue;if (!/^\/(?:connect\/redeem|v1\/connectors\/oauth\/consent\/redeem)\/[^/]+$/.test(parsed.pathname)) continue;const provider = parsed.searchParams.get("p") ?? "";- if (!CONNECTOR_NAMES[provider]) continue;+ if (!CONNECTOR_LABELS[provider]) continue;if (!out.some((l) => l.url === url)) out.push({ provider, url });}return out;diff --git a/plugins/web-ui/src/connector-widget.ts b/plugins/web-ui/src/connector-widget.tsindex e33a029d5..f949bdf17 100644--- a/plugins/web-ui/src/connector-widget.ts+++ b/plugins/web-ui/src/connector-widget.ts@@ -2,7 +2,7 @@ import { html, type TemplateResult } from "lit";import { ArrowUpRight, Check } from "lucide";import { icon } from "./icons";import { connectorLogo } from "./connector-logo";-import { CONNECTOR_NAMES, connectorService, type ConnectorLink } from "./connector-link";+import { CONNECTOR_LABELS, connectorService, type ConnectorLink } from "./connector-link";export function connectorCard(link: ConnectorLink,@@ -10,7 +10,7 @@ export function connectorCard(withReturnTo: (url: string) => string = (url) => url,): TemplateResult {const composio = link.provider === "composio";- const name = CONNECTOR_NAMES[link.provider] ?? "your account";+ const name = CONNECTOR_LABELS[link.provider]?.name ?? "your account";const service = connectorService(link);if (!composio && connected) {return html`<div class="connector-widget connected" role="status">diff --git a/plugins/web-ui/src/connectors.ts b/plugins/web-ui/src/connectors.tsindex c71889fd9..310ed68d3 100644--- a/plugins/web-ui/src/connectors.ts+++ b/plugins/web-ui/src/connectors.ts@@ -4,6 +4,7 @@ import { api } from "./core-bridge";import { errMessage } from "../../chassis/src/errors";import { icon } from "./icons";import { connectorLogo } from "./connector-logo";+import { CONNECTOR_LABELS } from "./connector-link";import { appState, replacePanePreservingFocus } from "./shell";import { scopedSession, scopedViewTopbar } from "./session-scope";import { focusDialogCancel, restoreDialogFocus, trapDialogFocus } from "./dialog-focus";@@ -19,37 +20,6 @@ interface ConnectorProvider {hosts?: Array<{ host?: string } | string>;}-const CONNECTOR_LABELS: Record<string, { name: string; hosts: string }> = {- google: {- name: "Google Workspace",- hosts: "Gmail, Calendar, Drive, Sheets",- },- slack: {- name: "Slack",- hosts: "Channels & messages",- },- notion: {- name: "Notion",- hosts: "Pages & databases",- },- linear: {- name: "Linear",- hosts: "Issues & projects",- },- github: {- name: "GitHub",- hosts: "Repos, issues & PRs",- },- dropbox: {- name: "Dropbox",- hosts: "Files & folders",- },- x: {- name: "X (Twitter)",- hosts: "Posts & profile",- },-};-interface KeychainCredential {id: string;service: string;diff --git a/plugins/web-ui/src/model-connect.ts b/plugins/web-ui/src/model-connect.tsindex a0f2baab8..0d43ff24f 100644--- a/plugins/web-ui/src/model-connect.ts+++ b/plugins/web-ui/src/model-connect.ts@@ -95,7 +95,7 @@ interface State {error: string;busy: boolean;saving: boolean;- connections: Partial<Record<ProviderKey, ConnKind>>;+ connections: Partial<Record<ProviderMeta["apiName"], ConnKind>>;open: ProviderKey | null;method: Method | null;flow: Flow;@@ -161,7 +161,7 @@ function applyStatus(status: StatusResponse): void {s.account = status.account;s.connections = {};for (const c of status.connections ?? []) {- s.connections[c.provider === "anthropic" ? "claude" : "chatgpt"] = c.kind;+ s.connections[c.provider] = c.kind;}s.loaded = true;if (appState.me) {@@ -555,7 +555,7 @@ function connectBody(p: ProviderMeta): TemplateResult {}function providerRow(p: ProviderMeta): TemplateResult {- const kind = s.connections[p.key];+ const kind = s.connections[p.apiName];const open = s.open === p.key;let statusLine = `Chat with ${p.name} on your own account`;if (kind === "oauth") statusLine = `Connected with your ${p.name} subscription`;@@ -632,7 +632,7 @@ async function switchAccount(account: "personal" | "company", provider?: "anthros.notice =account === "company"? "New chats will use company access."- : `New chats will use your ${provider === "anthropic" ? "Claude" : "ChatGPT / Codex"} account.`;+ : `New chats will use your ${PROVIDERS.find((p) => p.apiName === provider)?.name} account.`;} catch (e) {if (!current(state, revision)) return;s.error = friendly(e);@@ -644,7 +644,7 @@ async function switchAccount(account: "personal" | "company", provider?: "anthrofunction view(): TemplateResult {const anyConnected = PROVIDERS.some(- (p) => s.connections[p.key] && (s.account === "personal" || s.account === p.apiName),+ (p) => s.connections[p.apiName] && (s.account === "personal" || s.account === p.apiName),);let cta: TemplateResult | typeof nothing = nothing;if (s.loaded && (s.mode === "manager" || anyConnected || !s.personal)) {@@ -659,7 +659,7 @@ function view(): TemplateResult {if (!s.loaded) choices = html`<button type="button" class="btn" @click=${() => void load()}>Retry</button>`;else if (s.intent)choices = html`<div class="mc-simple-connect">- ${s.connections[s.intent.key] ? providerRow(s.intent) : connectBody(s.intent)}+ ${s.connections[s.intent.apiName] ? providerRow(s.intent) : connectBody(s.intent)}</div>`;elsechoices = html`<div class="mc-providers">@@ -774,7 +774,7 @@ export function openModelConnectManager(provider?: "anthropic" | "openai"): voidvoid load().then(() => {if (current(state) && s.loaded && s.intent) {s.open = s.intent.key;- if (!s.connections[s.intent.key]) void pickSubscription(s.intent);+ if (!s.connections[s.intent.apiName]) void pickSubscription(s.intent);else paint();}});diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex 696ee4910..345fb29f7 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -52,7 +52,7 @@ import {} from "../../security/security-posture.ts";import type { ApprovalGrantModes } from "../../types.ts";import { parseEgressPolicy } from "../../resolution/egress-policy.ts";-import { FEATURE_NAMES, type FeatureName } from "../../feature-flags.ts";+import { FEATURE_NAMES, FEATURES, type FeatureName } from "../../feature-flags.ts";import { parseSharingPosture, SHARING_POSTURES, type SharingPosture } from "../../resolution/sharing-posture.ts";export interface AutoFlaggerDraft {@@ -346,7 +346,14 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [target: "org",readKey: "featureFlags",label: "Live feature rollout table. Each feature maps to the scopes where it is enabled.",- get: (deps) => deps.featureFlags?.list(),+ get: async (deps) => {+ if (!deps.featureFlags) return undefined;+ const rows = await deps.featureFlags.list();+ return FEATURE_NAMES.map((featureName) => ({+ ...FEATURES[featureName],+ ...(rows.find((row) => row.featureName === featureName) ?? { featureName, enabledScopes: [] }),+ }));+ },apply: async (ctx, actor, scope) => {if (!ctx.deps.featureFlags) return { error: "not available on this deployment", status: 404 };const body = (ctx.body ?? {}) as { featureName?: unknown; scopeId?: unknown; on?: unknown };diff --git a/src/api/routes/admin/mcp-servers.ts b/src/api/routes/admin/mcp-servers.tsindex e14246d11..752abad7d 100644--- a/src/api/routes/admin/mcp-servers.ts+++ b/src/api/routes/admin/mcp-servers.ts@@ -5,7 +5,7 @@// model-provider credential, not like a personal connector.import { isValidMcpServerId, type McpServer, type McpServerAuthMode } from "../../../mcp/mcp-server-store.ts";-import { PROVIDERS } from "../../../connectors/oauth.ts";+import { isAccountType, PROVIDERS } from "../../../connectors/oauth.ts";import { discoverOAuth, httpsUrl, parseScopes, type DiscoveredOAuth } from "../../../mcp/oauth-discovery.ts";import { sendJson } from "../../http.ts";import type { ApiCtx } from "../route.ts";@@ -110,7 +110,7 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {let oauthAuthorizeUrl = httpsUrl(b.oauthAuthorizeUrl) ?? (oauthUser ? existing?.oauthAuthorizeUrl : undefined);let oauthTokenUrl = httpsUrl(b.oauthTokenUrl) ?? (oauthUser ? existing?.oauthTokenUrl : undefined);const credentialAccountType = b.credentialAccountType ?? existing?.credentialAccountType ?? "default";- if (!["default", "personal", "company"].includes(credentialAccountType)) {+ if (!isAccountType(credentialAccountType)) {return sendJson(ctx.res, 400, {error: "bad_request",message: "credentialAccountType must be default, personal, or company",diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.tsindex efdc96339..860166103 100644--- a/src/api/routes/connectors.ts+++ b/src/api/routes/connectors.ts@@ -14,8 +14,10 @@ import {type OAuthClientResolver,type AccountType,type OAuthState,+ ACCOUNT_TYPES,+ isAccountType,} from "../../connectors/oauth.ts";-import { CONNECTOR_STATUS_ACCOUNT_TYPES, providerTokenStatuses } from "../../credentials/connector-status.ts";+import { providerTokenStatuses } from "../../credentials/connector-status.ts";import type { ConnectorTokenStore, DerivedOAuthAuth, OAuthTokenStatus } from "../../credentials/keychain.ts";import { createEnvSecretSource } from "../../credentials/secret-source.ts";import type { ServerDeps } from "../deps.ts";@@ -54,7 +56,7 @@ export function resolverFor(deps: ServerDeps): OAuthClientResolver {}function parseAccountType(v: string | null | undefined): AccountType {- return v === "personal" || v === "company" ? v : "default";+ return isAccountType(v) ? v : "default";}async function providerConfigured(deps: ServerDeps, provider: string): Promise<boolean> {@@ -187,7 +189,7 @@ async function principalHasProvider(deps: ServerDeps, provider: string, principaconst p = oauthProvider(provider);if (!p || !deps.connectorTokens) return false;for (const host of p.hosts) {- for (const at of CONNECTOR_STATUS_ACCOUNT_TYPES) {+ for (const at of ACCOUNT_TYPES) {const st = await deps.connectorTokens.connectorTokenStatus(host, principalId, at).catch(() => ({ connected: false }) as OAuthTokenStatus);@@ -444,13 +446,11 @@ export async function oauthRevoke(ctx: ApiCtx): Promise<void> {if (!provider)return sendJson(res, 404, { error: "not_found", message: `unknown OAuth provider: ${providerName}` });for (const h of provider.hosts)- for (const at of CONNECTOR_STATUS_ACCOUNT_TYPES)- await deps.connectorTokens.deleteConnectorToken(h, principalId, at);+ for (const at of ACCOUNT_TYPES) await deps.connectorTokens.deleteConnectorToken(h, principalId, at);audit(deps, { principalId, action: "connector.oauth.revoked", resource: providerName, scopeLabel: principalId });return sendJson(res, 200, { ok: true, principalId, provider: providerName, hosts: provider.hosts });}- for (const at of CONNECTOR_STATUS_ACCOUNT_TYPES)- await deps.connectorTokens.deleteConnectorToken(host, principalId, at);+ for (const at of ACCOUNT_TYPES) await deps.connectorTokens.deleteConnectorToken(host, principalId, at);audit(deps, { principalId, action: "connector.oauth.revoked", resource: host, scopeLabel: principalId });return sendJson(res, 200, { ok: true, principalId, host });}@@ -502,7 +502,7 @@ export async function gmailSent(ctx: ApiCtx): Promise<void> {ctx.res.setHeader("Cache-Control", "no-store");if (!principal) return sendJson(ctx.res, 403, { error: "forbidden", message: "Sign in to read sent mail." });const requestedAccountType = ctx.url.searchParams.get("accountType");- if (requestedAccountType !== null && !["default", "personal", "company"].includes(requestedAccountType))+ if (requestedAccountType !== null && !isAccountType(requestedAccountType))return sendJson(ctx.res, 400, { error: "bad_request" });const pageToken = ctx.url.searchParams.get("pageToken") ?? undefined;if (pageToken && pageToken.length > 2048) return sendJson(ctx.res, 400, { error: "bad_request" });@@ -510,9 +510,7 @@ export async function gmailSent(ctx: ApiCtx): Promise<void> {let accountType: AccountType | undefined;let auth: DerivedOAuthAuth | null | undefined;let authError: unknown;- for (const candidate of requestedAccountType- ? [requestedAccountType as AccountType]- : (["default", "personal", "company"] satisfies AccountType[])) {+ for (const candidate of requestedAccountType ? [requestedAccountType] : ACCOUNT_TYPES) {try {auth = await ctx.deps.connectorTokens?.connectorDerivedAuth("gmail.googleapis.com", principal, candidate);if (auth) {diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.tsindex bd270d648..be8ce5df3 100644--- a/src/api/routes/loop-items.ts+++ b/src/api/routes/loop-items.ts@@ -1,5 +1,6 @@import { z } from "zod";import type { Cron, Loop, LoopItem, LoopSourcePayload } from "../../types.ts";+import { isAccountType } from "../../connectors/oauth.ts";import { canonicalJson } from "../../../cli/src/canonical-json.ts";import { errMessage } from "../../util/errors.ts";import { sendJson } from "../http.ts";@@ -550,12 +551,7 @@ export async function ensureSentChat(ctx: ApiCtx): Promise<void> {const accountType = body.accountType === undefined ? "default" : body.accountType;const to = addressList(body.to === undefined ? [] : [body.to]);const cc = addressList(body.cc === undefined ? [] : [body.cc]);- if (- typeof accountType !== "string" ||- !["default", "personal", "company"].includes(accountType) ||- to === null ||- cc === null- )+ if (!isAccountType(accountType) || to === null || cc === null)return sendJson(ctx.res, 400, { error: "bad_request", message: "invalid account or recipient headers" });const payload = {title: text("subject", 300),diff --git a/src/api/routes/slack-native.ts b/src/api/routes/slack-native.tsindex d091fa127..b3d8d183e 100644--- a/src/api/routes/slack-native.ts+++ b/src/api/routes/slack-native.ts@@ -4,6 +4,7 @@ import { errMessage } from "../../util/errors.ts";import { ErrorCode, type WebAPIPlatformError, type AuthTestResponse } from "@slack/web-api";import { slackWebClient } from "../../slack/web-client.ts";import { personIds, samePerson } from "../../directory/person.ts";+import { ACCOUNT_TYPES } from "../../connectors/oauth.ts";import { resolverFor } from "./connectors.ts";import type { ApiCtx } from "./route.ts";@@ -19,7 +20,7 @@ export async function nativeSlackConfigured(ctx: ApiCtx): Promise<boolean> {export async function nativeSlackConnection(ctx: ApiCtx) {const principal = ctx.actor!.p;for (const id of personIds(principal)) {- for (const accountType of ["default", "personal", "company"]) {+ for (const accountType of ACCOUNT_TYPES) {const auth = await ctx.deps.connectorTokens?.connectorDerivedAuth("slack.com", id, accountType);if (!auth) continue;const call = async (method: string, payload?: Record<string, unknown>, token = auth.accessToken) => {diff --git a/src/connectors/oauth.ts b/src/connectors/oauth.tsindex 00383c9ff..656041407 100644--- a/src/connectors/oauth.ts+++ b/src/connectors/oauth.ts@@ -5,7 +5,10 @@ import { decodeJwt } from "jose";import { mintSignedPayload, verifySignedPayload } from "../auth/signed-token.ts";import { swallow } from "../util/errors.ts";-export type AccountType = "default" | "personal" | "company";+export const ACCOUNT_TYPES = ["default", "personal", "company"] as const;+export type AccountType = (typeof ACCOUNT_TYPES)[number];+export const isAccountType = (value: unknown): value is AccountType =>+ typeof value === "string" && (ACCOUNT_TYPES as readonly string[]).includes(value);export function generateCodeVerifier(): string {return randomBytes(32).toString("base64url");@@ -38,6 +41,7 @@ type OAuthExchangeAdapter = (type OAuthRefreshAdapter = (args: OAuthAdapterArgs & { token: OAuthToken }) => Promise<OAuthToken>;export interface OAuthProviderConfig {+ label: string;hosts: string[];authUrl: string;tokenUrl: string;@@ -220,6 +224,7 @@ const notionExchange: OAuthExchangeAdapter = async ({ provider, client, code, reexport const PROVIDERS: Record<string, OAuthProviderConfig> = {google: {+ label: "Google",hosts: ["gmail.googleapis.com","www.googleapis.com",@@ -269,6 +274,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},slack: {+ label: "Slack",hosts: ["slack.com"],authUrl: "https://slack.com/oauth/v2/authorize",tokenUrl: "https://slack.com/api/oauth.v2.access",@@ -315,6 +321,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},notion: {+ label: "Notion",hosts: ["api.notion.com"],authUrl: "https://api.notion.com/v1/oauth/authorize",tokenUrl: "https://api.notion.com/v1/oauth/token",@@ -341,6 +348,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},linear: {+ label: "Linear",hosts: ["api.linear.app"],authUrl: "https://linear.app/oauth/authorize",tokenUrl: "https://api.linear.app/oauth/token",@@ -364,6 +372,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},dropbox: {+ label: "Dropbox",hosts: ["api.dropboxapi.com", "content.dropboxapi.com"],authUrl: "https://www.dropbox.com/oauth2/authorize",tokenUrl: "https://api.dropboxapi.com/oauth2/token",@@ -396,6 +405,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},github: {+ label: "GitHub",hosts: ["api.github.com"],authUrl: "https://github.com/login/oauth/authorize",tokenUrl: "https://github.com/login/oauth/access_token",@@ -421,6 +431,7 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {},x: {+ label: "X",hosts: ["api.x.com"],authUrl: "https://x.com/i/oauth2/authorize",tokenUrl: "https://api.x.com/2/oauth2/token",@@ -469,6 +480,7 @@ export function setPublicOAuthClients(clients: PublicOAuthClient[]): void {if (PROVIDERS[c.name]) continue;publicClients.set(c.name, c);publicProviders.set(c.name, {+ label: c.label,hosts: [c.host],authUrl: c.authUrl,tokenUrl: c.tokenUrl,@@ -540,8 +552,6 @@ export interface OAuthState {consentLinkId?: string;}-const ACCOUNT_TYPES: readonly AccountType[] = ["default", "personal", "company"];-function isOAuthState(v: unknown): v is OAuthState {if (typeof v !== "object" || v === null) return false;const s = v as OAuthState;@@ -553,7 +563,7 @@ function isOAuthState(v: unknown): v is OAuthState {typeof s.nonce === "string" &&(s.returnTo === undefined || typeof s.returnTo === "string") &&(s.orgId === undefined || typeof s.orgId === "string") &&- (s.accountType === undefined || (typeof s.accountType === "string" && ACCOUNT_TYPES.includes(s.accountType))) &&+ (s.accountType === undefined || isAccountType(s.accountType)) &&(s.clientRef === undefined || typeof s.clientRef === "string") &&(s.codeVerifier === undefined || typeof s.codeVerifier === "string") &&(s.consentLinkId === undefined || typeof s.consentLinkId === "string")diff --git a/src/credentials/connector-status.ts b/src/credentials/connector-status.tsindex fb6d21b1a..9f1792a7a 100644--- a/src/credentials/connector-status.ts+++ b/src/credentials/connector-status.ts@@ -1,6 +1,7 @@import type { DurableMap } from "../persistence/durable-map.ts";import type { ConnectorTokenStore, OAuthTokenStatus } from "./keychain.ts";import {+ ACCOUNT_TYPES,oauthProviderEntries,PROVIDERS,type OAuthClientResolver,@@ -34,8 +35,6 @@ export function createConnectorStatusCache(map: DurableMap<ConnectorStatusRecord};}-export const CONNECTOR_STATUS_ACCOUNT_TYPES: ReadonlyArray<string | undefined> = [undefined, "personal", "company"];-const CONNECTOR_STATUS_MAX_TTL_MS = 15 * 60_000;export function connectorStatusIsStale(@@ -89,9 +88,7 @@ export async function providerTokenStatuses(const hosts = await Promise.all(provider.hosts.map(async (host) => {const statuses = await Promise.all(- CONNECTOR_STATUS_ACCOUNT_TYPES.map((accountType) =>- tokens.connectorTokenStatus(host, principalId, accountType),- ),+ ACCOUNT_TYPES.map((accountType) => tokens.connectorTokenStatus(host, principalId, accountType)),);return { host, ...bestOAuthTokenStatus(statuses) };}),@@ -115,17 +112,8 @@ export async function refreshConnectorStatus(return { principalId, checkedAt: now, providers };}-const PROVIDER_LABELS: Record<string, string> = {- google: "Google",- slack: "Slack",- notion: "Notion",- linear: "Linear",- github: "GitHub",- dropbox: "Dropbox",-};-export function connectorLabel(name: string): string {- return PROVIDER_LABELS[name] ?? name.charAt(0).toUpperCase() + name.slice(1);+ return PROVIDERS[name]?.label ?? name.charAt(0).toUpperCase() + name.slice(1);}export async function configuredConnectorProviders(resolveClient: OAuthClientResolver): Promise<string[]> {diff --git a/src/feature-flags.ts b/src/feature-flags.tsindex 4f147d1bf..7442efbd8 100644--- a/src/feature-flags.ts+++ b/src/feature-flags.ts@@ -2,19 +2,35 @@ import type { DurableMap } from "./persistence/durable-map.ts";import { orgId as configOrgId } from "./config.ts";import { scopeId, type ScopeId } from "./types.ts";-export const FEATURE_NAMES = [- "app_annotations",- "persistent_subagents",- "responsive_spine",- "inbox_loops",- "slack_loading_indicator",- "external_app_sharing",- "loop_triage",- "swarms",- "team_scopes",- "ui_canvas",-] as const;-export type FeatureName = (typeof FEATURE_NAMES)[number];+export const FEATURES = {+ app_annotations: {+ label: "App annotations",+ personalOnly: true,+ hint: "Enables app text comments and annotation tools for the selected people. Applies on the next app page load; app management permission is still required.",+ },+ persistent_subagents: {+ label: "Persistent subagents",+ personalOnly: true,+ hint: "Persistent subagents are available for personal scopes only.",+ },+ responsive_spine: { label: "Responsive spine (delegation)", personalOnly: true },+ inbox_loops: { label: "Inbox Loops" },+ slack_loading_indicator: {+ label: "Slack loading indicator (experimental)",+ hint: "Shows an activity card in Slack threads, including background work and monitors. After five minutes, the card links to the web conversation. Everyone in a shared thread can see it. Top-level DMs stay unchanged. Turning this off leaves existing cards.",+ },+ external_app_sharing: { label: "External app sharing (public links, outside emails)" },+ loop_triage: { label: "Loop triage (prioritize and consolidate)" },+ swarms: { label: "Swarms", personalOnly: true },+ team_scopes: { label: "Team scopes" },+ ui_canvas: {+ label: "UI canvas and UI state (agent code runs in the page)",+ personalOnly: true,+ hint: "Lets the agent read the selected people's whole web UI and place live HTML/CSS/JS panels in their conversations. Canvas code runs unsandboxed in their page with their full session: it can do anything they can, including answering approvals. Personal scopes only. Turning it off stops canvases from loading on the next page load.",+ },+} as const satisfies Record<string, { label: string; personalOnly?: boolean; hint?: string }>;+export type FeatureName = keyof typeof FEATURES;+export const FEATURE_NAMES = Object.keys(FEATURES) as FeatureName[];export interface FeatureFlagRecord {featureName: FeatureName;diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 087a4bbb7..90e5c789b 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -25,6 +25,8 @@ import { redactCommand } from "../sandbox/exec-process-session.ts";import { redactSecrets } from "./redact-secrets.ts";import { isObj } from "../util/objects.ts";import { BOT_MODES } from "../surface-cache/channel-policy-store.ts";+import { WEBHOOK_SCHEMES } from "../webhooks/verifiers.ts";+import { HARNESS_IDS } from "../model/pi-models.ts";import { headSlice, tailSlice } from "../util/text.ts";import {applyGovernorVerdict,@@ -204,6 +206,7 @@ interface CronLike {}const LIST_PAGE_SIZE = 25;+const SENDER_WEBHOOK_SCHEMES = WEBHOOK_SCHEMES.filter((scheme) => scheme !== "hmac-sha256");const LIST_PAGE_MAX = 100;const LIST_TASK_PREVIEW_CHARS = 200;const WEBHOOK_ACTION_PREVIEW_CHARS = 2000;@@ -2477,18 +2480,11 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):[Type.Null(),Type.Object({- harnessId: Type.Union([Type.Literal("pi"), Type.Literal("claude")]),- modelId: Type.String(),- effortLevel: Type.Optional(- Type.Union([- Type.Literal("low"),- Type.Literal("medium"),- Type.Literal("high"),- Type.Literal("xhigh"),- Type.Literal("max"),- Type.Literal("ultracode"),- ]),+ harnessId: Type.Union(+ HARNESS_IDS.filter((harnessId) => harnessId !== "mock").map((harnessId) => Type.Literal(harnessId)),),+ modelId: Type.String(),+ effortLevel: Type.Optional(Type.String()),fastMode: Type.Optional(Type.Boolean()),}),],@@ -2795,8 +2791,8 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"action=create takes `action` (what to do on each event; the event payload is appended " +"automatically), `verification` (how the request is authenticated), optional `filters` (skip the turn " +'unless the event matches — cheap pre-gating, e.g. [{path:"action",in:["opened"]}]), and optional ' +- "`destinationKey` (same delivery menu as crons). verification.scheme is one of github | slack | " +- "stripe | hmac-sha256: for github/slack/stripe the USER gives you the signing secret from the " ++ `\`destinationKey\` (same delivery menu as crons). verification.scheme is one of ${WEBHOOK_SCHEMES.join(" | ")}: ` ++ `for ${SENDER_WEBHOOK_SCHEMES.join("/")} the USER gives you the signing secret from the ` +"sender's settings page; for hmac-sha256 generate a strong random secret yourself. A signing secret is always required.\n" +"create returns the inbound `url` and `secret` ONCE. You CANNOT open the sender's settings page, so " +"relay BOTH to the user verbatim — the `url` is already the full public inbound URL (hand it over as-is) " +@@ -2822,12 +2818,11 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):Type.Object({scheme: Type.Union(- [Type.Literal("github"), Type.Literal("slack"), Type.Literal("stripe"), Type.Literal("hmac-sha256")],+ WEBHOOK_SCHEMES.map((scheme) => Type.Literal(scheme)),{ description: "how the inbound request is authenticated." },),secret: Type.String({- description:- "the signing secret (from the sender for github/slack/stripe; self-generated for hmac-sha256).",+ description: `the signing secret (from the sender for ${SENDER_WEBHOOK_SCHEMES.join("/")}; self-generated for hmac-sha256).`,}),},{ description: "create only: the inbound authentication scheme + secret." },diff --git a/src/loops/sources/gmail.ts b/src/loops/sources/gmail.tsindex a86ecaacc..8348c7214 100644--- a/src/loops/sources/gmail.ts+++ b/src/loops/sources/gmail.ts@@ -1,4 +1,5 @@import type { LoopItem, LoopSourcePayload } from "../../types.ts";+import { isAccountType } from "../../connectors/oauth.ts";import { errMessage } from "../../util/errors.ts";import {addressList,@@ -32,11 +33,7 @@ function parseGmailMeta(v: unknown): GmailMeta | undefined {if (!isObj(v)) return undefined;const threadId = clip(v.threadId, 200);if (!threadId) return undefined;- if (- v.accountType !== undefined &&- (typeof v.accountType !== "string" || !["default", "personal", "company"].includes(v.accountType))- )- return undefined;+ if (v.accountType !== undefined && !isAccountType(v.accountType)) return undefined;const accountType = v.accountType as GmailMeta["accountType"];const messageId = clipOpt(v.messageId, 200);const rfcMessageId = clipOpt(v.rfcMessageId, 400);diff --git a/test/admin-resources.test.ts b/test/admin-resources.test.tsindex 483a2d62e..7c57d06bc 100644--- a/test/admin-resources.test.ts+++ b/test/admin-resources.test.ts@@ -339,8 +339,16 @@ test("feature flag table changes one scope live without restart", async () => {assert.equal(await srv.built.featureFlags.enabled("inbox_loops", "channel:C1"), true);assert.equal(await srv.built.featureFlags.enabled("inbox_loops", "channel:C2"), false);const read = await fetch(`${srv.base}/v1/admin/scopes/org:default-org`, { headers: ADMIN });- const flags = ((await read.json()) as { featureFlags: Array<{ enabledScopes: string[] }> }).featureFlags;- assert.deepEqual(flags[0]?.enabledScopes, ["channel:C1"]);+ const flags = (+ (await read.json()) as {+ featureFlags: Array<{ featureName: string; label: string; personalOnly?: boolean; enabledScopes: string[] }>;+ }+ ).featureFlags;+ assert.deepEqual(flags.find((flag) => flag.featureName === "inbox_loops")?.enabledScopes, ["channel:C1"]);+ const swarms = flags.find((flag) => flag.featureName === "swarms");+ assert.equal(swarms?.label, "Swarms");+ assert.equal(swarms?.personalOnly, true);+ assert.deepEqual(swarms?.enabledScopes, []);} finally {await srv.close();}diff --git a/test/web-ui-webhooks.test.ts b/test/web-ui-webhooks.test.tsindex 71b300470..910261ffc 100644--- a/test/web-ui-webhooks.test.ts+++ b/test/web-ui-webhooks.test.ts@@ -233,3 +233,19 @@ test("webhook history is relayed with the authenticated viewer, not a query-striconst stranger = await fetch(`${path}?viewer=history-owner`, asUser("stranger"));assert.equal(stranger.status, 404);});++test("create accepts every scheme core verifies, including Linear, and core rejects unknown schemes", async () => {+ const create = (scheme: string) =>+ fetch(+ `${webBase}/api/webhooks`,+ asUser("linear-user", {+ method: "POST",+ body: JSON.stringify({ action: "triage Linear issues", verification: { scheme } }),+ }),+ );+ const linear = await create("linear");+ assert.equal(linear.status, 200);+ const created = (await linear.json()) as { webhook: { verification: { scheme: string } } };+ assert.equal(created.webhook.verification.scheme, "linear");+ assert.equal((await create("bitbucket")).status, 400);+});