From a9b5abdac39e751b53bfbbbb00ab843f35342bcb Mon Sep 17 00:00:00 2001 From: m2 Date: Sat, 5 Dec 2026 13:09:14 -0500 Subject: [PATCH 1/4] Friendly model names everywhere; Slack DM replies when Rovara can't handle a message Model names (Code API 1.30) - Every offered model has a displayName beside its id (the id stays the key). The catalog stores the provider's own name when discovery has one (Bedrock modelName, an inference profile's name, Anthropic display_name), else a deterministic prettifier ("Qwen3 Coder 480B", "Ergo 1.0"), with a small override map. - The gateway sends displayName on the offered list only where its catalog is on; Code names every offered model itself when a gateway sends none. Returned to the website on the step models page (offered, state models, each step's effective model) and the company engine and learning model reads (displayNames). Slack DMs - A DM Rovara could not handle (the broker did not take it, or the person could not be checked) is answered once in the DM with plain words, never while the claim is pending; the once-only marker sits on the event's own claim partition (sort key REPLY), the only key family the ingress role may write. No message text in logs. Co-Authored-By: Claude Sonnet 5.5 --- contracts/shared/offered-agent-models.v1.json | 2 +- docs/architecture/company-inventory.md | 2 + .../src/aws/company-engine-model-routes.ts | 20 ++-- .../src/aws/company-learning-model-routes.ts | 20 ++-- packages/broker/src/aws/slack-direct-front.ts | 35 +++++-- .../src/core-host/company-engine-model.ts | 21 ++++- .../src/core-host/gateway-model-selection.ts | 14 ++- .../src/core/model-selection/service.ts | 6 +- packages/code-api/src/routes.ts | 1 + packages/code-api/src/version.ts | 2 +- packages/contracts/src/agent-model-choice.ts | 3 + packages/contracts/src/app-model-selection.ts | 5 + .../contracts/src/company-engine-model.ts | 3 + .../contracts/src/company-learning-model.ts | 3 + packages/contracts/src/index.ts | 1 + packages/contracts/src/model-display-name.ts | 92 +++++++++++++++++++ .../src/gateway-model-catalog.ts | 12 ++- .../src/model-catalog-discovery.ts | 26 ++++-- .../model-gateway/src/model-catalog-view.ts | 4 + .../model-gateway/src/model-display-name.ts | 83 +++++++++++++++++ packages/model-gateway/src/offered-models.ts | 23 ++++- packages/model-gateway/src/process.ts | 3 +- tests/contract/admin-health.test.ts | 4 +- tests/contract/admin-read-contracts.test.ts | 2 +- tests/contract/code-api-version.test.ts | 2 + .../company-engine-model-routes.test.ts | 11 ++- .../company-learning-model-routes.test.ts | 10 +- tests/contract/developer-contracts.test.ts | 2 +- .../developer-identity-server.test.ts | 2 +- .../developer-share-contracts.test.ts | 2 +- tests/contract/developer-task-shapes.test.ts | 2 +- tests/contract/slack-direct-messages.test.ts | 89 +++++++++++++++++- .../signin-company-goldens/configuration.json | 2 +- tests/unit/model-display-name.test.ts | 47 ++++++++++ tests/unit/model-display-names-broker.test.ts | 79 ++++++++++++++++ .../unit/model-gateway-display-names.test.ts | 87 ++++++++++++++++++ .../unit/model-gateway-offered-models.test.ts | 24 +++++ tests/unit/offered-model-prices.test.ts | 3 +- tests/unit/offered-models-http.test.ts | 2 +- 39 files changed, 686 insertions(+), 65 deletions(-) create mode 100644 packages/contracts/src/model-display-name.ts create mode 100644 packages/model-gateway/src/model-display-name.ts create mode 100644 tests/unit/model-display-name.test.ts create mode 100644 tests/unit/model-display-names-broker.test.ts create mode 100644 tests/unit/model-gateway-display-names.test.ts diff --git a/contracts/shared/offered-agent-models.v1.json b/contracts/shared/offered-agent-models.v1.json index a8759673a4..2bcfee81cd 100644 --- a/contracts/shared/offered-agent-models.v1.json +++ b/contracts/shared/offered-agent-models.v1.json @@ -6,7 +6,7 @@ }, "response": { "version": 1, - "models": "1 to 512 entries, each { model, price?, identity?, priceKnown? (false only, never with price), free? (true only), tested? (true only), limits? { contextWindow, maxOutputTokens } }; slash IDs require exact identity; legacy names have no identity", + "models": "1 to 512 entries, each { model, displayName? (Code API 1.30: the name people read, 1 to 100 characters on one line; the id stays the key), price?, identity?, priceKnown? (false only, never with price), free? (true only), tested? (true only), limits? { contextWindow, maxOutputTokens } }; slash IDs require exact identity; legacy names have no identity", "modelNamePattern": "^(?:[A-Za-z0-9][A-Za-z0-9._:-]{0,127}|[a-z0-9][a-z0-9._-]{0,62}\\/[a-z0-9][a-z0-9._-]{0,62}(?::[a-z0-9][a-z0-9._-]{0,31})?)$", "modelsMax": 512, "identity": { diff --git a/docs/architecture/company-inventory.md b/docs/architecture/company-inventory.md index c8b71b17d8..156ba5f9a3 100644 --- a/docs/architecture/company-inventory.md +++ b/docs/architecture/company-inventory.md @@ -937,6 +937,8 @@ A hit means a query does not itself prove per-row company isolation. It is not a | forwarding | packages/broker/src/aws/index-expiry.ts:34:76:pk | entry.pk | Generic runtime pk forwarding; preserves caller/loaded record identity rather than assigning a new record family. | all indexed record constructors with indexExpiresAt (generic index maintenance) | | forwarding | packages/broker/src/aws/index-expiry.ts:34:90:sk | entry.sk | Runtime sort component forwarded within the feeding partition; not an independent record family. | all indexed record constructors with indexExpiresAt (generic index maintenance) | | forwarding | packages/broker/src/aws/session-steps.ts:233:44:computed | [key] | Runtime property name forwarding; family-bearing pk/entityType constructors are inventoried separately. | invokePublicKey | +| forwarding | packages/broker/src/aws/slack-direct-front.ts:138:17:pk | partition | The direct message event's own claim partition (`ORG##CHANNEL_CLAIM#slack/DIRECT_EVENT#`), built once per event from the company the workspace is bound to and passed to the claim; the key family is unchanged. | pk:CHANNEL_CLAIM | +| forwarding | packages/broker/src/aws/slack-direct-front.ts:157:19:pk | partition | The same event partition, for the once-only failure-reply marker (sort key REPLY) beside the claim; no new key family. | pk:CHANNEL_CLAIM | | forwarding | packages/broker/src/aws/slack-interactivity.ts:618:54:computed | [callbackId === "agentx_feedback_review_changes_submission" ? "feedback_note" : callbackId === "agentx_workflow_checks_retry_submission" ? "workflow_checks" : callbackId === WORKFLOW_FINDINGS_SUBMISSION ? firstInputBlock(asRecord(payload.view)) : "workflow_feedback"] | Runtime property name forwarding; family-bearing pk/entityType constructors are inventoried separately. | confirmationKey | | forwarding | packages/broker/src/aws/slack-interactivity.ts:638:53:computed | [field] | Runtime property name forwarding; family-bearing pk/entityType constructors are inventoried separately. | confirmationKey | | forwarding | packages/broker/src/aws/stuck-setup.ts:73:120:sk | sk | Runtime sort component forwarded within the feeding partition; not an independent record family. | setupWatchKey and workspaceKey in developer/task-records.ts / core/task-flow/keys.ts | diff --git a/packages/broker/src/aws/company-engine-model-routes.ts b/packages/broker/src/aws/company-engine-model-routes.ts index b1f45e835a..51411d8dad 100644 --- a/packages/broker/src/aws/company-engine-model-routes.ts +++ b/packages/broker/src/aws/company-engine-model-routes.ts @@ -1,6 +1,6 @@ // Guided onboarding PR 14 (DEC 254n item 1): the company's own engine model on the deployed developer API (contracts company-engine-model.ts; core-host/company-engine-model.ts reads it). // -// GET /v1/dev/company/engine-model any member of the company -> { model, source, offered, preselect } +// GET /v1/dev/company/engine-model any member of the company -> { model, source, offered, preselect, displayNames } // PUT /v1/dev/company/engine-model owner or admin of the company { model: | null } -> the same view (null clears it: the install default applies again) // // Rules: @@ -17,7 +17,7 @@ import { routeNotServed, CompanyEngineModelBodySchema, agentXError, companyLog, import { Membership, membershipKey } from "./company-check.js"; import type { DeveloperCaller } from "./developer-routes.js"; import type { AdaptedHttpRequest } from "./lambda.js"; -import { COMPANY_ENGINE_MODEL_ENTITY, companyEngineModelKey, offeredEngineModels, readCompanyEngineModel, type EngineModelOfferedReader } from "../core-host/company-engine-model.js"; +import { COMPANY_ENGINE_MODEL_ENTITY, companyEngineModelKey, displayNamesOf, offeredEngineModelList, readCompanyEngineModel, type EngineModelOfferedReader, type OfferedEngineModelList } from "../core-host/company-engine-model.js"; import { roleMay } from "../developer/role-may.js"; export const COMPANY_ENGINE_MODEL_PATH = "/v1/dev/company/engine-model"; @@ -67,11 +67,13 @@ function bodyOf(request: AdaptedHttpRequest): unknown { try { return JSON.parse(request.body) as unknown; } catch { return undefined; } } -const viewOf = (own: string | undefined, install: string | undefined, offered: string[]): CompanyEngineModelView => { +const viewOf = (own: string | undefined, install: string | undefined, list: OfferedEngineModelList): CompanyEngineModelView => { + const offered = list.ids; // A company that chose none runs on the install default when its sources offer it, else on the best offered model (the gateway's first: it lists the model it prefers first); the same rule the start and each step follow. const replaced = own === undefined && install !== undefined && !offered.includes(install); const model = own ?? (replaced ? offered[0]! : install) ?? null; - return { model, source: own === undefined ? "install" : "company", ...(replaced ? { defaultNotOffered: install } : {}), offered, preselect: model !== null && offered.includes(model) ? model : offered[0]! }; + const preselect = model !== null && offered.includes(model) ? model : offered[0]!; + return { model, source: own === undefined ? "install" : "company", ...(replaced ? { defaultNotOffered: install } : {}), offered, preselect, displayNames: displayNamesOf([model, replaced ? install : undefined, ...offered, preselect], list.names) }; }; export async function routeCompanyEngineModel(ctx: CompanyEngineModelContext, caller: DeveloperCaller, companyId: string, request: AdaptedHttpRequest): Promise { @@ -82,8 +84,8 @@ export async function routeCompanyEngineModel(ctx: CompanyEngineModelContext, ca const readOwn = async (): Promise => { try { return await readCompanyEngineModel(reader, company); } catch { throw agentXError("RUNTIME_UNAVAILABLE", ENGINE_MODEL_SETTING_UNAVAILABLE); } }; - const readOffered = async (): Promise => { - try { return await offeredEngineModels(ctx.wiring.offered, company); } catch { throw agentXError("RUNTIME_UNAVAILABLE", ENGINE_MODEL_LIST_UNAVAILABLE); } + const readOffered = async (): Promise => { + try { return await offeredEngineModelList(ctx.wiring.offered, company); } catch { throw agentXError("RUNTIME_UNAVAILABLE", ENGINE_MODEL_LIST_UNAVAILABLE); } }; const installModel = (): string | undefined => { try { return ctx.wiring.installModel(); } catch { return undefined; } @@ -100,8 +102,8 @@ export async function routeCompanyEngineModel(ctx: CompanyEngineModelContext, ca if (!parsed.success) throw agentXError("CONFIG_INVALID", ENGINE_MODEL_BODY_INVALID); const chosen = parsed.data.model; const previous = await readOwn(); - const offered = await readOffered(); - if (chosen !== null && !offered.includes(chosen)) throw agentXError("CONFIG_INVALID", ENGINE_MODEL_NOT_OFFERED_TO_COMPANY); + const list = await readOffered(); + if (chosen !== null && !list.ids.includes(chosen)) throw agentXError("CONFIG_INVALID", ENGINE_MODEL_NOT_OFFERED_TO_COMPANY); const at = new Date(ctx.now()).toISOString(); const key = companyEngineModelKey(company); @@ -122,5 +124,5 @@ export async function routeCompanyEngineModel(ctx: CompanyEngineModelContext, ca if (!(error instanceof Error && error.name === "ConditionalCheckFailedException")) companyLog(company, ctx.wiring.log)({ event: "company.engine_model_validation_not_cleared" }); } companyLog(company, ctx.wiring.log)({ event: chosen === null ? "company.engine_model_cleared" : "company.engine_model_set", actor: caller.developerId }); - return viewOf(chosen ?? undefined, installModel(), offered); + return viewOf(chosen ?? undefined, installModel(), list); } diff --git a/packages/broker/src/aws/company-learning-model-routes.ts b/packages/broker/src/aws/company-learning-model-routes.ts index da9b1c7b45..33e5dde18b 100644 --- a/packages/broker/src/aws/company-learning-model-routes.ts +++ b/packages/broker/src/aws/company-learning-model-routes.ts @@ -1,7 +1,7 @@ // DEC 254zzz63: the company's own lessons LEARNING model on the deployed developer API (contracts company-learning-model.ts; core-host/company-learning-model.ts reads it). Mirrors the // company engine model route (company-engine-model-routes.ts, DEC 254n item 1). // -// GET /v1/dev/company/learning-model any member of the company -> { model, source, offered, preselect } +// GET /v1/dev/company/learning-model any member of the company -> { model, source, offered, preselect, displayNames } // PUT /v1/dev/company/learning-model owner or admin of the company { model: | null } -> the same view (null clears it: the install default applies again) // // Rules: @@ -18,7 +18,7 @@ import { routeNotServed, CompanyLearningModelBodySchema, agentXError, companyLog import { Membership, membershipKey } from "./company-check.js"; import type { DeveloperCaller } from "./developer-routes.js"; import type { AdaptedHttpRequest } from "./lambda.js"; -import { offeredEngineModels, type EngineModelOfferedReader } from "../core-host/company-engine-model.js"; +import { displayNamesOf, offeredEngineModelList, type EngineModelOfferedReader, type OfferedEngineModelList } from "../core-host/company-engine-model.js"; import { COMPANY_LEARNING_MODEL_ENTITY, companyLearningModelKey, isLearnableModel, readCompanyLearningModel } from "../core-host/company-learning-model.js"; import { roleMay } from "../developer/role-may.js"; @@ -68,9 +68,11 @@ function bodyOf(request: AdaptedHttpRequest): unknown { try { return JSON.parse(request.body) as unknown; } catch { return undefined; } } -const viewOf = (own: string | undefined, install: string | undefined, offered: string[]): CompanyLearningModelView => { +const viewOf = (own: string | undefined, install: string | undefined, list: OfferedEngineModelList): CompanyLearningModelView => { + const offered = list.ids; const model = own ?? install ?? null; - return { model, source: own === undefined ? "install" : "company", offered, preselect: model !== null && offered.includes(model) ? model : offered[0] ?? null }; + const preselect = model !== null && offered.includes(model) ? model : offered[0] ?? null; + return { model, source: own === undefined ? "install" : "company", offered, preselect, displayNames: displayNamesOf([model, ...offered, preselect], list.names) }; }; export async function routeCompanyLearningModel(ctx: CompanyLearningModelContext, caller: DeveloperCaller, companyId: string, request: AdaptedHttpRequest): Promise { @@ -82,8 +84,8 @@ export async function routeCompanyLearningModel(ctx: CompanyLearningModelContext try { return await readCompanyLearningModel(reader, company); } catch { throw agentXError("RUNTIME_UNAVAILABLE", LEARNING_MODEL_SETTING_UNAVAILABLE); } }; // Only the Claude models Code can price are offered here: the learning route is the company's own Anthropic account, and the per-call cap is priced from the catalog. - const readOffered = async (): Promise => { - try { return (await offeredEngineModels(ctx.wiring.offered, company)).filter(isLearnableModel); } catch { throw agentXError("RUNTIME_UNAVAILABLE", LEARNING_MODEL_LIST_UNAVAILABLE); } + const readOffered = async (): Promise => { + try { const all = await offeredEngineModelList(ctx.wiring.offered, company); return { ids: all.ids.filter(isLearnableModel), names: all.names }; } catch { throw agentXError("RUNTIME_UNAVAILABLE", LEARNING_MODEL_LIST_UNAVAILABLE); } }; const installModel = (): string | undefined => { try { return ctx.wiring.installModel(); } catch { return undefined; } @@ -100,8 +102,8 @@ export async function routeCompanyLearningModel(ctx: CompanyLearningModelContext if (!parsed.success) throw agentXError("CONFIG_INVALID", LEARNING_MODEL_BODY_INVALID); const chosen = parsed.data.model; const previous = await readOwn(); - const offered = await readOffered(); - if (chosen !== null && !offered.includes(chosen)) throw agentXError("CONFIG_INVALID", LEARNING_MODEL_NOT_OFFERED_TO_COMPANY); + const list = await readOffered(); + if (chosen !== null && !list.ids.includes(chosen)) throw agentXError("CONFIG_INVALID", LEARNING_MODEL_NOT_OFFERED_TO_COMPANY); const at = new Date(ctx.now()).toISOString(); const key = companyLearningModelKey(company); @@ -114,5 +116,5 @@ export async function routeCompanyLearningModel(ctx: CompanyLearningModelContext await ctx.documentClient.send(new TransactWriteCommand({ TransactItems: [setting, audit] })); } catch { throw agentXError("RUNTIME_UNAVAILABLE", LEARNING_MODEL_SETTING_UNAVAILABLE); } companyLog(company, ctx.wiring.log)({ event: chosen === null ? "company.learning_model_cleared" : "company.learning_model_set", actor: caller.developerId }); - return viewOf(chosen ?? undefined, installModel(), offered); + return viewOf(chosen ?? undefined, installModel(), list); } diff --git a/packages/broker/src/aws/slack-direct-front.ts b/packages/broker/src/aws/slack-direct-front.ts index b1d18793e7..4ea23a971e 100644 --- a/packages/broker/src/aws/slack-direct-front.ts +++ b/packages/broker/src/aws/slack-direct-front.ts @@ -38,6 +38,8 @@ export type SlackDirectResult = { kind: "ignored"; reason: string } | { kind: "h /** What a person the company does not know is told, when no link code can be given (the link notice is claimed once an interval). */ export const DIRECT_UNKNOWN_WORDS = "I don't know yet which Rovara person you are, so I haven't passed that on. Sign in to Rovara with Slack, then message me again."; +/** What a person is told when Rovara could not handle their message (the broker did not take it, or the person could not be checked): plain, no cause, nothing of their message. */ +export const DIRECT_FAILURE_WORDS = "Sorry, I couldn't handle that message. Please try again in a minute."; const CLAIM_SECONDS = 14 * 24 * 60 * 60; /** * How long a claim holds while its event is still being handled (the Slack Lambda times out after 10 seconds). Past it, a claim that was never marked done (the Lambda stopped mid-delivery) lapses, so Slack's @@ -132,8 +134,8 @@ type DirectClaim = { key: { pk: string; sk: string }; state: "first" | "done" | * is still handling it, and may yet fail: Slack must try again later, never be told it was handled. Only PutItem: a taken claim is told done from in flight by a put that applies only to a done claim (written back as done). * A read or write that fails throws (Slack tries again). */ -async function claim(store: NonNullable["store"], companyId: string, eventId: string, nowSeconds: number): Promise { - const key = { pk: orgScoped(OrgIdSchema.parse(companyId), `CHANNEL_CLAIM#slack/DIRECT_EVENT#${eventId}`), sk: "CLAIM" }; +async function claim(store: NonNullable["store"], partition: string, nowSeconds: number): Promise { + const key = { pk: partition, sk: "CLAIM" }; const first = await store.put({ item: { ...key, state: "pending", expiresAt: nowSeconds + PENDING_SECONDS }, condition: when.or(when.absent(), when.lte("expiresAt", nowSeconds)) }); if (first.applied) return { key, state: "first" }; const repeat = await store.put({ item: { ...key, state: "done", expiresAt: nowSeconds + CLAIM_SECONDS }, condition: when.eq("state", "done") }); @@ -145,10 +147,25 @@ async function markDone(store: NonNullable log("direct.claim_done_failed", { eventId, ...failureFields(error) })); } +/** + * The one failure reply of an event. A marker on the event's own claim partition (`CHANNEL_CLAIM#slack/DIRECT_EVENT#`, sort key `REPLY`: the only partition the ingress role may write) is put only when absent, so Slack's retries of + * the same event (and a repeated delivery) never say it twice; a marker that cannot be written says nothing (never a second reply). Said for a final failure only: an event still being handled (the claim is in flight) + * is a 500 for Slack to retry and is never answered. Logs the event id only, never the message or the words. + */ +async function sayFailureOnce(store: NonNullable["store"], partition: string, eventId: string, nowSeconds: number, say: (text: string) => Promise, log: (event: string, fields: Record) => void): Promise { + try { + const key = { pk: partition, sk: "REPLY" }; + const marked = await store.put({ item: { ...key, state: "replied", expiresAt: nowSeconds + CLAIM_SECONDS }, condition: when.or(when.absent(), when.lte("expiresAt", nowSeconds)) }); + if (!marked.applied) return; + } catch (error) { log("direct.failure_marker_failed", { eventId, ...failureFields(error) }); return; } + await say(DIRECT_FAILURE_WORDS); + log("direct.failure_answered", { eventId }); +} + /** The claim's answer before anything is said or handed on: undefined to go on (this request has the event), else what Slack gets. */ -async function claimOrAnswer(store: NonNullable["store"], companyId: string, eventId: string, nowSeconds: number, log: (event: string, fields: Record) => void): Promise<{ claimed: DirectClaim } | { result: SlackDirectResult }> { +async function claimOrAnswer(store: NonNullable["store"], partition: string, eventId: string, nowSeconds: number, log: (event: string, fields: Record) => void): Promise<{ claimed: DirectClaim } | { result: SlackDirectResult }> { let claimed: DirectClaim; - try { claimed = await claim(store, companyId, eventId, nowSeconds); } catch (error) { log("direct.claim_failed", { eventId, ...failureFields(error) }); return { result: { kind: "failed" } }; } + try { claimed = await claim(store, partition, nowSeconds); } catch (error) { log("direct.claim_failed", { eventId, ...failureFields(error) }); return { result: { kind: "failed" } }; } if (claimed.state === "done") return { result: { kind: "ignored", reason: "duplicate_event" } }; if (claimed.state === "in_flight") { log("direct.claim_in_flight", { eventId }); return { result: { kind: "failed" } }; } return { claimed }; @@ -160,8 +177,10 @@ export async function answerDirectMessage(deps: SlackDirectDependencies, message const { direct } = deps; const workspaces = deps.workspaces; let companyId: string; + let partition: string; let token: string; - try { companyId = await workspaces.requireCompany(message.teamId); } catch (error) { log("direct.workspace_check_failed", failureFields(error)); return { kind: "ignored", reason: "workspace_not_connected" }; } + // The event's one partition (its claim and, beside it, the failure-reply marker): the only key family the ingress role may write. + try { companyId = await workspaces.requireCompany(message.teamId); partition = orgScoped(OrgIdSchema.parse(companyId), `CHANNEL_CLAIM#slack/DIRECT_EVENT#${message.eventId}`); } catch (error) { log("direct.workspace_check_failed", failureFields(error)); return { kind: "ignored", reason: "workspace_not_connected" }; } try { token = await slackWorkspaceToken(workspaces, message.teamId); } catch (error) { log("direct.token_read_failed", failureFields(error)); return { kind: "ignored", reason: "workspace_token_missing" }; } const nowSeconds = Math.floor((deps.now ?? Date.now)() / 1_000); const thread = message.threadTs !== undefined && message.threadTs !== message.messageTs ? { threadTs: message.threadTs } : {}; @@ -170,10 +189,10 @@ export async function answerDirectMessage(deps: SlackDirectDependencies, message }; return await slackRequestWorkspace.run({ teamId: message.teamId, companyId, token }, async (): Promise => { let person: Awaited>; - try { person = await slackCompanyPerson(deps, message.teamId, message.userId, message.userTeamId); } catch (error) { log("direct.company_check_failed", { eventId: message.eventId, ...failureFields(error) }); return { kind: "ignored", reason: "company_check_failed" }; } + try { person = await slackCompanyPerson(deps, message.teamId, message.userId, message.userTeamId); } catch (error) { log("direct.company_check_failed", { eventId: message.eventId, ...failureFields(error) }); await sayFailureOnce(workspaces.store, partition, message.eventId, nowSeconds, say, log); return { kind: "ignored", reason: "company_check_failed" }; } // Nothing is looked up for, or said to, a person of another workspace. if (person.kind === "outsider") return { kind: "ignored", reason: "external_organization_user" }; - const taken = await claimOrAnswer(workspaces.store, companyId, message.eventId, nowSeconds, log); + const taken = await claimOrAnswer(workspaces.store, partition, message.eventId, nowSeconds, log); if ("result" in taken) return taken.result; const { claimed } = taken; if (person.kind !== "linked") { @@ -190,6 +209,8 @@ export async function answerDirectMessage(deps: SlackDirectDependencies, message // The broker did not take it: the claim goes back so Slack's retry is handled as new. await workspaces.store.delete({ key: claimed.key }).catch((deleteError: unknown) => log("direct.claim_release_failed", { eventId: message.eventId, ...failureFields(deleteError) })); log("direct.hand_off_failed", { eventId: message.eventId, ...failureFields(error) }); + // The message was not taken: say so once for the event (Slack's retries are handled as new and never repeat it). + await sayFailureOnce(workspaces.store, partition, message.eventId, nowSeconds, say, log); return { kind: "failed" }; } await markDone(workspaces.store, claimed, message.eventId, nowSeconds, log); diff --git a/packages/broker/src/core-host/company-engine-model.ts b/packages/broker/src/core-host/company-engine-model.ts index 8f0e6dfb04..eca31a2d2b 100644 --- a/packages/broker/src/core-host/company-engine-model.ts +++ b/packages/broker/src/core-host/company-engine-model.ts @@ -11,7 +11,7 @@ // (ENGINE_MODEL_UNCHECKED, never a guess); a company on the install's model whose list cannot be read starts as before (the signed price read next is the gateway's own readiness check). // // A row that is there but is not exactly this company's setting is unreadable: the route and the start fail closed (never the install default in its place). -import { ENGINE_MODEL_NOT_OFFERED, ENGINE_MODEL_UNCHECKED, OfferedAgentModelsSchema, OrgIdSchema, agentXError, isCoreAgentModelId, orgSettingsKey, +import { ENGINE_MODEL_NOT_OFFERED, ENGINE_MODEL_UNCHECKED, OfferedAgentModelsSchema, modelDisplayName, OrgIdSchema, agentXError, isCoreAgentModelId, orgSettingsKey, type AgentXError, type InvocationModelRoute, type OrgId, type OrgKey, type StoredDocument } from "@agentx/contracts"; import { gatewayRouteOf } from "./gateway-model-selection.js"; import { readGatewayModelAccess } from "./gateway-model-access.js"; @@ -86,14 +86,27 @@ export function companyEngineModelRoute(input: { /** Reads the models the gateway offers one company (the HTTP reader's `offered`, or the admin read's function). The answer is checked against the contract here. */ export type EngineModelOfferedReader = (companyId: OrgId) => Promise; -/** The gateway's offered model ids for the company (the models the engine model may be), in the gateway's order; throws (no cause) when the list cannot be read or is not the contract. */ -export async function offeredEngineModels(reader: EngineModelOfferedReader, companyId: OrgId): Promise { +/** The gateway's offered model ids for the company (the models the engine model may be), in the gateway's order, with the name people read for each (the gateway's own, else Code's prettified id). */ +export interface OfferedEngineModelList { ids: string[]; names: ReadonlyMap } +/** Throws (no cause) when the list cannot be read or is not the contract. */ +export async function offeredEngineModelList(reader: EngineModelOfferedReader, companyId: OrgId): Promise { let answer: unknown; try { answer = await reader(companyId); } catch { throw new Error("offered"); } const parsed = OfferedAgentModelsSchema.safeParse(answer); if (!parsed.success) throw new Error("offered"); // A vendor/model:variant name (OpenRouter's `:free`) is not offered here: the stack's own model pattern (CORE_AGENT_MODEL_PATTERN) has no ":" for such names, so a company could pick it and be refused. - return parsed.data.models.map((entry) => entry.model).filter((model) => !(model.includes("/") && model.includes(":"))); + const kept = parsed.data.models.filter((entry) => !(entry.model.includes("/") && entry.model.includes(":"))); + return { ids: kept.map((entry) => entry.model), names: new Map(kept.map((entry) => [entry.model, modelDisplayName(entry.model, entry.displayName)])) }; +} +/** The gateway's offered model ids for the company, in the gateway's order. */ +export async function offeredEngineModels(reader: EngineModelOfferedReader, companyId: OrgId): Promise { + return (await offeredEngineModelList(reader, companyId)).ids; +} +/** The name people read for each id a view names (an id the list has no name for, such as an install default no source offers, is prettified): `displayNames` of the company model views. */ +export function displayNamesOf(ids: readonly (string | null | undefined)[], names: ReadonlyMap): Record { + const out: Record = {}; + for (const id of ids) if (typeof id === "string") out[id] = names.get(id) ?? modelDisplayName(id); + return out; } /** diff --git a/packages/broker/src/core-host/gateway-model-selection.ts b/packages/broker/src/core-host/gateway-model-selection.ts index f47b6b7b48..95ed52b54c 100644 --- a/packages/broker/src/core-host/gateway-model-selection.ts +++ b/packages/broker/src/core-host/gateway-model-selection.ts @@ -11,7 +11,7 @@ import { publishAgentModelChoice } from "./stored-agent-model-choice.js"; // // Nothing here is built without a reader: a deployment without one keeps the single-model route of L2b (gateway-model-access.ts), byte for byte. import { - OfferedAgentModelsSchema, agentModelIdentity, agentModelName, canonicalModelName, + OfferedAgentModelsSchema, agentModelIdentity, agentModelName, canonicalModelName, modelDisplayName, type AuditSink, type Approvers, type DocumentStore, type InvocationModelRoute, type ModelIdentifier, type ModelSelectionState, type OfferedAgentModel, type OrgId, } from "@agentx/contracts"; import { createModelSelection, type ModelSelectionSeams, type ModelSelectionService } from "../core/model-selection/service.js"; @@ -56,7 +56,8 @@ export function createOfferedModelsView(input: { reader: OfferedModelsReader; co ]); const parsed = OfferedAgentModelsSchema.safeParse(answer); if (!parsed.success) throw new Error("shape"); - held = { at: now, models: Object.freeze(parsed.data.models.map((entry) => Object.freeze({ ...entry }))) }; + // Every offered model has a name people read: the gateway's own (Code API 1.30), else Code's reading of the id (a gateway older than 1.30 sends none). + held = { at: now, models: Object.freeze(parsed.data.models.map((entry) => Object.freeze({ ...entry, displayName: modelDisplayName(entry.model, entry.displayName) }))) }; return held.models; } catch { throw new OfferedModelsUnavailable(); } finally { if (timer !== undefined) clearTimeout(timer); } @@ -142,6 +143,10 @@ export function hostedStateView(state: ModelSelectionState, input: { offered: re const price = name === undefined ? undefined : input.offered.find((entry) => entry.model === name)?.price; return price === undefined ? undefined : { input: price.inputUsdPerMillion, output: price.outputUsdPerMillion, source: "catalog" as const }; }; + const nameOf = (model: ModelIdentifier): string => { + const name = agentModelName(model); + return modelDisplayName(model.modelId, name === undefined ? undefined : input.offered.find((entry) => entry.model === name)?.displayName); + }; const install = state.install; const companyModel = (model: ModelIdentifier): boolean => input.companyModelSet && install !== null && canonicalModelName(model) === canonicalModelName(install); const steps = state.steps.map((step) => { @@ -149,11 +154,12 @@ export function hostedStateView(state: ModelSelectionState, input: { offered: re const price = step.effective.priceUsdPerMillion ?? priceOf(step.effective.model); // A checking step's BUILTIN_DEFAULT is Rovara's own pick (a model of another AI company, or the same company's when none is usable): it keeps its words. const reason = step.effective.reason === "BUILTIN_DEFAULT" && !CHECKING_STAGES.has(step.stage) && companyModel(step.effective.model) ? "INSTALL_MODEL" as const : step.effective.reason; - return { ...step, effective: { ...step.effective, reason, ...(price === undefined ? {} : { priceUsdPerMillion: price }) } }; + return { ...step, effective: { ...step.effective, reason, displayName: nameOf(step.effective.model), ...(price === undefined ? {} : { priceUsdPerMillion: price }) } }; }); const models = state.models.map((entry) => { const price = entry.priceUsdPerMillion ?? priceOf(entry.model); - return price === undefined ? entry : { ...entry, priced: true, priceUsdPerMillion: price }; + const named = { ...entry, displayName: nameOf(entry.model) }; + return price === undefined ? named : { ...named, priced: true, priceUsdPerMillion: price }; }); return { ...state, steps, models }; } diff --git a/packages/broker/src/core/model-selection/service.ts b/packages/broker/src/core/model-selection/service.ts index 38178225ab..517bc9c0ea 100644 --- a/packages/broker/src/core/model-selection/service.ts +++ b/packages/broker/src/core/model-selection/service.ts @@ -7,7 +7,7 @@ // A model's price decides one thing here: where a cap applies (a run limit is held on the model proxy), a model with no price is not a candidate, exactly as the proxy would refuse it (`model_not_priced`). import { createHash } from "node:crypto"; import { - ModelSelectionBodySchema, STAGE_EDIT_GROUPS, STAGE_IDS, STAGE_REFERENCE, StageModelOverridesSchema, canonicalModelName, modelCompany, sameModelOrUnrecognised, + ModelSelectionBodySchema, STAGE_EDIT_GROUPS, STAGE_IDS, STAGE_REFERENCE, StageModelOverridesSchema, canonicalModelName, modelCompany, modelDisplayName, sameModelOrUnrecognised, type ApprovalRequest, type Approvers, type AuditSink, type InvocationModelRoute, type ModelChoiceView, type ModelFallback, type ModelIdentifier, type ModelSelectionState, type ModelStepView, type OrgId, type Principal, type StageId, type StageModelChoice, type StageModelRefusalCode, type DocumentStore, type ThinkingLevel, } from "@agentx/contracts"; @@ -247,7 +247,7 @@ export function createModelSelection(deps: ModelSelectionDependencies): ModelSel stage, setting: choiceOf(setting), ...(outcome.ok ? { effective: { - model: outcome.step.model, thinkingLevel: outcome.step.thinkingLevel, reason: outcome.step.reason, sameModelAsChecked: outcome.step.sameModelAsChecked, + model: outcome.step.model, displayName: modelDisplayName(outcome.step.model.modelId), thinkingLevel: outcome.step.thinkingLevel, reason: outcome.step.reason, sameModelAsChecked: outcome.step.sameModelAsChecked, ...(outcome.step.fallback === undefined ? {} : { fallback: outcome.step.fallback }), ...(price === undefined ? {} : { priceUsdPerMillion: price }), } } : { refusal: { code: outcome.code, words: outcome.words } }), @@ -257,7 +257,7 @@ export function createModelSelection(deps: ModelSelectionDependencies): ModelSel const models: ModelChoiceView[] = ctx.candidates.map((entry) => { const price = viewOfPrice(entry.model); return { - model: entry.model, company: modelCompany(entry.model), label: label(entry.model).slice(0, 100), priced: !unpricedNow.has(poolKey(entry.model)), + model: entry.model, displayName: modelDisplayName(entry.model.modelId), company: modelCompany(entry.model), label: label(entry.model).slice(0, 100), priced: !unpricedNow.has(poolKey(entry.model)), ...(price === undefined ? {} : { priceUsdPerMillion: price }), usable: entry.accountCannotUse !== true, }; }); diff --git a/packages/code-api/src/routes.ts b/packages/code-api/src/routes.ts index 2cc58524d9..0178598fa4 100644 --- a/packages/code-api/src/routes.ts +++ b/packages/code-api/src/routes.ts @@ -514,6 +514,7 @@ export const ROUTES: readonly Route[] = [ // Script tokens are long-lived credentials, and a person erase deletes a removed person's records: full access only (and a live owner or admin to make a token or erase). // #1175: the company's per-step agent model choice (core-host/agent-model-routes.ts): full access only, then the core reads the live role (any member reads, // an owner or admin changes). Without these rows the broker answered 404 before auth, and Cloud's "AI and spending" step could never finish. + // Code API 1.30: the answer (and the engine and learning model reads) also name `displayName` for every model, the name people read beside the id (optional, read tolerantly; the id stays the key). { method: "GET", path: "/v1/app/agent-models", requires: "full" }, { method: "POST", path: "/v1/app/agent-models", requires: "full" }, { method: "GET", path: "/v1/app/script-tokens", requires: "full" }, diff --git a/packages/code-api/src/version.ts b/packages/code-api/src/version.ts index 0828224a94..5d101b30c4 100644 --- a/packages/code-api/src/version.ts +++ b/packages/code-api/src/version.ts @@ -5,5 +5,5 @@ // // CODE_API_MIN_CLIENT ("major.minor") is the oldest version of this package a client may be built against and still be served. Code raises it only after the client side has stopped using what is // being removed (see README.md, "Skew"). A test pins a digest of the contract surface and fails when the surface changes without a bump here. -export const CODE_API_VERSION = "1.29"; +export const CODE_API_VERSION = "1.30"; export const CODE_API_MIN_CLIENT = "1.2"; diff --git a/packages/contracts/src/agent-model-choice.ts b/packages/contracts/src/agent-model-choice.ts index 04f885887e..2a0cee1421 100644 --- a/packages/contracts/src/agent-model-choice.ts +++ b/packages/contracts/src/agent-model-choice.ts @@ -7,6 +7,7 @@ // says what Cloud's side must answer). import { z } from "zod"; import { GatewayModelIdentitySchema } from "./gateway-model-identity.js"; +import { ModelDisplayNameSchema } from "./model-display-name.js"; import { ModelSelectionStateSchema } from "./app-model-selection.js"; import { OrgIdSchema } from "./company-scope.js"; import type { ModelIdentifier } from "./models-node.js"; @@ -39,6 +40,8 @@ export const OfferedModelLimitsSchema = z.object({ contextWindow: z.number().int * `free` (a `:free` model: rate-limited, and the provider may keep prompts), `tested` (one of the models Rovara proved by hand), `limits`. */ export const OfferedAgentModelSchema = z.object({ + /** Code API 1.30: the name people read (the provider's own, else a prettified id), beside the id. Display only; `model` stays the key. Absent from a gateway older than 1.30: Code names the model itself (`modelDisplayName`). */ + displayName: ModelDisplayNameSchema.optional(), model: z.string().regex(AGENT_MODEL_NAME), price: OfferedModelPriceSchema.optional(), identity: GatewayModelIdentitySchema.optional(), priceKnown: z.literal(false).optional(), free: z.literal(true).optional(), tested: z.literal(true).optional(), limits: OfferedModelLimitsSchema.optional(), }).strict().superRefine((entry, context) => { diff --git a/packages/contracts/src/app-model-selection.ts b/packages/contracts/src/app-model-selection.ts index b9d36d1e5f..1546585f9c 100644 --- a/packages/contracts/src/app-model-selection.ts +++ b/packages/contracts/src/app-model-selection.ts @@ -2,6 +2,7 @@ // reader for what a tool reads. Words, ids, counts and prices; never a model's output. The setting itself is written on the local page only (a tool with the API token reads it and cannot change it). import { z } from "zod"; import { forwardReader } from "./forward-reader.js"; +import { ModelDisplayNameSchema } from "./model-display-name.js"; import { ModelIdentifierSchema, ThinkingLevelSchema } from "./models.js"; import { StageIdSchema, ModelFallbackSchema, STAGE_MODEL_REFUSAL_CODES } from "./stage-model-shared.js"; import { StageModelChoiceSchema } from "./stage-models.js"; @@ -18,6 +19,8 @@ export const ModelStepViewSchema = z.object({ /** The model the step would run on now. Absent when none can be chosen (`refusal` says why). */ effective: z.object({ model: ModelIdentifierSchema, + /** Code API 1.30: the name people read for `model` (the id stays the key). */ + displayName: ModelDisplayNameSchema.optional(), thinkingLevel: ThinkingLevelSchema.nullable(), reason: z.enum(MODEL_STEP_REASONS), /** A checking step that runs on the same model as the step it checks (the install has one model, or nothing else was usable). */ @@ -33,6 +36,8 @@ export type ModelStepView = z.infer; export const ModelChoiceViewSchema = z.object({ model: ModelIdentifierSchema, + /** Code API 1.30: the name people read for `model` (the provider's own, else a prettified id); `label` stays the raw `provider/id`. */ + displayName: ModelDisplayNameSchema.optional(), /** The maker, a fixed word (`anthropic`, `openai`, ...; `other` when unknown). */ company: z.string().min(1).max(64), label: z.string().min(1).max(100), diff --git a/packages/contracts/src/company-engine-model.ts b/packages/contracts/src/company-engine-model.ts index 9a29e8363a..8dccd5025c 100644 --- a/packages/contracts/src/company-engine-model.ts +++ b/packages/contracts/src/company-engine-model.ts @@ -8,6 +8,7 @@ // BEFORE it starts (no machine, no spend) with ENGINE_MODEL_NOT_OFFERED; a list that cannot be read refuses with ENGINE_MODEL_UNCHECKED (never a guess). import { z } from "zod"; import { AGENT_MODEL_NAME } from "./agent-model-choice.js"; +import { ModelDisplayNameSchema } from "./model-display-name.js"; import { isCoreAgentModelId } from "./core-engine-infra.js"; /** A model id a company may hold: well formed as the gateway names models (and as the install's own setting is checked). Whether it is OFFERED is the gateway's live answer. */ @@ -24,6 +25,7 @@ export type CompanyEngineModelBody = z.infer because your sources can't run "); * offered the model ids the gateway offers THIS company now, in the gateway's order; + * displayNames Code API 1.30: the name people read for every id above (`model`, `defaultNotOffered`, `offered`, `preselect`), by id; the id stays the key; * preselect what a picker preselects: `model` when it is offered, else the BEST offered model, which is the gateway's first (the gateway lists its preferred model first). */ export const CompanyEngineModelViewSchema = z.object({ @@ -32,6 +34,7 @@ export const CompanyEngineModelViewSchema = z.object({ defaultNotOffered: z.string().regex(AGENT_MODEL_NAME).optional(), offered: z.array(z.string().regex(AGENT_MODEL_NAME)).min(1), preselect: z.string().regex(AGENT_MODEL_NAME), + displayNames: z.record(z.string().regex(AGENT_MODEL_NAME), ModelDisplayNameSchema).optional(), }).strict(); export type CompanyEngineModelView = z.infer; diff --git a/packages/contracts/src/company-learning-model.ts b/packages/contracts/src/company-learning-model.ts index afecde0859..14c5049146 100644 --- a/packages/contracts/src/company-learning-model.ts +++ b/packages/contracts/src/company-learning-model.ts @@ -8,6 +8,7 @@ // The company is always the caller's LIVE membership, never a body, query, header or claim. import { z } from "zod"; import { AGENT_MODEL_NAME } from "./agent-model-choice.js"; +import { ModelDisplayNameSchema } from "./model-display-name.js"; import { isCoreLearningModelId } from "./core-engine-infra.js"; /** A learning model a company may hold: a Claude engine name (the learning route is the company's own Anthropic account). Whether it is OFFERED is the gateway's live answer. */ @@ -22,6 +23,7 @@ export type CompanyLearningModelBody = z.infer; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index ba9ac49d61..b432aacbca 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -530,6 +530,7 @@ export * from "./eval-stand-in-descriptor.js"; export * from "./eval-standin-pool.js"; export * from "./eval-standin-cassettes.js"; export * from "./agent-model-choice.js"; +export * from "./model-display-name.js"; export * from "./company-engine-model.js"; export * from "./company-learning-model.js"; export * from "./company-details.js"; diff --git a/packages/contracts/src/model-display-name.ts b/packages/contracts/src/model-display-name.ts new file mode 100644 index 0000000000..2b0711bac9 --- /dev/null +++ b/packages/contracts/src/model-display-name.ts @@ -0,0 +1,92 @@ +// Friendly model names. Every model Rovara offers has a display name next to its id (the id stays the key: it is what is stored, chosen and called). +// +// 1. the provider's own name when discovery had one (Bedrock `modelName`, an inference profile's `inferenceProfileName`, OpenRouter `name`, Anthropic `display_name`), kept on the catalog record and +// sent on the offered list as `displayName`; +// 2. else this deterministic prettifier over the id (`qwen.qwen3-coder-480b-a35b-v1:0` is "Qwen3 Coder 480B", `us.amazon.ergo-1.0` is "Ergo 1.0"); +// 3. a small override map for ids the prettifier cannot read well. +// +// A pure function with no table or clock, so a Code that reads a gateway older than this change names every model the same way the gateway does. The gateway repeats the function +// (packages/model-gateway/src/model-display-name.ts: it takes no dependency on contracts); a contract test holds the two equal on every row of one shared table. +import { z } from "zod"; + +/** The longest display name carried anywhere. */ +export const MODEL_DISPLAY_NAME_MAX = 100; +export const ModelDisplayNameSchema = z.string().min(1).max(MODEL_DISPLAY_NAME_MAX).refine((value) => ![...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127), "no control characters"); + +/** Ids the prettifier cannot read well, by the id with its routing prefix and version suffix removed (see `normalized`). Keep it small. */ +export const MODEL_DISPLAY_NAME_OVERRIDES: Readonly> = Object.freeze({ + "openai.gpt-oss-120b": "GPT-OSS 120B", + "openai.gpt-oss-20b": "GPT-OSS 20B", + "openai.gpt-oss-safeguard-120b": "GPT-OSS Safeguard 120B", + "openai.gpt-oss-safeguard-20b": "GPT-OSS Safeguard 20B", + "zai.glm-4.7": "GLM 4.7", + "moonshot.kimi-k2-thinking": "Kimi K2 Thinking", + "moonshotai.kimi-k2.5": "Kimi K2.5", +}); + +const GEOGRAPHY = /^(?:us|eu|apac|jp|au|ca|global|us-gov)\./u; +const VERSION_SUFFIX = /-(?:v\d+(?::\d+)?|\d+:\d+)$/u; +const DATE_TOKEN = /^(?:\d{8}|\d{4})$/u; +/** Words that are the vendor's brand or an acronym, by lower-case token. */ +const WORDS: Readonly> = Object.freeze({ + gpt: "GPT", glm: "GLM", oss: "OSS", ai: "AI", llm: "LLM", vl: "VL", moe: "MoE", deepseek: "DeepSeek", openai: "OpenAI", minimax: "MiniMax", zai: "Z.AI", moonshot: "Moonshot", moonshotai: "Moonshot", qwen: "Qwen", amazon: "Amazon", anthropic: "Anthropic", mistral: "Mistral", +}); +/** A size such as `480b` or `20b`; an active-parameter marker such as `a35b` is dropped (`qwen3-coder-480b-a35b` is "Qwen3 Coder 480B"). */ +const SIZE = /^(\d+(?:\.\d+)?)([bkmt])$/iu; +const ACTIVE_PARAMETERS = /^a\d+(?:\.\d+)?b$/iu; +const SMALL_NUMBER = /^\d{1,2}$/u; + +/** The id as the prettifier reads it: no routing prefix (`us.`, a `vendor/` of OpenRouter's), no `-v1:0` version suffix, no `:variant`, lower case. */ +function normalized(id: string): { text: string; variant: string | undefined } { + let text = id.trim().toLowerCase(); + if (text.includes("/")) text = text.slice(text.lastIndexOf("/") + 1); + let variant: string | undefined; + const colon = text.lastIndexOf(":"); + if (colon > 0 && !/^\d+$/u.test(text.slice(colon + 1))) { variant = text.slice(colon + 1); text = text.slice(0, colon); } + text = text.replace(GEOGRAPHY, "").replace(VERSION_SUFFIX, ""); + return { text, variant }; +} +const capitalized = (token: string): string => WORDS[token] ?? (token.length === 0 ? token : `${token.slice(0, 1).toUpperCase()}${token.slice(1)}`); + +/** Joins two short number tokens that are one version (`4-5` is "4.5", `1-0` is "1.0"); every other token stays. */ +function versioned(tokens: readonly string[]): string[] { + const out: string[] = []; + for (const token of tokens) { + const last = out[out.length - 1]; + if (last !== undefined && SMALL_NUMBER.test(token) && SMALL_NUMBER.test(last)) out[out.length - 1] = `${last}.${token}`; + else out.push(token); + } + return out; +} + +function words(text: string): string { + const tokens = text.split(/[-_ ]+/u).filter((t) => t.length > 0 && !DATE_TOKEN.test(t) && !ACTIVE_PARAMETERS.test(t)); + return versioned(tokens).map((token) => { + const size = SIZE.exec(token); + if (size !== null) return `${size[1]}${size[2]!.toUpperCase()}`; + return /^v\d/u.test(token) ? `V${token.slice(1)}` : capitalized(token); + }).join(" "); +} + +/** + * The display name of a model id (any source: a Bedrock model or `us.` profile id, a Claude engine name, an OpenAI name, an OpenRouter `vendor/model`). Never empty and never longer than + * MODEL_DISPLAY_NAME_MAX; an id that reads to nothing is returned as it is. + */ +export function prettyModelName(id: string): string { + const { text, variant } = normalized(id); + const override = MODEL_DISPLAY_NAME_OVERRIDES[text]; + // A vendor word alone says nothing (`deepseek.v3.2`), so it stays when what follows has no word of its own; otherwise it is dropped (`qwen.qwen3-coder` is "Qwen3 Coder"). + const dot = text.indexOf("."); + const vendor = dot > 0 && /^[a-z]{2,30}$/u.test(text.slice(0, dot)) ? text.slice(0, dot) : undefined; + const rest = vendor === undefined ? text : text.slice(dot + 1); + const hasWord = /(?:^|[-_])[a-z]{3,}/u.test(rest); + const base = override ?? words(vendor !== undefined && !hasWord ? text.replace(".", " ") : rest); + const named = variant === undefined ? base : `${base} (${variant})`; + return named === "" ? id.slice(0, MODEL_DISPLAY_NAME_MAX) : named.slice(0, MODEL_DISPLAY_NAME_MAX); +} + +/** The provider's own name when it is a usable one (one line, 1 to 100 characters), else the prettified id. */ +export function modelDisplayName(id: string, providerName?: string): string { + const own = typeof providerName === "string" ? providerName.replace(/\s+/gu, " ").trim() : ""; + return ModelDisplayNameSchema.safeParse(own).success ? own : prettyModelName(id); +} diff --git a/packages/model-gateway/src/gateway-model-catalog.ts b/packages/model-gateway/src/gateway-model-catalog.ts index 81aa041fae..ce2500cd9d 100644 --- a/packages/model-gateway/src/gateway-model-catalog.ts +++ b/packages/model-gateway/src/gateway-model-catalog.ts @@ -14,6 +14,7 @@ // One record list per provider (`rovara` is Rovara's own Bedrock account, `openai` and `anthropic` are the providers' lists read with Rovara's own discovery key). OpenRouter keeps // its own live list (openrouter-catalog.ts); it is not repeated here. import { record, whole } from "./model-gateway-token.js"; +import { MODEL_DISPLAY_NAME_MAX, gatewayDisplayName } from "./model-display-name.js"; export const CATALOG_SOURCES = ["rovara", "openai", "anthropic"] as const; export type CatalogSource = typeof CATALOG_SOURCES[number]; @@ -48,6 +49,8 @@ export interface CatalogModel { id: string; /** The provider's own version stamp of this model when it lists one (OpenAI `created`, Anthropic `created_at`), else the id: a change means a new version to probe. */ version: string; + /** The name people read for the model: the provider's own (Bedrock `modelName`, a profile's `inferenceProfileName`, Anthropic `display_name`) when discovery had one, else the prettified id. Display only; `name` and `id` stay the keys. A seed no list has named has none (the offered list prettifies its id). */ + displayName?: string; origin: "seed" | "discovered"; discoveredAt: number; seenAt: number; /** Set when the latest list no longer shows the model. A discovered model that is gone is no longer offered; a seed stays. */ @@ -58,7 +61,10 @@ export interface CatalogModel { export interface CatalogSnapshot { version: number; source: CatalogSource; savedAt: number; models: CatalogModel[] } /** The provider's model as discovery reports it, before any state. */ -export interface DiscoveredModel { name: string; id: string; version: string } +export interface DiscoveredModel { name: string; id: string; version: string; /** The provider's own name for it, already checked (see `discoveredDisplayName`); absent: the id is prettified. */ displayName?: string } + +/** The display name stored for a discovered model: the provider's own name when it is a usable one, else the prettified id. */ +export const discoveredDisplayName = (id: string, providerName: unknown): string => gatewayDisplayName(id, typeof providerName === "string" ? providerName : undefined); const NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; const text = (value: unknown, max: number): value is string => typeof value === "string" && value.length >= 1 && value.length <= max && ![...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127); @@ -76,7 +82,7 @@ export function validCatalogProbe(value: unknown): value is CatalogProbe { } export function validCatalogModel(value: unknown): value is CatalogModel { const m = record(value); - return m !== undefined && typeof m.name === "string" && NAME.test(m.name) && text(m.id, 256) && text(m.version, 256) && (m.origin === "seed" || m.origin === "discovered") + return m !== undefined && typeof m.name === "string" && NAME.test(m.name) && text(m.id, 256) && text(m.version, 256) && (m.displayName === undefined || text(m.displayName, MODEL_DISPLAY_NAME_MAX)) && (m.origin === "seed" || m.origin === "discovered") && whole(m.discoveredAt) && whole(m.seenAt) && (m.goneAt === undefined || whole(m.goneAt)) && (m.price === undefined || validCatalogPrice(m.price)) && (m.probe === undefined || validCatalogProbe(m.probe)); } export function validCatalogSnapshot(value: unknown): value is CatalogSnapshot { @@ -111,6 +117,8 @@ function mergeFound(old: CatalogModel | undefined, f: DiscoveredModel, seeds: Re const origin: CatalogModel["origin"] = old?.origin === "seed" || seeds.has(f.name) ? "seed" : "discovered"; const rest: CatalogModel = { ...(old ?? { name: f.name, id: f.id, version: f.version, origin, discoveredAt: now, seenAt: now }), name: f.name, id: f.id, version: f.version, origin, seenAt: now }; delete rest.goneAt; + // The latest list's name wins (a provider may fix a name); a list that gives none keeps the one held. + if (f.displayName !== undefined) rest.displayName = f.displayName; return rest; } /** diff --git a/packages/model-gateway/src/model-catalog-discovery.ts b/packages/model-gateway/src/model-catalog-discovery.ts index 7bfdf24e62..135197b8cc 100644 --- a/packages/model-gateway/src/model-catalog-discovery.ts +++ b/packages/model-gateway/src/model-catalog-discovery.ts @@ -9,7 +9,7 @@ import { BEDROCK_CONVERSE_ID } from "./bedrock-converse.js"; import { geographiesOf } from "./bedrock-byo.js"; import { parseRovaraAiModels } from "./agent-ai.js"; import { record } from "./model-gateway-token.js"; -import type { DiscoveredModel } from "./gateway-model-catalog.js"; +import { discoveredDisplayName, type DiscoveredModel } from "./gateway-model-catalog.js"; /** * The Bedrock providers (the id's vendor word) Rovara AI may call and how each is reached: through a `.` profile, directly in this Region, or both. infra/lib/model-gateway.ts repeats this map as @@ -34,24 +34,31 @@ function listed(answer: unknown, key: string): Record[] { return Array.isArray(rows) ? rows.map(record).filter((r): r is Record => r !== undefined) : []; } /** One Bedrock summary the gateway could serve at all: text out only, streaming, active, an allowed provider and a plain id. */ -function bedrockCandidate(row: Record): { modelId: string; provider: string; onDemand: boolean } | undefined { +type BedrockCandidate = { modelId: string; provider: string; onDemand: boolean; modelName?: unknown }; +function bedrockCandidate(row: Record): BedrockCandidate | undefined { const modelId = row.modelId; const parts = typeof modelId === "string" ? BEDROCK_MODEL_ID.exec(modelId) : null; if (parts === null || typeof modelId !== "string" || !ROVARA_AI_ALLOWED_PROVIDERS.includes(parts[1]!)) return undefined; const out = strings(row.outputModalities); if (out.length !== 1 || out[0] !== "TEXT" || row.responseStreamingSupported !== true || record(row.modelLifecycle)?.status !== "ACTIVE") return undefined; - return { modelId, provider: parts[1]!, onDemand: strings(row.inferenceTypesSupported).includes("ON_DEMAND") }; + return { modelId, provider: parts[1]!, onDemand: strings(row.inferenceTypesSupported).includes("ON_DEMAND"), modelName: row.modelName }; } /** The Bedrock id and agent name to call a candidate by, or undefined when there is no way the gateway may (Claude only through a profile; others in-Region or through a profile). */ -function bedrockRoute(c: { modelId: string; provider: string; onDemand: boolean }, profiles: ReadonlySet, geo: string): DiscoveredModel | undefined { +function bedrockRoute(c: BedrockCandidate, profiles: ReadonlyMap, geo: string): DiscoveredModel | undefined { const profile = `${geo}.${c.modelId}`; if (c.provider === "anthropic") { const name = bedrockClaudeName(c.modelId); - return profiles.has(profile) && AGENT_CLAUDE_NAME.test(name) && BEDROCK_CLAUDE_ID.test(profile) ? { name, id: profile, version: profile } : undefined; + return profiles.has(profile) && AGENT_CLAUDE_NAME.test(name) && BEDROCK_CLAUDE_ID.test(profile) ? { name, id: profile, version: profile, displayName: bedrockDisplayName(profile, c.modelName, profiles.get(profile)) } : undefined; } // Only a way the grant allows: a direct id for a provider granted directly, a profile for one granted through profiles (a model reachable only the other way is not offered). const id = c.onDemand && reachedBy(c.provider, "direct") ? c.modelId : profiles.has(profile) && reachedBy(c.provider, "profile") ? profile : undefined; - return id === undefined || !BEDROCK_CONVERSE_ID.test(id) ? undefined : { name: id, id, version: id }; + return id === undefined || !BEDROCK_CONVERSE_ID.test(id) ? undefined : { name: id, id, version: id, displayName: bedrockDisplayName(id, c.modelName, profiles.get(profile)) }; +} +/** A routing profile's name carries the geography as a word (`US Anthropic Claude Haiku 4.5`); the model's own `modelName` is the better name, the profile's (without that word) the next. */ +const PROFILE_GEOGRAPHY = /^(?:US|EU|APAC|JP|AU|CA|Global|US-GOV)\s+/u; +function bedrockDisplayName(id: string, modelName: unknown, profileName: unknown): string { + if (typeof modelName === "string" && modelName.trim() !== "") return discoveredDisplayName(id, modelName); + return discoveredDisplayName(id, typeof profileName === "string" ? profileName.replace(PROFILE_GEOGRAPHY, "") : undefined); } /** Whether the gateway's own allow-list parser takes the pair (the same check the seed list passes). */ function parses(model: DiscoveredModel, region: string): boolean { @@ -62,7 +69,8 @@ function parses(model: DiscoveredModel, region: string): boolean { export function discoverBedrock(modelsAnswer: unknown, profilesAnswer: unknown, region: string): DiscoveredModel[] { const geo = geographiesOf(region)[0]; if (geo === undefined) return []; - const profiles = new Set(listed(profilesAnswer, "inferenceProfileSummaries").filter((p) => p.status === "ACTIVE" && p.type === "SYSTEM_DEFINED").map((p) => p.inferenceProfileId).filter((id): id is string => typeof id === "string")); + // Each active system profile's id, with the name Bedrock gives it. + const profiles = new Map(listed(profilesAnswer, "inferenceProfileSummaries").filter((p) => p.status === "ACTIVE" && p.type === "SYSTEM_DEFINED").flatMap((p): Array<[string, unknown]> => (typeof p.inferenceProfileId === "string" ? [[p.inferenceProfileId, p.inferenceProfileName]] : []))); const found = new Map(); for (const row of listed(modelsAnswer, "modelSummaries")) { const candidate = bedrockCandidate(row); @@ -81,7 +89,7 @@ export function discoverOpenAi(answer: unknown): DiscoveredModel[] { for (const row of listed(answer, "data")) { const id = row.id; if (typeof id !== "string" || !OPENAI_FAMILY.test(id) || OPENAI_NOT_AGENT.test(id) || found.has(id)) continue; - found.set(id, { name: id, id, version: typeof row.created === "number" && Number.isSafeInteger(row.created) ? `${id}@${String(row.created)}` : id }); + found.set(id, { name: id, id, version: typeof row.created === "number" && Number.isSafeInteger(row.created) ? `${id}@${String(row.created)}` : id, displayName: discoveredDisplayName(id, undefined) }); } return [...found.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); } @@ -92,7 +100,7 @@ export function discoverAnthropic(answer: unknown): DiscoveredModel[] { for (const row of listed(answer, "data")) { const id = row.id; if (typeof id !== "string" || !ANTHROPIC_ID.test(id) || found.has(id)) continue; - found.set(id, { name: id, id, version: typeof row.created_at === "string" ? `${id}@${row.created_at}` : id }); + found.set(id, { name: id, id, version: typeof row.created_at === "string" ? `${id}@${row.created_at}` : id, displayName: discoveredDisplayName(id, row.display_name) }); } return [...found.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); } diff --git a/packages/model-gateway/src/model-catalog-view.ts b/packages/model-gateway/src/model-catalog-view.ts index 25285f7a74..a16b9ce90c 100644 --- a/packages/model-gateway/src/model-catalog-view.ts +++ b/packages/model-gateway/src/model-catalog-view.ts @@ -60,6 +60,10 @@ export class CatalogLive { #live(source: CatalogSource): CatalogModel[] { return (this.#snapshots[source]?.models ?? []).filter((m) => m.origin === "discovered" && modelOffered(m, this.hidden(source, m.name))); } + /** Whether any catalog has been read: a gateway whose table holds none (the catalog is not switched on for it) names no model, so its offered list stays exactly as an older reader takes it. */ + loaded(): boolean { return Object.keys(this.#snapshots).length > 0; } + /** The display name the catalog holds for a model (its own record's, stored when the model was discovered), or undefined (a seed no list has named, a model the catalog does not know). */ + displayName(source: CatalogSource, name: string): string | undefined { return this.#snapshots[source]?.models.find((m) => m.name === name)?.displayName; } /** Every catalog model of a source with its state, for the operator's list. */ snapshot(source: CatalogSource): CatalogSnapshot | undefined { return this.#snapshots[source]; } diff --git a/packages/model-gateway/src/model-display-name.ts b/packages/model-gateway/src/model-display-name.ts new file mode 100644 index 0000000000..ee8376f8c4 --- /dev/null +++ b/packages/model-gateway/src/model-display-name.ts @@ -0,0 +1,83 @@ +// Friendly model names, the gateway's copy of packages/contracts/src/model-display-name.ts (this package takes no dependency on contracts; tests/unit/model-display-name.test.ts holds the two equal +// on every row of one table). The catalog stores the provider's own name when discovery had one, else this prettifier's reading of the id, and the offered list sends it as `displayName`. +/** The longest display name carried anywhere. */ +export const MODEL_DISPLAY_NAME_MAX = 100; +const usable = (value: string): boolean => value.length >= 1 && value.length <= MODEL_DISPLAY_NAME_MAX && ![...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127); + +/** Ids the prettifier cannot read well, by the id with its routing prefix and version suffix removed (see `normalized`). Keep it small. */ +export const MODEL_DISPLAY_NAME_OVERRIDES: Readonly> = Object.freeze({ + "openai.gpt-oss-120b": "GPT-OSS 120B", + "openai.gpt-oss-20b": "GPT-OSS 20B", + "openai.gpt-oss-safeguard-120b": "GPT-OSS Safeguard 120B", + "openai.gpt-oss-safeguard-20b": "GPT-OSS Safeguard 20B", + "zai.glm-4.7": "GLM 4.7", + "moonshot.kimi-k2-thinking": "Kimi K2 Thinking", + "moonshotai.kimi-k2.5": "Kimi K2.5", +}); + +const GEOGRAPHY = /^(?:us|eu|apac|jp|au|ca|global|us-gov)\./u; +const VERSION_SUFFIX = /-(?:v\d+(?::\d+)?|\d+:\d+)$/u; +const DATE_TOKEN = /^(?:\d{8}|\d{4})$/u; +/** Words that are the vendor's brand or an acronym, by lower-case token. */ +const WORDS: Readonly> = Object.freeze({ + gpt: "GPT", glm: "GLM", oss: "OSS", ai: "AI", llm: "LLM", vl: "VL", moe: "MoE", deepseek: "DeepSeek", openai: "OpenAI", minimax: "MiniMax", zai: "Z.AI", moonshot: "Moonshot", moonshotai: "Moonshot", qwen: "Qwen", amazon: "Amazon", anthropic: "Anthropic", mistral: "Mistral", +}); +/** A size such as `480b` or `20b`; an active-parameter marker such as `a35b` is dropped (`qwen3-coder-480b-a35b` is "Qwen3 Coder 480B"). */ +const SIZE = /^(\d+(?:\.\d+)?)([bkmt])$/iu; +const ACTIVE_PARAMETERS = /^a\d+(?:\.\d+)?b$/iu; +const SMALL_NUMBER = /^\d{1,2}$/u; + +/** The id as the prettifier reads it: no routing prefix (`us.`, a `vendor/` of OpenRouter's), no `-v1:0` version suffix, no `:variant`, lower case. */ +function normalized(id: string): { text: string; variant: string | undefined } { + let text = id.trim().toLowerCase(); + if (text.includes("/")) text = text.slice(text.lastIndexOf("/") + 1); + let variant: string | undefined; + const colon = text.lastIndexOf(":"); + if (colon > 0 && !/^\d+$/u.test(text.slice(colon + 1))) { variant = text.slice(colon + 1); text = text.slice(0, colon); } + text = text.replace(GEOGRAPHY, "").replace(VERSION_SUFFIX, ""); + return { text, variant }; +} +const capitalized = (token: string): string => WORDS[token] ?? (token.length === 0 ? token : `${token.slice(0, 1).toUpperCase()}${token.slice(1)}`); + +/** Joins two short number tokens that are one version (`4-5` is "4.5", `1-0` is "1.0"); every other token stays. */ +function versioned(tokens: readonly string[]): string[] { + const out: string[] = []; + for (const token of tokens) { + const last = out[out.length - 1]; + if (last !== undefined && SMALL_NUMBER.test(token) && SMALL_NUMBER.test(last)) out[out.length - 1] = `${last}.${token}`; + else out.push(token); + } + return out; +} + +function words(text: string): string { + const tokens = text.split(/[-_ ]+/u).filter((t) => t.length > 0 && !DATE_TOKEN.test(t) && !ACTIVE_PARAMETERS.test(t)); + return versioned(tokens).map((token) => { + const size = SIZE.exec(token); + if (size !== null) return `${size[1]}${size[2]!.toUpperCase()}`; + return /^v\d/u.test(token) ? `V${token.slice(1)}` : capitalized(token); + }).join(" "); +} + +/** + * The display name of a model id (any source: a Bedrock model or `us.` profile id, a Claude engine name, an OpenAI name, an OpenRouter `vendor/model`). Never empty and never longer than + * MODEL_DISPLAY_NAME_MAX; an id that reads to nothing is returned as it is. + */ +export function prettyModelName(id: string): string { + const { text, variant } = normalized(id); + const override = MODEL_DISPLAY_NAME_OVERRIDES[text]; + // A vendor word alone says nothing (`deepseek.v3.2`), so it stays when what follows has no word of its own; otherwise it is dropped (`qwen.qwen3-coder` is "Qwen3 Coder"). + const dot = text.indexOf("."); + const vendor = dot > 0 && /^[a-z]{2,30}$/u.test(text.slice(0, dot)) ? text.slice(0, dot) : undefined; + const rest = vendor === undefined ? text : text.slice(dot + 1); + const hasWord = /(?:^|[-_])[a-z]{3,}/u.test(rest); + const base = override ?? words(vendor !== undefined && !hasWord ? text.replace(".", " ") : rest); + const named = variant === undefined ? base : `${base} (${variant})`; + return named === "" ? id.slice(0, MODEL_DISPLAY_NAME_MAX) : named.slice(0, MODEL_DISPLAY_NAME_MAX); +} + +/** The provider's own name when it is a usable one (one line, 1 to 100 characters), else the prettified id. */ +export function gatewayDisplayName(id: string, providerName?: string): string { + const own = typeof providerName === "string" ? providerName.replace(/\s+/gu, " ").trim() : ""; + return usable(own) ? own : prettyModelName(id); +} diff --git a/packages/model-gateway/src/offered-models.ts b/packages/model-gateway/src/offered-models.ts index 4830ba4e63..f64a8dfd9d 100644 --- a/packages/model-gateway/src/offered-models.ts +++ b/packages/model-gateway/src/offered-models.ts @@ -29,6 +29,7 @@ import { serviceCallLimiter } from "./service-call.js"; import type { SignedTokenKind } from "./token.js"; import { validPrice, type PriceSource } from "./price.js"; import type { CatalogLive } from "./model-catalog-view.js"; +import { gatewayDisplayName } from "./model-display-name.js"; export const SERVICE_TOKEN_TYPE = "rovara-service+jwt"; export const SERVICE_TOKEN_AUDIENCE = "rovara-model-gateway-offered-models"; @@ -225,6 +226,11 @@ export interface OfferedModelsHandlerOptions { * answer is exactly as before (Code accepts the field only from the release that added it, so it stays off until that release is installed). */ priceOf?: (model: string, source: AgentAiSource | undefined) => Promise; + /** + * Each offered model's `displayName` (the name people read; the id stays the key): the catalog's stored name (the provider's own, else the prettified id), OpenRouter's own `name`, else the prettified id. + * Absent: the answer carries no `displayName` and is exactly as before (a reader older than this change refuses a member it does not know, so a gateway sends it only where its catalog is on: process.ts). + */ + displayNameOf?: (model: string, source: AgentAiSource | undefined) => string | undefined; /** DEC 254zzz41: set, the answer also carries `reviewerAccess` (above). Absent: the answer is exactly as before and no review can run. */ reviewer?: ReviewerAccessOptions; now?: () => number; @@ -334,7 +340,22 @@ export async function answerOfferedModels(options: OfferedModelsHandlerOptions, })); const identities = await Promise.all(entries.map(async (entry) => servedBy.get(entry.model) === "openrouter_key" ? await openRouterEntry(options, claims.iss, claims.cid, entry) : entry)).catch(() => undefined); if (identities === undefined) return ANSWERS.unavailable; - return { status: 200, body: fitToLimit(options, identities, reviewerAccess) }; + return { status: 200, body: fitToLimit(options, options.displayNameOf === undefined ? identities : identities.map((entry) => named(options.displayNameOf!, entry, servedBy.get(entry.model))), reviewerAccess) }; +} + +/** One row with its display name, where the source can give one (never a failure: a name that cannot be made leaves the row as it was). */ +function named(displayNameOf: NonNullable, entry: OfferedEntry, source: AgentAiSource | undefined): OfferedEntry { + try { const displayName = displayNameOf(entry.model, source); return displayName === undefined ? entry : { ...entry, displayName }; } catch { return entry; } +} +/** + * The display name of an offered model by the source that serves it: the catalog's stored name for Rovara's AI and the own-key sources (`seeds` that no list has named are prettified), OpenRouter's own + * `name` for an OpenRouter model, else the prettified id. `catalog` is the live view; a gateway that has read no catalog names nothing (undefined), so its answer stays as an older reader takes it. + */ +export function offeredDisplayName(catalog: Pick, openRouter: Pick | undefined, model: string, source: AgentAiSource | undefined): string | undefined { + if (!catalog.loaded()) return undefined; + if (source === "openrouter_key") return gatewayDisplayName(model, openRouter?.entry(model)?.name); + const from = source === "rovara" ? "rovara" : source === "openai_key" ? "openai" : source === undefined || source === "anthropic_key" ? "anthropic" : undefined; + return gatewayDisplayName(model, from === undefined ? undefined : catalog.displayName(from, model)); } /** A model's list price in US dollars per million tokens (Code's OfferedModelPriceSchema: each 0 to OFFERED_PRICE_USD_MAX). */ diff --git a/packages/model-gateway/src/process.ts b/packages/model-gateway/src/process.ts index 8aadd1923b..04567c133e 100644 --- a/packages/model-gateway/src/process.ts +++ b/packages/model-gateway/src/process.ts @@ -41,7 +41,7 @@ import { CompanyRecords } from "./company-records.js"; import { COMPANY_INSTRUCTIONS_PATH, COMPANY_INSTRUCTIONS_TOKEN_KIND, CompanyStoredInstructions, createCompanyInstructionsHandler, type CompanyInstructionsSource } from "./company-instructions.js"; import { catalogJobEntry, liveCatalogOf, maxNamesOf, readRovaraAiModelsMax, rovaraSharedModels, runCatalogIfConfigured, type CatalogJobSettings } from "./model-catalog-wiring.js"; import type { CatalogLive } from "./model-catalog-view.js"; -import { createOfferedModelsHandler, offeredModelPrice, OFFERED_MODELS_PATH, parseDisabledAgentModels, SERVICE_TOKEN_KIND } from "./offered-models.js"; +import { createOfferedModelsHandler, offeredDisplayName, offeredModelPrice, OFFERED_MODELS_PATH, parseDisabledAgentModels, SERVICE_TOKEN_KIND } from "./offered-models.js"; import { companyCapReadHandler, createInstallTaskCapReadHandler, isCompanyCapReadPath } from "./task-cap-read.js"; import { createUpkeepCapReadHandler, UPKEEP_CAP_READ_TOKEN_KIND } from "./upkeep-cap-read.js"; import { createRunChargesHandler, RUN_CHARGES_PATH, RUN_CHARGES_TOKEN_KIND } from "./run-charges-read.js"; @@ -699,6 +699,7 @@ export async function startServe(config: ServeConfig, deps: ServeDependencies = ...(config.bedrockByo === undefined || deps.byoBedrock === undefined ? {} : { byo: deps.byoBedrock }), now, switchedOn, chat: { openai: true, openrouter: true }, openRouter: openRouterCatalog, log: (event) => log({ ...event }), // DEC 254zzz96 (2): list prices on the offered list, only when switched on (display only). + displayNameOf: (model: string, source: AgentAiSource | undefined) => offeredDisplayName(catalogLive, openRouterCatalog, model, source), ...(config.offeredPrices === true ? { priceOf: (model: string, source: AgentAiSource | undefined) => offeredModelPrice(prices, model, source, rovaraModels) } : {}), // DEC 254zzz41: what reviews may use, from the company's real connections and the room left in its one company cap (the agent meter's company row). reviewer: { keys: companyKeys, companyLimitMicros: (iss: string, cid: string) => companyRoomMicros(caps, meter, iss, cid) }, diff --git a/tests/contract/admin-health.test.ts b/tests/contract/admin-health.test.ts index babed5a71a..28021de057 100644 --- a/tests/contract/admin-health.test.ts +++ b/tests/contract/admin-health.test.ts @@ -24,7 +24,7 @@ describe("GET /v1/admin/health (FR-030, A13)", () => { project: "payments", origin: "slack", requester: { kind: "none" }, kind: "task", status: "FAILED", category: "worker_unavailable", error: "RUNTIME_UNAVAILABLE: no capacity", endedAt: at }); const answer = await admin("GET", "/v1/admin/health"); expect(answer.body).toEqual({ - version: { developerApi: "1.29", adminApi: "1.1", release: "0.0.6" }, + version: { developerApi: "1.30", adminApi: "1.1", release: "0.0.6" }, alarms: [{ name: "agentx-live25d-ConnectorBroken", state: "ALARM" }, { name: "agentx-live25d-SlackDeadLetters", state: "OK" }], alarmsCheck: { status: "warn", detail: "1 alarm in ALARM" }, deadLetterQueues: [{ name: "dispatch", depth: 0 }, { name: "slack-requests", depth: 2 }], @@ -47,7 +47,7 @@ describe("GET /v1/admin/health (FR-030, A13)", () => { const answer = await admin("GET", "/v1/admin/health"); expect(answer.status).toBe(200); expect(answer.body).toMatchObject({ - version: { developerApi: "1.29", adminApi: "1.1" }, + version: { developerApi: "1.30", adminApi: "1.1" }, alarms: [], alarmsCheck: { status: "unknown", detail: "could not read the alarms (AccessDenied)" }, deadLetterQueues: [], deadLetterQueuesCheck: { status: "unknown", detail: "not set up in this deployment" }, slack: { status: "failed", detail: "Slack refused the bot token (token_revoked)" }, diff --git a/tests/contract/admin-read-contracts.test.ts b/tests/contract/admin-read-contracts.test.ts index c6a884914e..76eba8279b 100644 --- a/tests/contract/admin-read-contracts.test.ts +++ b/tests/contract/admin-read-contracts.test.ts @@ -46,7 +46,7 @@ describe("the index records (A5)", () => { describe("the wire shapes", () => { it("adds the admin API version beside the developer one, which stays 1.2 (A1)", () => { expect(ADMIN_API_VERSION).toBe("1.1"); - expect(DEVELOPER_API_VERSION).toBe("1.29"); + expect(DEVELOPER_API_VERSION).toBe("1.30"); expect(ADMIN_INDEX_RETENTION_DAYS).toBe(30); }); diff --git a/tests/contract/code-api-version.test.ts b/tests/contract/code-api-version.test.ts index 73c05cce08..22585cef76 100644 --- a/tests/contract/code-api-version.test.ts +++ b/tests/contract/code-api-version.test.ts @@ -64,6 +64,8 @@ const DIGESTS: Readonly> = { "1.28": "f35ca9cc07b595877aaef5b5b4ab34fc56ed8859cef1e3d7796c64769bb46131", // 1.29 (VIEWER-FLAGS; 1.28 is INBOX-HIDE's): the task read (`tasks.read`) also names `canRetryFeedback` and `canAnswerQuestions`, whether the person reading may retry the task's PR feedback (Retry fix, Retry review) and answer its questions, each computed by the function its own route judges with (`feedbackOwner`, `answerStandingOf`) served only where the deployment serves the action, and `false` where the task is closed, has no PR-feedback round, waits for no answers, or the caller is a script token. Both optional and read tolerantly. Code first: an older client ignores them, and the website then follows Code instead of guessing a role. "1.29": "d9e8f417e617355e947c3996bd0a573b3df73075d417ab581434670d077a2148", + // 1.30 (MODEL-NAMES): every model Code returns to the website also carries `displayName` (the provider's own name, else a prettified id; the id stays the key): each entry of the step models page's `offered` list (`GET /v1/app/agent-models`), each choice in its `state.models` and each step's `effective`, and the company AI reads (`GET /v1/dev/company/engine-model` and `/learning-model` name every id they return in `displayNames`). All optional and read tolerantly; none of those rows carries a schema or `webAppOnly`, so the digest is 1.29's. Code first: an older client ignores the member. + "1.30": "d9e8f417e617355e947c3996bd0a573b3df73075d417ab581434670d077a2148", }; const schemaOf = (schema: z.ZodType | undefined) => (schema === undefined ? null : z.toJSONSchema(schema)); diff --git a/tests/contract/company-engine-model-routes.test.ts b/tests/contract/company-engine-model-routes.test.ts index 81c5a6bb8d..ef0e725f92 100644 --- a/tests/contract/company-engine-model-routes.test.ts +++ b/tests/contract/company-engine-model-routes.test.ts @@ -45,9 +45,18 @@ function world(options: { lists?: Record { const { requestId: _r, ...rest } = body; void _r; return CompanyEngineModelViewSchema.parse(rest); }; +const fullViewOf = (body: Answer) => { const { requestId: _r, ...rest } = body; void _r; return CompanyEngineModelViewSchema.parse(rest); }; +/** The view without its `displayNames` (the names are held by their own tests below, so each exact-shape check still says what the ids are). */ +const viewOf = (body: Answer) => { const { displayNames: _names, ...rest } = fullViewOf(body); void _names; return rest; }; describe("GET /v1/dev/company/engine-model", () => { + it("names every id of the view in displayNames (the id stays the key): the model, the install default it replaced, every offered model and the preselect", async () => { + const w = world({ lists: { [A]: ["zai.glm-5", "claude-haiku-5-5", "qwen.qwen3-coder-480b-a35b-v1:0"] } }); + const view = fullViewOf((await w.call("GET")).body); + expect(view.displayNames).toEqual({ "zai.glm-5": "GLM 5", "claude-haiku-5-5": "Claude Haiku 5.5", "qwen.qwen3-coder-480b-a35b-v1:0": "Qwen3 Coder 480B", "claude-sonnet-5-5": "Claude Sonnet 5.5" }); + for (const id of [view.model, view.defaultNotOffered, view.preselect, ...view.offered]) expect(view.displayNames![id!], String(id)).toBeTruthy(); + }); + it("a company that chose none, whose sources do not offer the install default, runs on the best offered (the gateway's first) and the view says what it replaced; nothing is saved", async () => { const w = world({ lists: { [A]: ["zai.glm-5", "claude-haiku-5-5"] } }); diff --git a/tests/contract/company-learning-model-routes.test.ts b/tests/contract/company-learning-model-routes.test.ts index 6ce7bb4261..0c6ac0255f 100644 --- a/tests/contract/company-learning-model-routes.test.ts +++ b/tests/contract/company-learning-model-routes.test.ts @@ -47,9 +47,17 @@ function world(options: { lists?: Record { const { requestId: _r, ...rest } = body; void _r; return CompanyLearningModelViewSchema.parse(rest); }; +const fullViewOf = (body: Answer) => { const { requestId: _r, ...rest } = body; void _r; return CompanyLearningModelViewSchema.parse(rest); }; +/** The view without its `displayNames` (the names are held by their own tests below, so each exact-shape check still says what the ids are). */ +const viewOf = (body: Answer) => { const { displayNames: _names, ...rest } = fullViewOf(body); void _names; return rest; }; describe("GET /v1/dev/company/learning-model", () => { + it("names every id of the view in displayNames (the id stays the key)", async () => { + const view = fullViewOf((await world({ lists: { [A]: ["zai.glm-5", SONNET, HAIKU] } }).call("GET")).body); + expect(view.displayNames).toEqual({ [HAIKU]: "Claude Haiku 5.5", [SONNET]: "Claude Sonnet 5.5" }); + for (const id of [view.model, view.preselect, ...view.offered]) expect(view.displayNames![id!], String(id)).toBeTruthy(); + }); + it("preselects the first offered Claude model when the default is not offered, and null when no Claude model is offered", async () => { expect(viewOf((await world({ lists: { [A]: ["zai.glm-5", SONNET] } }).call("GET")).body)).toEqual({ model: HAIKU, source: "install", offered: [SONNET], preselect: SONNET }); diff --git a/tests/contract/developer-contracts.test.ts b/tests/contract/developer-contracts.test.ts index 2844cdbfdd..4a94023c9f 100644 --- a/tests/contract/developer-contracts.test.ts +++ b/tests/contract/developer-contracts.test.ts @@ -25,7 +25,7 @@ const configuration = { describe("developer sign-in contracts", () => { it("names the public client, audience and API version", () => { - expect([AGENTX_CLI_CLIENT_ID, DEVELOPER_TOKEN_AUDIENCE, DEVELOPER_API_VERSION]).toEqual(["agentx-cli", "agentx-developer", "1.29"]); + expect([AGENTX_CLI_CLIENT_ID, DEVELOPER_TOKEN_AUDIENCE, DEVELOPER_API_VERSION]).toEqual(["agentx-cli", "agentx-developer", "1.30"]); }); it.each([ diff --git a/tests/contract/developer-identity-server.test.ts b/tests/contract/developer-identity-server.test.ts index 333009347c..5e6ca54645 100644 --- a/tests/contract/developer-identity-server.test.ts +++ b/tests/contract/developer-identity-server.test.ts @@ -19,7 +19,7 @@ describe("discovery (FR-001, FR-048)", () => { it("reports the environment, API version and the methods that can actually be used", async () => { const both = identityHarness({ oidc: {} }); expect(json((await both.http(httpEvent("GET", "/v1/auth/.well-known/agentx-configuration"))).body)).toEqual({ - env: "staging", apiVersion: "1.29", adminApiVersion: "1.1", issuer: ISSUER, authorizationEndpoint: `${ISSUER}/authorize`, tokenEndpoint: `${ISSUER}/token`, + env: "staging", apiVersion: "1.30", adminApiVersion: "1.1", issuer: ISSUER, authorizationEndpoint: `${ISSUER}/authorize`, tokenEndpoint: `${ISSUER}/token`, revocationEndpoint: `${ISSUER}/revoke`, clientId: "agentx-cli", methods: { slack: true, oidc: { displayName: "Okta" } }, confirm: { elicitation: true, slack: true }, }); diff --git a/tests/contract/developer-share-contracts.test.ts b/tests/contract/developer-share-contracts.test.ts index 6df9489a06..075f7f3715 100644 --- a/tests/contract/developer-share-contracts.test.ts +++ b/tests/contract/developer-share-contracts.test.ts @@ -106,6 +106,6 @@ describe("records and codes", () => { // errorStatus answers 409 for any code it does not list, so pin the code's membership too. expect(AgentXErrorCodeSchema.options).toContain("CHANNEL_AMBIGUOUS"); expect(agentXError("CHANNEL_AMBIGUOUS", "name one").statusCode).toBe(409); - expect(DEVELOPER_API_VERSION).toBe("1.29"); + expect(DEVELOPER_API_VERSION).toBe("1.30"); }); }); diff --git a/tests/contract/developer-task-shapes.test.ts b/tests/contract/developer-task-shapes.test.ts index 9f923d65fb..eae45ad8ed 100644 --- a/tests/contract/developer-task-shapes.test.ts +++ b/tests/contract/developer-task-shapes.test.ts @@ -84,7 +84,7 @@ describe("changed files from the workspace diff (R18)", () => { describe("developer API 1.2 (R23, Q7)", () => { it("reports 1.2 and adds the project's task policy and channel names", () => { - expect(DEVELOPER_API_VERSION).toBe("1.29"); + expect(DEVELOPER_API_VERSION).toBe("1.30"); const project = DeveloperProjectSchema.parse({ name: "payments", latestRevision: 7, access: "channel", channels: [{ channelId: "C0123456789", name: "payments-dev", isPrivate: false }], diff --git a/tests/contract/slack-direct-messages.test.ts b/tests/contract/slack-direct-messages.test.ts index b636762559..7cd2228088 100644 --- a/tests/contract/slack-direct-messages.test.ts +++ b/tests/contract/slack-direct-messages.test.ts @@ -5,7 +5,7 @@ import { createHmac } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; import { MemoryDocumentStore } from "../../packages/broker/src/ports/memory-document-store.js"; import { createSlackAdapterFront } from "../../packages/broker/src/aws/slack-ingress.js"; -import { parseDirectMessage, DIRECT_UNKNOWN_WORDS, type SlackDirectAnswer, type SlackDirectMessage } from "../../packages/broker/src/aws/slack-direct-front.js"; +import { parseDirectMessage, DIRECT_FAILURE_WORDS, DIRECT_UNKNOWN_WORDS, type SlackDirectAnswer, type SlackDirectMessage } from "../../packages/broker/src/aws/slack-direct-front.js"; import { developerIdForSlackUser } from "../../packages/broker/src/aws/admin-actions.js"; import { isSlackDirectMessageEvent } from "../../packages/broker/src/aws/slack-broker-events.js"; import { coreDirectMessage, DIRECT_MESSAGES_UNAVAILABLE_WORDS } from "../../packages/broker/src/aws/slack-core-direct-message.js"; @@ -98,7 +98,92 @@ describe("a direct message from a person mapped to a Rovara person", () => { fail = false; expect((await retried.handler(again)).statusCode).toBe(200); expect(retried.handOff).toHaveBeenCalledTimes(2); - expect(retried.posted).toHaveLength(1); + // The failed first try said sorry once; the handled retry said the saved words. + expect(retried.posted).toEqual([{ channel: DM, text: DIRECT_FAILURE_WORDS }, { channel: DM, text: THREAD_INPUT_WORDS.note_saved }]); + }); +}); + +describe("a direct message Rovara could not handle", () => { + const FAILURE = "Sorry, I couldn't handle that message. Please try again in a minute."; + function same(store: MemoryDocumentStore, nowMs: number, handOff: (message: SlackDirectMessage) => Promise) { + const w = world(); + const posted: string[] = []; + const logs: Array<{ event: string; fields: Record }> = []; + const spy = vi.fn(handOff); + const handler = createSlackAdapterFront({ ...w, workspaces: { ...w.workspaces, store }, secrets: async () => ({ signingSecret: SECRET }), now: () => nowMs, isRovaraThread: async () => false, handOff: async () => undefined, + direct: { handOff: spy, post: async (input) => { posted.push(input.text); } }, log: (event, fields) => logs.push({ event, fields }) }); + const timestamp = String(Math.floor(nowMs / 1000)); + const body = JSON.stringify({ type: "event_callback", event_id: "EvFAIL00001", team_id: TEAM, event: { type: "message", channel_type: "im", channel: DM, user: USER, ts: TS, text: "words not for the log or the reply" } }); + const send = () => handler({ body, headers: { "x-slack-request-timestamp": timestamp, "x-slack-signature": `v0=${createHmac("sha256", SECRET).update(`v0:${timestamp}:${body}`).digest("hex")}` }, requestContext: { http: { method: "POST" } } }); + return { handOff: spy, posted, logs, send }; + } + const down = async (): Promise => { throw new Error("broker down with private words"); }; + + it("says so in the direct message, in plain words, and still answers Slack with a 500 so it retries", async () => { + const first = same(new MemoryDocumentStore(), NOW, down); + expect((await first.send()).statusCode).toBe(500); + expect(first.posted).toEqual([FAILURE]); + expect(DIRECT_FAILURE_WORDS).toBe(FAILURE); + expect(JSON.stringify([first.posted, first.logs])).not.toContain("words not for the log"); + expect(JSON.stringify(first.logs)).not.toContain("private words"); + }); + + it("never says it twice for the same event, however often Slack retries it and it fails again", async () => { + const store = new MemoryDocumentStore(); + const posted: string[] = []; + for (const at of [0, 60_000, 360_000]) { + const retry = same(store, NOW + at, down); + expect((await retry.send()).statusCode).toBe(500); + posted.push(...retry.posted); + } + expect(posted).toEqual([FAILURE]); + }); + + it("says nothing while the first delivery is still with the broker (a claim pending is a 500 for Slack to retry), and nothing once the event is handled", async () => { + const store = new MemoryDocumentStore(); + let finish!: (answer: SlackDirectAnswer) => void; + const first = same(store, NOW, () => new Promise((resolve) => { finish = resolve; })); + const running = first.send(); + await vi.waitFor(() => expect(first.handOff).toHaveBeenCalledOnce()); + const retry = same(store, NOW + 3_000, async () => ({ outcome: "captured", notice: "note_saved" })); + expect((await retry.send()).statusCode).toBe(500); + expect(retry.handOff).not.toHaveBeenCalled(); + expect(retry.posted).toEqual([]); + finish({ outcome: "captured", notice: "note_saved" }); + expect((await running).statusCode).toBe(200); + const repeat = same(store, NOW + 60_000, down); + expect((await repeat.send()).statusCode).toBe(200); + expect(repeat.posted).toEqual([]); + expect(first.posted).toEqual([THREAD_INPUT_WORDS.note_saved]); + }); + + it("writes only inside the event's own claim partition (a marker, sort key REPLY), and says nothing when the marker cannot be written", async () => { + const inner = new MemoryDocumentStore(); + const writes: Array<{ pk: string; sk: string }> = []; + let refuse = false; + const store = new Proxy(inner, { get(target, field) { + const value = (target as unknown as Record)[field]; + if (field === "put") return async (request: { item: { pk: string; sk: string } }) => { + writes.push({ pk: request.item.pk, sk: request.item.sk }); + if (refuse && request.item.sk === "REPLY") throw new Error("the put failed: AccessDeniedException"); + return (value as (r: unknown) => Promise).call(target, request); + }; + return typeof value === "function" ? (value as (...args: unknown[]) => unknown).bind(target) : value; + } }); + const first = same(store, NOW, down); + await first.send(); + expect(first.posted).toEqual([FAILURE]); + expect(writes.every(({ pk }) => pk === `ORG#${A}#CHANNEL_CLAIM#slack/DIRECT_EVENT#EvFAIL00001`)).toBe(true); + expect(writes.some(({ sk }) => sk === "REPLY")).toBe(true); + refuse = true; + const other = same(new Proxy(new MemoryDocumentStore(), { get(target, field) { + const value = (target as unknown as Record)[field]; + if (field === "put") return async (request: { item: { sk: string } }) => { if (request.item.sk === "REPLY") throw new Error("the put failed: AccessDeniedException"); return (value as (r: unknown) => Promise).call(target, request); }; + return typeof value === "function" ? (value as (...args: unknown[]) => unknown).bind(target) : value; + } }), NOW, down); + expect((await other.send()).statusCode).toBe(500); + expect(other.posted).toEqual([]); + expect(other.logs.map(({ event }) => event)).toContain("direct.failure_marker_failed"); }); }); diff --git a/tests/fixtures/signin-company-goldens/configuration.json b/tests/fixtures/signin-company-goldens/configuration.json index 507ad93130..94541434c9 100644 --- a/tests/fixtures/signin-company-goldens/configuration.json +++ b/tests/fixtures/signin-company-goldens/configuration.json @@ -1 +1 @@ -{"value":{"responses":[{"statusCode":200,"headers":{"content-type":"application/json","cache-control":"no-store","pragma":"no-cache"},"body":"{\"env\":\"staging\",\"apiVersion\":\"1.29\",\"adminApiVersion\":\"1.1\",\"issuer\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth\",\"authorizationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/authorize\",\"tokenEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/token\",\"revocationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/revoke\",\"clientId\":\"agentx-cli\",\"methods\":{\"slack\":true,\"oidc\":{\"displayName\":\"Okta\"}},\"confirm\":{\"elicitation\":true,\"slack\":true}}"}],"items":[]},"jwts":[]} +{"value":{"responses":[{"statusCode":200,"headers":{"content-type":"application/json","cache-control":"no-store","pragma":"no-cache"},"body":"{\"env\":\"staging\",\"apiVersion\":\"1.30\",\"adminApiVersion\":\"1.1\",\"issuer\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth\",\"authorizationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/authorize\",\"tokenEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/token\",\"revocationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/revoke\",\"clientId\":\"agentx-cli\",\"methods\":{\"slack\":true,\"oidc\":{\"displayName\":\"Okta\"}},\"confirm\":{\"elicitation\":true,\"slack\":true}}"}],"items":[]},"jwts":[]} diff --git a/tests/unit/model-display-name.test.ts b/tests/unit/model-display-name.test.ts new file mode 100644 index 0000000000..ceb44f22f2 --- /dev/null +++ b/tests/unit/model-display-name.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { MODEL_DISPLAY_NAME_MAX, modelDisplayName, prettyModelName } from "../../packages/contracts/src/model-display-name.js"; +import { prettyModelName as gatewayPretty, gatewayDisplayName } from "../../packages/model-gateway/src/model-display-name.js"; + +/** One table both copies of the prettifier must read the same (contracts for Code, model-gateway for the catalog). */ +export const DISPLAY_NAME_ROWS: ReadonlyArray = [ + ["us.amazon.ergo-1.0", "Ergo 1.0"], + ["qwen.qwen3-coder-480b-a35b-v1:0", "Qwen3 Coder 480B"], + ["zai.glm-4.7", "GLM 4.7"], + ["moonshot.kimi-k2-thinking", "Kimi K2 Thinking"], + ["claude-haiku-4-5", "Claude Haiku 4.5"], + ["us.anthropic.claude-haiku-4-5-20251001-v1:0", "Claude Haiku 4.5"], + ["claude-opus-5-5", "Claude Opus 5.5"], + ["us.amazon.nova-2-lite-v1:0", "Nova 2 Lite"], + ["openai.gpt-oss-120b-1:0", "GPT-OSS 120B"], + ["gpt-5-mini", "GPT 5 Mini"], + ["deepseek.v3.2", "DeepSeek V3.2"], + ["minimax.minimax-m2", "MiniMax M2"], + ["google/gemini-2.5-pro", "Gemini 2.5 Pro"], + ["deepseek/deepseek-r1:free", "DeepSeek R1 (free)"], +]; + +describe("friendly model names", () => { + it.each(DISPLAY_NAME_ROWS)("reads %s as %s", (id, name) => { + expect(prettyModelName(id)).toBe(name); + }); + + it("the gateway's copy reads every row the same as Code's", () => { + for (const [id] of DISPLAY_NAME_ROWS) expect(gatewayPretty(id)).toBe(prettyModelName(id)); + }); + + it("prefers the provider's own name, and falls back to the prettified id when it is unusable", () => { + expect(modelDisplayName("us.amazon.ergo-1.0", "Amazon Ergo")).toBe("Amazon Ergo"); + expect(modelDisplayName("us.amazon.ergo-1.0", " Amazon \n Ergo ")).toBe("Amazon Ergo"); + for (const bad of [undefined, "", " ", "x".repeat(MODEL_DISPLAY_NAME_MAX + 1), "bad\u0007name"]) expect(modelDisplayName("us.amazon.ergo-1.0", bad)).toBe("Ergo 1.0"); + expect(gatewayDisplayName("us.amazon.ergo-1.0", "Amazon Ergo")).toBe("Amazon Ergo"); + expect(gatewayDisplayName("us.amazon.ergo-1.0", "x".repeat(MODEL_DISPLAY_NAME_MAX + 1))).toBe("Ergo 1.0"); + }); + + it("never returns an empty or over-long name", () => { + for (const id of ["a", "x".repeat(300), "us.", "-"]) { + const name = prettyModelName(id); + expect(name.length).toBeGreaterThan(0); + expect(name.length).toBeLessThanOrEqual(MODEL_DISPLAY_NAME_MAX); + } + }); +}); diff --git a/tests/unit/model-display-names-broker.test.ts b/tests/unit/model-display-names-broker.test.ts new file mode 100644 index 0000000000..fe155814aa --- /dev/null +++ b/tests/unit/model-display-names-broker.test.ts @@ -0,0 +1,79 @@ +// Friendly model names where Code returns model lists and step models to the website: the company's step models page (`offered`, each step's `effective`, each choice in `models`) and the company AI reads +// (engine and learning model) carry `displayName` beside the id. The gateway's own name wins; a list from a gateway older than this change is named by Code's prettifier. The id is still the key. +import { describe, expect, it } from "vitest"; +import { OfferedAgentModelsSchema, ModelSelectionStateSchema, CompanyEngineModelViewSchema, agentModelIdentity, agentModelName, type OrgId, type Principal } from "@agentx/contracts"; +import { createAgentModelChoice, createOfferedModelsView } from "../../packages/broker/src/core-host/gateway-model-selection.js"; +import { displayNamesOf, offeredEngineModelList } from "../../packages/broker/src/core-host/company-engine-model.js"; +import { createLocalOwnerApprovers } from "../../packages/broker/src/ports/policy-defaults.js"; +import { testOwnerPrincipal } from "../support/test-owner.js"; +import { createHarness } from "../support/task-flow-harness.js"; + +const LIST = { version: 1, models: [ + { model: "claude-sonnet-5-5", displayName: "Claude Sonnet 5.5" }, + { model: "us.amazon.ergo-1.0" }, + { model: "qwen.qwen3-coder-480b-a35b-v1:0", displayName: "Qwen3 Coder 480B A35B Instruct" }, + { model: "zai.glm-4.7" }, +] }; + +describe("the offered list names every model", () => { + const company = "org_namesaaaaaaaaaaaaaaa" as OrgId; + const view = (answer: unknown) => createOfferedModelsView({ reader: { offered: async () => answer }, companyId: company, now: () => 1 }); + + it("keeps the gateway's own name and names the rest from the id", async () => { + const models = await view(LIST).list(); + expect(models.map((m) => [m.model, m.displayName])).toEqual([ + ["claude-sonnet-5-5", "Claude Sonnet 5.5"], ["us.amazon.ergo-1.0", "Ergo 1.0"], ["qwen.qwen3-coder-480b-a35b-v1:0", "Qwen3 Coder 480B A35B Instruct"], ["zai.glm-4.7", "GLM 4.7"], + ]); + }); + it("names the list of a gateway older than the field (none sent) the same way, and takes the contract with or without the field", async () => { + const old = await view({ version: 1, models: LIST.models.map(({ model }) => ({ model })) }).list(); + expect(old.map((m) => m.displayName)).toEqual(["Claude Sonnet 5.5", "Ergo 1.0", "Qwen3 Coder 480B", "GLM 4.7"]); + expect(OfferedAgentModelsSchema.safeParse(LIST).success).toBe(true); + expect(OfferedAgentModelsSchema.safeParse({ version: 1, models: [{ model: "zai.glm-4.7", displayName: "" }] }).success).toBe(false); + expect(OfferedAgentModelsSchema.safeParse({ version: 1, models: [{ model: "zai.glm-4.7", displayName: "bad\u0007" }] }).success).toBe(false); + }); +}); + +describe("the company's step models page", () => { + async function world(answer: unknown) { + const h = createHarness(); + const company = h.deps.companyId; + const choice = createAgentModelChoice({ store: h.store, companyId: company, audit: h.deps.audit, approvers: createLocalOwnerApprovers({ owner: testOwnerPrincipal({ companyId: company }), now: () => new Date(h.clock.now) }), + reader: { offered: async () => answer }, defaultModel: async () => "claude-sonnet-5-5", now: () => h.clock.now }); + const owner = { ...testOwnerPrincipal({ companyId: company }), authTime: new Date(h.clock.now).toISOString() } as Principal; + return { choice, owner }; + } + it("carries displayName on the offered list, on every model of the picker and on each step's effective model, beside the id, and still reads as the contract", async () => { + const w = await world(LIST); + const offered = await w.choice.offered(); + expect(offered.map((m) => m.displayName)).toEqual(["Claude Sonnet 5.5", "Ergo 1.0", "Qwen3 Coder 480B A35B Instruct", "GLM 4.7"]); + // A model a step is set to is a choice of the picker too (the picker holds what the install can call now and what is chosen). + expect(await w.choice.service().apply(w.owner, { action: "set", stage: "build", choice: { model: agentModelIdentity("qwen.qwen3-coder-480b-a35b-v1:0") }, expectedRevision: 0 }, { fresh: true })).toMatchObject({ ok: true }); + const state = await w.choice.service().state(); + expect(ModelSelectionStateSchema.safeParse(state).success).toBe(true); + for (const entry of state.models) expect(entry.displayName, entry.label).toBeTruthy(); + const nameOfModel = (name: string) => state.models.find((m) => agentModelName(m.model) === name)!.displayName; + expect(nameOfModel("qwen.qwen3-coder-480b-a35b-v1:0")).toBe("Qwen3 Coder 480B A35B Instruct"); + expect(nameOfModel("claude-sonnet-5-5")).toBe("Claude Sonnet 5.5"); + expect(state.steps.find((step) => step.stage === "build")!.effective!.displayName).toBe("Qwen3 Coder 480B A35B Instruct"); + const effective = state.steps.map((step) => step.effective).filter((e) => e !== undefined); + expect(effective.length).toBeGreaterThan(0); + for (const e of effective) expect(e.displayName).toBeTruthy(); + // The id is still the key: every model of the picker is an offered id. + for (const m of state.models) expect(offered.map((o) => o.model)).toContain(agentModelName(m.model)); + }); +}); + +describe("the company's engine model read", () => { + it("names every id of the view by its id, from the gateway's name or Code's reading of the id", async () => { + const company = "org_namesaaaaaaaaaaaaaaa" as OrgId; + const list = await offeredEngineModelList(async () => LIST, company); + expect(list.ids).toEqual(LIST.models.map((m) => m.model)); + const names = displayNamesOf(["claude-sonnet-5-5", "us.amazon.ergo-1.0", null, undefined, "zai.glm-5"], list.names); + expect(names).toEqual({ "claude-sonnet-5-5": "Claude Sonnet 5.5", "us.amazon.ergo-1.0": "Ergo 1.0", "zai.glm-5": "GLM 5" }); + const view = { model: "claude-sonnet-5-5", source: "install", offered: list.ids, preselect: "claude-sonnet-5-5", displayNames: displayNamesOf(list.ids, list.names) }; + expect(CompanyEngineModelViewSchema.safeParse(view).success).toBe(true); + // A view from a Code without names still reads. + expect(CompanyEngineModelViewSchema.safeParse({ ...view, displayNames: undefined }).success).toBe(true); + }); +}); diff --git a/tests/unit/model-gateway-display-names.test.ts b/tests/unit/model-gateway-display-names.test.ts new file mode 100644 index 0000000000..00c3a488c9 --- /dev/null +++ b/tests/unit/model-gateway-display-names.test.ts @@ -0,0 +1,87 @@ +// Friendly model names in the gateway: discovery keeps the provider's own name (Bedrock `modelName`, a profile's `inferenceProfileName`, Anthropic `display_name`), else the prettified id; the catalog record stores it; the offered +// list sends it as `displayName` beside the unchanged id, only where the catalog is on, and Code's contract takes it. +import { describe, expect, it } from "vitest"; +import { OfferedAgentModelsSchema } from "../../packages/contracts/src/agent-model-choice.js"; +import { discoverAnthropic, discoverBedrock, discoverOpenAi } from "../../packages/model-gateway/src/model-catalog-discovery.js"; +import { mergeDiscovery, validCatalogModel, validCatalogSnapshot, type CatalogSnapshot } from "../../packages/model-gateway/src/gateway-model-catalog.js"; +import { CatalogLive } from "../../packages/model-gateway/src/model-catalog-view.js"; +import { offeredDisplayName } from "../../packages/model-gateway/src/offered-models.js"; + +const fm = (modelId: string, over: Record = {}) => ({ modelId, outputModalities: ["TEXT"], responseStreamingSupported: true, inferenceTypesSupported: ["ON_DEMAND"], modelLifecycle: { status: "ACTIVE" }, ...over }); +const profile = (id: string, over: Record = {}) => ({ inferenceProfileId: id, status: "ACTIVE", type: "SYSTEM_DEFINED", ...over }); + +describe("discovery names every model", () => { + const models = { modelSummaries: [ + fm("qwen.qwen3-coder-480b-a35b-v1:0", { modelName: "Qwen3 Coder 480B A35B Instruct", providerName: "Qwen" }), + fm("zai.glm-4.7"), + fm("amazon.ergo-1.0", { inferenceTypesSupported: ["INFERENCE_PROFILE"] }), + fm("anthropic.claude-haiku-4-5-20251001-v1:0", { inferenceTypesSupported: ["INFERENCE_PROFILE"], modelName: "Claude Haiku 4.5" }), + fm("moonshot.kimi-k2-thinking", { modelName: "x".repeat(300) }), + ] }; + const profiles = { inferenceProfileSummaries: [ + profile("us.amazon.ergo-1.0", { inferenceProfileName: "US Amazon Ergo 1.0" }), profile("us.anthropic.claude-haiku-4-5-20251001-v1:0", { inferenceProfileName: "US Anthropic Claude Haiku 4.5" }), + ] }; + const byName = Object.fromEntries(discoverBedrock(models, profiles, "us-east-1").map((m) => [m.id, m.displayName])); + + it("takes the provider's own model name when it has one", () => { + expect(byName["qwen.qwen3-coder-480b-a35b-v1:0"]).toBe("Qwen3 Coder 480B A35B Instruct"); + expect(byName["us.anthropic.claude-haiku-4-5-20251001-v1:0"]).toBe("Claude Haiku 4.5"); + }); + it("takes an inference profile's name, without its geography word, when the model has no name", () => { + expect(byName["us.amazon.ergo-1.0"]).toBe("Amazon Ergo 1.0"); + }); + it("falls back to the prettified id when the provider gives no name, or an unusable one", () => { + expect(byName["zai.glm-4.7"]).toBe("GLM 4.7"); + expect(byName["moonshot.kimi-k2-thinking"]).toBe("Kimi K2 Thinking"); + }); + it("names OpenAI models from the id and Anthropic models from their display_name", () => { + expect(discoverOpenAi({ data: [{ id: "gpt-5-mini", created: 1 }] })[0]!.displayName).toBe("GPT 5 Mini"); + const found = discoverAnthropic({ data: [{ id: "claude-new-9", display_name: "Claude New 9" }, { id: "claude-opus-5-5" }] }); + expect(found.map((m) => m.displayName)).toEqual(["Claude New 9", "Claude Opus 5.5"]); + }); +}); + +describe("the catalog record keeps the name", () => { + const found = [{ name: "zai.glm-4.7", id: "zai.glm-4.7", version: "zai.glm-4.7", displayName: "GLM 4.7" }]; + it("stores it when the model is discovered, keeps it when a later list gives none, and takes a corrected one", () => { + const first = mergeDiscovery(undefined, "rovara", found, new Map(), 1); + expect(first.models[0]!.displayName).toBe("GLM 4.7"); + expect(validCatalogSnapshot(first)).toBe(true); + const kept = mergeDiscovery(first, "rovara", [{ name: "zai.glm-4.7", id: "zai.glm-4.7", version: "zai.glm-4.7" }], new Map(), 2); + expect(kept.models[0]!.displayName).toBe("GLM 4.7"); + const fixed = mergeDiscovery(kept, "rovara", [{ ...found[0]!, displayName: "Z.AI GLM 4.7" }], new Map(), 3); + expect(fixed.models[0]!.displayName).toBe("Z.AI GLM 4.7"); + }); + it("reads a record stored before names existed (none), and refuses a name that is not one line of 1 to 100 characters", () => { + const record = mergeDiscovery(undefined, "rovara", [{ name: "a.b", id: "a.b", version: "a.b" }], new Map(), 1).models[0]!; + expect(record.displayName).toBeUndefined(); + expect(validCatalogModel(record)).toBe(true); + for (const bad of ["", "x".repeat(101), "two\nlines"]) expect(validCatalogModel({ ...record, displayName: bad })).toBe(false); + }); +}); + +describe("the offered name of a model", () => { + const snapshot = (source: "rovara" | "anthropic", displayName: string, name: string): CatalogSnapshot => ({ version: 1, source, savedAt: 1, models: [{ name, id: name, version: name, displayName, origin: "discovered", discoveredAt: 1, seenAt: 1 }] }); + const live = (...snapshots: CatalogSnapshot[]) => new CatalogLive({ + catalog: { rovara: { load: async () => snapshots.find((s) => s.source === "rovara") }, openai: { load: async () => undefined }, anthropic: { load: async () => snapshots.find((s) => s.source === "anthropic") } }, + overlay: { overlay: async () => ({ version: 0, entries: {} }) }, + }); + it("is the catalog's stored name, OpenRouter's own name for its models, else the prettified id", async () => { + const view = live(snapshot("rovara", "Qwen3 Coder", "qwen.qwen3-coder-480b-a35b-v1:0"), snapshot("anthropic", "Claude Haiku Four Point Five", "claude-haiku-4-5")); + await view.reload(); + expect(offeredDisplayName(view, undefined, "qwen.qwen3-coder-480b-a35b-v1:0", "rovara")).toBe("Qwen3 Coder"); + expect(offeredDisplayName(view, undefined, "zai.glm-4.7", "rovara")).toBe("GLM 4.7"); + expect(offeredDisplayName(view, undefined, "claude-haiku-4-5", "anthropic_key")).toBe("Claude Haiku Four Point Five"); + expect(offeredDisplayName(view, undefined, "claude-haiku-4-5", undefined)).toBe("Claude Haiku Four Point Five"); + expect(offeredDisplayName(view, { entry: () => ({ name: "Google: Gemini 2.5 Pro" }) as never }, "google/gemini-2.5-pro", "openrouter_key")).toBe("Google: Gemini 2.5 Pro"); + expect(offeredDisplayName(view, { entry: () => undefined }, "google/gemini-2.5-pro", "openrouter_key")).toBe("Gemini 2.5 Pro"); + }); + it("names nothing while no catalog has been read (a gateway without the catalog answers exactly as before)", () => { + expect(offeredDisplayName(live(), undefined, "zai.glm-4.7", "rovara")).toBeUndefined(); + }); + it("is a member of Code's offered list contract, beside the unchanged id", () => { + const body = { version: 1, models: [{ model: "zai.glm-4.7", displayName: "GLM 4.7" }, { model: "claude-haiku-4-5" }] }; + expect(OfferedAgentModelsSchema.safeParse(body).success).toBe(true); + expect(OfferedAgentModelsSchema.safeParse({ version: 1, models: [{ model: "zai.glm-4.7", displayName: "" }] }).success).toBe(false); + }); +}); diff --git a/tests/unit/model-gateway-offered-models.test.ts b/tests/unit/model-gateway-offered-models.test.ts index 1521f96fb1..c019e14759 100644 --- a/tests/unit/model-gateway-offered-models.test.ts +++ b/tests/unit/model-gateway-offered-models.test.ts @@ -587,3 +587,27 @@ describe("OpenRouter's live list is what an OpenRouter-key company is offered (O it("the gateway's size limit is Code's", () => { expect(OFFERED_BODY_MAX_BYTES).toBe(OFFERED_AGENT_MODELS_BODY_MAX_BYTES); }); }); + +// ---- Code API 1.30: each offered model also carries `displayName` (display only, sent only where the gateway's catalog is on) --------------------------------------- +describe("display names on the offered list", () => { + it("with no name source (the catalog is off): the answer carries no displayName, exactly as before", async () => { + const out = await get(options().opts, cidA, mintService()); + expect((out.body as { models: Array> }).models.some((m) => "displayName" in m)).toBe(false); + }); + it("with a name source: every row carries displayName beside its unchanged id, the source is the one that serves it, and the answer is Code's contract", async () => { + const sources = new Set(); + const out = await get(options({ displayNameOf: (model, source) => { sources.add(source); return model === "zai.glm-5" ? "GLM 5 (own)" : undefined; } }).opts, cidA, mintService()); + expect(out.status).toBe(200); + const models = (out.body as { models: Array<{ model: string; displayName?: string }> }).models; + expect(models.find((m) => m.model === "zai.glm-5")?.displayName).toBe("GLM 5 (own)"); + expect(models.filter((m) => m.displayName === undefined).length).toBe(models.length - 1); + expect(names(out.body)).toEqual([...CLAUDE_OFFERED, ...BEDROCK_17]); + expect([...sources]).toEqual(["rovara"]); + expect(CodeListSchema.safeParse(out.body).success).toBe(true); + }); + it("a name source that throws leaves the row as it was (never a refusal)", async () => { + const out = await get(options({ displayNameOf: () => { throw new Error("boom"); } }).opts, cidA, mintService()); + expect(out.status).toBe(200); + expect(CodeListSchema.safeParse(out.body).success).toBe(true); + }); +}); diff --git a/tests/unit/offered-model-prices.test.ts b/tests/unit/offered-model-prices.test.ts index 2465592797..a03888d842 100644 --- a/tests/unit/offered-model-prices.test.ts +++ b/tests/unit/offered-model-prices.test.ts @@ -40,7 +40,8 @@ describe("the engine with a priced list", () => { } it("the page's list carries the prices; a step is set, chosen and stored as before", async () => { const w = await world(); - expect(await w.choice.offered()).toEqual(PRICED.models); + // Every offered model also carries the name people read (Code names the ones the gateway did not). + expect(await w.choice.offered()).toEqual(PRICED.models.map((entry) => ({ ...entry, displayName: expect.any(String) as unknown }))); expect(await w.choice.service().apply(w.owner, { action: "set", stage: "build", choice: { model: agentModelIdentity("zai.glm-5") }, expectedRevision: 0 }, { fresh: true })).toMatchObject({ ok: true }); expect(await w.choice.stepModels.choose({ stage: "build" })).toMatchObject({ ok: true, step: { route: { alias: "zai.glm-5" } } }); const dispatcher = dispatcherStoredAgentModelChoice({ store: w.h.store, companyId: w.company, now: () => w.h.clock.now, defaultRoute: async () => ({ alias: "claude-sonnet-5-5", api: "anthropic-messages", catalog: "claude-sonnet-5-5" }), log: () => undefined }); diff --git a/tests/unit/offered-models-http.test.ts b/tests/unit/offered-models-http.test.ts index ab98089ac0..f39e16cdf0 100644 --- a/tests/unit/offered-models-http.test.ts +++ b/tests/unit/offered-models-http.test.ts @@ -46,7 +46,7 @@ describe("a live OpenRouter list", () => { it("is read whole even at the schema's worst case (512 models with the longest names and ids, every fact, 64 reviewer models), and a body past the limit is refused", async () => { const name = (i: number) => `${"a".repeat(62)}/${String(i).padStart(3, "0")}${"b".repeat(59)}:${"c".repeat(31)}`; const long = "z".repeat(511); - const models = Array.from({ length: OFFERED_AGENT_MODELS_MAX }, (_, i) => ({ model: name(i), price: { inputUsdPerMillion: 9999.123456, outputUsdPerMillion: 9999.123456 }, identity: { provider: "openrouter", sourceId: `s${long}`, connectionRevision: `r${long}`, modelId: name(i) }, free: true, tested: true, limits: { contextWindow: 10_000_000, maxOutputTokens: 10_000_000 } })); + const models = Array.from({ length: OFFERED_AGENT_MODELS_MAX }, (_, i) => ({ model: name(i), displayName: "n".repeat(100), price: { inputUsdPerMillion: 9999.123456, outputUsdPerMillion: 9999.123456 }, identity: { provider: "openrouter", sourceId: `s${long}`, connectionRevision: `r${long}`, modelId: name(i) }, free: true, tested: true, limits: { contextWindow: 10_000_000, maxOutputTokens: 10_000_000 } })); const reviewerAccess = { companyId: "org_aaaaaaaaaaaaaaaaaaaa", companyLimitUsd: 999999.99, models: models.slice(0, REVIEWER_ACCESS_MODELS_MAX).map(({ model }) => ({ model, provider: "openrouter" })) }; const worst = { version: 1, models, reviewerAccess }; expect(OfferedAgentModelsSchema.safeParse(worst).success).toBe(true); From 6e852daedea234f75c0ad07cb459a4c379a7ba2e Mon Sep 17 00:00:00 2001 From: m2 Date: Sat, 5 Dec 2026 13:34:41 -0500 Subject: [PATCH 2/4] Model names: take Code API 1.31 (1.30 is the connection permission gaps change's) Co-Authored-By: Claude Sonnet 5.5 --- contracts/shared/offered-agent-models.v1.json | 2 +- packages/broker/src/core-host/gateway-model-selection.ts | 2 +- packages/code-api/src/routes.ts | 2 +- packages/code-api/src/version.ts | 2 +- packages/contracts/src/agent-model-choice.ts | 2 +- packages/contracts/src/app-model-selection.ts | 4 ++-- packages/contracts/src/company-engine-model.ts | 2 +- packages/contracts/src/company-learning-model.ts | 2 +- tests/contract/admin-health.test.ts | 4 ++-- tests/contract/admin-read-contracts.test.ts | 2 +- tests/contract/code-api-version.test.ts | 4 ++-- tests/contract/developer-contracts.test.ts | 2 +- tests/contract/developer-identity-server.test.ts | 2 +- tests/contract/developer-share-contracts.test.ts | 2 +- tests/contract/developer-task-shapes.test.ts | 2 +- tests/fixtures/signin-company-goldens/configuration.json | 2 +- tests/unit/model-gateway-offered-models.test.ts | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/contracts/shared/offered-agent-models.v1.json b/contracts/shared/offered-agent-models.v1.json index 2bcfee81cd..56cc51277a 100644 --- a/contracts/shared/offered-agent-models.v1.json +++ b/contracts/shared/offered-agent-models.v1.json @@ -6,7 +6,7 @@ }, "response": { "version": 1, - "models": "1 to 512 entries, each { model, displayName? (Code API 1.30: the name people read, 1 to 100 characters on one line; the id stays the key), price?, identity?, priceKnown? (false only, never with price), free? (true only), tested? (true only), limits? { contextWindow, maxOutputTokens } }; slash IDs require exact identity; legacy names have no identity", + "models": "1 to 512 entries, each { model, displayName? (Code API 1.31: the name people read, 1 to 100 characters on one line; the id stays the key), price?, identity?, priceKnown? (false only, never with price), free? (true only), tested? (true only), limits? { contextWindow, maxOutputTokens } }; slash IDs require exact identity; legacy names have no identity", "modelNamePattern": "^(?:[A-Za-z0-9][A-Za-z0-9._:-]{0,127}|[a-z0-9][a-z0-9._-]{0,62}\\/[a-z0-9][a-z0-9._-]{0,62}(?::[a-z0-9][a-z0-9._-]{0,31})?)$", "modelsMax": 512, "identity": { diff --git a/packages/broker/src/core-host/gateway-model-selection.ts b/packages/broker/src/core-host/gateway-model-selection.ts index 95ed52b54c..13c11cc554 100644 --- a/packages/broker/src/core-host/gateway-model-selection.ts +++ b/packages/broker/src/core-host/gateway-model-selection.ts @@ -56,7 +56,7 @@ export function createOfferedModelsView(input: { reader: OfferedModelsReader; co ]); const parsed = OfferedAgentModelsSchema.safeParse(answer); if (!parsed.success) throw new Error("shape"); - // Every offered model has a name people read: the gateway's own (Code API 1.30), else Code's reading of the id (a gateway older than 1.30 sends none). + // Every offered model has a name people read: the gateway's own (Code API 1.31), else Code's reading of the id (a gateway older than 1.31 sends none). held = { at: now, models: Object.freeze(parsed.data.models.map((entry) => Object.freeze({ ...entry, displayName: modelDisplayName(entry.model, entry.displayName) }))) }; return held.models; } catch { throw new OfferedModelsUnavailable(); } diff --git a/packages/code-api/src/routes.ts b/packages/code-api/src/routes.ts index 0178598fa4..25d57370fb 100644 --- a/packages/code-api/src/routes.ts +++ b/packages/code-api/src/routes.ts @@ -514,7 +514,7 @@ export const ROUTES: readonly Route[] = [ // Script tokens are long-lived credentials, and a person erase deletes a removed person's records: full access only (and a live owner or admin to make a token or erase). // #1175: the company's per-step agent model choice (core-host/agent-model-routes.ts): full access only, then the core reads the live role (any member reads, // an owner or admin changes). Without these rows the broker answered 404 before auth, and Cloud's "AI and spending" step could never finish. - // Code API 1.30: the answer (and the engine and learning model reads) also name `displayName` for every model, the name people read beside the id (optional, read tolerantly; the id stays the key). + // Code API 1.31: the answer (and the engine and learning model reads) also name `displayName` for every model, the name people read beside the id (optional, read tolerantly; the id stays the key). { method: "GET", path: "/v1/app/agent-models", requires: "full" }, { method: "POST", path: "/v1/app/agent-models", requires: "full" }, { method: "GET", path: "/v1/app/script-tokens", requires: "full" }, diff --git a/packages/code-api/src/version.ts b/packages/code-api/src/version.ts index 5d101b30c4..93e01a357e 100644 --- a/packages/code-api/src/version.ts +++ b/packages/code-api/src/version.ts @@ -5,5 +5,5 @@ // // CODE_API_MIN_CLIENT ("major.minor") is the oldest version of this package a client may be built against and still be served. Code raises it only after the client side has stopped using what is // being removed (see README.md, "Skew"). A test pins a digest of the contract surface and fails when the surface changes without a bump here. -export const CODE_API_VERSION = "1.30"; +export const CODE_API_VERSION = "1.31"; export const CODE_API_MIN_CLIENT = "1.2"; diff --git a/packages/contracts/src/agent-model-choice.ts b/packages/contracts/src/agent-model-choice.ts index 2a0cee1421..486b900461 100644 --- a/packages/contracts/src/agent-model-choice.ts +++ b/packages/contracts/src/agent-model-choice.ts @@ -40,7 +40,7 @@ export const OfferedModelLimitsSchema = z.object({ contextWindow: z.number().int * `free` (a `:free` model: rate-limited, and the provider may keep prompts), `tested` (one of the models Rovara proved by hand), `limits`. */ export const OfferedAgentModelSchema = z.object({ - /** Code API 1.30: the name people read (the provider's own, else a prettified id), beside the id. Display only; `model` stays the key. Absent from a gateway older than 1.30: Code names the model itself (`modelDisplayName`). */ + /** Code API 1.31: the name people read (the provider's own, else a prettified id), beside the id. Display only; `model` stays the key. Absent from a gateway older than 1.31: Code names the model itself (`modelDisplayName`). */ displayName: ModelDisplayNameSchema.optional(), model: z.string().regex(AGENT_MODEL_NAME), price: OfferedModelPriceSchema.optional(), identity: GatewayModelIdentitySchema.optional(), priceKnown: z.literal(false).optional(), free: z.literal(true).optional(), tested: z.literal(true).optional(), limits: OfferedModelLimitsSchema.optional(), diff --git a/packages/contracts/src/app-model-selection.ts b/packages/contracts/src/app-model-selection.ts index 1546585f9c..e5e0462b7e 100644 --- a/packages/contracts/src/app-model-selection.ts +++ b/packages/contracts/src/app-model-selection.ts @@ -19,7 +19,7 @@ export const ModelStepViewSchema = z.object({ /** The model the step would run on now. Absent when none can be chosen (`refusal` says why). */ effective: z.object({ model: ModelIdentifierSchema, - /** Code API 1.30: the name people read for `model` (the id stays the key). */ + /** Code API 1.31: the name people read for `model` (the id stays the key). */ displayName: ModelDisplayNameSchema.optional(), thinkingLevel: ThinkingLevelSchema.nullable(), reason: z.enum(MODEL_STEP_REASONS), @@ -36,7 +36,7 @@ export type ModelStepView = z.infer; export const ModelChoiceViewSchema = z.object({ model: ModelIdentifierSchema, - /** Code API 1.30: the name people read for `model` (the provider's own, else a prettified id); `label` stays the raw `provider/id`. */ + /** Code API 1.31: the name people read for `model` (the provider's own, else a prettified id); `label` stays the raw `provider/id`. */ displayName: ModelDisplayNameSchema.optional(), /** The maker, a fixed word (`anthropic`, `openai`, ...; `other` when unknown). */ company: z.string().min(1).max(64), diff --git a/packages/contracts/src/company-engine-model.ts b/packages/contracts/src/company-engine-model.ts index 8dccd5025c..df3e9ca764 100644 --- a/packages/contracts/src/company-engine-model.ts +++ b/packages/contracts/src/company-engine-model.ts @@ -25,7 +25,7 @@ export type CompanyEngineModelBody = z.infer because your sources can't run "); * offered the model ids the gateway offers THIS company now, in the gateway's order; - * displayNames Code API 1.30: the name people read for every id above (`model`, `defaultNotOffered`, `offered`, `preselect`), by id; the id stays the key; + * displayNames Code API 1.31: the name people read for every id above (`model`, `defaultNotOffered`, `offered`, `preselect`), by id; the id stays the key; * preselect what a picker preselects: `model` when it is offered, else the BEST offered model, which is the gateway's first (the gateway lists its preferred model first). */ export const CompanyEngineModelViewSchema = z.object({ diff --git a/packages/contracts/src/company-learning-model.ts b/packages/contracts/src/company-learning-model.ts index 14c5049146..915129e7d3 100644 --- a/packages/contracts/src/company-learning-model.ts +++ b/packages/contracts/src/company-learning-model.ts @@ -23,7 +23,7 @@ export type CompanyLearningModelBody = z.infer { project: "payments", origin: "slack", requester: { kind: "none" }, kind: "task", status: "FAILED", category: "worker_unavailable", error: "RUNTIME_UNAVAILABLE: no capacity", endedAt: at }); const answer = await admin("GET", "/v1/admin/health"); expect(answer.body).toEqual({ - version: { developerApi: "1.30", adminApi: "1.1", release: "0.0.6" }, + version: { developerApi: "1.31", adminApi: "1.1", release: "0.0.6" }, alarms: [{ name: "agentx-live25d-ConnectorBroken", state: "ALARM" }, { name: "agentx-live25d-SlackDeadLetters", state: "OK" }], alarmsCheck: { status: "warn", detail: "1 alarm in ALARM" }, deadLetterQueues: [{ name: "dispatch", depth: 0 }, { name: "slack-requests", depth: 2 }], @@ -47,7 +47,7 @@ describe("GET /v1/admin/health (FR-030, A13)", () => { const answer = await admin("GET", "/v1/admin/health"); expect(answer.status).toBe(200); expect(answer.body).toMatchObject({ - version: { developerApi: "1.30", adminApi: "1.1" }, + version: { developerApi: "1.31", adminApi: "1.1" }, alarms: [], alarmsCheck: { status: "unknown", detail: "could not read the alarms (AccessDenied)" }, deadLetterQueues: [], deadLetterQueuesCheck: { status: "unknown", detail: "not set up in this deployment" }, slack: { status: "failed", detail: "Slack refused the bot token (token_revoked)" }, diff --git a/tests/contract/admin-read-contracts.test.ts b/tests/contract/admin-read-contracts.test.ts index 76eba8279b..7273fa7f30 100644 --- a/tests/contract/admin-read-contracts.test.ts +++ b/tests/contract/admin-read-contracts.test.ts @@ -46,7 +46,7 @@ describe("the index records (A5)", () => { describe("the wire shapes", () => { it("adds the admin API version beside the developer one, which stays 1.2 (A1)", () => { expect(ADMIN_API_VERSION).toBe("1.1"); - expect(DEVELOPER_API_VERSION).toBe("1.30"); + expect(DEVELOPER_API_VERSION).toBe("1.31"); expect(ADMIN_INDEX_RETENTION_DAYS).toBe(30); }); diff --git a/tests/contract/code-api-version.test.ts b/tests/contract/code-api-version.test.ts index 22585cef76..39353f4e6d 100644 --- a/tests/contract/code-api-version.test.ts +++ b/tests/contract/code-api-version.test.ts @@ -64,8 +64,8 @@ const DIGESTS: Readonly> = { "1.28": "f35ca9cc07b595877aaef5b5b4ab34fc56ed8859cef1e3d7796c64769bb46131", // 1.29 (VIEWER-FLAGS; 1.28 is INBOX-HIDE's): the task read (`tasks.read`) also names `canRetryFeedback` and `canAnswerQuestions`, whether the person reading may retry the task's PR feedback (Retry fix, Retry review) and answer its questions, each computed by the function its own route judges with (`feedbackOwner`, `answerStandingOf`) served only where the deployment serves the action, and `false` where the task is closed, has no PR-feedback round, waits for no answers, or the caller is a script token. Both optional and read tolerantly. Code first: an older client ignores them, and the website then follows Code instead of guessing a role. "1.29": "d9e8f417e617355e947c3996bd0a573b3df73075d417ab581434670d077a2148", - // 1.30 (MODEL-NAMES): every model Code returns to the website also carries `displayName` (the provider's own name, else a prettified id; the id stays the key): each entry of the step models page's `offered` list (`GET /v1/app/agent-models`), each choice in its `state.models` and each step's `effective`, and the company AI reads (`GET /v1/dev/company/engine-model` and `/learning-model` name every id they return in `displayNames`). All optional and read tolerantly; none of those rows carries a schema or `webAppOnly`, so the digest is 1.29's. Code first: an older client ignores the member. - "1.30": "d9e8f417e617355e947c3996bd0a573b3df73075d417ab581434670d077a2148", + // 1.31 (MODEL-NAMES): every model Code returns to the website also carries `displayName` (the provider's own name, else a prettified id; the id stays the key): each entry of the step models page's `offered` list (`GET /v1/app/agent-models`), each choice in its `state.models` and each step's `effective`, and the company AI reads (`GET /v1/dev/company/engine-model` and `/learning-model` name every id they return in `displayNames`). All optional and read tolerantly; none of those rows carries a schema or `webAppOnly`, so the digest is 1.29's. Code first: an older client ignores the member. + "1.31": "d9e8f417e617355e947c3996bd0a573b3df73075d417ab581434670d077a2148", }; const schemaOf = (schema: z.ZodType | undefined) => (schema === undefined ? null : z.toJSONSchema(schema)); diff --git a/tests/contract/developer-contracts.test.ts b/tests/contract/developer-contracts.test.ts index 4a94023c9f..c55e3b8590 100644 --- a/tests/contract/developer-contracts.test.ts +++ b/tests/contract/developer-contracts.test.ts @@ -25,7 +25,7 @@ const configuration = { describe("developer sign-in contracts", () => { it("names the public client, audience and API version", () => { - expect([AGENTX_CLI_CLIENT_ID, DEVELOPER_TOKEN_AUDIENCE, DEVELOPER_API_VERSION]).toEqual(["agentx-cli", "agentx-developer", "1.30"]); + expect([AGENTX_CLI_CLIENT_ID, DEVELOPER_TOKEN_AUDIENCE, DEVELOPER_API_VERSION]).toEqual(["agentx-cli", "agentx-developer", "1.31"]); }); it.each([ diff --git a/tests/contract/developer-identity-server.test.ts b/tests/contract/developer-identity-server.test.ts index 5e6ca54645..aa65c56ca0 100644 --- a/tests/contract/developer-identity-server.test.ts +++ b/tests/contract/developer-identity-server.test.ts @@ -19,7 +19,7 @@ describe("discovery (FR-001, FR-048)", () => { it("reports the environment, API version and the methods that can actually be used", async () => { const both = identityHarness({ oidc: {} }); expect(json((await both.http(httpEvent("GET", "/v1/auth/.well-known/agentx-configuration"))).body)).toEqual({ - env: "staging", apiVersion: "1.30", adminApiVersion: "1.1", issuer: ISSUER, authorizationEndpoint: `${ISSUER}/authorize`, tokenEndpoint: `${ISSUER}/token`, + env: "staging", apiVersion: "1.31", adminApiVersion: "1.1", issuer: ISSUER, authorizationEndpoint: `${ISSUER}/authorize`, tokenEndpoint: `${ISSUER}/token`, revocationEndpoint: `${ISSUER}/revoke`, clientId: "agentx-cli", methods: { slack: true, oidc: { displayName: "Okta" } }, confirm: { elicitation: true, slack: true }, }); diff --git a/tests/contract/developer-share-contracts.test.ts b/tests/contract/developer-share-contracts.test.ts index 075f7f3715..8f1e60a479 100644 --- a/tests/contract/developer-share-contracts.test.ts +++ b/tests/contract/developer-share-contracts.test.ts @@ -106,6 +106,6 @@ describe("records and codes", () => { // errorStatus answers 409 for any code it does not list, so pin the code's membership too. expect(AgentXErrorCodeSchema.options).toContain("CHANNEL_AMBIGUOUS"); expect(agentXError("CHANNEL_AMBIGUOUS", "name one").statusCode).toBe(409); - expect(DEVELOPER_API_VERSION).toBe("1.30"); + expect(DEVELOPER_API_VERSION).toBe("1.31"); }); }); diff --git a/tests/contract/developer-task-shapes.test.ts b/tests/contract/developer-task-shapes.test.ts index eae45ad8ed..6b647d360d 100644 --- a/tests/contract/developer-task-shapes.test.ts +++ b/tests/contract/developer-task-shapes.test.ts @@ -84,7 +84,7 @@ describe("changed files from the workspace diff (R18)", () => { describe("developer API 1.2 (R23, Q7)", () => { it("reports 1.2 and adds the project's task policy and channel names", () => { - expect(DEVELOPER_API_VERSION).toBe("1.30"); + expect(DEVELOPER_API_VERSION).toBe("1.31"); const project = DeveloperProjectSchema.parse({ name: "payments", latestRevision: 7, access: "channel", channels: [{ channelId: "C0123456789", name: "payments-dev", isPrivate: false }], diff --git a/tests/fixtures/signin-company-goldens/configuration.json b/tests/fixtures/signin-company-goldens/configuration.json index 94541434c9..47fb2013d3 100644 --- a/tests/fixtures/signin-company-goldens/configuration.json +++ b/tests/fixtures/signin-company-goldens/configuration.json @@ -1 +1 @@ -{"value":{"responses":[{"statusCode":200,"headers":{"content-type":"application/json","cache-control":"no-store","pragma":"no-cache"},"body":"{\"env\":\"staging\",\"apiVersion\":\"1.30\",\"adminApiVersion\":\"1.1\",\"issuer\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth\",\"authorizationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/authorize\",\"tokenEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/token\",\"revocationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/revoke\",\"clientId\":\"agentx-cli\",\"methods\":{\"slack\":true,\"oidc\":{\"displayName\":\"Okta\"}},\"confirm\":{\"elicitation\":true,\"slack\":true}}"}],"items":[]},"jwts":[]} +{"value":{"responses":[{"statusCode":200,"headers":{"content-type":"application/json","cache-control":"no-store","pragma":"no-cache"},"body":"{\"env\":\"staging\",\"apiVersion\":\"1.31\",\"adminApiVersion\":\"1.1\",\"issuer\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth\",\"authorizationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/authorize\",\"tokenEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/token\",\"revocationEndpoint\":\"https://abc123.execute-api.us-east-1.amazonaws.com/v1/auth/revoke\",\"clientId\":\"agentx-cli\",\"methods\":{\"slack\":true,\"oidc\":{\"displayName\":\"Okta\"}},\"confirm\":{\"elicitation\":true,\"slack\":true}}"}],"items":[]},"jwts":[]} diff --git a/tests/unit/model-gateway-offered-models.test.ts b/tests/unit/model-gateway-offered-models.test.ts index c019e14759..2b4cfaeeb6 100644 --- a/tests/unit/model-gateway-offered-models.test.ts +++ b/tests/unit/model-gateway-offered-models.test.ts @@ -588,7 +588,7 @@ describe("OpenRouter's live list is what an OpenRouter-key company is offered (O it("the gateway's size limit is Code's", () => { expect(OFFERED_BODY_MAX_BYTES).toBe(OFFERED_AGENT_MODELS_BODY_MAX_BYTES); }); }); -// ---- Code API 1.30: each offered model also carries `displayName` (display only, sent only where the gateway's catalog is on) --------------------------------------- +// ---- Code API 1.31: each offered model also carries `displayName` (display only, sent only where the gateway's catalog is on) --------------------------------------- describe("display names on the offered list", () => { it("with no name source (the catalog is off): the answer carries no displayName, exactly as before", async () => { const out = await get(options().opts, cidA, mintService()); From 2eaf2c545fdb5ba6b19cd222273a904b31d34a5d Mon Sep 17 00:00:00 2001 From: m2 Date: Sat, 5 Dec 2026 14:15:59 -0500 Subject: [PATCH 3/4] DM failure reply: never answer a pending or handled event when the person check fails; explicit Ergo name override The person check failing now takes the event's claim first (a claim in flight is a 500 for Slack to retry, a handled one is ignored, neither says sorry), says the failure once, and gives the claim back. The IAM test records sort keys and covers the REPLY marker on that path. Ergo has an explicit override in both copies of the name map. Co-Authored-By: Claude Sonnet 5.5 --- packages/broker/src/aws/slack-direct-front.ts | 14 +++++- packages/contracts/src/model-display-name.ts | 1 + .../model-gateway/src/model-display-name.ts | 1 + .../contract/slack-direct-ingress-iam.test.ts | 17 +++++-- tests/contract/slack-direct-messages.test.ts | 49 +++++++++++++++++++ tests/unit/model-display-name.test.ts | 12 ++++- 6 files changed, 86 insertions(+), 8 deletions(-) diff --git a/packages/broker/src/aws/slack-direct-front.ts b/packages/broker/src/aws/slack-direct-front.ts index 4ea23a971e..edebf0ef23 100644 --- a/packages/broker/src/aws/slack-direct-front.ts +++ b/packages/broker/src/aws/slack-direct-front.ts @@ -171,6 +171,18 @@ async function claimOrAnswer(store: NonNullable["store"], partition: string, eventId: string, nowSeconds: number, say: (text: string) => Promise, log: (event: string, fields: Record) => void): Promise { + const taken = await claimOrAnswer(store, partition, eventId, nowSeconds, log); + if ("result" in taken) return taken.result; + await sayFailureOnce(store, partition, eventId, nowSeconds, say, log); + await store.delete({ key: taken.claimed.key }).catch((deleteError: unknown) => log("direct.claim_release_failed", { eventId, ...failureFields(deleteError) })); + return { kind: "ignored", reason: "company_check_failed" }; +} + /** One direct message: the company's workspace, the person, then the broker's core. Never throws what Slack should not retry; a failure before the message was taken is `failed`, and the claim is given back. */ export async function answerDirectMessage(deps: SlackDirectDependencies, message: SlackDirectMessage, log: (event: string, fields: Record) => void): Promise { if (deps.workspaces === undefined || deps.direct === undefined) return { kind: "ignored", reason: "direct_messages_not_handled" }; @@ -189,7 +201,7 @@ export async function answerDirectMessage(deps: SlackDirectDependencies, message }; return await slackRequestWorkspace.run({ teamId: message.teamId, companyId, token }, async (): Promise => { let person: Awaited>; - try { person = await slackCompanyPerson(deps, message.teamId, message.userId, message.userTeamId); } catch (error) { log("direct.company_check_failed", { eventId: message.eventId, ...failureFields(error) }); await sayFailureOnce(workspaces.store, partition, message.eventId, nowSeconds, say, log); return { kind: "ignored", reason: "company_check_failed" }; } + try { person = await slackCompanyPerson(deps, message.teamId, message.userId, message.userTeamId); } catch (error) { log("direct.company_check_failed", { eventId: message.eventId, ...failureFields(error) }); return await companyCheckFailed(workspaces.store, partition, message.eventId, nowSeconds, say, log); } // Nothing is looked up for, or said to, a person of another workspace. if (person.kind === "outsider") return { kind: "ignored", reason: "external_organization_user" }; const taken = await claimOrAnswer(workspaces.store, partition, message.eventId, nowSeconds, log); diff --git a/packages/contracts/src/model-display-name.ts b/packages/contracts/src/model-display-name.ts index 2b0711bac9..4ccbf680aa 100644 --- a/packages/contracts/src/model-display-name.ts +++ b/packages/contracts/src/model-display-name.ts @@ -19,6 +19,7 @@ export const MODEL_DISPLAY_NAME_OVERRIDES: Readonly> = Ob "openai.gpt-oss-20b": "GPT-OSS 20B", "openai.gpt-oss-safeguard-120b": "GPT-OSS Safeguard 120B", "openai.gpt-oss-safeguard-20b": "GPT-OSS Safeguard 20B", + "amazon.ergo-1.0": "Ergo 1.0", "zai.glm-4.7": "GLM 4.7", "moonshot.kimi-k2-thinking": "Kimi K2 Thinking", "moonshotai.kimi-k2.5": "Kimi K2.5", diff --git a/packages/model-gateway/src/model-display-name.ts b/packages/model-gateway/src/model-display-name.ts index ee8376f8c4..82ca95f543 100644 --- a/packages/model-gateway/src/model-display-name.ts +++ b/packages/model-gateway/src/model-display-name.ts @@ -10,6 +10,7 @@ export const MODEL_DISPLAY_NAME_OVERRIDES: Readonly> = Ob "openai.gpt-oss-20b": "GPT-OSS 20B", "openai.gpt-oss-safeguard-120b": "GPT-OSS Safeguard 120B", "openai.gpt-oss-safeguard-20b": "GPT-OSS Safeguard 20B", + "amazon.ergo-1.0": "Ergo 1.0", "zai.glm-4.7": "GLM 4.7", "moonshot.kimi-k2-thinking": "Kimi K2 Thinking", "moonshotai.kimi-k2.5": "Kimi K2.5", diff --git a/tests/contract/slack-direct-ingress-iam.test.ts b/tests/contract/slack-direct-ingress-iam.test.ts index 8c997cb654..ce333d414a 100644 --- a/tests/contract/slack-direct-ingress-iam.test.ts +++ b/tests/contract/slack-direct-ingress-iam.test.ts @@ -11,6 +11,7 @@ import { buildAgentXApp } from "../../infra/lib/app.js"; import { skipLambdaBundling } from "../support/skip-bundling.js"; import { MemoryDocumentStore } from "../../packages/broker/src/ports/memory-document-store.js"; import { createSlackAdapterFront } from "../../packages/broker/src/aws/slack-ingress.js"; +import { slackRequestWorkspace } from "../../packages/broker/src/aws/slack-person.js"; import { developerIdForSlackUser } from "../../packages/broker/src/aws/admin-actions.js"; import { slackTokens } from "../../packages/testing/src/channel/slack-world.js"; @@ -19,7 +20,7 @@ skipLambdaBundling(); type Resource = { Type: string; Properties: Record }; type Statement = { Effect: string; Action: string | string[]; Resource: unknown; Condition?: Record> }; type TemplateJson = { Resources: Record }; -type Operation = { action: string; pk: string }; +type Operation = { action: string; pk: string; sk?: string }; const controlPlane = (env: string | undefined): TemplateJson => { const app = buildAgentXApp(env === undefined ? {} : { agentxEnv: env }); @@ -83,7 +84,7 @@ function recordingStore(): { store: DocumentStore; operations: Operation[] } { if (typeof value !== "function") return value; const run = value.bind(target) as (...args: unknown[]) => unknown; if ((READS as readonly PropertyKey[]).includes(field)) return (arg: DocumentKey | DocumentKey[]) => { for (const key of [arg].flat()) operations.push({ action: "dynamodb:GetItem", pk: key.pk }); return run(arg); }; - if ((WRITES as readonly PropertyKey[]).includes(field)) return (request: { item?: DocumentKey; key?: DocumentKey }) => { operations.push({ action: `dynamodb:${{ put: "PutItem", update: "UpdateItem", delete: "DeleteItem" }[String(field) as "put"]}`, pk: (request.item ?? request.key)!.pk }); return run(request); }; + if ((WRITES as readonly PropertyKey[]).includes(field)) return (request: { item?: DocumentKey; key?: DocumentKey }) => { operations.push({ action: `dynamodb:${{ put: "PutItem", update: "UpdateItem", delete: "DeleteItem" }[String(field) as "put"]}`, pk: (request.item ?? request.key)!.pk, sk: (request.item ?? request.key)!.sk }); return run(request); }; if (field === "transact") return (items: readonly TransactItem[]) => { for (const item of items) operations.push({ action: transactAction[item.kind], pk: ("item" in item ? item.item : item.key).pk }); return run(items); }; return run; } }) as DocumentStore; @@ -97,11 +98,11 @@ function signed(payload: unknown) { } /** The front as the Slack Lambda wires it: the link notice is the broker's to write (no State write here), so it is given as a delegated notice. */ -function frontWith(options: { linked: boolean; handOff: () => Promise<{ outcome: "captured"; notice: "note_saved" }> }) { +function frontWith(options: { linked: boolean; handOff: () => Promise<{ outcome: "captured"; notice: "note_saved" }>; checkFails?: boolean }) { const { store, operations } = recordingStore(); const members = new Map(options.linked ? [[native, A]] : []); const workspaces = { store, getProject: async () => ({ companyId: A }), linkUrl: (code: string) => `https://example.test/review/link/${code}`, linkNotice: async () => "link your account: Open in Rovara: https://example.test/review/link/x", - requireCompany: async (): Promise => A, tokenForEvent: async () => ({ companyId: A, token: slackTokens(TEAM).bot }) }; + requireCompany: async (): Promise => { if (options.checkFails === true && slackRequestWorkspace.getStore() !== undefined) throw new Error("directory down"); return A; }, tokenForEvent: async () => ({ companyId: A, token: slackTokens(TEAM).bot }) }; const handler = createSlackAdapterFront({ workspaces, companies: { companyOf: async (id: string) => members.get(id) }, secrets: async () => ({ signingSecret: SECRET }), now: () => NOW, isRovaraThread: async () => false, handOff: async () => undefined, direct: { handOff: options.handOff, post: vi.fn(async () => undefined) }, log: () => undefined }); const send = (eventId: string) => handler(signed({ type: "event_callback", event_id: eventId, team_id: TEAM, api_app_id: "A0ROVARA", authorizations: [{ user_id: BOT, is_bot: true }], @@ -118,7 +119,9 @@ async function directMessageOperations(): Promise { expect((await refused.send("EvIAM0002")).statusCode).toBe(500); const unknown = frontWith({ linked: false, handOff: async () => ({ outcome: "captured", notice: "note_saved" }) }); expect((await unknown.send("EvIAM0003")).statusCode).toBe(200); - return [...taken.operations, ...refused.operations, ...unknown.operations]; + const unchecked = frontWith({ linked: true, handOff: async () => ({ outcome: "captured", notice: "note_saved" }), checkFails: true }); + expect((await unchecked.send("EvIAM0004")).statusCode).toBe(200); + return [...taken.operations, ...refused.operations, ...unknown.operations, ...unchecked.operations]; } let named: TemplateJson; @@ -135,6 +138,10 @@ describe("the Slack Lambda's role covers every State-table operation of the dire const writes = operations.filter(({ action }) => action !== "dynamodb:GetItem"); expect([...new Set(writes.map(({ action }) => action))].sort()).toEqual(["dynamodb:DeleteItem", "dynamodb:PutItem"]); expect(new Set(writes.map(({ pk }) => pk.replace(/#[A-Za-z0-9._-]+$/u, "#")))).toEqual(new Set([`ORG#${A}#CHANNEL_CLAIM#slack/DIRECT_EVENT#`])); + // The failure reply's once-only marker (sort key REPLY) is put beside the claim, in the same partition, after a refused hand-off and after a person who could not be checked. + const markers = writes.filter(({ sk }) => sk === "REPLY"); + expect(markers.map(({ action }) => action)).toEqual(["dynamodb:PutItem", "dynamodb:PutItem"]); + expect(markers.map(({ pk }) => pk).sort()).toEqual([`ORG#${A}#CHANNEL_CLAIM#slack/DIRECT_EVENT#EvIAM0002`, `ORG#${A}#CHANNEL_CLAIM#slack/DIRECT_EVENT#EvIAM0004`]); // The person's link row is the one thing it reads from the store. expect(new Set(operations.filter(({ action }) => action === "dynamodb:GetItem").map(({ pk }) => pk))).toEqual(new Set([`ORG#${A}#CHANNEL_LINK#slack/${TEAM}`])); }); diff --git a/tests/contract/slack-direct-messages.test.ts b/tests/contract/slack-direct-messages.test.ts index 7cd2228088..b8a2791f1d 100644 --- a/tests/contract/slack-direct-messages.test.ts +++ b/tests/contract/slack-direct-messages.test.ts @@ -8,6 +8,7 @@ import { createSlackAdapterFront } from "../../packages/broker/src/aws/slack-ing import { parseDirectMessage, DIRECT_FAILURE_WORDS, DIRECT_UNKNOWN_WORDS, type SlackDirectAnswer, type SlackDirectMessage } from "../../packages/broker/src/aws/slack-direct-front.js"; import { developerIdForSlackUser } from "../../packages/broker/src/aws/admin-actions.js"; import { isSlackDirectMessageEvent } from "../../packages/broker/src/aws/slack-broker-events.js"; +import { slackRequestWorkspace } from "../../packages/broker/src/aws/slack-person.js"; import { coreDirectMessage, DIRECT_MESSAGES_UNAVAILABLE_WORDS } from "../../packages/broker/src/aws/slack-core-direct-message.js"; import { THREAD_INPUT_WORDS } from "../../packages/broker/src/aws/slack-thread-input-words.js"; import type { CoreTaskEntry } from "../../packages/broker/src/aws/engine-boundary.js"; @@ -157,6 +158,54 @@ describe("a direct message Rovara could not handle", () => { expect(first.posted).toEqual([THREAD_INPUT_WORDS.note_saved]); }); + describe("when the person cannot be checked", () => { + /** The same event against a shared store, where the person check fails when `checking` is false (the company lookup is down) and the hand-off is the given one. */ + function checked(store: MemoryDocumentStore, nowMs: number, checking: boolean, handOff: (message: SlackDirectMessage) => Promise) { + const w = world(); + const posted: string[] = []; + const spy = vi.fn(handOff); + // The person check asks for the team's company again, inside the verified workspace's context (after the front's own first read); it is that read that fails. + const requireCompany = async (team: string): Promise => { if (!checking && slackRequestWorkspace.getStore() !== undefined) throw new Error("directory down with private words"); return await w.workspaces.requireCompany(team); }; + const handler = createSlackAdapterFront({ ...w, workspaces: { ...w.workspaces, requireCompany, store }, secrets: async () => ({ signingSecret: SECRET }), now: () => nowMs, isRovaraThread: async () => false, handOff: async () => undefined, + direct: { handOff: spy, post: async (input) => { posted.push(input.text); } }, log: () => undefined }); + const timestamp = String(Math.floor(nowMs / 1000)); + const body = JSON.stringify({ type: "event_callback", event_id: "EvCHECK0001", team_id: TEAM, event: { type: "message", channel_type: "im", channel: DM, user: USER, ts: TS, text: "words" } }); + const send = () => handler({ body, headers: { "x-slack-request-timestamp": timestamp, "x-slack-signature": `v0=${createHmac("sha256", SECRET).update(`v0:${timestamp}:${body}`).digest("hex")}` }, requestContext: { http: { method: "POST" } } }); + return { handOff: spy, posted, send }; + } + const handled = async (): Promise => ({ outcome: "captured", notice: "note_saved" }); + + it("says so once for the event, however often Slack delivers it again, and gives the claim back", async () => { + const store = new MemoryDocumentStore(); + const posted: string[] = []; + for (const at of [0, 60_000, 360_000]) { + const retry = checked(store, NOW + at, false, handled); + expect((await retry.send()).statusCode).toBe(200); + posted.push(...retry.posted); + } + expect(posted).toEqual([FAILURE]); + const later = checked(store, NOW + 400_000, true, handled); + expect((await later.send()).statusCode).toBe(200); + expect(later.handOff).toHaveBeenCalledOnce(); + }); + + it("says nothing while the first delivery is still with the broker (a 500 for Slack to retry), and nothing once the event is handled", async () => { + const store = new MemoryDocumentStore(); + let finish!: (answer: SlackDirectAnswer) => void; + const first = checked(store, NOW, true, () => new Promise((resolve) => { finish = resolve; })); + const running = first.send(); + await vi.waitFor(() => expect(first.handOff).toHaveBeenCalledOnce()); + const pending = checked(store, NOW + 3_000, false, handled); + expect((await pending.send()).statusCode).toBe(500); + expect(pending.posted).toEqual([]); + finish({ outcome: "captured", notice: "note_saved" }); + expect((await running).statusCode).toBe(200); + const done = checked(store, NOW + 60_000, false, handled); + expect((await done.send()).statusCode).toBe(200); + expect(done.posted).toEqual([]); + }); + }); + it("writes only inside the event's own claim partition (a marker, sort key REPLY), and says nothing when the marker cannot be written", async () => { const inner = new MemoryDocumentStore(); const writes: Array<{ pk: string; sk: string }> = []; diff --git a/tests/unit/model-display-name.test.ts b/tests/unit/model-display-name.test.ts index ceb44f22f2..357e942a90 100644 --- a/tests/unit/model-display-name.test.ts +++ b/tests/unit/model-display-name.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from "vitest"; -import { MODEL_DISPLAY_NAME_MAX, modelDisplayName, prettyModelName } from "../../packages/contracts/src/model-display-name.js"; -import { prettyModelName as gatewayPretty, gatewayDisplayName } from "../../packages/model-gateway/src/model-display-name.js"; +import { MODEL_DISPLAY_NAME_MAX, MODEL_DISPLAY_NAME_OVERRIDES, modelDisplayName, prettyModelName } from "../../packages/contracts/src/model-display-name.js"; +import { MODEL_DISPLAY_NAME_OVERRIDES as GATEWAY_OVERRIDES, prettyModelName as gatewayPretty, gatewayDisplayName } from "../../packages/model-gateway/src/model-display-name.js"; /** One table both copies of the prettifier must read the same (contracts for Code, model-gateway for the catalog). */ export const DISPLAY_NAME_ROWS: ReadonlyArray = [ ["us.amazon.ergo-1.0", "Ergo 1.0"], + ["global.amazon.ergo-1.0", "Ergo 1.0"], + ["amazon.ergo-1.0", "Ergo 1.0"], ["qwen.qwen3-coder-480b-a35b-v1:0", "Qwen3 Coder 480B"], ["zai.glm-4.7", "GLM 4.7"], ["moonshot.kimi-k2-thinking", "Kimi K2 Thinking"], @@ -37,6 +39,12 @@ describe("friendly model names", () => { expect(gatewayDisplayName("us.amazon.ergo-1.0", "x".repeat(MODEL_DISPLAY_NAME_MAX + 1))).toBe("Ergo 1.0"); }); + it("names Ergo from the override map, in both copies, whatever the prettifier would make of it", () => { + expect(MODEL_DISPLAY_NAME_OVERRIDES["amazon.ergo-1.0"]).toBe("Ergo 1.0"); + expect(GATEWAY_OVERRIDES["amazon.ergo-1.0"]).toBe("Ergo 1.0"); + expect(GATEWAY_OVERRIDES).toEqual(MODEL_DISPLAY_NAME_OVERRIDES); + }); + it("never returns an empty or over-long name", () => { for (const id of ["a", "x".repeat(300), "us.", "-"]) { const name = prettyModelName(id); From 05e10909fe834f1e8f237b62bab0129386199ff1 Mon Sep 17 00:00:00 2001 From: m2 Date: Sat, 5 Dec 2026 14:49:37 -0500 Subject: [PATCH 4/4] CI: give the tests-unit-w-z lint shard a 6 GB heap It ran out of the 4 GB heap on CI twice on this branch (the type graph behind the workflow-* tests grew), the same fix tests-unit-c and tests-unit-m already have. Co-Authored-By: Claude Opus 5.5 --- scripts/lint-shards.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/lint-shards.ts b/scripts/lint-shards.ts index 4eece30ed3..6798269109 100644 --- a/scripts/lint-shards.ts +++ b/scripts/lint-shards.ts @@ -56,7 +56,8 @@ export const SHARD_DIRECTORIES: readonly { name: string; directories: readonly s { name: "tests-unit-m", directories: ["tests/unit/m*.ts"], heapMb: 6144 }, { name: "tests-unit-n-q", directories: ["tests/unit/n*.ts", "tests/unit/o*.ts", "tests/unit/p*.ts", "tests/unit/q*.ts"] }, { name: "tests-unit-r-v", directories: ["tests/unit/r*.ts", "tests/unit/s*.ts", "tests/unit/t*.ts", "tests/unit/u*.ts", "tests/unit/v*.ts"] }, - { name: "tests-unit-w-z", directories: ["tests/unit/w*.ts", "tests/unit/x*.ts", "tests/unit/y*.ts", "tests/unit/z*.ts"] }, + // #1900: tests-unit-w-z ran out of the 4 GB heap on CI twice (the type graph behind the workflow-* tests grew), so it gets a bigger heap like c and m. + { name: "tests-unit-w-z", directories: ["tests/unit/w*.ts", "tests/unit/x*.ts", "tests/unit/y*.ts", "tests/unit/z*.ts"], heapMb: 6144 }, { name: "tests-unit-folders", directories: ["tests/unit/context-sources", "tests/unit/contracts", "tests/unit/cx-a", "tests/unit/intake", "tests/unit/knowledge", "tests/unit/knowledge-wiring", "tests/unit/lessons", "tests/unit/lessons-by-area", "tests/unit/support", "tests/unit/task-log"] }, { name: "tests-integration", directories: ["tests/integration"] }, { name: "tests-support", directories: ["tests/support"] },