diff --git a/AGENTS.md b/AGENTS.md index b3dc62e..6271444 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,8 +146,20 @@ first publish and later OIDC releases. ## Where things stand -All five synchronized packages and exact internal Support pins are published -and strictly verified at `0.2.11`; the root stays private at `0.0.0`. This release +The current source candidate is synchronized `0.2.12`, adding explicit opt-in +provider-group routing for learning and engineering independent checks. All +five source package versions, exact internal Support pins and root Support +development pins select `0.2.12`; the root stays private at `0.0.0`. External +dependency selections are unchanged. Route, static allowlist and Admin approval +must agree on group scope, with a newly hash-bound price policy and current +qualification/privacy evidence. Azure group selection does not guarantee a +region or activate a host. See the [source preparation](docs/RELEASING.md#source-version-0212) +and [candidate notes](docs/RELEASE_NOTES.md#0212-opt-in-provider-group-checks). +Normal Node 22/24, review, CI and protected release gates remain required; +the candidate is not a published dependency. + +The latest verified public synchronized release remains `0.2.11`, with exact +internal Support pins at `0.2.11`; the root stays private at `0.0.0`. This release corrects the trusted independent-check policy boundary and selects wire v2. Exact KB `0.1.8`, `zod@4.6.7` and other external selections are unchanged. See [release notes](docs/RELEASE_NOTES.md#0211-trusted-independent-check-policy) and diff --git a/docs/AI_OPERATIONS.md b/docs/AI_OPERATIONS.md index 6a67802..c30f48c 100644 --- a/docs/AI_OPERATIONS.md +++ b/docs/AI_OPERATIONS.md @@ -60,6 +60,17 @@ version, verification time, and expiry. Typed references alone do not verify the provider's settings. Disabled, expired, unavailable, or changed proof holds new work. There is no implicit provider or retention-mode fallback. +The source-only [provider-group checker option](../packages/ai/README.md#opt-in-provider-group-checks-source-only) +requires explicit route, static allowlist and Admin-approval scope selections, +plus a newly hash-bound price policy and current group privacy/qualification +evidence. It does not extend the published `0.2.11` contract or enable a host. +An Azure group may include eligible regions and variants; it does not establish +the exact region of a previous endpoint approval. Preserve ZDR-only routing, +disabled input/output logging and no-other-provider fallback. The prompt and +completion price filters are USD per million tokens, separate from total +spending caps and actual native charges. Retain durable unknown-usage holds and +require the host's independent approval and activation gates before live use. + ## Bounded workers and durable recovery Persist a separate opaque cursor for each scheduled scan loop and purpose. diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 5b2aa71..1df490e 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,5 +1,46 @@ # Release notes + + + + +## 0.2.12 source candidate — opt-in provider-group checks + +Source preparation dated 2026-11-14 synchronizes all five package versions, +exact internal Support pins, root Support development pins and lock importers +at `0.2.12`. The root stays private at `0.0.0`; all external dependency +selections remain unchanged. This candidate is not published. The verified +`0.2.11` release and its original artifacts/receipts remain unchanged; see the +[source checkpoint](RELEASING.md#source-version-0212). + +Learning and engineering independent checks may explicitly opt into +`providerSelectionScope: "provider_group"` on the route, matching static +allowlist entry and Admin approval. The route requires +`providerMaxPrice: { prompt, completion, request: 0 }`; scope and prices bind +the newly approved route-policy hash. Leaving these keys absent retains existing +selector policy, refusals, request bodies and hashes. Explicit `undefined` +properties are refused as incomplete policy, even where optional authoring types +can represent them; omit unused keys entirely. Group mode uses a +bare provider slug such as `azure`, which can include eligible variants and +regions; it does not guarantee Sweden or another endpoint's location. The +release follow-up checker refuses group mode before funding; answering and +generation policies are unchanged. + +ZDR-only routing, no-other-provider fallback, disabled input/output logging, +current evidence/expiry, token limits and durable spending caps remain in +force. Prompt and completion price ceilings are USD per million text tokens, +separate from total request cost and actual native charges. Missing request +price metadata is not proven zero by `request: 0`: the host must review eligible +endpoint metadata and non-token charges under its current verified evidence. +No metadata network port, automatic paid retry, permission or durable layout +is added. Unknown usage retains conservative accounting. + +See the [adapter contract](../packages/ai/README.md#opt-in-provider-group-checks-source-only) +for approval and qualification requirements. Normal source/release gates, +actual provider privacy and price enforcement, model quality and each host's +deployment, client and activation acceptance remain required. Structural +support does not authorize a live call. + diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ffab25a..5591bbe 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,5 +1,36 @@ # Release operations + + + + +## 0.2.12 source preparation: 2026-11-14 + +The synchronized source candidate selects `0.2.12` for all five package +versions and exact internal Support pins, including root Support development +pins and matching workspace lock importers. The root remains private at +`0.0.0`. Exact KB application/contracts `0.1.8`, `zod@4.6.7` and every other +external dependency selection are unchanged. + +This candidate adds explicit opt-in provider-group routing for learning and +engineering independent checks. The route, static allowlist and Admin approval +must agree on group scope; scope and explicit price ceilings enter the route +policy hash. Existing exact mode, request bodies and hashes remain unchanged +when the new fields are omitted. See the +[candidate notes](RELEASE_NOTES.md#0212-opt-in-provider-group-checks) and +[adapter contract](../packages/ai/README.md#opt-in-provider-group-checks-source-only). + +This is source preparation, not publication or host activation. The latest +verified public release remains `0.2.11`, recorded below. Before release, the +final source must pass the normal Node 22/24 format, types, complete runtime +tests, examples, release metadata, clean release-pack and consumer gates, +configured review and CI, then the protected signed-tag/OIDC workflow in this +guide. Unpublished candidate archives are not production dependencies. Actual +group privacy, endpoint/price eligibility, wire/model/tokenizer qualification, +native accounting, model quality and each host's deployment and activation +gates remain separate. Historical receipts, anchors and release policy below +remain unchanged. + ## Verified 0.2.11 publication: 2026-11-14 diff --git a/package.json b/package.json index 9c1f8e2..8a976d3 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,9 @@ "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-ai": "0.2.11", - "@pegma/support-desk-application": "0.2.11", - "@pegma/support-desk-templates": "0.2.11", + "@pegma/support-desk-ai": "0.2.12", + "@pegma/support-desk-application": "0.2.12", + "@pegma/support-desk-templates": "0.2.12", "@types/node": "^26.6.6", "azurite": "^3.37.0", "prettier": "^3.9.10", diff --git a/packages/ai/README.md b/packages/ai/README.md index b6a4d26..bf82a25 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -418,6 +418,61 @@ written. Expiry redaction removes request text and retains the attempt and its proof reservation. Retain these finite limits in host scheduling and funding plans. +### Opt-in provider-group checks (source only) + +The source addition permits an explicitly approved provider group for learning +and engineering independent checks. It is not part of the published `0.2.11` +contract. Structural support does not activate a host or authorize a live call. +Answering and generation routes retain their existing policies; the release +follow-up checker refuses group mode before funding. + +The host must set `providerSelectionScope: "provider_group"` in all three places: +the independent-check route, its matching static allowlist entry, and +`route.approval`. The route also requires +`providerMaxPrice: { prompt, completion, request: 0 }`. Group `endpointTag` is a +bare base-provider slug, such as `azure`, rather than a region-suffixed selector. +Leaving the new property keys absent preserves the existing selector policy, +refusals, request body and route-policy hashes; there is no inferred group or +default. A present key whose value is `undefined` is not absent: verified routes +refuse it before credentials or admission, including after schema parsing. +Optional authoring types can represent that incomplete object, but verification +still fails closed. Omit unused keys entirely; conditional spreads should add +no group keys when disabled rather than assigning `undefined`. + +Build the complete new route base and calculate +`independentCheckRoutePolicyHash(base)` before obtaining fresh Admin-approved +evidence. The scope and price object participate in that hash; +`approval.requestPolicySha256` must match it and the approval's scope must match +the route and allowlist. An old exact-route approval cannot authorize a group +route. Requalify the actual wire, model, token counter, response identity and +provider-group privacy evidence before returning ready configuration. + +OpenRouter's [base-slug matching](https://openrouter.ai/docs/guides/routing/provider-selection#base-slug-matching) +can include eligible variants and regions. Selecting `azure` therefore does +not guarantee Sweden, another particular region or a previously observed +endpoint. Approve the actual group scope rather than reusing an exact regional +attestation. The request still restricts `provider.only` to that group with +`allow_fallbacks: false`, `zdr: true`, `data_collection: "deny"` and +`require_parameters: true`. No other provider or retention-mode fallback is +enabled. Existing verified controls keep SafetyRetention, input/output logging +and use, broadcast and response caching off; current evidence, expiry and +implicit-cache approval checks still apply. + +The group's `providerMaxPrice` is serialized as `provider.max_price`. +OpenRouter's [price filter](https://openrouter.ai/docs/guides/routing/provider-selection#max-price) +uses USD per **million** text tokens for `prompt` and `completion`; +`request` is a separate per-request price ceiling. This mode requires and sends +`request: 0`; actual provider eligibility and enforcement still need live +qualification. Missing request-price metadata is not proof of zero charges. +The host must review eligible endpoint metadata and non-token charges before +admission under its current verified features, exceptions and evaluation +references; the SDK adds no metadata network port. These unit-price ceilings do +not replace `maxCostMicros`, token limits, durable reservation/spending caps or +actual native-charge accounting. +Unknown or over-limit native usage remains conservatively held, never recorded +as free or retried automatically. SDK qualification and publication, then each +host's current privacy, evaluation and activation gates, remain separate. + ### Release follow-up provider ports Published `0.2.9` adds `createSupportReleaseFollowupModel(options, diff --git a/packages/ai/package.json b/packages/ai/package.json index b6d9e5f..0581d0e 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-ai", - "version": "0.2.11", + "version": "0.2.12", "description": "Optional bounded, provider-neutral Support Desk answer coordinator.", "license": "MIT", "type": "module", @@ -42,7 +42,7 @@ "@pegma/knowledge-base-application": "0.1.8", "@pegma/knowledge-base-contracts": "0.1.8", "@pegma/spine": "0.1.2", - "@pegma/support-desk-application": "0.2.11", + "@pegma/support-desk-application": "0.2.12", "@pegma/storage-core": "0.4.0", "zod": "4.6.7" } diff --git a/packages/ai/src/openrouter/provider-selection.ts b/packages/ai/src/openrouter/provider-selection.ts new file mode 100644 index 0000000..9c9d58e --- /dev/null +++ b/packages/ai/src/openrouter/provider-selection.ts @@ -0,0 +1,98 @@ +import { z } from "zod"; + +/** Provider pricing filters, not a total-request budget. The host must verify + * eligible metadata and non-token charges; missing pricing is not zero. */ +export const providerMaxPrice = z + .object({ + /** USD per million text input tokens. */ + prompt: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER), + /** USD per million billed completion tokens, including reasoning. */ + completion: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER), + /** No per-request charge is approved. This filter is not metadata proof. */ + request: z.literal(0), + }) + .strict(); + +export type SupportProviderMaxPrice = z.infer; + +interface Selection { + readonly endpointTag: string; + readonly providerSelectionScope?: "provider_group" | undefined; + readonly providerMaxPrice?: SupportProviderMaxPrice | undefined; + readonly approval: { + readonly providerSelectionScope?: "provider_group" | undefined; + }; +} + +interface PriceBudget { + readonly maxInputTokens: number; + readonly maxOutputTokens: number; + readonly maxCostMicros: number; + readonly currency: string; +} + +function decimal(value: number): { digits: bigint; scale: number } { + const [mantissa, exponent = "0"] = value.toString().split("e"); + const [whole, fraction = ""] = mantissa!.split("."); + return { + digits: BigInt(whole! + fraction), + scale: fraction.length - Number(exponent), + }; +} + +/** Token price USD/million is numerically microUSD/token. Add exact decimal + * terms before rounding once; binary multiplication must not lower the bound. */ +function fitsPriceBudget(price: SupportProviderMaxPrice, budget: PriceBudget) { + if ( + budget.currency !== "USD" || + !Number.isSafeInteger(budget.maxInputTokens) || + budget.maxInputTokens < 1 || + !Number.isSafeInteger(budget.maxOutputTokens) || + budget.maxOutputTokens < 1 || + !Number.isSafeInteger(budget.maxCostMicros) || + budget.maxCostMicros < 0 + ) + return false; + const prompt = decimal(price.prompt); + const completion = decimal(price.completion); + const scale = Math.max(0, prompt.scale, completion.scale); + const denominator = 10n ** BigInt(scale); + const numerator = + BigInt(budget.maxInputTokens) * + prompt.digits * + 10n ** BigInt(scale - prompt.scale) + + BigInt(budget.maxOutputTokens) * + completion.digits * + 10n ** BigInt(scale - completion.scale); + const micros = (numerator + denominator - 1n) / denominator; + return micros <= BigInt(budget.maxCostMicros); +} + +/** New policy is opt-in. Absence means no own property, not a property set to + * undefined. Incomplete policy objects fail closed even when authoring types + * can describe them. Truly absent keys add no wire property and retain the + * generic transport's existing selector contract. */ +export function selectedProviderMaxPrice( + route: Selection, + budget: PriceBudget, + allowProviderGroup: boolean, +): SupportProviderMaxPrice | undefined { + const scoped = Object.hasOwn(route, "providerSelectionScope"); + const priced = Object.hasOwn(route, "providerMaxPrice"); + const approved = Object.hasOwn(route.approval, "providerSelectionScope"); + if (!scoped && !priced && !approved) return undefined; + if ( + !allowProviderGroup || + !scoped || + !priced || + !approved || + route.providerSelectionScope !== "provider_group" || + route.approval.providerSelectionScope !== "provider_group" || + !/^[a-z0-9-]+$/u.test(route.endpointTag) + ) + throw new TypeError("Provider-group policy unavailable"); + const price = providerMaxPrice.parse(route.providerMaxPrice); + if (!fitsPriceBudget(price, budget)) + throw new TypeError("Provider-group price exceeds total budget"); + return price; +} diff --git a/packages/ai/src/openrouter/support-independent-checks-model.ts b/packages/ai/src/openrouter/support-independent-checks-model.ts index c237e42..722038f 100644 --- a/packages/ai/src/openrouter/support-independent-checks-model.ts +++ b/packages/ai/src/openrouter/support-independent-checks-model.ts @@ -3,6 +3,10 @@ import { releaseFollowupContent } from "../release-followup-output.js"; import type { Clock } from "@pegma/spine"; import { z } from "zod"; import { sameApprovalRenewal } from "./approval-renewal.js"; +import { + providerMaxPrice, + selectedProviderMaxPrice, +} from "./provider-selection.js"; import { knowledgeDigest, checkedLogicalHost, @@ -102,6 +106,7 @@ const approval = evidence responseCache: z.literal(false), unreviewedFeatures: z.literal(false), implicitCache: z.enum(["absent", "approved"]), + providerSelectionScope: z.literal("provider_group").optional(), }) .strict(); const route = z @@ -109,7 +114,9 @@ const route = z host: z.string().min(1).max(253), purpose: z.literal(INDEPENDENT_CHECK_PURPOSE), endpoint: z.literal(INDEPENDENT_CHECK_ENDPOINT), - endpointTag: scalar.regex(/^[a-z0-9-]+\/[a-z0-9._/-]+$/u), + endpointTag: scalar, + providerSelectionScope: z.literal("provider_group").optional(), + providerMaxPrice: providerMaxPrice.optional(), outputTokenParameter: z.enum(["max_tokens", "max_completion_tokens"]), credentialRef: scalar, usageScopeRef: scalar, @@ -151,6 +158,8 @@ export interface IndependentCheckModelOptions { readonly provider: string; readonly endpointTag: string; readonly outputTokenParameter: "max_tokens" | "max_completion_tokens"; + /** Explicit server-admin permission for a provider family, not one region. */ + readonly providerSelectionScope?: "provider_group"; }[]; readonly counter?: IndependentCheckCounter; readonly readApiKey?: (credentialRef: string) => string | undefined; @@ -491,12 +500,17 @@ function live(at: { verifiedAt: string; validUntil: string }, now: number) { export function createSupportIndependentCheckModel( options: IndependentCheckModelOptions, logicalHost: string, - attemptPolicy?: { readonly allowApprovalRenewal: boolean }, + attemptPolicy?: { + readonly allowApprovalRenewal: boolean; + readonly allowProviderGroup?: boolean; + }, ) { const host = checkedLogicalHost(logicalHost); - // Only the SD05 wrapper opts in. Capture the policy rather than trusting a - // mutable caller object to change an already-created model's behavior. + // Capture per-instance policy before callers can mutate the supplied object. + // SD05 alone opts into approval renewal and explicitly disables groups. + // Independent checks support groups only with route/allowlist/approval opt-in. const allowApprovalRenewal = attemptPolicy?.allowApprovalRenewal === true; + const allowProviderGroup = attemptPolicy?.allowProviderGroup !== false; const sameRoute = ( current: IndependentCheckRoute, captured: IndependentCheckRoute, @@ -526,6 +540,16 @@ export function createSupportIndependentCheckModel( if (r.host !== host) return undefined; const q = qualification.parse(options.counter.qualification); const c = r.configuration; + const groupPrice = selectedProviderMaxPrice( + r, + c.budgets, + allowProviderGroup, + ); + if ( + groupPrice === undefined && + !/^[a-z0-9-]+\/[a-z0-9._/-]+$/u.test(r.endpointTag) + ) + return undefined; const now = Date.parse(options.clock.now()); if ( !Number.isFinite(now) || @@ -538,7 +562,8 @@ export function createSupportIndependentCheckModel( a.model === c.model && a.provider === c.provider && a.endpointTag === r.endpointTag && - a.outputTokenParameter === r.outputTokenParameter, + a.outputTokenParameter === r.outputTokenParameter && + a.providerSelectionScope === r.providerSelectionScope, ) || r.approval.configurationVersion !== c.version || c.dataControls.configurationBinding !== c.version || @@ -584,8 +609,9 @@ export function createSupportIndependentCheckModel( context?: IndependentCheckContext, ): boolean { try { + const currentRoute = read(configured.version); if ( - !read(configured.version) || + !currentRoute || input.trustedInstructions !== configured.trustedInstructions ) return false; @@ -605,6 +631,21 @@ export function createSupportIndependentCheckModel( context?.budgets.maxContextTokens ?? configured.budgets.maxContextTokens, ); + selectedProviderMaxPrice( + currentRoute, + { + maxInputTokens: maximumTokens, + maxOutputTokens: + context?.budgets.maxOutputTokens ?? + configured.budgets.maxOutputTokens, + maxCostMicros: Math.min( + configured.budgets.maxCostMicros, + context?.budgets.maxCostMicros ?? configured.budgets.maxCostMicros, + ), + currency: context?.budgets.currency ?? configured.budgets.currency, + }, + allowProviderGroup, + ); // Count both actual message contents. The unchanged framing allowance is // retained for the schema/envelope; no SYSTEM policy is hidden inside it. const tokens = @@ -665,6 +706,7 @@ export function createSupportIndependentCheckModel( schemaName: "support_independent_check_v1", schema: OUTPUT_SCHEMA, allowApprovalRenewal: allowApprovalRenewal && allowRenewal, + allowProviderGroup, input(input) { return JSON.stringify(input); }, @@ -683,6 +725,7 @@ export function createSupportIndependentCheckModel( const r = read(config.version); if ( !r?.releaseFollowup || + r.providerSelectionScope !== undefined || !live(r.releaseFollowup, Date.parse(options.clock.now())) || Date.parse(r.approval.validUntil) > Date.parse(r.releaseFollowup.validUntil) @@ -784,6 +827,7 @@ export function createSupportIndependentCheckModel( followupInput(input); if ( !route.releaseFollowup || + route.providerSelectionScope !== undefined || !live(route.releaseFollowup, Date.parse(options.clock.now())) || Date.parse(route.approval.validUntil) > Date.parse(route.releaseFollowup.validUntil) diff --git a/packages/ai/src/openrouter/support-openrouter-model.ts b/packages/ai/src/openrouter/support-openrouter-model.ts index 0a8c020..8f3938c 100644 --- a/packages/ai/src/openrouter/support-openrouter-model.ts +++ b/packages/ai/src/openrouter/support-openrouter-model.ts @@ -1,5 +1,10 @@ import type { Clock } from "@pegma/spine"; import { sameApprovalRenewal } from "./approval-renewal.js"; +import { + selectedProviderMaxPrice, + type SupportProviderMaxPrice, +} from "./provider-selection.js"; +export type { SupportProviderMaxPrice } from "./provider-selection.js"; export type SupportOpenRouterModelFailure = | "route_unavailable" @@ -55,10 +60,16 @@ export interface SupportOpenRouterRoute { readonly credentialRef: string; readonly usageScopeRef: string; readonly endpointTag: string; + /** Omit unused policy keys entirely; an own property set to undefined refuses. */ + readonly providerSelectionScope?: "provider_group" | undefined; + /** Required for group mode; absent, rather than undefined, in legacy mode. */ + readonly providerMaxPrice?: SupportProviderMaxPrice | undefined; readonly outputTokenParameter: "max_tokens" | "max_completion_tokens"; readonly approval: { readonly validUntil: string; readonly implicitCache: "absent" | "approved"; + /** Omit in legacy approvals; explicit undefined is not an absent key. */ + readonly providerSelectionScope?: "provider_group" | undefined; }; } export interface SupportOpenRouterModelOptions { @@ -548,6 +559,9 @@ export function createSupportOpenRouterModel< readonly schema: unknown; /** Internal purpose opt-in; all other route fields remain exactly pinned. */ readonly allowApprovalRenewal?: boolean; + /** Only a purpose controller with explicit route/allowlist/approval policy + * may enable group serialization. Omission retains the legacy wire. */ + readonly allowProviderGroup?: boolean; input(input: Input, context: Context): string; output(content: string, context: Context): string; validate( @@ -630,6 +644,16 @@ export function createSupportOpenRouterModel< protocol.validate(input, context, configuration); if (context.budgets.currency !== configuration.budgets.currency) fail("usage_invalid"); + let providerPrice: SupportProviderMaxPrice | undefined; + try { + providerPrice = selectedProviderMaxPrice( + route, + context.budgets, + protocol.allowProviderGroup === true, + ); + } catch { + fail("route_unavailable"); + } const routeBinding = canonical(route); const guard = () => { if (stopped || context.signal.aborted) fail("aborted"); @@ -692,6 +716,9 @@ export function createSupportOpenRouterModel< data_collection: "deny", zdr: true, require_parameters: true, + ...(providerPrice === undefined + ? {} + : { max_price: providerPrice }), }, }); context.signal.addEventListener("abort", onAbort, { once: true }); diff --git a/packages/ai/src/openrouter/support-release-followup-checks.ts b/packages/ai/src/openrouter/support-release-followup-checks.ts index 66b9e86..cd6b03c 100644 --- a/packages/ai/src/openrouter/support-release-followup-checks.ts +++ b/packages/ai/src/openrouter/support-release-followup-checks.ts @@ -296,6 +296,7 @@ export function createSupportReleaseFollowupChecks( const host = checkedLogicalHost(logicalHost); const model = createSupportIndependentCheckModel(options, host, { allowApprovalRenewal: true, + allowProviderGroup: false, }); const policy = options.usagePolicy === undefined diff --git a/packages/application/package.json b/packages/application/package.json index 3df7c17..9706dd2 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-application", - "version": "0.2.11", + "version": "0.2.12", "description": "Authorized application services, declared collections, and durable outbox records for Support Desk.", "license": "MIT", "type": "module", @@ -39,7 +39,7 @@ "@pegma/mail": "0.1.1", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-contracts": "0.2.11", - "@pegma/support-desk-core": "0.2.11" + "@pegma/support-desk-contracts": "0.2.12", + "@pegma/support-desk-core": "0.2.12" } } diff --git a/packages/contracts/package.json b/packages/contracts/package.json index e1d74b2..4675d17 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-contracts", - "version": "0.2.11", + "version": "0.2.12", "description": "Provider-neutral ticket and message contracts for Support Desk.", "license": "MIT", "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index f2170d1..dc03d6a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-core", - "version": "0.2.11", + "version": "0.2.12", "description": "Pure ticket creation and workflow transitions for Support Desk.", "license": "MIT", "type": "module", @@ -29,7 +29,7 @@ "directory": "packages/core" }, "dependencies": { - "@pegma/support-desk-contracts": "0.2.11" + "@pegma/support-desk-contracts": "0.2.12" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/templates/package.json b/packages/templates/package.json index 7895f29..94c3687 100644 --- a/packages/templates/package.json +++ b/packages/templates/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/support-desk-templates", - "version": "0.2.11", + "version": "0.2.12", "description": "Safe, versioned notification templates for Support Desk.", "license": "MIT", "type": "module", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0aca541..9ec85e0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,13 +39,13 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.11 + specifier: 0.2.12 version: link:packages/ai '@pegma/support-desk-application': - specifier: 0.2.11 + specifier: 0.2.12 version: link:packages/application '@pegma/support-desk-templates': - specifier: 0.2.11 + specifier: 0.2.12 version: link:packages/templates '@types/node': specifier: ^26.6.6 @@ -81,7 +81,7 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-application': - specifier: 0.2.11 + specifier: 0.2.12 version: link:../application zod: specifier: 4.6.7 @@ -105,10 +105,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-contracts': - specifier: 0.2.11 + specifier: 0.2.12 version: link:../contracts '@pegma/support-desk-core': - specifier: 0.2.11 + specifier: 0.2.12 version: link:../core packages/contracts: @@ -120,7 +120,7 @@ importers: packages/core: dependencies: '@pegma/support-desk-contracts': - specifier: 0.2.11 + specifier: 0.2.12 version: link:../contracts packages/templates: {} diff --git a/tests/openrouter-export.test.ts b/tests/openrouter-export.test.ts index 3d0a3a8..0930ea6 100644 --- a/tests/openrouter-export.test.ts +++ b/tests/openrouter-export.test.ts @@ -1,10 +1,36 @@ import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; -import { describe, expect, it } from "vitest"; +import { describe, expect, expectTypeOf, it } from "vitest"; import * as root from "@pegma/support-desk-ai"; import * as provider from "@pegma/support-desk-ai/openrouter"; +import type { + IndependentCheckModelOptions, + IndependentCheckRoute, + SupportProviderMaxPrice, +} from "@pegma/support-desk-ai/openrouter"; describe("optional public provider subpath", () => { + it("types an explicit provider-group policy through the public subpath", () => { + expectTypeOf().toEqualTypeOf<{ + prompt: number; + completion: number; + request: 0; + }>(); + expectTypeOf().toEqualTypeOf< + SupportProviderMaxPrice | undefined + >(); + expectTypeOf< + IndependentCheckRoute["providerSelectionScope"] + >().toEqualTypeOf<"provider_group" | undefined>(); + expectTypeOf< + IndependentCheckRoute["approval"]["providerSelectionScope"] + >().toEqualTypeOf<"provider_group" | undefined>(); + expectTypeOf< + NonNullable< + IndependentCheckModelOptions["allowlist"] + >[number]["providerSelectionScope"] + >().toEqualTypeOf<"provider_group" | undefined>(); + }); it("exports one optional level while keeping the AI root provider-neutral", () => { const manifest = JSON.parse( readFileSync("packages/ai/package.json", "utf8"), @@ -27,6 +53,7 @@ describe("optional public provider subpath", () => { expect(provider[name]).toBeTypeOf("function"); expect(root).not.toHaveProperty(name); } + expect(root).not.toHaveProperty("providerMaxPrice"); }); it("imports in a clean process without provider, secret, application or Store activity", () => { const child = spawnSync( diff --git a/tests/openrouter-provider-groups.test.ts b/tests/openrouter-provider-groups.test.ts new file mode 100644 index 0000000..ddd3441 --- /dev/null +++ b/tests/openrouter-provider-groups.test.ts @@ -0,0 +1,680 @@ +import { createHash } from "node:crypto"; +import { describe, expect, it, vi } from "vitest"; +import { createMemoryStore } from "@pegma/storage-core"; +import { + createSupportIndependentCheckModel, + createSupportOpenRouterModel, + createSupportReleaseFollowupChecks, + independentCheckRoutePolicyHash, + INDEPENDENT_CHECK_ENDPOINT, + INDEPENDENT_CHECK_PURPOSE, + type ReleaseFollowupIndependentCheckInput, +} from "@pegma/support-desk-ai/openrouter"; +import { + checkerModelFixture, + CHECK_PASS, +} from "../test/openrouter-fixtures.js"; +import { followupChecksFixture } from "../test/openrouter-release-followup-fixtures.js"; + +type Fixture = Awaited>; +const PRICE = { prompt: 0.05, completion: 0.1, request: 0 } as const; +const sha256 = (text: string) => + createHash("sha256").update(text).digest("hex"); + +async function approve(f: Fixture) { + const { approval, ...base } = f.route; + approval.requestPolicySha256 = await independentCheckRoutePolicyHash(base); +} + +function group(f: Fixture) { + f.route.endpointTag = "azure"; + Reflect.set(f.route, "providerSelectionScope", "provider_group"); + Reflect.set(f.route, "providerMaxPrice", { ...PRICE }); + Reflect.set(f.route.approval, "providerSelectionScope", "provider_group"); + f.options.allowlist[0]!.endpointTag = "azure"; + Reflect.set( + f.options.allowlist[0]!, + "providerSelectionScope", + "provider_group", + ); +} + +async function groupFixture() { + const f = await checkerModelFixture(); + group(f); + await approve(f); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + return { ...f, model }; +} + +function wire(f: Fixture) { + return JSON.parse(String(f.state.requests.at(-1)!.init.body)) as { + messages: { role: string; content: string }[]; + provider: Record; + [key: string]: unknown; + }; +} + +async function refusesBeforeCredentials(f: Fixture) { + const credential = vi.fn(f.options.readApiKey); + f.options.readApiKey = credential; + const admission = vi.fn(async () => {}); + const physical = vi.fn(); + expect(await f.model.resolve()).toBeNull(); + await expect( + f.model.generate( + f.input, + { + ...f.context, + beforePhysicalCall: admission, + onPhysicalCall: physical, + }, + f.c, + ), + ).rejects.toThrow(); + expect(credential).not.toHaveBeenCalled(); + expect(admission).not.toHaveBeenCalled(); + expect(physical).not.toHaveBeenCalled(); + expect(f.state.calls).toBe(0); +} + +describe("explicit independent-check provider groups", () => { + it("preserves the fixed legacy route hash, parsed keys and complete request bytes when the new fields are omitted", async () => { + const f = await checkerModelFixture(); + expect(f.route.approval.requestPolicySha256).toBe( + "a80a31ceaa5fedaf772cba38da2fa50ed4d9abaf5ffb731c1bc854cea77f9db3", + ); + expect(await f.model.resolve()).not.toBeNull(); + const parsed = f.model.currentRoute(); + expect(parsed).toEqual(f.route); + expect(Object.keys(parsed!).sort()).toEqual(Object.keys(f.route).sort()); + expect(parsed).not.toHaveProperty("providerSelectionScope"); + expect(parsed).not.toHaveProperty("providerMaxPrice"); + expect(parsed!.approval).not.toHaveProperty("providerSelectionScope"); + await f.model.generate(f.input, f.context, f.c); + expect(sha256(String(f.state.requests[0]!.init.body))).toBe( + "b82aa04aa9b048dd6fb60207cce786c64881544e6b776993ef7f5bd2766b4274", + ); + expect(wire(f).provider).toEqual({ + only: ["fictional/region"], + allow_fallbacks: false, + data_collection: "deny", + zdr: true, + require_parameters: true, + }); + }); + + it.each(["route scope", "route price", "approval scope"] as const)( + "refuses an explicitly present undefined %s before credentials or dispatch", + async (field) => { + const f = await checkerModelFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const approvedHash = f.route.approval.requestPolicySha256; + const target = field === "approval scope" ? f.route.approval : f.route; + const key = + field === "route price" ? "providerMaxPrice" : "providerSelectionScope"; + Reflect.set(target, key, undefined); + expect(Object.hasOwn(target, key)).toBe(true); + expect(f.route.approval.requestPolicySha256).toBe(approvedHash); + await refusesBeforeCredentials(f); + }, + ); + + it.each(Array.from({ length: 8 }, (_, mask) => mask))( + "requires matching route, approval and allowlist scope opt-ins (mask %i)", + async (mask) => { + const f = await checkerModelFixture(); + if (mask & 1) { + f.route.endpointTag = "azure"; + f.options.allowlist[0]!.endpointTag = "azure"; + Reflect.set(f.route, "providerSelectionScope", "provider_group"); + Reflect.set(f.route, "providerMaxPrice", { ...PRICE }); + } + if (mask & 2) + Reflect.set( + f.route.approval, + "providerSelectionScope", + "provider_group", + ); + if (mask & 4) + Reflect.set( + f.options.allowlist[0]!, + "providerSelectionScope", + "provider_group", + ); + await approve(f); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + const current = { ...f, model }; + if (mask === 0 || mask === 7) { + expect(await model.resolve()).not.toBeNull(); + expect( + model.parseVerdict( + (await model.generate(f.input, f.context, f.c)).outputJson, + ), + ).toEqual(CHECK_PASS); + expect(f.state.calls).toBe(1); + } else await refusesBeforeCredentials(current); + }, + ); + + it("sends only the group selector and explicit prices while preserving all privacy controls and the frozen SYSTEM and USER", async () => { + const legacy = await checkerModelFixture(); + expect(await legacy.model.resolve()).not.toBeNull(); + await legacy.model.generate(legacy.input, legacy.context, legacy.c); + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const result = await f.model.generate(f.input, f.context, f.c); + expect(f.model.parseVerdict(result.outputJson)).toEqual(CHECK_PASS); + expect(f.state.requests[0]!.url).toBe(INDEPENDENT_CHECK_ENDPOINT); + expect(wire(f).provider).toEqual({ + only: ["azure"], + allow_fallbacks: false, + data_collection: "deny", + zdr: true, + require_parameters: true, + max_price: { prompt: 0.05, completion: 0.1, request: 0 }, + }); + expect(wire(f)).toEqual({ ...wire(legacy), provider: wire(f).provider }); + expect(sha256(wire(f).messages[0]!.content)).toBe( + "b5e1901057196db873ca9d0245b6cdac5bb2c50ab1de6d4128904223fe4bc5c4", + ); + expect(sha256(wire(f).messages[1]!.content)).toBe( + "a8bd2c77c4d2b1a5a61739914a4271bf56e75e1ce9b8fcba423e757454bc7d47", + ); + expect(f.state.requests[0]!.init).toMatchObject({ + method: "POST", + redirect: "error", + cache: "no-store", + credentials: "omit", + headers: { + "X-OpenRouter-Cache": "false", + "Cache-Control": "no-store", + }, + }); + expect(f.state.calls).toBe(1); + }); + + it.each([ + "azure/region", + "azure/eastus", + "Azure", + "azure_*", + "azure,other", + "azure/", + "*", + "", + ])( + "refuses non-bare group selector %j even with a matching allowlist and fresh hash", + async (endpointTag) => { + const f = await groupFixture(); + f.route.endpointTag = endpointTag; + f.options.allowlist[0]!.endpointTag = endpointTag; + await approve(f); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + await refusesBeforeCredentials({ ...f, model }); + }, + ); + + it.each(["fictional/region", "azure/eastus.v2/nested", "fictional/a_-b"])( + "keeps legacy qualified selector %s valid with all group fields omitted", + async (endpointTag) => { + const f = await checkerModelFixture(); + f.route.endpointTag = endpointTag; + f.options.allowlist[0]!.endpointTag = endpointTag; + await approve(f); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + expect(await model.resolve()).not.toBeNull(); + await model.generate(f.input, f.context, f.c); + expect(wire(f).provider.only).toEqual([endpointTag]); + expect(wire(f).provider).not.toHaveProperty("max_price"); + }, + ); + + it("does not infer group scope from a bare slug on a legacy route", async () => { + const f = await checkerModelFixture(); + f.route.endpointTag = "azure"; + f.options.allowlist[0]!.endpointTag = "azure"; + await approve(f); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + await refusesBeforeCredentials({ ...f, model }); + }); + + it("binds group semantics and every price to a new reviewed route hash", async () => { + const f = await checkerModelFixture(); + group(f); + f.model = createSupportIndependentCheckModel(f.options, "pegma.dev"); + await refusesBeforeCredentials(f); + await approve(f); + const first = f.route.approval.requestPolicySha256; + expect(await f.model.resolve()).not.toBeNull(); + Reflect.set(f.route, "providerMaxPrice", { ...PRICE, completion: 0.09 }); + await refusesBeforeCredentials(f); + await approve(f); + expect(f.route.approval.requestPolicySha256).not.toBe(first); + expect(await f.model.resolve()).not.toBeNull(); + await f.model.generate(f.input, f.context, f.c); + expect(wire(f).provider.max_price).toEqual({ ...PRICE, completion: 0.09 }); + }); +}); + +describe("group text-price ceilings", () => { + it("refuses a lower live attempt cost cap before credentials when the current token envelope can cost more", async () => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const credential = vi.fn(f.options.readApiKey); + f.options.readApiKey = credential; + const admission = vi.fn(async () => {}); + const physical = vi.fn(); + // The configured envelope costs at most 900 micros; the fictional native + // response would cost only 100. Admission must bound the request first. + await expect( + f.model.generate( + f.input, + { + ...f.context, + budgets: { ...f.context.budgets, maxCostMicros: 899 }, + beforePhysicalCall: admission, + onPhysicalCall: physical, + }, + f.c, + ), + ).rejects.toThrow(); + expect(credential).not.toHaveBeenCalled(); + expect(admission).not.toHaveBeenCalled(); + expect(physical).not.toHaveBeenCalled(); + expect(f.state.calls).toBe(0); + }); + + it.each([ + { + name: "zero prices", + prompt: 0, + completion: 0, + input: 16_000, + output: 1000, + maximum: 1, + allowed: true, + }, + { + name: "USD per million, not USD per token", + prompt: 0.05, + completion: 0.1, + input: 16_000, + output: 1000, + maximum: 900, + allowed: true, + }, + { + name: "one micro below the configured worst case", + prompt: 0.05, + completion: 0.1, + input: 16_000, + output: 1000, + maximum: 899, + allowed: false, + }, + { + name: "exact integral boundary", + prompt: 0.05625, + completion: 0.1, + input: 16_000, + output: 1000, + maximum: 1000, + allowed: true, + }, + { + name: "decimal just over integral boundary", + prompt: 0.05625000000000001, + completion: 0.1, + input: 16_000, + output: 1000, + maximum: 1000, + allowed: false, + }, + { + name: "combined decimal rounding instead of rounding each leg", + prompt: 0.1, + completion: 0.1, + input: 3, + output: 7, + maximum: 1, + allowed: true, + }, + { + name: "fractional micro rounds up", + prompt: 0.00001, + completion: 0, + input: 16_000, + output: 1000, + maximum: 1, + allowed: true, + }, + { + name: "smallest positive exponent rounds up", + prompt: Number.MIN_VALUE, + completion: 0, + input: 16_000, + output: 1000, + maximum: 1, + allowed: true, + }, + { + name: "huge finite price exceeds the safe budget", + prompt: Number.MAX_VALUE, + completion: 0, + input: 16_000, + output: 1000, + maximum: Number.MAX_SAFE_INTEGER, + allowed: false, + }, + ])( + "uses an exact decimal sum for $name", + async ({ prompt, completion, input, output, maximum, allowed }) => { + const f = await groupFixture(); + Reflect.set(f.route, "providerMaxPrice", { + prompt, + completion, + request: 0, + }); + Object.assign(f.c.budgets, { + maxInputTokens: input, + maxOutputTokens: output, + maxContextTokens: input + output, + maxCostMicros: maximum, + }); + if (input <= f.c.framingTokens) { + f.c.framingTokens = 0; + Object.assign(f.counter.qualification, { framingTokens: 0 }); + } + await approve(f); + if (allowed) expect(await f.model.resolve()).not.toBeNull(); + else await refusesBeforeCredentials(f); + expect(f.state.calls).toBe(0); + }, + ); + + const malformed: { name: string; value: unknown; hashable?: boolean }[] = [ + { name: "missing cap", value: undefined }, + { name: "null cap", value: null }, + { name: "empty cap", value: {} }, + { name: "missing prompt", value: { completion: 0.1, request: 0 } }, + { name: "missing completion", value: { prompt: 0.05, request: 0 } }, + { name: "missing request fee", value: { prompt: 0.05, completion: 0.1 } }, + { name: "negative prompt", value: { ...PRICE, prompt: -0.01 } }, + { name: "negative completion", value: { ...PRICE, completion: -0.01 } }, + { name: "text prompt", value: { ...PRICE, prompt: "0.05" } }, + { name: "text completion", value: { ...PRICE, completion: "0.1" } }, + { name: "NaN prompt", value: { ...PRICE, prompt: NaN }, hashable: false }, + { + name: "infinite completion", + value: { ...PRICE, completion: Infinity }, + hashable: false, + }, + { name: "positive request fee", value: { ...PRICE, request: 0.000001 } }, + { name: "negative request fee", value: { ...PRICE, request: -1 } }, + { name: "text zero request fee", value: { ...PRICE, request: "0" } }, + { name: "extra image price", value: { ...PRICE, image: 0 } }, + { name: "extra request-fee feature", value: { ...PRICE, web_search: 0 } }, + ]; + it.each(malformed)( + "refuses $name before credentials or admission", + async ({ value, hashable }) => { + const f = await groupFixture(); + if (value === undefined) + Reflect.deleteProperty(f.route, "providerMaxPrice"); + else Reflect.set(f.route, "providerMaxPrice", value); + if (hashable !== false) await approve(f); + await refusesBeforeCredentials(f); + }, + ); + + it("does not add a price cap to a legacy route without the three group approvals", async () => { + const f = await checkerModelFixture(); + Reflect.set(f.route, "providerMaxPrice", { ...PRICE }); + await approve(f); + await refusesBeforeCredentials(f); + }); +}); + +describe("group route final dispatch fences", () => { + it.each(["scope", "approval scope", "price", "selector"] as const)( + "refuses a freshly rehashed %s mutation during final source admission before the physical callback", + async (change) => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const credential = vi.fn(f.options.readApiKey); + f.options.readApiKey = credential; + const physical = vi.fn(); + const admission = vi.fn(async () => { + await Promise.resolve(); + if (change === "scope") + Reflect.deleteProperty(f.route, "providerSelectionScope"); + if (change === "approval scope") + Reflect.deleteProperty(f.route.approval, "providerSelectionScope"); + if (change === "price") + Reflect.set(f.route, "providerMaxPrice", { ...PRICE, prompt: 0.04 }); + if (change === "selector") f.route.endpointTag = "other"; + await approve(f); + }); + await expect( + f.model.generate( + f.input, + { + ...f.context, + beforePhysicalCall: admission, + onPhysicalCall: physical, + }, + f.c, + ), + ).rejects.toThrow(); + expect(credential).toHaveBeenCalledTimes(1); + expect(admission).toHaveBeenCalledTimes(1); + expect(physical).not.toHaveBeenCalled(); + expect(f.state.calls).toBe(0); + }, + ); + + it("refuses a price mutation inside the synchronous credential callback before physical dispatch", async () => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + f.options.readApiKey = () => { + Reflect.set(f.route, "providerMaxPrice", { ...PRICE, prompt: 0.04 }); + return "fictional-provider-key"; + }; + const physical = vi.fn(); + await expect( + f.model.generate( + f.input, + { ...f.context, onPhysicalCall: physical }, + f.c, + ), + ).rejects.toThrow(); + expect(physical).not.toHaveBeenCalled(); + expect(f.state.calls).toBe(0); + }); + + it.each([undefined, false])( + "does not let the shared transport serialize a group when its purpose protocol opt-in is %s", + async (allowProviderGroup) => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const credential = vi.fn(() => "fictional-provider-key"); + const model = createSupportOpenRouterModel( + { + clock: f.options.clock, + configuration: f.model, + readApiKey: credential, + fetch: f.options.fetch, + }, + { + purpose: INDEPENDENT_CHECK_PURPOSE, + endpoint: INDEPENDENT_CHECK_ENDPOINT, + system: "Fictional raw protocol without group authorization.", + schemaName: "fictional_raw", + schema: {}, + ...(allowProviderGroup === undefined ? {} : { allowProviderGroup }), + input: (value) => JSON.stringify(value), + output: (content) => content, + validate: () => {}, + }, + ); + await expect( + model.generate(f.input, f.context, f.c), + ).rejects.toMatchObject({ code: "route_unavailable" }); + expect(credential).not.toHaveBeenCalled(); + expect(f.state.calls).toBe(0); + }, + ); +}); + +describe("group routing preserves independent response guards", () => { + it.each([ + "unknown response field", + "unknown usage field", + "reasoning text", + "reasoning details", + "reasoning tokens", + "missing native charge", + "unknown native fee", + ] as const)( + "rejects %s after exactly one physical group call", + async (change) => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + if (change === "unknown response field") + Reflect.set(f.state.document, "unreviewed", true); + if (change === "unknown usage field") + Reflect.set(f.state.document.usage, "unreviewed", 0); + if (change === "reasoning text") + Reflect.set( + f.state.document.choices[0]!.message, + "reasoning", + "Unreviewed reasoning", + ); + if (change === "reasoning details") + Reflect.set(f.state.document.choices[0]!.message, "reasoning_details", [ + { text: "Unreviewed reasoning" }, + ]); + if (change === "reasoning tokens") + f.state.document.usage.completion_tokens_details.reasoning_tokens = 1; + if (change === "missing native charge") + Reflect.deleteProperty(f.state.document.usage, "cost"); + if (change === "unknown native fee") + Reflect.set(f.state.document.usage, "cost_details", { + web_search: 0.001, + }); + const physical = vi.fn(); + await expect( + f.model.generate( + f.input, + { ...f.context, onPhysicalCall: physical }, + f.c, + ), + ).rejects.toThrow(); + expect(physical).toHaveBeenCalledTimes(1); + expect(f.state.calls).toBe(1); + }, + ); + + it("keeps the actual native charge and withholds the verdict when group usage exceeds the budget", async () => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + f.state.document.usage.cost = 0.001001; + const result = await f.model.generate(f.input, f.context, f.c); + expect(result.outputJson).toBe(""); + expect(result.usage.costMicros).toBe(1001); + expect(f.state.calls).toBe(1); + }); +}); + +describe("SD05 remains outside provider-group approval", () => { + it("refuses a group at SD05 model resolution even though the ordinary independent checker accepts it", async () => { + const f = await groupFixture(); + expect(await f.model.resolve()).not.toBeNull(); + const model = createSupportIndependentCheckModel(f.options, "pegma.dev", { + allowApprovalRenewal: true, + allowProviderGroup: false, + }); + await refusesBeforeCredentials({ ...f, model }); + }); + + it("refuses a complete direct release_followup request before credentials despite live SD05 evidence", async () => { + const f = await followupChecksFixture(createMemoryStore()); + group(f.wire); + await approve(f.wire); + const ordinary = createSupportIndependentCheckModel( + f.wire.options, + "pegma.dev", + ); + expect(await ordinary.resolve()).not.toBeNull(); + const input: ReleaseFollowupIndependentCheckInput = { + trustedInstructions: f.wire.c.trustedInstructions, + kind: "release_followup", + purpose: "support_release_followup", + facts: { + messages: ["The fictional export was empty."], + publicReleaseFacts: [ + { + ref: "release-1", + text: "The fictional deployed fix exports every row.", + }, + ], + }, + candidate: f.input.candidate, + outbound: f.input.exactBundle, + binding: f.input.binding, + targetBaseline: null, + validationRequirements: null, + }; + const credential = vi.fn(f.wire.options.readApiKey); + f.wire.options.readApiKey = credential; + const admission = vi.fn(async () => {}); + const physical = vi.fn(); + await expect( + ordinary.generate( + input, + { + ...f.wire.context, + deadline: new Date(Date.parse(f.wire.state.now) + 2000).toISOString(), + beforePhysicalCall: admission, + onPhysicalCall: physical, + }, + f.wire.c, + ), + ).rejects.toMatchObject({ code: "route_unavailable" }); + expect(credential).not.toHaveBeenCalled(); + expect(admission).not.toHaveBeenCalled(); + expect(physical).not.toHaveBeenCalled(); + expect(f.wire.state.calls).toBe(0); + }); + + it("makes SD05 policy unavailable and holds an actual check before model credentials, authority or durable admission", async () => { + const f = await followupChecksFixture(createMemoryStore()); + group(f.wire); + await approve(f.wire); + const credential = vi.fn(() => "fictional-provider-key"); + const authority = vi.fn(f.options.authority.resolve); + const application = vi.fn(f.options.application); + const options = { + ...f.options, + allowlist: f.wire.options.allowlist, + readApiKey: credential, + authority: { resolve: authority }, + application, + }; + const checks = createSupportReleaseFollowupChecks(options, "pegma.dev"); + expect( + await checks.resolvePolicy( + f.input.binding.checkPolicyVersion, + new AbortController().signal, + ), + ).toEqual({ outcome: "unavailable" }); + expect(await checks.forWork(f.f.key).check(f.input, f.context)).toEqual({ + outcome: "held", + }); + expect(credential).not.toHaveBeenCalled(); + expect(authority).not.toHaveBeenCalled(); + expect(application).not.toHaveBeenCalled(); + expect(f.wire.state.calls).toBe(0); + }); +}); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 070f600..911f33c 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -90,7 +90,7 @@ describe("release package metadata", () => { ]); }); - it("ships the synchronized 0.2.11 package set with exact internal pins", () => { + it("ships the synchronized 0.2.12 package set with exact internal pins", () => { const manifests = RELEASE_PACKAGES.map(({ directory }) => JSON.parse( readFileSync( @@ -105,24 +105,24 @@ describe("release package metadata", () => { }>; expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ - { name: "@pegma/support-desk-contracts", version: "0.2.11" }, - { name: "@pegma/support-desk-core", version: "0.2.11" }, - { name: "@pegma/support-desk-templates", version: "0.2.11" }, - { name: "@pegma/support-desk-application", version: "0.2.11" }, - { name: "@pegma/support-desk-ai", version: "0.2.11" }, + { name: "@pegma/support-desk-contracts", version: "0.2.12" }, + { name: "@pegma/support-desk-core", version: "0.2.12" }, + { name: "@pegma/support-desk-templates", version: "0.2.12" }, + { name: "@pegma/support-desk-application", version: "0.2.12" }, + { name: "@pegma/support-desk-ai", version: "0.2.12" }, ]); expect(manifests[1]?.dependencies?.["@pegma/support-desk-contracts"]).toBe( - "0.2.11", + "0.2.12", ); expect(manifests[3]?.dependencies?.["@pegma/support-desk-contracts"]).toBe( - "0.2.11", + "0.2.12", ); expect(manifests[3]?.dependencies?.["@pegma/support-desk-core"]).toBe( - "0.2.11", + "0.2.12", ); expect( manifests[4]?.dependencies?.["@pegma/support-desk-application"], - ).toBe("0.2.11"); + ).toBe("0.2.12"); expect( manifests[4]?.dependencies?.["@pegma/support-desk-contracts"], ).toBeUndefined(); @@ -245,7 +245,7 @@ packages: "@pegma/support-desk-contracts" ], ).toEqual({ - specifier: "0.2.11", + specifier: "0.2.12", version: "link:../contracts", }); expect( diff --git a/tests/release-verification.test.ts b/tests/release-verification.test.ts index 05cc534..88e0590 100644 --- a/tests/release-verification.test.ts +++ b/tests/release-verification.test.ts @@ -1230,7 +1230,7 @@ describe("source-bound original release artifact", () => { }); it("reads real gzip/tar artifacts and accepts the independently pinned exact five-package candidate", async () => { - expect(releaseVerificationVersion).toBe("0.2.11"); + expect(releaseVerificationVersion).toBe("0.2.12"); const f = fixture(); expect( f.manifest.packages.map(({ name, version }) => ({ name, version })),