diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e770659e2..1060c1067 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,6 +40,7 @@ jobs:
- run: npm run verify:doc-snippets -- typescript --negative-test
- run: npm run check:machine-credentials
- run: npm run check:coverage
+ - run: node --test scripts/sync-business-account-modes.test.mjs scripts/check-business-account-modes.test.mjs
- run: node scripts/check-native-coverage.mjs
- run: npm run check:functions
- run: npm run check:names
diff --git a/README.md b/README.md
index 028ccbdef..41d64d3e5 100644
--- a/README.md
+++ b/README.md
@@ -1092,3 +1092,19 @@ or Number authority. Writes require the exact `expectedRevision`, `prefer`, and
MIT
Treat every Polymorfa credential as an opaque string. Never parse it or assume a fixed length. Credential storage must support at least 512 characters, preferably unrestricted text. Client-token length varies with its bindings and Customer scope.
+
+## Business account-mode supplement
+
+All six SDKs expose the Test-number account-mode operation, the corresponding
+QuickLink testing fields and optional business contact encryption values. See
+the package READMEs for the native calls. The separately produced
+`contracts/business-account-modes.json` binds API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4`; it does not replace the API baseline
+or other supplements. `contracts/native-business-account-modes.json` attributes
+the native fixtures. Check receipts and package consumers remain separate gates.
+This source is not a package release or proof that the API is deployed.
+
+The existing documentation snippet catalog must be rebound to the actual combined
+SDK source after these public changes. It retains its baseline recipes. The new
+account-mode operation has no catalog recipe until the consuming API reference
+can bind this separate supplement; it keeps the documented cURL fallback.
diff --git a/contracts/business-account-modes.json b/contracts/business-account-modes.json
new file mode 100644
index 000000000..3e0c58dd5
--- /dev/null
+++ b/contracts/business-account-modes.json
@@ -0,0 +1,1263 @@
+{
+ "repository": "polymorfa/polymorfa",
+ "commit": "14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4",
+ "releaseStatus": "source-only",
+ "sources": {
+ "messaging": {
+ "sourcePath": "apps/api/docs/openapi.json",
+ "sourceSha256": "44a2cc304483d7cd4e12974b8f31df92a3b7880d21152aa70af0a50948b40cb1",
+ "paths": {
+ "/messaging/{session}/contacts/{contactId}/business-profile": {
+ "get": {
+ "operationId": "getBusinessProfile",
+ "tags": ["Contacts"],
+ "summary": "Get a WhatsApp business profile",
+ "security": [{ "BearerAuth": [] }],
+ "x-required-scope": "contacts:read",
+ "parameters": [
+ {
+ "schema": { "type": "string" },
+ "required": true,
+ "name": "session",
+ "in": "path"
+ },
+ {
+ "schema": { "type": "string", "pattern": "^[1-9][0-9]{0,18}$" },
+ "required": true,
+ "name": "contactId",
+ "in": "path"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Business profile",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetBusinessProfileResponse"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request — request body or params failed validation",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "invalid_parameter",
+ "message": "Correct the invalid request field.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#invalid-parameter"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid authentication token",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "authentication_error",
+ "code": "invalid_credential",
+ "message": "Supply a valid credential.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#invalid-credential"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "403": {
+ "description": "Authenticated but not permitted (missing scope or rule violation)",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "permission_error",
+ "code": "permission_denied",
+ "message": "The credential does not have access to this resource.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#permission-denied"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "404": {
+ "description": "Resource not found",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "resource_not_found",
+ "message": "The resource is unavailable to this caller.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#resource-not-found"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "api_error",
+ "code": "internal_error",
+ "message": "An unexpected service failure occurred. Keep the request ID for support.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#internal-error"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ }
+ },
+ "x-mint": {
+ "content": "Linked Device API contacts:read"
+ },
+ "x-protocols": ["Linked Device API"],
+ "description": "**Protocols:** Linked Device API\n\n**Required scope:** `contacts:read`"
+ }
+ },
+ "/messaging/quicklinks": {
+ "post": {
+ "operationId": "createQuickLink",
+ "tags": ["QuickLink"],
+ "summary": "Create a QuickLink",
+ "description": "**Required scope:** `quicklink:manage`\n\nCreates a persistent hosted link that connects one WhatsApp number to a new session in the project.",
+ "security": [{ "BearerAuth": [] }],
+ "x-required-scope": "quicklink:manage",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateQuickLinkRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "201": {
+ "description": "QuickLink created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/QuickLinkResponse"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request — request body or params failed validation",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "invalid_parameter",
+ "message": "Correct the invalid request field.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#invalid-parameter"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid authentication token",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "authentication_error",
+ "code": "invalid_credential",
+ "message": "Supply a valid credential.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#invalid-credential"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "403": {
+ "description": "Authenticated but not permitted (missing scope or rule violation)",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "permission_error",
+ "code": "permission_denied",
+ "message": "The credential does not have access to this resource.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#permission-denied"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "404": {
+ "description": "Resource not found",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "resource_not_found",
+ "message": "The resource is unavailable to this caller.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#resource-not-found"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "api_error",
+ "code": "internal_error",
+ "message": "An unexpected service failure occurred. Keep the request ID for support.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#internal-error"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ }
+ },
+ "x-mint": {
+ "content": "quicklink:manage"
+ }
+ }
+ },
+ "/messaging/{session}/phone/account-mode": {
+ "put": {
+ "operationId": "setTestingAccountMode",
+ "tags": ["Testing"],
+ "security": [{ "BearerAuth": [] }],
+ "summary": "Change a Test number's account type or phone platform",
+ "description": "**Protocols:** Linked Device API\n\n**Required scope:** `sandbox:write`\n\nChanges how the Test number presents itself. A change unlinks every companion, including the Number's own session, so each must pair again. Repeating the current mode changes nothing.",
+ "x-required-scope": "sandbox:write",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "description": "The Test number's session ID."
+ },
+ "required": true,
+ "name": "session",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TestingAccountModeRequest"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The account mode is set",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TestingAccountMode"
+ }
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid mode, or the phone is offline",
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "invalid_parameter",
+ "message": "Correct the invalid request field.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#invalid-parameter"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Test numbers access required, or a client token was used",
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "permission_error",
+ "code": "permission_denied",
+ "message": "The credential does not have access to this resource.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#permission-denied"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Resource not found",
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "resource_not_found",
+ "message": "The resource is unavailable to this caller.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#resource-not-found"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The Test number is claimed in Inspector, or another mode change is pending. Unclaim it or retry.",
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "conflict_error",
+ "code": "state_conflict",
+ "message": "The request conflicts with the resource state.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#state-conflict"
+ }
+ }
+ }
+ },
+ "502": {
+ "description": "The phone could not change mode. Retry later.",
+ "headers": {
+ "X-RateLimit-Limit": {
+ "$ref": "#/components/headers/X-RateLimit-Limit"
+ },
+ "X-RateLimit-Remaining": {
+ "$ref": "#/components/headers/X-RateLimit-Remaining"
+ },
+ "X-RateLimit-Reset": {
+ "$ref": "#/components/headers/X-RateLimit-Reset"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PublicError" },
+ "example": {
+ "error": {
+ "type": "upstream_error",
+ "code": "upstream_failure",
+ "message": "The messaging provider could not complete the request.",
+ "param": null,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
+ },
+ "data": null,
+ "docs": "https://docs.polymorfa.com/api/errors#upstream-failure"
+ }
+ }
+ }
+ }
+ },
+ "x-mint": {
+ "content": "Linked Device API sandbox:write"
+ },
+ "x-protocols": ["Linked Device API"]
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "GetBusinessProfileResponse": {
+ "type": "object",
+ "properties": {
+ "success": { "type": "boolean", "enum": [true] },
+ "data": { "$ref": "#/components/schemas/BusinessProfile" }
+ },
+ "required": ["success", "data"]
+ },
+ "BusinessProfile": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[1-9][0-9]{0,18}$",
+ "description": "Opaque Polymorfa resource ID. Keep this value as a string.",
+ "example": "739182640518203"
+ },
+ "phoneNumber": { "type": "string" },
+ "bsuid": { "type": "string" },
+ "username": { "type": "string" },
+ "address": { "type": "string" },
+ "email": { "type": "string" },
+ "description": { "type": "string" },
+ "websites": {
+ "type": "array",
+ "items": { "type": "string", "format": "uri" }
+ },
+ "coverPhotoId": { "type": "string" },
+ "categories": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": { "type": "string" },
+ "name": { "type": "string" }
+ },
+ "required": ["id", "name"]
+ }
+ },
+ "options": {
+ "type": "object",
+ "additionalProperties": { "type": "string" }
+ },
+ "hoursTimeZone": { "type": "string" },
+ "hours": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "dayOfWeek": { "type": "string" },
+ "mode": { "type": "string" },
+ "openTime": { "type": "string" },
+ "closeTime": { "type": "string" }
+ },
+ "required": ["dayOfWeek", "mode", "openTime", "closeTime"]
+ }
+ },
+ "encryption": {
+ "type": "string",
+ "enum": ["end_to_end", "hybrid", "not_end_to_end"],
+ "description": "How messages with this business are encrypted, as WhatsApp reports it. Omitted when the connection does not report it.",
+ "x-enumDescriptions": {
+ "end_to_end": "Messages are end-to-end encrypted.",
+ "hybrid": "Some of the business's messaging uses a service that is not end-to-end encrypted, such as a hosting provider.",
+ "not_end_to_end": "Messages with this business are not end-to-end encrypted."
+ }
+ }
+ },
+ "required": [
+ "id",
+ "address",
+ "email",
+ "description",
+ "websites",
+ "coverPhotoId",
+ "categories",
+ "options",
+ "hoursTimeZone",
+ "hours"
+ ]
+ },
+ "PublicError": {
+ "type": "object",
+ "properties": {
+ "error": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "invalid_request_error",
+ "authentication_error",
+ "permission_error",
+ "billing_error",
+ "conflict_error",
+ "rate_limit_error",
+ "api_error",
+ "upstream_error"
+ ]
+ },
+ "code": {
+ "type": "string",
+ "enum": [
+ "zero_knowledge_session",
+ "invalid_parameter",
+ "invalid_credential",
+ "entitlement_required",
+ "cloud_template_authority_restricted",
+ "gate_limit_reached",
+ "billing_credit_required",
+ "addon_required",
+ "safe_mode_not_entitled",
+ "warmup_plan_not_entitled",
+ "method_not_allowed",
+ "permission_denied",
+ "missing_scope",
+ "resource_not_found",
+ "hms_not_enabled",
+ "media_fetch_failed",
+ "resource_gone",
+ "feature_unavailable",
+ "stream_cursor_invalid",
+ "stream_cursor_expired",
+ "stream_connection_limit_reached",
+ "state_conflict",
+ "team_deletion_scheduled",
+ "hybrid_routing_paused",
+ "hybrid_choice_required",
+ "hybrid_transition_ineligible",
+ "hybrid_automation_unavailable",
+ "hybrid_group_linked_devices_unavailable",
+ "hybrid_transport_unavailable",
+ "hybrid_target_reference_unavailable",
+ "send_outcome_unknown",
+ "terms_acceptance_required",
+ "terms_activation_blocked",
+ "idempotency_conflict",
+ "idempotency_in_progress",
+ "idempotency_outcome_unknown",
+ "idempotency_replay_unavailable",
+ "call_claimed",
+ "call_not_ringing",
+ "connection_limit",
+ "unsupported_for_connection",
+ "call_permission_required",
+ "invalid_sip_trunk",
+ "calls_disabled",
+ "call_recipient_opted_out",
+ "call_destination_blocked",
+ "call_permission_request_limited",
+ "call_permission_granted",
+ "order_status_transition_invalid",
+ "order_cancellation_failed",
+ "call_opt_out_limit",
+ "number_restricted",
+ "sip_trunk_in_use",
+ "sip_trunk_revision_conflict",
+ "sip_trunk_limit",
+ "sip_unavailable",
+ "voice_not_enabled",
+ "provider_credential_invalid",
+ "provider_unavailable",
+ "asset_not_ready",
+ "voice_asset_in_use",
+ "voice_asset_revision_conflict",
+ "voice_unavailable",
+ "rate_limit_exceeded",
+ "internal_error",
+ "operation_not_supported",
+ "upstream_failure",
+ "service_unavailable",
+ "credential_verification_unavailable",
+ "session_not_ready",
+ "command_dispatch_failed",
+ "result_unknown",
+ "parent_bsuid_not_supported",
+ "recipient_not_on_whatsapp",
+ "conversation_window_closed",
+ "template_not_approved",
+ "media_too_large",
+ "whatsapp_rate_limited",
+ "new_chat_limit_reached",
+ "marketing_disabled_on_cloud_api",
+ "whatsapp_account_restricted",
+ "whatsapp_authorization_required",
+ "whatsapp_payment_method_required",
+ "whatsapp_number_not_registered",
+ "whatsapp_groups_ineligible",
+ "whatsapp_group_creation_paused",
+ "whatsapp_group_limit_reached",
+ "whatsapp_group_full",
+ "whatsapp_group_suspended",
+ "whatsapp_group_has_no_participants",
+ "bansafe_suspended",
+ "bansafe_org_suspended",
+ "bansafe_cold_blocked",
+ "bansafe_cold_held",
+ "bansafe_throttled",
+ "bansafe_daily_allowance_reached",
+ "bansafe_accounting_unavailable",
+ "bansafe_send_outcome_unknown",
+ "campaigns_not_entitled",
+ "campaign_throughput_capped",
+ "campaign_approval_required",
+ "campaign_approval_stale",
+ "campaign_variables_missing"
+ ]
+ },
+ "message": { "type": "string" },
+ "param": { "type": "string", "nullable": true },
+ "request_id": {
+ "type": "string",
+ "description": "Matches the X-Request-Id response header. Include it when you contact support."
+ },
+ "request_log_url": {
+ "type": "string",
+ "format": "uri",
+ "description": "Console page that shows this request. Returned only to organization and project credentials whose request was logged."
+ }
+ },
+ "required": ["type", "code", "message", "param", "request_id"]
+ },
+ "data": {
+ "type": "string",
+ "nullable": true,
+ "enum": [null],
+ "description": "Always null for a failed request."
+ },
+ "docs": { "type": "string", "format": "uri" }
+ },
+ "required": ["error", "data", "docs"]
+ },
+ "CreateQuickLinkRequest": {
+ "type": "object",
+ "properties": {
+ "signalMode": {
+ "type": "string",
+ "enum": ["standard", "zero_knowledge"],
+ "description": "Signal key custody for a new Number. Inherits Customer then Project default; cannot change an existing Number. Customer-owned custody requires beta admission and real Linked Devices."
+ },
+ "purpose": {
+ "type": "string",
+ "enum": ["initial", "add_connection"],
+ "description": "Initial setup, or add a transport to an existing session without replacing the Number."
+ },
+ "connectionGoal": {
+ "type": "string",
+ "enum": ["single", "hybrid"]
+ },
+ "session": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Existing session name. Required only for add_connection."
+ },
+ "addConnection": {
+ "type": "string",
+ "enum": ["linked_devices", "official_api"]
+ },
+ "projectId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Project that receives the connected number. Required for team keys with more than one project."
+ },
+ "customerId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Customer that owns the connected number when Customers is enabled for the project."
+ },
+ "billingControls": {
+ "type": "object",
+ "properties": {
+ "limitCredits": {
+ "type": "number",
+ "nullable": true,
+ "minimum": 0,
+ "maximum": 1000000
+ },
+ "priority": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 1000000
+ }
+ },
+ "required": ["limitCredits", "priority"],
+ "additionalProperties": false,
+ "description": "Initial monthly spending limit and funding priority for a real Number. Requires a team key with billing:manage or a live team owner/admin on Pay-As-You-Go. Applied atomically before pairing admission."
+ },
+ "externalId": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[^\\x00-\\x1f\\x7f]+$",
+ "description": "Integrator correlation copied to the resulting session. May repeat across invitations; does not grant access."
+ },
+ "configuration": {
+ "$ref": "#/components/schemas/QuickLinkConfiguration"
+ }
+ },
+ "additionalProperties": false
+ },
+ "QuickLinkConfiguration": {
+ "type": "object",
+ "properties": {
+ "testing": {
+ "type": "object",
+ "properties": {
+ "country": { "type": "string" },
+ "configuration": {
+ "type": "object",
+ "properties": {
+ "profile": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ },
+ "status": { "type": "string", "maxLength": 139 }
+ },
+ "additionalProperties": false
+ },
+ "accountType": {
+ "type": "string",
+ "enum": [
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence"
+ ],
+ "description": "How the account uses WhatsApp.",
+ "x-enumDescriptions": {
+ "whatsapp_app": "WhatsApp app, connected as a linked device.",
+ "business_app": "WhatsApp Business app, connected as a linked device.",
+ "meta_cloud": "Meta Cloud API.",
+ "meta_coexistence": "Meta Cloud API, with the WhatsApp Business app still active on the phone."
+ }
+ },
+ "primaryPlatform": {
+ "type": "string",
+ "enum": ["android", "ios"],
+ "description": "Primary phone platform the Test number emulates. Defaults to `android`. Not accepted when `accountType` is `meta_cloud`.",
+ "x-enumDescriptions": {
+ "android": "An Android phone.",
+ "ios": "An iPhone."
+ }
+ },
+ "replyBehavior": {
+ "type": "string",
+ "enum": ["off", "echo"]
+ },
+ "failureScenario": {
+ "type": "string",
+ "enum": ["none", "reject-send"]
+ },
+ "historyFixtureId": { "type": "string", "format": "uuid" }
+ },
+ "additionalProperties": false
+ },
+ "editable": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": [
+ "profile.name",
+ "profile.status",
+ "accountType",
+ "primaryPlatform",
+ "replyBehavior",
+ "failureScenario",
+ "historyFixtureId"
+ ]
+ },
+ "maxItems": 3
+ }
+ },
+ "additionalProperties": false
+ },
+ "prefillPhone": {
+ "type": "string",
+ "pattern": "^\\+?\\d{6,15}$"
+ },
+ "connectionPreference": {
+ "type": "string",
+ "enum": ["cloud", "linked", "both"]
+ },
+ "connectionEnforcement": {
+ "type": "string",
+ "enum": ["prefer", "force"]
+ },
+ "methods": {
+ "type": "array",
+ "items": { "type": "string", "enum": ["qr", "pairing"] },
+ "minItems": 1,
+ "maxItems": 2,
+ "description": "Linked Devices methods offered for this connection."
+ },
+ "defaultMethod": {
+ "type": "string",
+ "nullable": true,
+ "enum": ["qr", "pairing", null],
+ "description": "Linked Devices method opened first. Omit to inherit the saved project setting, or set null to choose by recipient device."
+ },
+ "allowPhoneChange": { "type": "boolean" },
+ "historySync": {
+ "type": "object",
+ "properties": {
+ "mode": {
+ "type": "string",
+ "enum": ["metadata_only", "deliver"]
+ },
+ "requestFull": { "type": "boolean" },
+ "delivery": {
+ "type": "string",
+ "enum": ["descriptor"],
+ "description": "Polymorfa-Version 2026-10-14 and later. `descriptor` keeps history chunks with the recipient for local processing. Omit to inherit saved defaults. Recipient history consent remains required."
+ },
+ "consent": {
+ "type": "string",
+ "enum": ["ask", "force_on", "force_off"]
+ }
+ },
+ "additionalProperties": false
+ },
+ "hms": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "enabled": { "type": "boolean", "enum": [false] }
+ },
+ "required": ["enabled"],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "enabled": { "type": "boolean", "enum": [true] },
+ "region": {
+ "type": "string",
+ "pattern": "^[a-z0-9][a-z0-9-]{0,31}$"
+ },
+ "policy": {
+ "type": "string",
+ "enum": [
+ "short",
+ "standard",
+ "extended",
+ "compliance",
+ "enterprise_archive"
+ ]
+ },
+ "retentionDays": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 2555
+ },
+ "policyVersion": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ },
+ "legalHold": { "type": "boolean" }
+ },
+ "required": ["enabled", "region", "policy"],
+ "additionalProperties": false
+ }
+ ]
+ },
+ "observation": {
+ "type": "object",
+ "properties": {
+ "presenceMode": {
+ "type": "string",
+ "enum": ["off", "events", "cache"]
+ },
+ "typingMode": {
+ "type": "string",
+ "enum": ["off", "events", "cache"]
+ },
+ "labelMode": {
+ "type": "string",
+ "enum": ["off", "events", "cache", "project"]
+ },
+ "quickReplyMode": {
+ "type": "string",
+ "enum": ["off", "events", "cache"]
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "additionalProperties": false,
+ "description": "Connection, pairing, phone, and history overrides. Omitted fields inherit saved defaults. Presentation, legal links, and callbacks belong to saved project settings."
+ },
+ "QuickLinkResponse": {
+ "type": "object",
+ "properties": {
+ "success": { "type": "boolean", "enum": [true] },
+ "data": { "$ref": "#/components/schemas/QuickLink" }
+ },
+ "required": ["success", "data"]
+ },
+ "QuickLink": {
+ "type": "object",
+ "properties": {
+ "purpose": {
+ "type": "string",
+ "enum": ["initial", "add_connection", "reauthorization"]
+ },
+ "connectionGoal": {
+ "type": "string",
+ "enum": ["single", "hybrid"]
+ },
+ "addConnection": {
+ "type": "string",
+ "enum": ["linked_devices", "official_api"]
+ },
+ "id": {
+ "type": "string",
+ "description": "Stable QuickLink identifier, prefixed `ql_`."
+ },
+ "url": {
+ "type": "string",
+ "description": "Hosted connection URL. Share it only with the person holding the phone."
+ },
+ "session": {
+ "type": "string",
+ "description": "Session name that receives the connected number."
+ },
+ "expiresAt": {
+ "type": "string",
+ "nullable": true,
+ "description": "Null for new persistent QuickLinks. Legacy links retain their ISO-8601 expiry."
+ }
+ },
+ "required": [
+ "purpose",
+ "connectionGoal",
+ "id",
+ "url",
+ "session",
+ "expiresAt"
+ ]
+ },
+ "TestingAccountModeRequest": {
+ "type": "object",
+ "properties": {
+ "accountType": {
+ "type": "string",
+ "enum": [
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence"
+ ],
+ "description": "How the account uses WhatsApp.",
+ "x-enumDescriptions": {
+ "whatsapp_app": "WhatsApp app, connected as a linked device.",
+ "business_app": "WhatsApp Business app, connected as a linked device.",
+ "meta_cloud": "Meta Cloud API.",
+ "meta_coexistence": "Meta Cloud API, with the WhatsApp Business app still active on the phone."
+ }
+ },
+ "primaryPlatform": {
+ "type": "string",
+ "enum": ["android", "ios"],
+ "description": "Primary phone platform the Test number emulates. Defaults to `android`. Not accepted when `accountType` is `meta_cloud`.",
+ "x-enumDescriptions": {
+ "android": "An Android phone.",
+ "ios": "An iPhone."
+ }
+ }
+ },
+ "required": ["accountType"],
+ "additionalProperties": false
+ },
+ "TestingAccountMode": {
+ "type": "object",
+ "properties": {
+ "session": { "type": "string" },
+ "accountType": {
+ "type": "string",
+ "enum": [
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence"
+ ],
+ "description": "How the account uses WhatsApp.",
+ "x-enumDescriptions": {
+ "whatsapp_app": "WhatsApp app, connected as a linked device.",
+ "business_app": "WhatsApp Business app, connected as a linked device.",
+ "meta_cloud": "Meta Cloud API.",
+ "meta_coexistence": "Meta Cloud API, with the WhatsApp Business app still active on the phone."
+ }
+ },
+ "primaryPlatform": {
+ "type": "string",
+ "nullable": true,
+ "enum": ["android", "ios", null],
+ "description": "Null for `meta_cloud`, which has no phone.",
+ "x-enumDescriptions": {
+ "android": "An Android phone.",
+ "ios": "An iPhone."
+ }
+ },
+ "changed": {
+ "type": "boolean",
+ "description": "False when the Test number already used this mode. Nothing was unlinked."
+ },
+ "unlinkedDevices": {
+ "type": "array",
+ "items": { "type": "integer" },
+ "description": "Companions the phone unlinked. Each must pair again, including Polymorfa's own session."
+ }
+ },
+ "required": [
+ "session",
+ "accountType",
+ "primaryPlatform",
+ "changed",
+ "unlinkedDevices"
+ ]
+ }
+ },
+ "headers": {
+ "X-RateLimit-Limit": {
+ "description": "Team request quota per rolling minute, when the per-team request limiter applies.",
+ "schema": { "type": "integer", "minimum": 1 }
+ },
+ "X-RateLimit-Remaining": {
+ "description": "Requests left in the per-team quota; zero when this limiter rejects the request.",
+ "schema": { "type": "integer", "minimum": 0 }
+ },
+ "X-RateLimit-Reset": {
+ "description": "Unix timestamp in seconds when the oldest counted request leaves the rolling window, when the per-team request limiter applies. Follow Retry-After on a rejected request.",
+ "schema": { "type": "integer", "minimum": 0 }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/contracts/coverage.json b/contracts/coverage.json
index bcbb5ad2a..0d35816a4 100644
--- a/contracts/coverage.json
+++ b/contracts/coverage.json
@@ -21877,6 +21877,11 @@
"baselineUnchanged": true,
"published": false
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "typescript",
diff --git a/contracts/doc-snippets.json b/contracts/doc-snippets.json
index eb1532571..339b0f913 100644
--- a/contracts/doc-snippets.json
+++ b/contracts/doc-snippets.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
- "sourceCommit": "641230d38744d862cbf66ae3af56fbfb203e1e73",
- "sourceFilesSha256": "2c9b8c527fdebf3ca68ffb320c2ac118778502c74571365cd116c53427b475f8",
+ "sourceCommit": "44add8e5f4a10124df5b60bd6862f4e721305b88",
+ "sourceFilesSha256": "0d42a268524fe6374ac2d0ab29300676cc44321256e3c634f7b006caafbb77e2",
"apiVersion": "2026-09-22",
"apiSourceCommit": "f180dc1ee2bd45dbecf01702f73bdd75c664634b",
"specs": {
diff --git a/contracts/native-business-account-modes.json b/contracts/native-business-account-modes.json
new file mode 100644
index 000000000..9644db944
--- /dev/null
+++ b/contracts/native-business-account-modes.json
@@ -0,0 +1,92 @@
+{
+ "schemaVersion": 1,
+ "sourceCommit": "14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4",
+ "pin": "contracts/business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "claim": "Source and native fixture attribution. Executed checks, package qualification and release acceptance are separate evidence.",
+ "operations": [
+ {
+ "operationId": "setTestingAccountMode",
+ "method": "PUT",
+ "path": "/messaging/{session}/phone/account-mode",
+ "languages": {
+ "typescript": {
+ "method": "MessagingClient.testing.setAccountMode",
+ "test": "test/business-account-modes.test.ts"
+ },
+ "go": {
+ "method": "MessagingClient.Testing.SetAccountMode",
+ "test": "business_account_modes_test.go"
+ },
+ "python": {
+ "method": "AsyncMessagingClient.testing.set_account_mode",
+ "test": "tests/test_business_account_modes.py"
+ },
+ "php": {
+ "method": "MessagingClient.testing.setAccountMode",
+ "test": "tests/business_account_modes.php"
+ },
+ "rust": {
+ "method": "MessagingClient.testing.set_account_mode",
+ "test": "tests/business_account_modes.rs"
+ },
+ "dotnet": {
+ "method": "MessagingClient.Testing.SetAccountModeAsync",
+ "test": "tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs"
+ }
+ }
+ }
+ ],
+ "fields": {
+ "quickLinkTesting": {
+ "operationId": "createQuickLink",
+ "fields": ["accountType", "primaryPlatform"],
+ "languages": {
+ "typescript": {
+ "test": "test/business-account-modes.test.ts"
+ },
+ "go": {
+ "test": "business_account_modes_test.go"
+ },
+ "python": {
+ "test": "tests/test_business_account_modes.py"
+ },
+ "php": {
+ "test": "tests/business_account_modes.php"
+ },
+ "rust": {
+ "test": "tests/configuration.rs"
+ },
+ "dotnet": {
+ "test": "tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs"
+ }
+ }
+ },
+ "businessProfileEncryption": {
+ "operationId": "getBusinessProfile",
+ "enum": ["end_to_end", "hybrid", "not_end_to_end"],
+ "optional": true,
+ "languages": {
+ "typescript": {
+ "test": "test/business-account-modes.test.ts"
+ },
+ "go": {
+ "test": "business_account_modes_test.go"
+ },
+ "python": {
+ "test": "tests/test_business_account_modes.py"
+ },
+ "php": {
+ "test": "tests/business_account_modes.php"
+ },
+ "rust": {
+ "test": "tests/business_account_modes.rs"
+ },
+ "dotnet": {
+ "test": "tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs"
+ }
+ }
+ }
+ }
+}
diff --git a/examples/full-platform/app/api/messaging/onboarding/route.ts b/examples/full-platform/app/api/messaging/onboarding/route.ts
index c0a5f18c2..9318caf12 100644
--- a/examples/full-platform/app/api/messaging/onboarding/route.ts
+++ b/examples/full-platform/app/api/messaging/onboarding/route.ts
@@ -53,7 +53,7 @@ export const POST = route("admin", async ({ body }) => {
country: "US",
configuration: {
profile: { name: "Acme Test" },
- accountType: "business",
+ accountType: "business_app",
replyBehavior: "echo",
},
editable: ["profile.name", "replyBehavior"],
diff --git a/internal/agent-sessions/business-consumer-20261105.md b/internal/agent-sessions/business-consumer-20261105.md
new file mode 100644
index 000000000..e31fcdbb8
--- /dev/null
+++ b/internal/agent-sessions/business-consumer-20261105.md
@@ -0,0 +1,35 @@
+# Business SDK consumer source, 2026-11-05
+
+The existing Business source owner implements the human-authorized SDK counterpart in this branch. Newsletter SDK366 and CLI92 retain their separate ownership and contract supplements. No replacement agent or writer was used.
+
+The owner is Codex, gpt-6.1-sol, high reasoning effort, hosted by T3 Code through the Codex harness. The user requested Standard service; the service tier is not exposed. The branch is `rajeh/business-account-modes-sdk`. The retained thread is `thread:delegated-task:command%3Amcp%3A521d1645-1500-4d68-8d3c-2c884e9fde54%3Adelegate-task%3Awa-business-emulation-owner-1`. Historical Claude-authored source and the original dependency-audit repair attribution remain preserved in history. This checkpoint records visible source and check evidence; it contains no hidden reasoning, credentials or customer material.
+
+## Source and behavior
+
+The separately pinned Business contract is produced from polymorfa#895 commit `f391fb49bbffddb45459525091fe8851182fc298`. It adds the Test account-mode PUT operation, four account types, primary-platform constraints and optional business-profile encryption values in TypeScript, Go, Python, PHP, Rust and .NET. Existing baseline API documents and other supplements retain their pins. Each native client enforces the server-credential boundary, validates requests before transport, handles the bare response and preserves omitted encryption. QuickLink configuration uses the same account-mode rules and preserves unrelated simulation settings.
+
+The root dependency-audit repair comes from the existing owner commit `07bb625640f8d84fdd995f4c5887b5b890f642c1`; it is retained with attribution, rather than replacing SDK366. Python's lock is genuinely resolved against the current declared manifest. The Rust lock's unused local-core patch entry is genuine package-producer output.
+
+## Verification before source commit
+
+- TypeScript: typecheck, lint, build, formatting and native Business fixtures passed. The full Node22 suite passed 2223 tests with 113 explicitly optional environment skips; two added session constraints and the physical npm archive consumer also passed. No optional skip is claimed as runtime acceptance.
+- Go: canonical native verifier passed formatting, vet, race tests, build and framework host. Additional mode/QuickLink fixtures and an independent exact-source archive consumer passed all four native HTTP mode requests.
+- Python: canonical verifier passed Ruff, mypy, 1732 tests and wheel/sdist build, with 30 optional environment skips. An independent installed wheel consumer passed all four native mode requests.
+- Rust: canonical verifier passed formatting, Clippy, native tests, example/WASM checks, doctests and genuine crate packaging. An independent installed archive consumer used the SDK/core crates and passed all four native mode requests. Four existing ignored documentation examples remain reported as ignored.
+- .NET: canonical verifier passed formatting, warnings-as-errors builds, native tests, framework examples and NuGet packaging. A separate physical NuGet consumer resolved the package from a fresh local feed and passed all four native HTTP requests.
+- PHP: the cached Docker runtime is PHP8.4.26 and Composer2.10.3, with json, openssl, curl and zlib present. It uses current source and both original Composer lockfiles with fresh vendor closures. A physical archive consumer passed all four native mode requests and Composer audit returned no advisories. Canonical Composer validation, frozen-lock installs, lint, PHPStan, full native tests, archive build and actual Laravel/Symfony host checks passed with exit0; the exact snapshot, locks, argv and logs are retained under the Business task directory. An observed 40ms pre-header deadline fixture race was repaired without changing SDK timeouts or relaxing the admission, single-attempt and one-second completion assertions. JSON now also asserts the elapsed bound. PHP8.2 compatibility is not inferred from PHP8.4.
+- Shared Business producer unit tests, contract/native coverage and production dependency audit passed. The documentation catalog must bind this real source commit and pass its genuine six-language producer/checker workflow before publication of the complete branch.
+
+## Impact and remaining release gates
+
+This is a public SDK surface. CLI97 has its own current Business implementation and package proof; it is not acceptance of this SDK package. Customer guides and the backend/API release record remain in the owning Business family. Admin control authority, Temporal workflows, retention, ZK custody and browser pairing tunnel authorization are unchanged by this client transport code. QuickLink changes are typed client inputs only; the server remains responsible for live membership, enrollment, Test capability and custody checks.
+
+No registry package, API contract release, deployment, actual database or provider action is performed. Backend/native/Inspector acceptance and the complete-family hosted checks and clean code/security reviews remain separate gates. The accepted migration source reservations preserve Business0455 and Bartender023; installed-history attestation remains with the human/Release. This checkpoint supplies no migration application or legal approval.
+
+## Documentation export checkpoint
+
+The catalog binds actual source commit `32ec05155cd999afe5c544454bd47495aff386a4`. The API baseline, package versions and other supplements stay unchanged. The 31 existing explicit recipes per language remain 186 programs; the new Business operation has no baseline-matched recipe and therefore retains cURL fallback in consumers. Business native coverage and examples are recorded separately.
+
+Genuine generation, byte drift checks and ten catalog tests passed. Each exported language uses its native checker against an actual package artifact and rejects the deliberately nonexistent public method. PHP's checker uses a private exact-source clone, the task's fresh Linux dependency closure and Git2.47.3 installed only inside the disposable Docker container. No old Docs vendor or filtered warning result is used. Rust packaging leaves target selection to ordinary Cargo through the active MrBoxington shim and copies only produced distribution archives into the private checker directory.
+
+The complete source family remains unmerged. Hosted build/lint/type/test/security, code/security reviews, conflict checks, matching API availability and package release acceptance remain required. No local result is a staging or production acceptance receipt.
diff --git a/packages/dotnet/README.md b/packages/dotnet/README.md
index 16eb34717..7261f3f91 100644
--- a/packages/dotnet/README.md
+++ b/packages/dotnet/README.md
@@ -1188,3 +1188,30 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```csharp
+var result = await client.Testing.SetAccountModeAsync("demo", new(
+ WhatsAppAccountType.BusinessApp, TestingPrimaryPlatform.Ios));
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/dotnet/coverage.json b/packages/dotnet/coverage.json
index 52e856f5a..eb3516849 100644
--- a/packages/dotnet/coverage.json
+++ b/packages/dotnet/coverage.json
@@ -5246,6 +5246,12 @@
"published": false,
"language": "dotnet"
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "language": "dotnet"
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "dotnet",
diff --git a/packages/dotnet/src/Polymorfa.Sdk/BusinessAccountModes.cs b/packages/dotnet/src/Polymorfa.Sdk/BusinessAccountModes.cs
new file mode 100644
index 000000000..47f90f0ce
--- /dev/null
+++ b/packages/dotnet/src/Polymorfa.Sdk/BusinessAccountModes.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+namespace Polymorfa.Sdk;
+
+[JsonConverter(typeof(WhatsAppAccountTypeConverter))]
+public enum WhatsAppAccountType { WhatsappApp, BusinessApp, MetaCloud, MetaCoexistence }
+internal sealed class WhatsAppAccountTypeConverter() : KnownStringEnumConverter(new Dictionary { [WhatsAppAccountType.WhatsappApp] = "whatsapp_app", [WhatsAppAccountType.BusinessApp] = "business_app", [WhatsAppAccountType.MetaCloud] = "meta_cloud", [WhatsAppAccountType.MetaCoexistence] = "meta_coexistence" });
+[JsonConverter(typeof(TestingPrimaryPlatformConverter))]
+public enum TestingPrimaryPlatform { Android, Ios }
+internal sealed class TestingPrimaryPlatformConverter() : KnownStringEnumConverter(new Dictionary { [TestingPrimaryPlatform.Android] = "android", [TestingPrimaryPlatform.Ios] = "ios" });
+[JsonConverter(typeof(ContactEncryptionConverter))]
+public enum ContactEncryption { EndToEnd, Hybrid, NotEndToEnd }
+internal sealed class ContactEncryptionConverter() : KnownStringEnumConverter(new Dictionary { [ContactEncryption.EndToEnd] = "end_to_end", [ContactEncryption.Hybrid] = "hybrid", [ContactEncryption.NotEndToEnd] = "not_end_to_end" });
+public sealed record TestingAccountModeRequest(WhatsAppAccountType AccountType, TestingPrimaryPlatform? PrimaryPlatform = null);
+public sealed record TestingAccountMode(string Session, WhatsAppAccountType AccountType, TestingPrimaryPlatform? PrimaryPlatform, bool Changed, IReadOnlyList UnlinkedDevices);
+internal static class BusinessAccountModeValidation
+{
+ internal static void Fields(WhatsAppAccountType? account, TestingPrimaryPlatform? platform)
+ {
+ if (account is { } a && !Enum.IsDefined(a) || platform is { } p && !Enum.IsDefined(p) || account == WhatsAppAccountType.MetaCloud && platform is not null)
+ throw new PolymorfaValidationException("Invalid Test account mode or primaryPlatform.", "invalid_parameter");
+ }
+}
diff --git a/packages/dotnet/src/Polymorfa.Sdk/MessagingClient.cs b/packages/dotnet/src/Polymorfa.Sdk/MessagingClient.cs
index 333b4d6f1..b7eb8109f 100644
--- a/packages/dotnet/src/Polymorfa.Sdk/MessagingClient.cs
+++ b/packages/dotnet/src/Polymorfa.Sdk/MessagingClient.cs
@@ -91,6 +91,7 @@ public sealed class QuickLinks
public Task>> CreateAsync(CreateQuickLinkRequest? body = null, RequestOptions? options = null)
{
http.Credential.RequireServer(); body ??= new();
+ if (body.Configuration?.Testing?.Configuration is { } testing) BusinessAccountModeValidation.Fields(testing.AccountType, testing.PrimaryPlatform);
if (body.Purpose == "add_connection" && string.IsNullOrWhiteSpace(body.Session)) throw new PolymorfaValidationException("An add_connection link requires session.", "invalid_parameter");
if (body.BillingControls is { } billing && (billing.Priority < 0 || billing.Priority > 1_000_000 || billing.LimitCredits < 0 || billing.LimitCredits > 1_000_000 || billing.LimitCredits is decimal limit && decimal.Round(limit, 6) != limit || body.Purpose == "add_connection" || body.Configuration?.Testing is not null)) throw new PolymorfaValidationException("Invalid billingControls.", "invalid_parameter");
var captured = ConfigurationContract.QuickLink(body, out var intent);
diff --git a/packages/dotnet/src/Polymorfa.Sdk/MessagingModels.cs b/packages/dotnet/src/Polymorfa.Sdk/MessagingModels.cs
index c64fc6576..5ab1a3699 100644
--- a/packages/dotnet/src/Polymorfa.Sdk/MessagingModels.cs
+++ b/packages/dotnet/src/Polymorfa.Sdk/MessagingModels.cs
@@ -11,7 +11,7 @@ public sealed record ContactUserInfo(string Id, string Status, string PictureId,
public sealed record ContactPicture(string Url);
public sealed record BusinessProfileCategory(string Id, string Name);
public sealed record BusinessProfileHours(string DayOfWeek, string Mode, string OpenTime, string CloseTime);
-public sealed record BusinessProfile(string Id, string Address, string Email, string Description, IReadOnlyList Websites, string CoverPhotoId, IReadOnlyList Categories, IReadOnlyDictionary Options, string HoursTimeZone, IReadOnlyList Hours, string? Bsuid = null, string? PhoneNumber = null, string? Username = null);
+public sealed record BusinessProfile(string Id, string Address, string Email, string Description, IReadOnlyList Websites, string CoverPhotoId, IReadOnlyList Categories, IReadOnlyDictionary Options, string HoursTimeZone, IReadOnlyList Hours, string? Bsuid = null, string? PhoneNumber = null, string? Username = null, ContactEncryption? Encryption = null);
public sealed record ProfileData(string Name, string Status, string? ProfilePicUrl = null, string? PhonePlatform = null, string? AccountType = null);
public sealed record SetProfileNameRequest(string Name);
public sealed record SetProfileStatusRequest(string Status);
diff --git a/packages/dotnet/src/Polymorfa.Sdk/Models.cs b/packages/dotnet/src/Polymorfa.Sdk/Models.cs
index 81d36bf61..79998ed07 100644
--- a/packages/dotnet/src/Polymorfa.Sdk/Models.cs
+++ b/packages/dotnet/src/Polymorfa.Sdk/Models.cs
@@ -50,7 +50,7 @@ public sealed record MessageOperationReceipt([property: JsonPropertyName("whatsa
public sealed record CreateQuickLinkRequest(string? Purpose = null, string? Session = null, string? ProjectId = null, string? CustomerId = null, string? ExternalId = null, string? ConnectionGoal = null, string? AddConnection = null, QuickLinkConfiguration? Configuration = null, BillingControls? BillingControls = null, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] PatchValue SignalMode = default);
public sealed record BillingControls([property: JsonIgnore(Condition = JsonIgnoreCondition.Never)] decimal? LimitCredits, int Priority);
public sealed record TestingProfile(string? Name = null, string? Status = null);
-public sealed record TestingConfiguration(TestingProfile? Profile = null, string? AccountType = null, string? ReplyBehavior = null, string? FailureScenario = null, string? HistoryFixtureId = null);
+public sealed record TestingConfiguration(TestingProfile? Profile = null, WhatsAppAccountType? AccountType = null, string? ReplyBehavior = null, string? FailureScenario = null, string? HistoryFixtureId = null, TestingPrimaryPlatform? PrimaryPlatform = null);
public sealed record QuickLinkTesting(string? Country = null, TestingConfiguration? Configuration = null, IReadOnlyList? Editable = null);
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record QuickLinkConfiguration(string? ConnectionPreference = null, string? ConnectionEnforcement = null, IReadOnlyList? Methods = null, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] PatchValue DefaultMethod = default, string? PrefillPhone = null, bool? AllowPhoneChange = null, QuickLinkHistorySync? HistorySync = null, ObservationOverride? Observation = null, HmsConfiguration? Hms = null, QuickLinkTesting? Testing = null);
diff --git a/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs b/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs
index 936a74f09..b73201844 100644
--- a/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs
+++ b/packages/dotnet/src/Polymorfa.Sdk/Onboarding.cs
@@ -24,6 +24,14 @@ public sealed record UnlinkTestingPhoneDeviceResponse(string Session, int Device
public sealed class Testing : Resource
{
internal Testing(HttpTransport http) : base(http) { }
+ public Task> SetAccountModeAsync(string session, TestingAccountModeRequest input, RequestOptions? options = null)
+ {
+ Http.Credential.RequireServer();
+ CampaignContractValidation.Unicode(session);
+ if (session is null || session.Length is < 1 or > 256) throw new PolymorfaValidationException("Invalid session.", "invalid_parameter");
+ BusinessAccountModeValidation.Fields(input.AccountType, input.PrimaryPlatform);
+ return ExistingContractCodec.Request(Http, HttpMethod.Put, "/messaging/" + E(session) + "/phone/account-mode", ExistingContractCodec.Capture(input), options);
+ }
private static string Path(string projectId) => "/messaging/projects/" + E(projectId);
private static string PhonePath(string session) => "/messaging/" + E(session) + "/phone";
private Task> Request(HttpMethod method, string path, object? body, RequestOptions? options) { Http.Credential.RequireServer(); return Http.RequestAsync(method, path, body, options); }
diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs
new file mode 100644
index 000000000..8a4b4d855
--- /dev/null
+++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/BusinessAccountModeTests.cs
@@ -0,0 +1,31 @@
+using Polymorfa.Sdk;
+internal static class BusinessAccountModeTests
+{
+ public static async Task RunAsync()
+ {
+ foreach (var (mode, wire) in new[] { (WhatsAppAccountType.WhatsappApp,"whatsapp_app"), (WhatsAppAccountType.BusinessApp,"business_app"), (WhatsAppAccountType.MetaCloud,"meta_cloud"), (WhatsAppAccountType.MetaCoexistence,"meta_coexistence") })
+ await ResourceTests.Messaging("PUT", "/messaging/demo%20%2Fa/phone/account-mode", "{\"accountType\":\"" + wire + "\"}", "{\"session\":\"demo /a\",\"accountType\":\"" + wire + "\",\"primaryPlatform\":null,\"changed\":true,\"unlinkedDevices\":[2,7]}", async c => { var value = (await c.Testing.SetAccountModeAsync("demo /a", new(mode))).Data; ResourceTests.Equal(value.AccountType,mode); ResourceTests.True(value.Changed); ResourceTests.Equal(value.UnlinkedDevices.Count,2); });
+ await ResourceTests.Messaging("PUT", "/messaging/demo/phone/account-mode", """{"accountType":"business_app","primaryPlatform":"ios"}""", """{"session":"demo","accountType":"business_app","primaryPlatform":"ios","changed":false,"unlinkedDevices":[]}""", async c => { var value = (await c.Testing.SetAccountModeAsync("demo",new(WhatsAppAccountType.BusinessApp,TestingPrimaryPlatform.Ios))).Data; ResourceTests.True(!value.Changed); ResourceTests.Equal(value.PrimaryPlatform,TestingPrimaryPlatform.Ios); });
+ using var server = new MessagingClient(Credential.TeamApiKey("pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k"));
+ foreach (var invalid in new[] { new TestingAccountModeRequest(WhatsAppAccountType.MetaCloud,TestingPrimaryPlatform.Android), new TestingAccountModeRequest((WhatsAppAccountType)99), new TestingAccountModeRequest(WhatsAppAccountType.BusinessApp,(TestingPrimaryPlatform)99) })
+ try { await server.Testing.SetAccountModeAsync("demo",invalid); throw new Exception("Invalid mode accepted"); } catch (PolymorfaValidationException) { }
+ using var client = new MessagingClient(Credential.ClientToken("pmfa_ct_Zml4dHVyZQ"));
+ try { await client.Testing.SetAccountModeAsync("demo",new(WhatsAppAccountType.BusinessApp)); throw new Exception("Client token accepted"); } catch (PolymorfaConfigurationException) { }
+ foreach (var malformed in new[] { "{}", """{"session":"demo","accountType":"business","primaryPlatform":null,"changed":false,"unlinkedDevices":[]}""", """{"session":"demo","accountType":"business_app","changed":false,"unlinkedDevices":[]}""" })
+ await ResourceTests.Messaging("PUT", "/messaging/demo/phone/account-mode", """{"accountType":"business_app"}""",malformed,async c => { try { await c.Testing.SetAccountModeAsync("demo",new(WhatsAppAccountType.BusinessApp)); throw new Exception("Malformed mode accepted"); } catch (PolymorfaServerException) { } });
+ foreach (var (encryption,wire) in new (ContactEncryption?,string?)[] { (ContactEncryption.EndToEnd,"end_to_end"), (ContactEncryption.Hybrid,"hybrid"), (ContactEncryption.NotEndToEnd,"not_end_to_end"),(null,null) })
+ await ResourceTests.Messaging("GET","/messaging/demo/contacts/123/business-profile",null,"{\"success\":true,\"data\":{\"id\":\"123\",\"address\":\"\",\"email\":\"\",\"description\":\"\",\"websites\":[],\"coverPhotoId\":\"\",\"categories\":[],\"options\":{},\"hoursTimeZone\":\"\",\"hours\":[]" + (wire is null ? "" : ",\"encryption\":\"" + wire + "\"") + "}}",async c => ResourceTests.Equal((await c.Contacts.BusinessProfileAsync("demo","123")).Data.Data.Encryption,encryption));
+ var quickLink = new CreateQuickLinkRequest(Configuration: new QuickLinkConfiguration(
+ Testing: new QuickLinkTesting(Configuration: new TestingConfiguration(
+ AccountType: WhatsAppAccountType.BusinessApp,
+ PrimaryPlatform: TestingPrimaryPlatform.Ios,
+ ReplyBehavior: "echo"))));
+ await ResourceTests.Messaging("POST", "/messaging/quicklinks", """{"configuration":{"testing":{"configuration":{"accountType":"business_app","primaryPlatform":"ios","replyBehavior":"echo"}}}}""", """{"success":true,"data":{"id":"ql","url":"https://example.test/ql","session":"demo","expiresAt":null}}""", async c => { await c.QuickLinks.CreateAsync(quickLink); });
+ var invalidQuickLink = new CreateQuickLinkRequest(Configuration: new QuickLinkConfiguration(
+ Testing: new QuickLinkTesting(Configuration: new TestingConfiguration(
+ AccountType: WhatsAppAccountType.MetaCloud,
+ PrimaryPlatform: TestingPrimaryPlatform.Ios))));
+ try { await server.QuickLinks.CreateAsync(invalidQuickLink); throw new Exception("Cloud QuickLink accepted a phone platform"); } catch (PolymorfaValidationException) { }
+ Console.WriteLine("PASS Business account modes: four modes, iOS, pre-I/O refusal, server credentials, malformed replies and encryption omission");
+ }
+}
diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs
index 46945a0f4..3af50855a 100644
--- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs
+++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/Program.cs
@@ -3,6 +3,7 @@
using System.Text.Json;
using Polymorfa.Sdk;
+if (args.Contains("--business-account-modes-only")) { await BusinessAccountModeTests.RunAsync(); return; }
if (args.Contains("--session-call-history-only")) { await ProjectPairingTests.SessionCallHistoryAsync(); return; }
if (args.Contains("--cloud-order-quantity-only")) { await CloudOrderQuantityTests.RunAsync(); return; }
@@ -167,6 +168,7 @@
await OfficialGroupTests.RunAsync();
await TemplateTests.RunAsync();
await OnboardingTests.RunAsync();
+ await BusinessAccountModeTests.RunAsync();
await AudienceSettingsTests.RunAsync();
await CampaignTests.RunAsync();
await CampaignExistingTests.RunAsync();
diff --git a/packages/go/README.md b/packages/go/README.md
index 2bc663f3c..294668c7f 100644
--- a/packages/go/README.md
+++ b/packages/go/README.md
@@ -999,3 +999,32 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```go
+result, err := client.Testing().SetAccountMode(ctx, "demo", polymorfa.TestingAccountModeRequest{
+ AccountType: polymorfa.BusinessApp,
+ PrimaryPlatform: polymorfa.TestingIOS,
+})
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/go/business_account_modes.go b/packages/go/business_account_modes.go
new file mode 100644
index 000000000..5048aa67e
--- /dev/null
+++ b/packages/go/business_account_modes.go
@@ -0,0 +1,81 @@
+package polymorfa
+
+import "context"
+
+type WhatsAppAccountType string
+
+const (
+ WhatsAppApp WhatsAppAccountType = "whatsapp_app"
+ BusinessApp WhatsAppAccountType = "business_app"
+ MetaCloud WhatsAppAccountType = "meta_cloud"
+ MetaCoexistence WhatsAppAccountType = "meta_coexistence"
+)
+
+type TestingPrimaryPlatform string
+
+const (
+ TestingAndroid TestingPrimaryPlatform = "android"
+ TestingIOS TestingPrimaryPlatform = "ios"
+)
+
+type ContactEncryption string
+
+const (
+ ContactEndToEnd ContactEncryption = "end_to_end"
+ ContactHybrid ContactEncryption = "hybrid"
+ ContactNotEndToEnd ContactEncryption = "not_end_to_end"
+)
+
+type TestingAccountModeRequest struct {
+ AccountType WhatsAppAccountType `json:"accountType"`
+ PrimaryPlatform TestingPrimaryPlatform `json:"primaryPlatform,omitempty"`
+}
+type TestingAccountMode struct {
+ Session string `json:"session"`
+ AccountType WhatsAppAccountType `json:"accountType"`
+ PrimaryPlatform *TestingPrimaryPlatform `json:"primaryPlatform"`
+ Changed bool `json:"changed"`
+ UnlinkedDevices []int `json:"unlinkedDevices"`
+}
+
+func validateTestingMode(account WhatsAppAccountType, platform TestingPrimaryPlatform, required bool) error {
+ if account == "" && !required {
+ account = WhatsAppApp
+ }
+ if err := contractOne(string(account), "accountType", "whatsapp_app", "business_app", "meta_cloud", "meta_coexistence"); err != nil {
+ return err
+ }
+ if platform != "" {
+ if account == MetaCloud {
+ return configuration("primaryPlatform", "Official API mode does not accept a phone platform.")
+ }
+ if err := contractOne(string(platform), "primaryPlatform", "android", "ios"); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// SetAccountMode changes a Test number's mode and unlinks its companions on a change.
+func (r *Testing) SetAccountMode(ctx context.Context, session string, input TestingAccountModeRequest, o ...RequestOptions) (Response[TestingAccountMode], error) {
+ if err := serverOnly(r.t); err != nil {
+ return Response[TestingAccountMode]{}, err
+ }
+ if err := contractText(session, "session", 1, 256); err != nil {
+ return Response[TestingAccountMode]{}, err
+ }
+ if err := validateTestingMode(input.AccountType, input.PrimaryPlatform, true); err != nil {
+ return Response[TestingAccountMode]{}, err
+ }
+ response, err := endpointBare[TestingAccountMode](ctx, r.t, "PUT", "/messaging/"+escaped(session)+"/phone/account-mode", nil, input, options(o), 200)
+ if err != nil {
+ return response, err
+ }
+ if contractOne(string(response.Data.AccountType), "accountType", "whatsapp_app", "business_app", "meta_cloud", "meta_coexistence") != nil {
+ return response, campaignResponseError(response.Metadata)
+ }
+ if p := response.Data.PrimaryPlatform; p != nil && contractOne(string(*p), "primaryPlatform", "android", "ios") != nil {
+ return response, campaignResponseError(response.Metadata)
+ }
+ return response, nil
+}
diff --git a/packages/go/business_account_modes_test.go b/packages/go/business_account_modes_test.go
new file mode 100644
index 000000000..9ce598886
--- /dev/null
+++ b/packages/go/business_account_modes_test.go
@@ -0,0 +1,172 @@
+package polymorfa
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestBusinessAccountModesWire(t *testing.T) {
+ for _, account := range []WhatsAppAccountType{WhatsAppApp, BusinessApp, MetaCloud, MetaCoexistence} {
+ t.Run(string(account), func(t *testing.T) {
+ calls := 0
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if r.Method != "PUT" || r.URL.EscapedPath() != "/messaging/demo%20%2Fa/phone/account-mode" {
+ t.Errorf("wrong request: %s %s", r.Method, r.URL.EscapedPath())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ return
+ }
+ if body["accountType"] != string(account) || len(body) != 1 {
+ t.Errorf("body: %#v", body)
+ }
+ if r.Header.Get("Polymorfa-Version") != APIVersion {
+ t.Error("wrong API version")
+ }
+ var platform any = "android"
+ if account == MetaCloud {
+ platform = nil
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"session": "demo /a", "accountType": account, "primaryPlatform": platform, "changed": true, "unlinkedDevices": []int{3, 7}})
+ }))
+ defer s.Close()
+ result, err := mustMessaging(t, s.URL).Testing().SetAccountMode(context.Background(), "demo /a", TestingAccountModeRequest{AccountType: account})
+ if err != nil {
+ t.Errorf("decode request: %v", err)
+ return
+ }
+ if result.Data.AccountType != account || !result.Data.Changed || len(result.Data.UnlinkedDevices) != 2 || calls != 1 {
+ t.Fatalf("result: %#v calls=%d", result, calls)
+ }
+ if (result.Data.PrimaryPlatform == nil) != (account == MetaCloud) {
+ t.Fatal("nullable platform changed")
+ }
+ })
+ }
+}
+
+func TestBusinessAccountModesRejectBeforeTransport(t *testing.T) {
+ calls := 0
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(500) }))
+ defer s.Close()
+ m := mustMessaging(t, s.URL)
+ for _, input := range []TestingAccountModeRequest{{}, {AccountType: "personal"}, {AccountType: "business"}, {AccountType: MetaCloud, PrimaryPlatform: TestingIOS}, {AccountType: BusinessApp, PrimaryPlatform: "web"}} {
+ if _, err := m.Testing().SetAccountMode(context.Background(), "demo", input); err == nil {
+ t.Errorf("accepted %#v", input)
+ }
+ }
+ config := teamConfig(s.URL)
+ config.Credential = Credential{ClientToken, "pmfa_ct_eA"}
+ client, err := NewMessagingClient(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = client.Testing().SetAccountMode(context.Background(), "demo", TestingAccountModeRequest{AccountType: BusinessApp}); err == nil {
+ t.Fatal("client token accepted")
+ }
+ if calls != 0 {
+ t.Fatalf("unexpected transport: %d", calls)
+ }
+}
+
+func TestBusinessAccountModesRequireCompleteResults(t *testing.T) {
+ for _, reply := range []string{
+ `{"session":"demo","accountType":"business_app","primaryPlatform":"ios","changed":"false","unlinkedDevices":[]}`,
+ `{"session":"demo","accountType":"business_app","primaryPlatform":"ios","unlinkedDevices":[]}`,
+ `{"session":"demo","accountType":"personal","primaryPlatform":"ios","changed":false,"unlinkedDevices":[]}`,
+ } {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(reply))
+ }))
+ _, err := mustMessaging(t, s.URL).Testing().SetAccountMode(context.Background(), "demo", TestingAccountModeRequest{AccountType: BusinessApp})
+ s.Close()
+ if err == nil {
+ t.Fatalf("accepted malformed result %s", reply)
+ }
+ }
+}
+
+func TestBusinessContactEncryptionOmission(t *testing.T) {
+ for _, encryption := range []string{"", "end_to_end", "hybrid", "not_end_to_end"} {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ profile := map[string]any{"id": "contact"}
+ if encryption != "" {
+ profile["encryption"] = encryption
+ }
+ json.NewEncoder(w).Encode(map[string]any{"success": true, "data": profile})
+ }))
+ result, err := mustMessaging(t, s.URL).Contacts().BusinessProfile(context.Background(), "demo", "contact")
+ s.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if encryption == "" {
+ if result.Data.Data.Encryption != nil {
+ t.Fatal("invented encryption")
+ }
+ } else if result.Data.Data.Encryption == nil || string(*result.Data.Data.Encryption) != encryption {
+ t.Fatal("encryption lost")
+ }
+ }
+}
+
+func TestBusinessQuickLinkModeAndPlatform(t *testing.T) {
+ calls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if r.Method != "POST" || r.URL.Path != "/messaging/quicklinks" {
+ t.Errorf("wrong route %s %s", r.Method, r.URL.Path)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ return
+ }
+ configuration := body["configuration"].(map[string]any)["testing"].(map[string]any)["configuration"].(map[string]any)
+ if configuration["accountType"] != "business_app" || configuration["primaryPlatform"] != "ios" || configuration["replyBehavior"] != "echo" {
+ t.Errorf("lost configuration: %#v", configuration)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"success":true,"data":{"id":"ql","url":"https://example.test/ql","session":"demo","expiresAt":null}}`))
+ }))
+ defer server.Close()
+ client := mustMessaging(t, server.URL)
+ input := CreateQuickLinkRequest{Configuration: &QuickLinkConfiguration{Testing: &QuickLinkTesting{Configuration: &TestingConfiguration{AccountType: BusinessApp, PrimaryPlatform: TestingIOS, ReplyBehavior: "echo"}}}}
+ if _, err := client.QuickLinks().Create(context.Background(), input); err != nil {
+ t.Fatal(err)
+ }
+ input.Configuration.Testing.Configuration.AccountType = MetaCloud
+ if _, err := client.QuickLinks().Create(context.Background(), input); err == nil {
+ t.Fatal("cloud accepted a primary phone platform")
+ }
+ input.Configuration.Testing.Configuration.AccountType = "business"
+ if _, err := client.QuickLinks().Create(context.Background(), input); err == nil {
+ t.Fatal("legacy account type accepted")
+ }
+ if calls != 1 {
+ t.Fatalf("invalid mode reached transport: %d", calls)
+ }
+}
+
+func TestBusinessAccountModesSurfaceConflict(t *testing.T) {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(409)
+ w.Write([]byte(`{"error":{"type":"conflict_error","code":"state_conflict","message":"The request conflicts with the resource state.","param":null,"request_id":"5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"},"data":null}`))
+ }))
+ defer s.Close()
+ _, err := mustMessaging(t, s.URL).Testing().SetAccountMode(context.Background(), "demo", TestingAccountModeRequest{AccountType: BusinessApp})
+ var apiErr *Error
+ if !errors.As(err, &apiErr) || apiErr.Kind != ConflictError || apiErr.Status != 409 || apiErr.Code != "state_conflict" {
+ t.Fatalf("conflict was not typed: %#v", err)
+ }
+}
diff --git a/packages/go/contacts.go b/packages/go/contacts.go
index 89cdde3f5..c51f913c0 100644
--- a/packages/go/contacts.go
+++ b/packages/go/contacts.go
@@ -45,6 +45,7 @@ type BusinessProfileHours struct {
CloseTime string `json:"closeTime"`
}
type BusinessProfile struct {
+ Encryption *ContactEncryption `json:"encryption,omitempty"`
ConversationReference
Address string `json:"address"`
Email string `json:"email"`
diff --git a/packages/go/coverage.json b/packages/go/coverage.json
index 7f18c0c45..ef12829c5 100644
--- a/packages/go/coverage.json
+++ b/packages/go/coverage.json
@@ -5246,6 +5246,12 @@
"published": false,
"language": "go"
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "language": "go"
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "go",
diff --git a/packages/go/messaging.go b/packages/go/messaging.go
index 55f3229a5..049ae5df2 100644
--- a/packages/go/messaging.go
+++ b/packages/go/messaging.go
@@ -231,6 +231,12 @@ func (r *QuickLinks) Create(ctx context.Context, b CreateQuickLinkRequest, o ...
if err := serverOnly(r.t); err != nil {
return Response[Envelope[QuickLink]]{}, err
}
+ if b.Configuration != nil && b.Configuration.Testing != nil && b.Configuration.Testing.Configuration != nil {
+ v := b.Configuration.Testing.Configuration
+ if err := validateTestingMode(v.AccountType, v.PrimaryPlatform, false); err != nil {
+ return Response[Envelope[QuickLink]]{}, err
+ }
+ }
intent, err := quickLinkIntent(b)
if err != nil {
return Response[Envelope[QuickLink]]{}, err
diff --git a/packages/go/testing.go b/packages/go/testing.go
index a71690692..4bbaa109e 100644
--- a/packages/go/testing.go
+++ b/packages/go/testing.go
@@ -10,10 +10,11 @@ type TestingConfiguration struct {
Name string `json:"name,omitempty"`
Status string `json:"status,omitempty"`
} `json:"profile,omitempty"`
- AccountType string `json:"accountType,omitempty"`
- ReplyBehavior string `json:"replyBehavior,omitempty"`
- FailureScenario string `json:"failureScenario,omitempty"`
- HistoryFixtureID string `json:"historyFixtureId,omitempty"`
+ AccountType WhatsAppAccountType `json:"accountType,omitempty"`
+ PrimaryPlatform TestingPrimaryPlatform `json:"primaryPlatform,omitempty"`
+ ReplyBehavior string `json:"replyBehavior,omitempty"`
+ FailureScenario string `json:"failureScenario,omitempty"`
+ HistoryFixtureID string `json:"historyFixtureId,omitempty"`
}
type TestingHistoryMessage struct {
ID string `json:"id"`
diff --git a/packages/php/README.md b/packages/php/README.md
index 4a31f7cad..c7381fbef 100644
--- a/packages/php/README.md
+++ b/packages/php/README.md
@@ -1134,3 +1134,32 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```php
+$result = $client->testing->setAccountMode('demo', [
+ 'accountType' => 'business_app',
+ 'primaryPlatform' => 'ios',
+]);
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/php/coverage.json b/packages/php/coverage.json
index 8040d515a..ae4abbed7 100644
--- a/packages/php/coverage.json
+++ b/packages/php/coverage.json
@@ -5383,6 +5383,12 @@
"published": false,
"language": "php"
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "language": "php"
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "php",
diff --git a/packages/php/src/BusinessAccountMode.php b/packages/php/src/BusinessAccountMode.php
new file mode 100644
index 000000000..6948d7552
--- /dev/null
+++ b/packages/php/src/BusinessAccountMode.php
@@ -0,0 +1,22 @@
+ $value */
+ public static function fields(array $value, bool $required = false): void
+ {
+ $account = array_key_exists('accountType', $value) ? $value['accountType'] : ($required ? null : 'whatsapp_app');
+ CampaignContractValidation::enum($account, ['whatsapp_app', 'business_app', 'meta_cloud', 'meta_coexistence'], 'accountType');
+ if (array_key_exists('primaryPlatform', $value)) {
+ CampaignContractValidation::enum($value['primaryPlatform'], ['android', 'ios'], 'primaryPlatform');
+ if ($account === 'meta_cloud') {
+ CampaignContractValidation::invalid('primaryPlatform');
+ }
+ }
+ }
+}
diff --git a/packages/php/src/ExistingContractCodec.php b/packages/php/src/ExistingContractCodec.php
index 4e1509228..f88b17574 100644
--- a/packages/php/src/ExistingContractCodec.php
+++ b/packages/php/src/ExistingContractCodec.php
@@ -64,6 +64,7 @@ public static function model(string $model): mixed
'platformRecipients' => $l($platformRecipient),
'addedRecipients' => $o(['campaignId' => 'string','added' => 'int','recipientCount' => 'int','duplicateCount' => 'int','invalidCount' => 'int','invalidRows' => $l($o(['row' => 'int','reason' => $e(['missing_phone','invalid_phone','invalid_variables','invalid_entry'])]))]),
'groupCapabilities' => $o(['status' => $e(['synced','unknown']),'syncedAt' => $n('string'),'checkedAt' => $n('string'),'capabilities' => $l($o(['key' => $e(['polls.endTime','polls.hideVoters','polls.creatorEdit']),'kind' => $e(['feature']),'unit' => $e([null]),'value' => $n('bool'),'source' => $n($e(['server','client_default']))]))]),
+ 'testingAccountMode' => $o(['session' => 'string', 'accountType' => $e(['whatsapp_app','business_app','meta_cloud','meta_coexistence']), 'primaryPlatform' => $n($e(['android','ios'])), 'changed' => 'bool', 'unlinkedDevices' => $l('int')]),
'testingPhone' => $o(['session' => 'string','phone' => 'string','online' => 'bool','devices' => $l($o(['deviceId' => 'int']))]),
'testingSend' => $o(['session' => 'string','to' => 'string','messageId' => $n('string')]),
'testingUnlink' => $o(['session' => 'string','deviceId' => 'int','unlinked' => $e([true])]),
diff --git a/packages/php/src/Models.php b/packages/php/src/Models.php
index be53a49a3..e30357fc7 100644
--- a/packages/php/src/Models.php
+++ b/packages/php/src/Models.php
@@ -11,7 +11,7 @@
* @phpstan-type Contact array{id:string,name:string,pushName:string,phoneNumber?:string,bsuid?:string,username?:string,businessName?:string,profileUrl?:string}
* @phpstan-type ContactCheck array{exists:bool,id?:string,phoneNumber?:string,bsuid?:string,username?:string}
* @phpstan-type UserInfo array{id:string,status:string,pictureId:string,verifiedName:string,devices:list,phoneNumber?:string,bsuid?:string,username?:string}
- * @phpstan-type BusinessProfile array{id:string,phoneNumber?:string,bsuid?:string,username?:string,address:string,email:string,description:string,websites:list,coverPhotoId:string,categories:list,options:array,hoursTimeZone:string,hours:list}
+ * @phpstan-type BusinessProfile array{encryption?:'end_to_end'|'hybrid'|'not_end_to_end',id:string,phoneNumber?:string,bsuid?:string,username?:string,address:string,email:string,description:string,websites:list,coverPhotoId:string,categories:list,options:array,hoursTimeZone:string,hours:list}
* @phpstan-type Profile array{name:string,status:string,profilePicUrl?:string,phonePlatform?:string,accountType?:string}
* @phpstan-type Privacy array{groupAdd:'all'|'contacts'|'contact_blacklist'|'none',lastSeen:'all'|'contacts'|'contact_blacklist'|'none',status:'all'|'contacts'|'contact_blacklist'|'none',profile:'all'|'contacts'|'contact_blacklist'|'none',readReceipts:'all'|'none',online:'all'|'match_last_seen',callAdd:'all'|'known',messages:'all'|'contacts',defense:'on_standard'|'off',stickers:'contacts'|'contact_allowlist'|'none'}
* @phpstan-type Label array{id:string,name:string,color:int,orderIndex?:int,chatCount?:int,observedAt?:string}
diff --git a/packages/php/src/OnboardingModels.php b/packages/php/src/OnboardingModels.php
index 0a6690d59..4c859b500 100644
--- a/packages/php/src/OnboardingModels.php
+++ b/packages/php/src/OnboardingModels.php
@@ -19,6 +19,8 @@
* @phpstan-type Overrides array{text?:string,from?:string,pushName?:string,mediaType?:'image'|'video'|'audio'|'document'|'sticker',caption?:string,ackStatus?:'delivered'|'read'|'played'|'error',messageId?:string,failureReason?:'invalid_recipient'|'session_not_connected'|'ack_timeout'|'send_failed'|'blocked_by_safety',video?:bool,durationSeconds?:int|float,callEndReason?:'user_hangup'|'timeout'|'lost_connection'|'rejected'|'call_restricted',restrictionActive?:bool,status?:'CONNECTING'|'CONNECTED'|'DISCONNECTED',statusReason?:'SCAN_QR'|'AUTO_RECONNECT'|'FAILED'|'MANUAL_STOP'|'QR_TIMEOUT'|'LOGGED_OUT'|'TEMPORARY_BAN'|'STREAM_ERROR',templateName?:string,templateStatus?:'APPROVED'|'REJECTED',reason?:string}
* @phpstan-type Trigger array{event:Fixture,overrides?:Overrides,fromNumber?:string}
* @phpstan-type TriggerResult array{event:Fixture,session:string,delivery:'generated'|'simulated',eventId:?string,source:'test'|'runtime'}
+ * @phpstan-type AccountModeInput array{accountType:'whatsapp_app'|'business_app'|'meta_cloud'|'meta_coexistence',primaryPlatform?:'android'|'ios'}
+ * @phpstan-type AccountMode array{session:string,accountType:'whatsapp_app'|'business_app'|'meta_cloud'|'meta_coexistence',primaryPlatform:'android'|'ios'|null,changed:bool,unlinkedDevices:list}
* @phpstan-type Phone array{session:string,phone:string,online:bool,devices:list}
*/
final class OnboardingModels
diff --git a/packages/php/src/QuickLinkModels.php b/packages/php/src/QuickLinkModels.php
index 88462475f..93da79579 100644
--- a/packages/php/src/QuickLinkModels.php
+++ b/packages/php/src/QuickLinkModels.php
@@ -10,8 +10,8 @@
* @phpstan-import-type Hms from SessionModels
* @phpstan-type Connection 'linked_devices'|'official_api'
* @phpstan-type Method 'qr'|'pairing'
- * @phpstan-type TestingConfiguration array{profile?:array{name?:string,status?:string},accountType?:'personal'|'business',replyBehavior?:'off'|'echo',failureScenario?:'none'|'reject-send',historyFixtureId?:string}
- * @phpstan-type Configuration array{observation?:ObservationPatch,hms?:Hms,testing?:array{country?:string,configuration?:TestingConfiguration,editable?:list<'profile.name'|'profile.status'|'accountType'|'replyBehavior'|'failureScenario'|'historyFixtureId'>},connectionPreference?:'cloud'|'linked'|'both',connectionEnforcement?:'prefer'|'force',methods?:list,defaultMethod?:Method|null,prefillPhone?:string,allowPhoneChange?:bool,historySync?:array{delivery?:'descriptor',consent?:'ask'|'force_on'|'force_off',mode?:'metadata_only'|'deliver',requestFull?:bool}}
+ * @phpstan-type TestingConfiguration array{profile?:array{name?:string,status?:string},accountType?:'whatsapp_app'|'business_app'|'meta_cloud'|'meta_coexistence',primaryPlatform?:'android'|'ios',replyBehavior?:'off'|'echo',failureScenario?:'none'|'reject-send',historyFixtureId?:string}
+ * @phpstan-type Configuration array{observation?:ObservationPatch,hms?:Hms,testing?:array{country?:string,configuration?:TestingConfiguration,editable?:list<'profile.name'|'profile.status'|'accountType'|'primaryPlatform'|'replyBehavior'|'failureScenario'|'historyFixtureId'>},connectionPreference?:'cloud'|'linked'|'both',connectionEnforcement?:'prefer'|'force',methods?:list,defaultMethod?:Method|null,prefillPhone?:string,allowPhoneChange?:bool,historySync?:array{delivery?:'descriptor',consent?:'ask'|'force_on'|'force_off',mode?:'metadata_only'|'deliver',requestFull?:bool}}
* @phpstan-type CreateInput array{purpose?:'initial',signalMode?:Mode,billingControls?:array{limitCredits:int|float|null,priority:int},connectionGoal?:'single'|'hybrid',projectId?:string,customerId?:string,externalId?:string,configuration?:Configuration}|array{purpose:'add_connection',session:string,addConnection:Connection,connectionGoal?:'hybrid',projectId?:string,configuration?:Configuration}
* @phpstan-type Link array{purpose:'initial'|'add_connection'|'reauthorization',connectionGoal:'single'|'hybrid',addConnection?:Connection,id:string,url:string,session:string,expiresAt:?string}
* @phpstan-type SyncRequest 'not_applicable'|'not_requested'|'pending'|'requesting'|'accepted'|'declined'|'unknown'
diff --git a/packages/php/src/Resources/QuickLinks.php b/packages/php/src/Resources/QuickLinks.php
index 71bf48260..10388c0a3 100644
--- a/packages/php/src/Resources/QuickLinks.php
+++ b/packages/php/src/Resources/QuickLinks.php
@@ -28,6 +28,10 @@ public function create(array $body = [], ?RequestOptions $options = null): ApiRe
$this->server();
$options = \Polymorfa\ExistingContract::options($options, \Polymorfa\SessionDeliveryValidation::quickLink($body));
$this->validateBilling($body);
+ if (isset($body['configuration']['testing']['configuration'])) {
+ \Polymorfa\BusinessAccountMode::fields($body['configuration']['testing']['configuration']);
+ }
+
/** @var ApiResponse */
return $this->request('POST', '/messaging/quicklinks', \Polymorfa\ExistingContract::body($body), options: $options);
}
diff --git a/packages/php/src/Resources/Testing.php b/packages/php/src/Resources/Testing.php
index 764f68fa4..c35b76567 100644
--- a/packages/php/src/Resources/Testing.php
+++ b/packages/php/src/Resources/Testing.php
@@ -11,6 +11,8 @@
* @phpstan-import-type Fixture from OnboardingModels
* @phpstan-import-type Trigger from OnboardingModels
* @phpstan-import-type TriggerResult from OnboardingModels
+ * @phpstan-import-type AccountModeInput from OnboardingModels
+ * @phpstan-import-type AccountMode from OnboardingModels
* @phpstan-import-type Phone from OnboardingModels
*/
final class Testing extends Resource
@@ -56,6 +58,17 @@ public function unlinkPhoneDevice(string $session, int $deviceId, ?RequestOption
throw new ValidationException('deviceId must be a companion device ID from 1 to 99.');
} /** @var ApiResponse */ return \Polymorfa\ExistingContract::bare($this->transport, 'POST', $this->phone($session).'/devices/'.$deviceId.'/unlink', null, $options, 'testingUnlink');
}
+ /** @param AccountModeInput $input
+ * @return ApiResponse */
+ public function setAccountMode(string $session, array $input, ?RequestOptions $options = null): ApiResponse
+ {
+ $this->server();
+ \Polymorfa\CampaignContractValidation::text($session, 'session', 1, 256);
+ \Polymorfa\CampaignContractValidation::fields($input, ['accountType', 'primaryPlatform'], ['accountType']);
+ \Polymorfa\BusinessAccountMode::fields($input, true);
+ /** @var ApiResponse */
+ return \Polymorfa\ExistingContract::bare($this->transport, 'PUT', '/messaging/'.self::segment($session).'/phone/account-mode', $input, $options, 'testingAccountMode');
+ }
private function phone(string $session): string
{
return '/messaging/'.self::segment($session).'/phone';
diff --git a/packages/php/tests/business_account_modes.php b/packages/php/tests/business_account_modes.php
new file mode 100644
index 000000000..16bb99701
--- /dev/null
+++ b/packages/php/tests/business_account_modes.php
@@ -0,0 +1,41 @@
+ $account], ['session' => 'demo /a', 'accountType' => $account, 'primaryPlatform' => null, 'changed' => true, 'unlinkedDevices' => [2, 7]], fn ($c) => $c->testing->setAccountMode('demo /a', ['accountType' => $account])];
+}
+$businessModeCases[] = ['PUT', '/messaging/demo/phone/account-mode', ['accountType' => 'business_app', 'primaryPlatform' => 'ios'], ['session' => 'demo', 'accountType' => 'business_app', 'primaryPlatform' => 'ios', 'changed' => false, 'unlinkedDevices' => []], fn ($c) => $c->testing->setAccountMode('demo', ['accountType' => 'business_app', 'primaryPlatform' => 'ios'])];
+nativeCases($businessModeCases, fn ($credential, $url) => new Polymorfa\MessagingClient($credential, baseUrl: $url));
+foreach ([[], ['accountType' => 'personal'], ['accountType' => 'business'], ['accountType' => 'meta_cloud', 'primaryPlatform' => 'android'], ['accountType' => 'business_app', 'primaryPlatform' => null], ['accountType' => 'business_app', 'extra' => true]] as $invalid) {
+ $captured = [];
+ $client = new Polymorfa\MessagingClient($credential, http: mocked([], $captured));
+ raises(fn () => $client->testing->setAccountMode('demo', $invalid), Polymorfa\ConfigurationException::class);
+ check($captured === [], 'Invalid mode refused before transport');
+}
+raises(fn () => (new Polymorfa\MessagingClient(Polymorfa\Credential::clientToken('pmfa_ct_Zml4dHVyZQ')))->testing->setAccountMode('demo', ['accountType' => 'business_app']), Polymorfa\ConfigurationException::class);
+foreach ([[], ['session' => 'demo', 'accountType' => 'business', 'primaryPlatform' => null, 'changed' => false, 'unlinkedDevices' => []], ['session' => 'demo', 'accountType' => 'business_app', 'changed' => false, 'unlinkedDevices' => []]] as $malformed) {
+ $captured = [];
+ $client = new Polymorfa\MessagingClient($credential, http: mocked([jsonResponse($malformed)], $captured));
+ raises(fn () => $client->testing->setAccountMode('demo', ['accountType' => 'business_app']), Polymorfa\ServerException::class);
+}
+$encryptionCases = [];
+foreach (['end_to_end', 'hybrid', 'not_end_to_end', null] as $encryption) {
+ $profile = ['id' => '123', 'address' => '', 'email' => '', 'description' => '', 'websites' => [], 'coverPhotoId' => '', 'categories' => [], 'options' => (object) [], 'hoursTimeZone' => '', 'hours' => []];
+ if ($encryption !== null) { $profile['encryption'] = $encryption; }
+ $body = ['success' => true, 'data' => $profile];
+ // The PHP public model returns JSON objects as associative maps.
+ $expected = json_decode(json_encode($body, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
+ $encryptionCases[] = ['GET', '/messaging/demo/contacts/123/business-profile', null, $body, fn ($c) => $c->contacts->businessProfile('demo', '123'), $expected];
+}
+nativeCases($encryptionCases, fn ($credential, $url) => new Polymorfa\MessagingClient($credential, baseUrl: $url));
+
+$businessQuickLink = ['configuration' => ['testing' => ['configuration' => ['accountType' => 'business_app', 'primaryPlatform' => 'ios', 'replyBehavior' => 'echo']]]];
+nativeCases([['POST', '/messaging/quicklinks', $businessQuickLink, ['success' => true, 'data' => ['id' => 'ql', 'url' => 'https://example.test/ql', 'session' => 'demo', 'purpose' => 'initial', 'connectionGoal' => 'single', 'expiresAt' => null]], fn ($c) => $c->quickLinks->create($businessQuickLink)]], fn ($credential, $url) => new Polymorfa\MessagingClient($credential, baseUrl: $url));
+foreach ([['accountType' => 'business'], ['accountType' => 'meta_cloud', 'primaryPlatform' => 'ios']] as $mode) {
+ $captured = [];
+ $client = new Polymorfa\MessagingClient($credential, http: mocked([], $captured));
+ raises(fn () => $client->quickLinks->create(['configuration' => ['testing' => ['configuration' => $mode]]]), Polymorfa\ConfigurationException::class);
+ check($captured === [], 'Invalid QuickLink mode refused before transport');
+}
diff --git a/packages/php/tests/campaign_contract_validation.php b/packages/php/tests/campaign_contract_validation.php
index 7bef6d101..b81b14c3a 100644
--- a/packages/php/tests/campaign_contract_validation.php
+++ b/packages/php/tests/campaign_contract_validation.php
@@ -137,11 +137,14 @@
$ccConfigure(['method' => 'GET', 'path' => '/platform/campaign-reply-flows/'.$ccFlowId.'?projectId='.$ccProject, 'response' => $ccJson($ccBadFlow)]);
ccThrows(fn () => $ccTeam->campaigns->getReplyFlow($ccFlowId, ['projectId' => $ccProject]), Polymorfa\ServerException::class);
}
-$ccConfigure(['method' => 'GET', 'path' => '/messaging/projects/slug/campaigns/'.$ccCampaign.'/recipients/export', 'response' => "phone,status\r\n", 'contentType' => 'text/csv', 'bodyDelaySeconds' => 0.15, 'headers' => ['X-Polymorfa-Operation-Id' => 'csv-admitted']]);
+// Leave time for local scheduling before headers, then stall well beyond the
+// unchanged one-second completion assertion. These assert admitted-body timeouts.
+$ccConfigure(['method' => 'GET', 'path' => '/messaging/projects/slug/campaigns/'.$ccCampaign.'/recipients/export', 'response' => "phone,status\r\n", 'contentType' => 'text/csv', 'bodyDelaySeconds' => 2, 'headers' => ['X-Polymorfa-Operation-Id' => 'csv-admitted']]);
$ccStarted = microtime(true);
-$ccTimeout = ccThrows(fn () => $ccMessaging->campaigns->exportRecipients('slug', $ccCampaign, [], new Polymorfa\RequestOptions(timeout: 0.04, maxNetworkRetries: 0)), Polymorfa\PolymorfaException::class);
-ccCheck(($ccTimeout instanceof Polymorfa\ConnectionException || $ccTimeout instanceof Polymorfa\TimeoutException) && $ccTimeout->metadata->operationId === 'csv-admitted' && microtime(true) - $ccStarted < 1 && count($ccObservations()) === 1, 'CSV stalled read retains admitted metadata without restarting body');
-$ccConfigure(['method' => 'GET', 'path' => '/platform/campaign-settings', 'response' => $ccJson(['launchApproval' => ['recipientThreshold' => null]]), 'bodyDelaySeconds' => 0.15, 'headers' => ['X-Polymorfa-Operation-Id' => 'json-admitted']]);
-$ccTimeout = ccThrows(fn () => $ccTeam->campaigns->getSettings(new Polymorfa\RequestOptions(timeout: 0.04, maxNetworkRetries: 0)), Polymorfa\TimeoutException::class);
-ccCheck($ccTimeout->metadata->operationId === 'json-admitted' && count($ccObservations()) === 1, 'JSON stalled response retains admitted metadata');
+$ccTimeout = ccThrows(fn () => $ccMessaging->campaigns->exportRecipients('slug', $ccCampaign, [], new Polymorfa\RequestOptions(timeout: 0.25, maxNetworkRetries: 0)), Polymorfa\PolymorfaException::class);
+ccCheck(($ccTimeout instanceof Polymorfa\ConnectionException || $ccTimeout instanceof Polymorfa\TimeoutException) && $ccTimeout->metadata?->operationId === 'csv-admitted' && microtime(true) - $ccStarted < 1 && count($ccObservations()) === 1, 'CSV stalled read retains admitted metadata without restarting body');
+$ccConfigure(['method' => 'GET', 'path' => '/platform/campaign-settings', 'response' => $ccJson(['launchApproval' => ['recipientThreshold' => null]]), 'bodyDelaySeconds' => 2, 'headers' => ['X-Polymorfa-Operation-Id' => 'json-admitted']]);
+$ccStarted = microtime(true);
+$ccTimeout = ccThrows(fn () => $ccTeam->campaigns->getSettings(new Polymorfa\RequestOptions(timeout: 0.25, maxNetworkRetries: 0)), Polymorfa\TimeoutException::class);
+ccCheck($ccTimeout->metadata?->operationId === 'json-admitted' && microtime(true) - $ccStarted < 1 && count($ccObservations()) === 1, 'JSON stalled response retains admitted metadata');
echo "30 malformed result guards, normalized responses, CSV redirects and native deadlines passed.\n";
diff --git a/packages/php/tests/run.php b/packages/php/tests/run.php
index f69e508ad..dc2a8ba48 100644
--- a/packages/php/tests/run.php
+++ b/packages/php/tests/run.php
@@ -171,6 +171,7 @@ function mocked(array $responses, array &$history): HttpClient
require __DIR__.'/official_groups.php';
require __DIR__.'/onboarding.php';
+require __DIR__.'/business_account_modes.php';
require __DIR__.'/templates.php';
diff --git a/packages/python/README.md b/packages/python/README.md
index 362ebd789..4ba3b1949 100644
--- a/packages/python/README.md
+++ b/packages/python/README.md
@@ -1005,3 +1005,31 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```python
+result = await client.testing.set_account_mode(
+ "demo", {"accountType": "business_app", "primaryPlatform": "ios"}
+)
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/python/coverage.json b/packages/python/coverage.json
index e41b61eeb..c934c6f1c 100644
--- a/packages/python/coverage.json
+++ b/packages/python/coverage.json
@@ -5383,6 +5383,12 @@
"published": false,
"language": "python"
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "language": "python"
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "python",
diff --git a/packages/python/src/polymorfa/__init__.py b/packages/python/src/polymorfa/__init__.py
index 1aa4288a6..229981313 100644
--- a/packages/python/src/polymorfa/__init__.py
+++ b/packages/python/src/polymorfa/__init__.py
@@ -1,5 +1,12 @@
"""Polymorfa server SDK. No package publication is implied by local availability."""
+from .business_account_modes import (
+ ContactEncryption,
+ TestingAccountMode,
+ TestingAccountModeInput,
+ TestingPrimaryPlatform,
+ WhatsAppAccountType,
+)
from .call_policy import AsyncCallRetentionClient
from .calls import (
AudioFrame,
@@ -584,3 +591,11 @@
from .webhooks import (
parse_verified_webhook_delivery as parse_verified_webhook_delivery,
)
+
+__all__ += [
+ "ContactEncryption",
+ "TestingAccountMode",
+ "TestingAccountModeInput",
+ "TestingPrimaryPlatform",
+ "WhatsAppAccountType",
+]
diff --git a/packages/python/src/polymorfa/business_account_modes.py b/packages/python/src/polymorfa/business_account_modes.py
new file mode 100644
index 000000000..6353e58a5
--- /dev/null
+++ b/packages/python/src/polymorfa/business_account_modes.py
@@ -0,0 +1,43 @@
+"""Typed Test-number account modes and optional business encryption state."""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from typing_extensions import NotRequired, TypedDict
+
+from . import campaign_contract_validation as V
+
+WhatsAppAccountType = Literal["whatsapp_app", "business_app", "meta_cloud", "meta_coexistence"]
+TestingPrimaryPlatform = Literal["android", "ios"]
+ContactEncryption = Literal["end_to_end", "hybrid", "not_end_to_end"]
+
+
+class TestingAccountModeInput(TypedDict):
+ accountType: WhatsAppAccountType
+ primaryPlatform: NotRequired[TestingPrimaryPlatform]
+
+
+class TestingAccountMode(TypedDict):
+ session: str
+ accountType: WhatsAppAccountType
+ primaryPlatform: TestingPrimaryPlatform | None
+ changed: bool
+ unlinkedDevices: list[int]
+
+
+def validate_testing_mode_fields(value: object, *, required: bool = False) -> None:
+ mode = V.obj(value)
+ account = mode.get("accountType", "whatsapp_app" if not required else None)
+ V.choice(
+ account, ("whatsapp_app", "business_app", "meta_cloud", "meta_coexistence"), "accountType"
+ )
+ if "primaryPlatform" in mode:
+ V.choice(mode["primaryPlatform"], ("android", "ios"), "primaryPlatform")
+ if account == "meta_cloud":
+ V.invalid("primaryPlatform")
+
+
+def validate_testing_account_mode(value: object) -> None:
+ V.fields(value, ["accountType", "primaryPlatform"], ["accountType"])
+ validate_testing_mode_fields(value, required=True)
diff --git a/packages/python/src/polymorfa/messaging.py b/packages/python/src/polymorfa/messaging.py
index 8a036dc98..abfb50542 100644
--- a/packages/python/src/polymorfa/messaging.py
+++ b/packages/python/src/polymorfa/messaging.py
@@ -14,6 +14,7 @@
from . import campaign_contract_validation as V
from . import session_delivery_validation as D
+from .business_account_modes import validate_testing_mode_fields
from .cloud import (
CloudCredentialHealth,
CloudReauthorization,
@@ -356,6 +357,10 @@ async def create(
self._server()
value = {} if body is None else body
options = D.options(options, D.quicklink_intent(value))
+ testing = value.get("configuration", {}).get("testing", {}).get("configuration")
+ if testing is not None:
+ validate_testing_mode_fields(testing)
+
if value.get("purpose") == "add_connection" and not value.get("session"):
raise ValidationError("An add_connection QuickLink requires session.")
billing = value.get("billingControls")
diff --git a/packages/python/src/polymorfa/models.py b/packages/python/src/polymorfa/models.py
index 5d521a6ac..22dc5305b 100644
--- a/packages/python/src/polymorfa/models.py
+++ b/packages/python/src/polymorfa/models.py
@@ -6,6 +6,7 @@
from typing_extensions import NotRequired, TypedDict
+from .business_account_modes import ContactEncryption
from .campaign_contract_models import SignalCustodyMode
from .cloud_order import CloudOrder
from .configuration import ConfigurationPatch, ConfigurationView
@@ -281,6 +282,7 @@ class BusinessHours(TypedDict):
class BusinessProfile(TypedDict):
+ encryption: NotRequired[ContactEncryption]
id: str
address: str
email: str
diff --git a/packages/python/src/polymorfa/onboarding.py b/packages/python/src/polymorfa/onboarding.py
index fd6ecc2d5..73cdb252f 100644
--- a/packages/python/src/polymorfa/onboarding.py
+++ b/packages/python/src/polymorfa/onboarding.py
@@ -7,6 +7,11 @@
from typing_extensions import NotRequired, TypedDict
from . import campaign_contract_validation as V
+from .business_account_modes import (
+ TestingAccountMode,
+ TestingAccountModeInput,
+ validate_testing_account_mode,
+)
from .campaign_contract_response import acknowledged
from .errors import ValidationError
from .messaging import O, Resource, segment
@@ -193,6 +198,20 @@ class UnlinkedDevice(TypedDict):
class Testing(Resource):
+ @acknowledged()
+ async def set_account_mode(
+ self, session: str, body: TestingAccountModeInput, *, options: RequestOptions = O
+ ) -> ApiResponse[TestingAccountMode]:
+ self._server()
+ V.text(session, "session", 1, 256)
+ validate_testing_account_mode(body)
+ return await self._request(
+ "PUT",
+ f"/messaging/{segment(session)}/phone/account-mode",
+ body=V.capture(body),
+ options=options,
+ )
+
async def create_history_fixture(
self, project_id: str, body: HistoryFixture, *, options: RequestOptions = O
) -> ApiResponse[CreatedHistoryFixture]:
diff --git a/packages/python/src/polymorfa/quicklink_models.py b/packages/python/src/polymorfa/quicklink_models.py
index 554df0728..c6a4e2002 100644
--- a/packages/python/src/polymorfa/quicklink_models.py
+++ b/packages/python/src/polymorfa/quicklink_models.py
@@ -4,6 +4,7 @@
from typing_extensions import Never, NotRequired, TypedDict
+from .business_account_modes import TestingPrimaryPlatform, WhatsAppAccountType
from .campaign_contract_models import SignalCustodyMode
from .configuration import Hms, ObservationPatch
@@ -19,7 +20,8 @@ class TestingProfile(TypedDict, total=False):
class TestingConfiguration(TypedDict, total=False):
profile: TestingProfile
- accountType: Literal["personal", "business"]
+ accountType: WhatsAppAccountType
+ primaryPlatform: TestingPrimaryPlatform
replyBehavior: Literal["off", "echo"]
failureScenario: Literal["none", "reject-send"]
historyFixtureId: str
@@ -29,6 +31,7 @@ class TestingConfiguration(TypedDict, total=False):
"profile.name",
"profile.status",
"accountType",
+ "primaryPlatform",
"replyBehavior",
"failureScenario",
"historyFixtureId",
diff --git a/packages/python/tests/test_business_account_modes.py b/packages/python/tests/test_business_account_modes.py
new file mode 100644
index 000000000..0878a0345
--- /dev/null
+++ b/packages/python/tests/test_business_account_modes.py
@@ -0,0 +1,172 @@
+import json
+
+import httpx
+import pytest
+
+from polymorfa import (
+ AsyncMessagingClient,
+ ConfigurationError,
+ ConflictError,
+ Credential,
+ ServerError,
+ ValidationError,
+)
+
+KEY = Credential("team_api_key", "pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k")
+
+
+@pytest.mark.parametrize(
+ "account", ["whatsapp_app", "business_app", "meta_cloud", "meta_coexistence"]
+)
+async def test_business_account_modes_wire(account):
+ reply = {
+ "session": "demo /a",
+ "accountType": account,
+ "primaryPlatform": None if account == "meta_cloud" else "android",
+ "changed": True,
+ "unlinkedDevices": [3, 7],
+ }
+
+ def handler(request):
+ assert request.method == "PUT"
+ assert request.url.raw_path == b"/messaging/demo%20%2Fa/phone/account-mode"
+ assert json.loads(request.content) == {"accountType": account}
+ return httpx.Response(200, json=reply, headers={"x-request-id": "mode-request"})
+
+ async with AsyncMessagingClient(KEY, http_transport=httpx.MockTransport(handler)) as client:
+ result = await client.testing.set_account_mode("demo /a", {"accountType": account})
+ assert result.data == reply
+ assert result.metadata.request_id == "mode-request"
+
+
+@pytest.mark.parametrize(
+ "body",
+ [
+ {},
+ {"accountType": "personal"},
+ {"accountType": "business"},
+ {"accountType": "meta_cloud", "primaryPlatform": "android"},
+ {"accountType": "business_app", "primaryPlatform": None},
+ {"accountType": "business_app", "unknown": True},
+ ],
+)
+async def test_business_account_modes_reject_before_io(body):
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(500)
+
+ async with AsyncMessagingClient(KEY, http_transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(ValidationError):
+ await client.testing.set_account_mode("demo", body)
+ assert not calls
+
+
+async def test_business_account_mode_rejects_client_tokens():
+ async with AsyncMessagingClient(Credential("client_token", "pmfa_ct_bG9jYWw")) as client:
+ with pytest.raises(ConfigurationError):
+ await client.testing.set_account_mode("demo", {"accountType": "business_app"})
+
+
+async def test_business_account_mode_checks_required_response_shape():
+ reply = {
+ "session": "demo",
+ "accountType": "business_app",
+ "primaryPlatform": "ios",
+ "changed": "false",
+ "unlinkedDevices": [],
+ }
+ async with AsyncMessagingClient(
+ KEY, http_transport=httpx.MockTransport(lambda _: httpx.Response(200, json=reply))
+ ) as client:
+ with pytest.raises(ServerError):
+ await client.testing.set_account_mode(
+ "demo", {"accountType": "business_app", "primaryPlatform": "ios"}
+ )
+
+
+@pytest.mark.parametrize("encryption", [None, "end_to_end", "hybrid", "not_end_to_end"])
+async def test_business_profile_preserves_encryption_and_omission(encryption):
+ profile = {"id": "contact"}
+ if encryption is not None:
+ profile["encryption"] = encryption
+ async with AsyncMessagingClient(
+ KEY,
+ http_transport=httpx.MockTransport(
+ lambda _: httpx.Response(200, json={"success": True, "data": profile})
+ ),
+ ) as client:
+ result = await client.contacts.business_profile("demo", "contact")
+ assert result.data["data"] == profile
+ if encryption is None:
+ assert "encryption" not in result.data["data"]
+
+
+async def test_business_quicklink_keeps_mode_and_platform_with_simulation_fields():
+ configuration = {
+ "testing": {
+ "configuration": {
+ "accountType": "business_app",
+ "primaryPlatform": "ios",
+ "replyBehavior": "echo",
+ }
+ }
+ }
+
+ def handler(request):
+ assert request.method == "POST"
+ assert request.url.path == "/messaging/quicklinks"
+ assert json.loads(request.content) == {"configuration": configuration}
+ return httpx.Response(
+ 200,
+ json={
+ "success": True,
+ "data": {
+ "id": "ql",
+ "url": "https://example.test/ql",
+ "session": "demo",
+ "expiresAt": None,
+ },
+ },
+ )
+
+ async with AsyncMessagingClient(KEY, http_transport=httpx.MockTransport(handler)) as client:
+ await client.quick_links.create({"configuration": configuration})
+
+
+@pytest.mark.parametrize(
+ "mode", [{"accountType": "business"}, {"accountType": "meta_cloud", "primaryPlatform": "ios"}]
+)
+async def test_business_quicklink_rejects_invalid_modes_before_io(mode):
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(500)
+
+ async with AsyncMessagingClient(KEY, http_transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(ValidationError):
+ await client.quick_links.create({"configuration": {"testing": {"configuration": mode}}})
+ assert not calls
+
+
+async def test_business_account_modes_surface_conflict():
+ def handler(request):
+ return httpx.Response(
+ 409,
+ json={
+ "error": {
+ "type": "conflict_error",
+ "code": "state_conflict",
+ "message": "The request conflicts with the resource state.",
+ "param": None,
+ "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30",
+ },
+ "data": None,
+ },
+ )
+
+ async with AsyncMessagingClient(KEY, http_transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(ConflictError):
+ await client.testing.set_account_mode("demo", {"accountType": "business_app"})
diff --git a/packages/python/tests/test_system_quicklinks_webhooks.py b/packages/python/tests/test_system_quicklinks_webhooks.py
index 82e7979ee..164e2a6bf 100644
--- a/packages/python/tests/test_system_quicklinks_webhooks.py
+++ b/packages/python/tests/test_system_quicklinks_webhooks.py
@@ -330,7 +330,7 @@ async def test_quicklink_testing_configuration_shape():
"country": "US",
"configuration": {
"profile": {"name": "Ada", "status": "Available"},
- "accountType": "business",
+ "accountType": "business_app",
"replyBehavior": "echo",
"failureScenario": "none",
"historyFixtureId": "fixture_1",
diff --git a/packages/rust/README.md b/packages/rust/README.md
index dfc1ea4e3..ab1ee9059 100644
--- a/packages/rust/README.md
+++ b/packages/rust/README.md
@@ -1125,3 +1125,46 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```no_run
+use polymorfa_sdk::{Credential, MessagingClient};
+use polymorfa_sdk::business_account_modes::{
+ TestingAccountModeRequest, TestingPrimaryPlatform, WhatsAppAccountType,
+};
+
+#[tokio::main(flavor = "current_thread")]
+async fn main() -> Result<(), Box> {
+ let client = MessagingClient::new(
+ Credential::team_api_key(std::env::var("POLYMORFA_API_KEY")?)?,
+ Default::default(),
+ )?;
+ let result = client.testing().set_account_mode("demo", &TestingAccountModeRequest {
+ account_type: WhatsAppAccountType::BusinessApp,
+ primary_platform: Some(TestingPrimaryPlatform::Ios),
+ }, Default::default()).await?;
+ println!("{:?}", result.data.account_type);
+ Ok(())
+}
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/rust/coverage.json b/packages/rust/coverage.json
index 16bbadce3..ccefd129c 100644
--- a/packages/rust/coverage.json
+++ b/packages/rust/coverage.json
@@ -5383,6 +5383,12 @@
"published": false,
"language": "rust"
},
+ "businessAccountModes": {
+ "inventory": "contracts/native-business-account-modes.json",
+ "baselineUnchanged": true,
+ "published": false,
+ "language": "rust"
+ },
"interactiveMessages": {
"inventory": "contracts/native-interactive-messages.json",
"language": "rust",
diff --git a/packages/rust/src/account.rs b/packages/rust/src/account.rs
index 6d32846eb..a6b361741 100644
--- a/packages/rust/src/account.rs
+++ b/packages/rust/src/account.rs
@@ -83,6 +83,8 @@ pub struct BusinessProfile {
pub options: BTreeMap,
pub hours_time_zone: String,
pub hours: Vec,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub encryption: Option,
}
pub struct Contacts<'a>(pub(crate) &'a HttpTransport);
impl Contacts<'_> {
diff --git a/packages/rust/src/business_account_modes.rs b/packages/rust/src/business_account_modes.rs
new file mode 100644
index 000000000..d80dc4e05
--- /dev/null
+++ b/packages/rust/src/business_account_modes.rs
@@ -0,0 +1,70 @@
+//! Test-number account modes. This operation is restricted to trusted servers.
+pub use crate::webhook_payloads::WhatsAppAccountType;
+use crate::{
+ transport::{encode, HttpTransport},
+ ApiResponse, RequestOptions, Result,
+};
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TestingPrimaryPlatform {
+ Android,
+ Ios,
+}
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ContactEncryption {
+ EndToEnd,
+ Hybrid,
+ NotEndToEnd,
+}
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TestingAccountModeRequest {
+ pub account_type: WhatsAppAccountType,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub primary_platform: Option,
+}
+#[derive(Clone, Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TestingAccountMode {
+ pub session: String,
+ pub account_type: WhatsAppAccountType,
+ #[serde(deserialize_with = "crate::campaign_contracts::required_nullable")]
+ pub primary_platform: Option,
+ pub changed: bool,
+ pub unlinked_devices: Vec,
+}
+pub(crate) fn validate(
+ account: Option<&WhatsAppAccountType>,
+ platform: Option<&TestingPrimaryPlatform>,
+) -> Result<()> {
+ if matches!(account, Some(WhatsAppAccountType::MetaCloud)) && platform.is_some() {
+ return Err(crate::transport::configuration("primaryPlatform"));
+ }
+ Ok(())
+}
+impl crate::onboarding::Testing<'_> {
+ pub async fn set_account_mode(
+ &self,
+ session: &str,
+ input: &TestingAccountModeRequest,
+ options: RequestOptions,
+ ) -> Result> {
+ let http: &HttpTransport = self.0;
+ http.server()?;
+ crate::campaign_contract_validation::text(session, 1, 256, "session")?;
+ validate(Some(&input.account_type), input.primary_platform.as_ref())?;
+ let response: ApiResponse = http
+ .request(
+ reqwest::Method::PUT,
+ &format!("/messaging/{}/phone/account-mode", encode(session)),
+ &[],
+ Some(input),
+ options,
+ )
+ .await?;
+ crate::onboarding::phone_response(response, 200, true)
+ }
+}
diff --git a/packages/rust/src/configuration.rs b/packages/rust/src/configuration.rs
index fc6593f74..5f6ad119f 100644
--- a/packages/rust/src/configuration.rs
+++ b/packages/rust/src/configuration.rs
@@ -305,7 +305,9 @@ pub struct TestingConfiguration {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option,
#[serde(skip_serializing_if = "Option::is_none")]
- pub account_type: Option,
+ pub account_type: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub primary_platform: Option,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply_behavior: Option,
#[serde(skip_serializing_if = "Option::is_none")]
diff --git a/packages/rust/src/lib.rs b/packages/rust/src/lib.rs
index e56aa24eb..72cece390 100644
--- a/packages/rust/src/lib.rs
+++ b/packages/rust/src/lib.rs
@@ -10,6 +10,7 @@ pub mod audiences;
pub mod billing;
pub mod bridge;
pub mod business;
+pub mod business_account_modes;
pub mod call_consent;
pub mod calls;
pub mod calls_protocol;
diff --git a/packages/rust/src/messaging.rs b/packages/rust/src/messaging.rs
index 9a60f11b2..7ea4459cb 100644
--- a/packages/rust/src/messaging.rs
+++ b/packages/rust/src/messaging.rs
@@ -460,6 +460,17 @@ impl QuickLinks<'_> {
options: RequestOptions,
) -> Result>> {
self.0.server()?;
+ if let Some(testing) = body
+ .configuration
+ .as_ref()
+ .and_then(|c| c.testing.as_ref())
+ .and_then(|t| t.configuration.as_ref())
+ {
+ crate::business_account_modes::validate(
+ testing.account_type.as_ref(),
+ testing.primary_platform.as_ref(),
+ )?;
+ }
let supplementary = matches!(body.purpose, Some(CreateQuickLinkPurpose::AddConnection));
if supplementary {
if body.session.as_ref().is_none_or(|s| s.is_empty())
diff --git a/packages/rust/src/onboarding.rs b/packages/rust/src/onboarding.rs
index f6e1f4ce2..0b1db6eab 100644
--- a/packages/rust/src/onboarding.rs
+++ b/packages/rust/src/onboarding.rs
@@ -126,7 +126,11 @@ pub struct UnlinkTestingPhoneDeviceResponse {
pub device_id: u8,
pub unlinked: bool,
}
-fn phone_response(response: ApiResponse, status: u16, valid: bool) -> Result> {
+pub(crate) fn phone_response(
+ response: ApiResponse,
+ status: u16,
+ valid: bool,
+) -> Result> {
if response.metadata.status != status || !valid {
return Err(Error::local(
ErrorKind::Server,
diff --git a/packages/rust/tests/business_account_modes.rs b/packages/rust/tests/business_account_modes.rs
new file mode 100644
index 000000000..3150f85ba
--- /dev/null
+++ b/packages/rust/tests/business_account_modes.rs
@@ -0,0 +1,173 @@
+#[allow(dead_code)]
+mod support;
+use polymorfa_sdk::{business_account_modes::*, ErrorKind, RequestOptions};
+use serde_json::json;
+
+#[tokio::test]
+async fn all_four_account_modes_use_native_put_and_preserve_bare_response() {
+ for (mode, wire) in [
+ (WhatsAppAccountType::WhatsappApp, "whatsapp_app"),
+ (WhatsAppAccountType::BusinessApp, "business_app"),
+ (WhatsAppAccountType::MetaCloud, "meta_cloud"),
+ (WhatsAppAccountType::MetaCoexistence, "meta_coexistence"),
+ ] {
+ let reply = json!({"session":"demo /a","accountType":wire,"primaryPlatform":null,"changed":true,"unlinkedDevices":[2,7]});
+ let (base, server) = support::wire(
+ "PUT",
+ "/messaging/demo%20%2Fa/phone/account-mode",
+ Some(json!({"accountType":wire})),
+ reply,
+ )
+ .await;
+ let client = support::messaging(base);
+ let result = client
+ .testing()
+ .set_account_mode(
+ "demo /a",
+ &TestingAccountModeRequest {
+ account_type: mode,
+ primary_platform: None,
+ },
+ RequestOptions::default(),
+ )
+ .await
+ .unwrap();
+ assert!(result.data.changed);
+ assert_eq!(result.data.unlinked_devices, vec![2, 7]);
+ server.await.unwrap();
+ }
+}
+#[tokio::test]
+async fn ios_mode_and_completed_noop_survive_native_wire() {
+ let (base, server) = support::wire("PUT", "/messaging/demo/phone/account-mode", Some(json!({"accountType":"business_app","primaryPlatform":"ios"})), json!({"session":"demo","accountType":"business_app","primaryPlatform":"ios","changed":false,"unlinkedDevices":[]})).await;
+ let result = support::messaging(base)
+ .testing()
+ .set_account_mode(
+ "demo",
+ &TestingAccountModeRequest {
+ account_type: WhatsAppAccountType::BusinessApp,
+ primary_platform: Some(TestingPrimaryPlatform::Ios),
+ },
+ RequestOptions::default(),
+ )
+ .await
+ .unwrap();
+ assert!(!result.data.changed);
+ assert!(matches!(
+ result.data.primary_platform,
+ Some(TestingPrimaryPlatform::Ios)
+ ));
+ server.await.unwrap();
+}
+#[tokio::test]
+async fn cloud_platform_is_refused_before_io() {
+ let client = support::messaging("http://127.0.0.1:1".into());
+ let result = client
+ .testing()
+ .set_account_mode(
+ "demo",
+ &TestingAccountModeRequest {
+ account_type: WhatsAppAccountType::MetaCloud,
+ primary_platform: Some(TestingPrimaryPlatform::Android),
+ },
+ RequestOptions::default(),
+ )
+ .await;
+ assert_eq!(result.unwrap_err().kind, ErrorKind::Configuration);
+}
+#[tokio::test]
+async fn required_mode_response_fields_are_checked() {
+ for malformed in [
+ json!({"session":"demo"}),
+ json!({"session":"demo","accountType":"personal","primaryPlatform":null,"changed":false,"unlinkedDevices":[]}),
+ json!({"session":"demo","accountType":"business_app","changed":false,"unlinkedDevices":[]}),
+ ] {
+ let (base, server) = support::wire(
+ "PUT",
+ "/messaging/demo/phone/account-mode",
+ Some(json!({"accountType":"business_app"})),
+ malformed,
+ )
+ .await;
+ assert!(support::messaging(base)
+ .testing()
+ .set_account_mode(
+ "demo",
+ &TestingAccountModeRequest {
+ account_type: WhatsAppAccountType::BusinessApp,
+ primary_platform: None
+ },
+ RequestOptions::default()
+ )
+ .await
+ .is_err());
+ server.await.unwrap();
+ }
+}
+#[tokio::test]
+async fn encryption_values_and_omission_survive_contact_profile_wire() {
+ for encryption in [
+ Some("end_to_end"),
+ Some("hybrid"),
+ Some("not_end_to_end"),
+ None,
+ ] {
+ let mut data = json!({"id":"123","address":"","email":"","description":"","websites":[],"coverPhotoId":"","categories":[],"options":{},"hoursTimeZone":"","hours":[]});
+ if let Some(value) = encryption {
+ data["encryption"] = json!(value);
+ }
+ let (base, server) = support::wire(
+ "GET",
+ "/messaging/demo/contacts/123/business-profile",
+ None,
+ json!({"success":true,"data":data}),
+ )
+ .await;
+ let response = support::messaging(base)
+ .contacts()
+ .business_profile("demo", "123", RequestOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(
+ response
+ .data
+ .data
+ .encryption
+ .map(|e| serde_json::to_value(e).unwrap()),
+ encryption.map(|e| json!(e))
+ );
+ server.await.unwrap();
+ }
+}
+
+#[tokio::test]
+async fn quicklink_cloud_platform_is_refused_before_io() {
+ use polymorfa_sdk::{
+ configuration::{QuickLinkTestingConfiguration, TestingConfiguration},
+ models::{CreateQuickLinkRequest, QuickLinkConfiguration},
+ };
+ let input = CreateQuickLinkRequest {
+ configuration: Some(QuickLinkConfiguration {
+ testing: Some(QuickLinkTestingConfiguration {
+ configuration: Some(TestingConfiguration {
+ account_type: Some(WhatsAppAccountType::MetaCloud),
+ primary_platform: Some(TestingPrimaryPlatform::Ios),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let client = support::messaging("http://127.0.0.1:1".into());
+ assert_eq!(
+ client
+ .quick_links()
+ .create(&input, RequestOptions::default())
+ .await
+ .unwrap_err()
+ .kind,
+ ErrorKind::Configuration
+ );
+}
diff --git a/packages/rust/tests/configuration.rs b/packages/rust/tests/configuration.rs
index 69457b3cb..87c2ae430 100644
--- a/packages/rust/tests/configuration.rs
+++ b/packages/rust/tests/configuration.rs
@@ -66,7 +66,12 @@ async fn quicklink_configuration_testing_history_and_onboarding_native_wire() {
name: Some("Support".into()),
status: Some("Ready".into()),
}),
- account_type: Some("business".into()),
+ account_type: Some(
+ polymorfa_sdk::business_account_modes::WhatsAppAccountType::BusinessApp,
+ ),
+ primary_platform: Some(
+ polymorfa_sdk::business_account_modes::TestingPrimaryPlatform::Ios,
+ ),
reply_behavior: Some("echo".into()),
failure_scenario: Some("none".into()),
history_fixture_id: Some("support".into()),
@@ -91,7 +96,7 @@ async fn quicklink_configuration_testing_history_and_onboarding_native_wire() {
configuration: Some(overrides.clone()),
..CreateQuickLinkRequest::default()
};
- let expected = json!({"projectId":"project","configuration":{"observation":{"labelMode":"project"},"hms":{"enabled":false},"testing":{"country":"US","configuration":{"profile":{"name":"Support","status":"Ready"},"accountType":"business","replyBehavior":"echo","failureScenario":"none","historyFixtureId":"support"},"editable":["profile.name"]},"connectionPreference":"both","connectionEnforcement":"prefer","methods":["qr","code"],"defaultMethod":null,"prefillPhone":"+15551234567","allowPhoneChange":false,"historySync":{"consent":"optional","mode":"deliver","requestFull":true}}});
+ let expected = json!({"projectId":"project","configuration":{"observation":{"labelMode":"project"},"hms":{"enabled":false},"testing":{"country":"US","configuration":{"profile":{"name":"Support","status":"Ready"},"accountType":"business_app","primaryPlatform":"ios","replyBehavior":"echo","failureScenario":"none","historyFixtureId":"support"},"editable":["profile.name"]},"connectionPreference":"both","connectionEnforcement":"prefer","methods":["qr","code"],"defaultMethod":null,"prefillPhone":"+15551234567","allowPhoneChange":false,"historySync":{"consent":"optional","mode":"deliver","requestFull":true}}});
wire_messaging!(
client,
"POST",
diff --git a/packages/typescript/README.md b/packages/typescript/README.md
index 9b915ba09..0a223c8f8 100644
--- a/packages/typescript/README.md
+++ b/packages/typescript/README.md
@@ -3595,3 +3595,32 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP
path; programmatic media WebSocket controls retain their credential rechecks.
This source requires the matching unreleased backend. It does not enable a
customer environment or advance package/API availability.
+
+## Test-number account modes
+
+The Business supplement is pinned separately to API source
+`14153ad9d69ddd3bae972594e6b3dc3ddae8e8e4` in
+`contracts/business-account-modes.json`. The existing API baseline remains unchanged.
+This source support does not establish hosted availability or package publication.
+
+Use a trusted-server Messaging client to change a Test number's account mode:
+
+```ts
+await client.testing.setAccountMode("demo", {
+ accountType: "business_app",
+ primaryPlatform: "ios",
+});
+```
+
+The request requires `accountType`: `whatsapp_app`, `business_app`, `meta_cloud`
+or `meta_coexistence`. Phone modes accept `primaryPlatform` (`android` or `ios`);
+omit it for `meta_cloud`. Legacy `personal` and `business` names are rejected.
+A change unlinks companions, which must pair again. The response distinguishes a
+completed unchanged mode with `changed: false`. Client tokens cannot perform this
+operation. It does not convert a real WhatsApp account.
+
+QuickLink `configuration.testing.configuration` uses the same mode names and
+platform rule while preserving other simulation fields. Business contact profiles
+retain optional `encryption`: `end_to_end`, `hybrid` or `not_end_to_end`. Omission
+remains omission. These fields describe API responses, not a new encryption
+control in the SDK.
diff --git a/packages/typescript/src/campaign-contract-response.ts b/packages/typescript/src/campaign-contract-response.ts
index 5aee33ed3..a43c6e8e6 100644
--- a/packages/typescript/src/campaign-contract-response.ts
+++ b/packages/typescript/src/campaign-contract-response.ts
@@ -306,6 +306,18 @@ export async function requestContract(
}
const phoneModels = {
+ mode: object({
+ session: string,
+ accountType: one(
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence",
+ ),
+ primaryPlatform: nullable(one("android", "ios")),
+ changed: boolean,
+ unlinkedDevices: list(integer),
+ }),
phone: object({
session: string,
phone: string,
diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts
index 49602ff56..7f17e4c4d 100644
--- a/packages/typescript/src/index.ts
+++ b/packages/typescript/src/index.ts
@@ -373,6 +373,7 @@ export type {
CarouselCard,
CarouselMessageContent,
BusinessProfile,
+ ContactEncryption,
BusinessProfileCategory,
BusinessProfileHours,
BusinessQuickReply,
diff --git a/packages/typescript/src/messaging/onboarding.ts b/packages/typescript/src/messaging/onboarding.ts
index 93cec178c..ad3b6d20c 100644
--- a/packages/typescript/src/messaging/onboarding.ts
+++ b/packages/typescript/src/messaging/onboarding.ts
@@ -1,3 +1,5 @@
+import { contractString } from "../campaign-contract-validation.js";
+import { assertTestingAccountMode } from "./testing-account-mode.js";
import { requestPhone } from "../campaign-contract-response.js";
import { existingOptions } from "../campaign-existing-validation.js";
import {
@@ -13,6 +15,8 @@ import type {
TestEventFixtureInfo,
TestingHistoryMessage,
TestingPhone,
+ TestingAccountMode,
+ TestingAccountModeRequest,
UnlinkTestingPhoneDeviceResponse,
TriggerTestEventRequest,
TriggerTestEventResponse,
@@ -154,6 +158,27 @@ export class TestingResource {
);
}
+ /** Change a Test number's mode. A change unlinks every companion. */
+ setAccountMode(
+ session: string,
+ input: TestingAccountModeRequest,
+ options: RequestOptions = {},
+ ): Promise> {
+ assertServerCredential(this.credentialType);
+ assertTestingAccountMode(input);
+ contractString(session, "session", 1, 256);
+ return requestPhone(
+ this.transport,
+ {
+ method: "PUT",
+ path: `/messaging/${encodeURIComponent(session)}/phone/account-mode`,
+ body: input,
+ ...existingOptions(options),
+ },
+ "mode",
+ );
+ }
+
/**
* Unlink a companion from a Test number's phone, as a person would from
* Linked devices. The companion is logged out. The phone itself (device 0)
diff --git a/packages/typescript/src/messaging/quicklinks.ts b/packages/typescript/src/messaging/quicklinks.ts
index 88cf716dd..c481fbc95 100644
--- a/packages/typescript/src/messaging/quicklinks.ts
+++ b/packages/typescript/src/messaging/quicklinks.ts
@@ -1,3 +1,4 @@
+import { assertTestingModeFields } from "./testing-account-mode.js";
import { quickLinkIntent } from "../session-delivery-validation.js";
import { existingOptions } from "../campaign-existing-validation.js";
import type { SignalCustodyMode } from "../campaign-contracts.js";
@@ -187,6 +188,8 @@ export class QuickLinksResource {
): Promise> {
this.assertServerCredential();
options = existingOptions(options, quickLinkIntent(input));
+ if (input.configuration?.testing?.configuration)
+ assertTestingModeFields(input.configuration.testing.configuration);
if (input.billingControls) {
billingLimit(input.billingControls.limitCredits);
billingPriority(input.billingControls.priority);
diff --git a/packages/typescript/src/messaging/testing-account-mode.ts b/packages/typescript/src/messaging/testing-account-mode.ts
new file mode 100644
index 000000000..0d3e36de9
--- /dev/null
+++ b/packages/typescript/src/messaging/testing-account-mode.ts
@@ -0,0 +1,45 @@
+import { PolymorfaValidationError } from "../errors.js";
+
+const accounts: readonly unknown[] = [
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence",
+];
+export function assertTestingModeFields(input: {
+ accountType?: unknown;
+ primaryPlatform?: unknown;
+}): void {
+ if (input.accountType !== undefined && !accounts.includes(input.accountType))
+ throw new PolymorfaValidationError(
+ "accountType must be whatsapp_app, business_app, meta_cloud or meta_coexistence.",
+ );
+ if (
+ input.primaryPlatform !== undefined &&
+ input.primaryPlatform !== "android" &&
+ input.primaryPlatform !== "ios"
+ )
+ throw new PolymorfaValidationError(
+ "primaryPlatform must be android or ios.",
+ );
+ if (input.accountType === "meta_cloud" && input.primaryPlatform !== undefined)
+ throw new PolymorfaValidationError(
+ "primaryPlatform is not accepted when accountType is meta_cloud.",
+ );
+}
+export function assertTestingAccountMode(input: unknown): void {
+ if (!input || typeof input !== "object" || Array.isArray(input))
+ throw new PolymorfaValidationError("Account mode must be an object.");
+ const value = input as Record;
+ if (
+ !Object.hasOwn(value, "accountType") ||
+ value.accountType === undefined ||
+ Object.keys(value).some(
+ (key) => key !== "accountType" && key !== "primaryPlatform",
+ )
+ )
+ throw new PolymorfaValidationError(
+ "Account mode requires accountType and accepts only primaryPlatform alongside it.",
+ );
+ assertTestingModeFields(value);
+}
diff --git a/packages/typescript/src/messaging/testing-configuration.ts b/packages/typescript/src/messaging/testing-configuration.ts
index 9234ef825..4b063d67e 100644
--- a/packages/typescript/src/messaging/testing-configuration.ts
+++ b/packages/typescript/src/messaging/testing-configuration.ts
@@ -1,7 +1,10 @@
+import type { WhatsAppAccountType } from "./types.js";
+
/** Initial identity of an isolated simulated account. No real credentials or message content. */
export interface TestingConfiguration {
profile?: { name?: string; status?: string };
- accountType?: "personal" | "business";
+ accountType?: WhatsAppAccountType;
+ primaryPlatform?: TestingPrimaryPlatform;
replyBehavior?: "off" | "echo";
failureScenario?: "none" | "reject-send";
historyFixtureId?: string;
@@ -10,6 +13,7 @@ export type TestingConfigurationField =
| "profile.name"
| "profile.status"
| "accountType"
+ | "primaryPlatform"
| "replyBehavior"
| "failureScenario"
| "historyFixtureId";
@@ -151,3 +155,18 @@ export interface UnlinkTestingPhoneDeviceResponse {
deviceId: number;
unlinked: true;
}
+
+export type TestingPrimaryPlatform = "android" | "ios";
+export type TestingAccountModeRequest =
+ | { accountType: "meta_cloud"; primaryPlatform?: never }
+ | {
+ accountType: Exclude;
+ primaryPlatform?: TestingPrimaryPlatform;
+ };
+export interface TestingAccountMode {
+ session: string;
+ accountType: WhatsAppAccountType;
+ primaryPlatform: TestingPrimaryPlatform | null;
+ changed: boolean;
+ unlinkedDevices: number[];
+}
diff --git a/packages/typescript/src/messaging/types.ts b/packages/typescript/src/messaging/types.ts
index 635ba8ee0..821290a21 100644
--- a/packages/typescript/src/messaging/types.ts
+++ b/packages/typescript/src/messaging/types.ts
@@ -792,7 +792,10 @@ export interface BusinessProfileHours {
readonly closeTime: string;
}
+export type ContactEncryption = "end_to_end" | "hybrid" | "not_end_to_end";
+
export interface BusinessProfile extends ConversationIdentity {
+ readonly encryption?: ContactEncryption;
readonly address: string;
readonly email: string;
readonly description: string;
diff --git a/packages/typescript/test/business-account-modes.test.ts b/packages/typescript/test/business-account-modes.test.ts
new file mode 100644
index 000000000..f89135286
--- /dev/null
+++ b/packages/typescript/test/business-account-modes.test.ts
@@ -0,0 +1,233 @@
+import { expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import {
+ MessagingClient,
+ PolymorfaConfigurationError,
+ PolymorfaConflictError,
+ PolymorfaValidationError,
+ type TestingAccountModeRequest,
+ type ContactEncryption,
+} from "../src/index.js";
+import { TEAM_API_KEY } from "./support/credentials.js";
+
+function fixture(
+ body: unknown,
+ credential: "apiKey" | "clientToken" = "apiKey",
+) {
+ const fetch = vi.fn(
+ async () =>
+ new Response(JSON.stringify(body), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const client = new MessagingClient({
+ baseUrl: "https://api.example",
+ fetch,
+ credential:
+ credential === "apiKey"
+ ? { type: "apiKey", value: TEAM_API_KEY }
+ : { type: "clientToken", value: "pmfa_ct_YnJvd3Nlcg" },
+ });
+ return { client, fetch };
+}
+
+it.each([
+ "whatsapp_app",
+ "business_app",
+ "meta_cloud",
+ "meta_coexistence",
+] as const)(
+ "sends the exact %s mode to the pinned operation",
+ async (accountType) => {
+ const body = {
+ session: "test /a",
+ accountType,
+ primaryPlatform: accountType === "meta_cloud" ? null : "android",
+ changed: true,
+ unlinkedDevices: [3, 7],
+ };
+ const f = fixture(body);
+ const result = await f.client.testing.setAccountMode("test /a", {
+ accountType,
+ });
+ expect(result.data).toEqual(body);
+ const [url, init] = f.fetch.mock.calls[0]!;
+ expect(String(url)).toBe(
+ "https://api.example/messaging/test%20%2Fa/phone/account-mode",
+ );
+ expect(init?.method).toBe("PUT");
+ expect(JSON.parse(String(init?.body))).toEqual({ accountType });
+ const contract = JSON.parse(
+ readFileSync(
+ new URL(
+ "../../../contracts/business-account-modes.json",
+ import.meta.url,
+ ),
+ "utf8",
+ ),
+ );
+ expect(
+ contract.sources.messaging.paths[
+ "/messaging/{session}/phone/account-mode"
+ ].put.operationId,
+ ).toBe("setTestingAccountMode");
+ },
+);
+
+it("preserves an explicit phone platform and a completed no-op", async () => {
+ const body = {
+ session: "demo",
+ accountType: "business_app",
+ primaryPlatform: "ios",
+ changed: false,
+ unlinkedDevices: [],
+ };
+ const f = fixture(body);
+ expect(
+ (
+ await f.client.testing.setAccountMode("demo", {
+ accountType: "business_app",
+ primaryPlatform: "ios",
+ })
+ ).data,
+ ).toEqual(body);
+ expect(JSON.parse(String(f.fetch.mock.calls[0]![1]?.body))).toEqual({
+ accountType: "business_app",
+ primaryPlatform: "ios",
+ });
+});
+
+it.each([
+ { accountType: "personal" },
+ { accountType: "business" },
+ { accountType: "future" },
+ {},
+ { accountType: "meta_cloud", primaryPlatform: "android" },
+ { accountType: "business_app", primaryPlatform: null },
+ { accountType: "business_app", primaryPlatform: "web" },
+ { accountType: "business_app", extra: true },
+])("rejects invalid mode %j before transport", (input) => {
+ const f = fixture({});
+ expect(() =>
+ f.client.testing.setAccountMode("demo", input as TestingAccountModeRequest),
+ ).toThrow(PolymorfaValidationError);
+ expect(f.fetch).not.toHaveBeenCalled();
+});
+
+it("refuses a client token without sending a request", () => {
+ const f = fixture({}, "clientToken");
+ expect(() =>
+ f.client.testing.setAccountMode("demo", { accountType: "business_app" }),
+ ).toThrow(PolymorfaConfigurationError);
+ expect(f.fetch).not.toHaveBeenCalled();
+});
+
+it("rejects malformed result types", async () => {
+ const f = fixture({
+ session: "demo",
+ accountType: "business_app",
+ primaryPlatform: "android",
+ changed: "false",
+ unlinkedDevices: [],
+ });
+ await expect(
+ f.client.testing.setAccountMode("demo", { accountType: "business_app" }),
+ ).rejects.toMatchObject({ code: "invalid_response" });
+});
+
+it.each([
+ "end_to_end",
+ "hybrid",
+ "not_end_to_end",
+] satisfies ContactEncryption[])(
+ "preserves the optional encryption value %s",
+ async (encryption) => {
+ const f = fixture({ success: true, data: { id: "contact", encryption } });
+ const response = await f.client.contacts.businessProfile("demo", "contact");
+ expect(response.data.data.encryption).toBe(encryption);
+ },
+);
+
+it("does not invent encryption when the runtime omitted it", async () => {
+ const f = fixture({ success: true, data: { id: "contact" } });
+ expect(
+ (await f.client.contacts.businessProfile("demo", "contact")).data.data,
+ ).not.toHaveProperty("encryption");
+});
+
+it("sends QuickLink testing mode and platform without dropping simulation fields", async () => {
+ const f = fixture({
+ success: true,
+ data: {
+ id: "ql",
+ url: "https://example.test/ql",
+ session: "demo",
+ expiresAt: null,
+ },
+ });
+ const configuration = {
+ testing: {
+ configuration: {
+ accountType: "business_app" as const,
+ primaryPlatform: "ios" as const,
+ replyBehavior: "echo" as const,
+ },
+ },
+ };
+ await f.client.quickLinks.create({ configuration });
+ expect(JSON.parse(String(f.fetch.mock.calls[0]![1]?.body))).toEqual({
+ configuration,
+ });
+});
+it("rejects legacy QuickLink modes and cloud phone platforms before I/O", async () => {
+ for (const mode of [
+ { accountType: "business" },
+ { accountType: "meta_cloud", primaryPlatform: "ios" },
+ ]) {
+ const f = fixture({});
+ expect(() =>
+ f.client.quickLinks.create({
+ configuration: { testing: { configuration: mode } },
+ } as never),
+ ).toThrow(PolymorfaValidationError);
+ expect(f.fetch).not.toHaveBeenCalled();
+ }
+});
+
+it.each(["", "x".repeat(257)])(
+ "refuses an invalid session length before transport",
+ (session) => {
+ const f = fixture({});
+ expect(() =>
+ f.client.testing.setAccountMode(session, { accountType: "business_app" }),
+ ).toThrow();
+ expect(f.fetch).not.toHaveBeenCalled();
+ },
+);
+
+it("surfaces a 409 account-mode conflict as a typed conflict error", async () => {
+ const fetch = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ error: {
+ type: "conflict_error",
+ code: "state_conflict",
+ message: "The request conflicts with the resource state.",
+ param: null,
+ request_id: "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30",
+ },
+ data: null,
+ }),
+ { status: 409, headers: { "content-type": "application/json" } },
+ ),
+ );
+ const client = new MessagingClient({
+ baseUrl: "https://api.example",
+ fetch,
+ credential: { type: "apiKey", value: TEAM_API_KEY },
+ });
+ await expect(
+ client.testing.setAccountMode("demo", { accountType: "business_app" }),
+ ).rejects.toBeInstanceOf(PolymorfaConflictError);
+});
diff --git a/packages/typescript/test/package.test.ts b/packages/typescript/test/package.test.ts
index bd3335f7c..5442b0964 100644
--- a/packages/typescript/test/package.test.ts
+++ b/packages/typescript/test/package.test.ts
@@ -91,6 +91,12 @@ describe("npm package", () => {
consumer,
[
'import * as sdk from "@polymorfa/sdk";',
+ 'import assert from "node:assert/strict";',
+ 'import { createServer } from "node:http";',
+ 'let modeRequest; const server = createServer(async (req,res) => { let body=""; for await (const part of req) body += part; modeRequest={method:req.method,path:req.url,body:JSON.parse(body)}; res.writeHead(200,{"content-type":"application/json"}); res.end(JSON.stringify({session:"demo/a",accountType:"business_app",primaryPlatform:"ios",changed:false,unlinkedDevices:[]})); });',
+ 'await new Promise(resolve => server.listen(0,"127.0.0.1",resolve));',
+ 'try { const client = new sdk.MessagingClient({credential:{type:"apiKey",value:"pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k"},baseUrl:`http://127.0.0.1:${server.address().port}`}); const result=await client.testing.setAccountMode("demo/a",{accountType:"business_app",primaryPlatform:"ios"}); assert.equal(result.data.changed,false); assert.deepEqual(modeRequest,{method:"PUT",path:"/messaging/demo%2Fa/phone/account-mode",body:{accountType:"business_app",primaryPlatform:"ios"}}); } finally { await new Promise(resolve => server.close(resolve)); }',
+
"const { MessagingClient, Client, SystemClient, BridgeClient, PRESENCE_STATES, PRIVACY_SETTING_VALUES, SDK_VERSION, webhooks } = sdk;",
'const messaging = new MessagingClient({ credential: { type: "apiKey", value: "pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k" } });',
'const platform = new Client({ credential: { type: "teamApiKey", value: "pmfa_AAECAwQFBgcICQoLDA0ODxAREhM73f-k" } });',
diff --git a/scripts/check-business-account-modes.mjs b/scripts/check-business-account-modes.mjs
new file mode 100644
index 000000000..c9be176ee
--- /dev/null
+++ b/scripts/check-business-account-modes.mjs
@@ -0,0 +1,139 @@
+// Source attribution only. Native execution and release acceptance are separate gates.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+const root = resolve(import.meta.dirname, "..");
+const json = (file) => JSON.parse(readFileSync(resolve(root, file), "utf8"));
+const text = (file) => readFileSync(resolve(root, file), "utf8");
+export function checkBusinessAccountModes({
+ json: load = json,
+ text: read = text,
+} = {}) {
+ const json = load;
+ const text = read;
+ const pin = json("contracts/business-account-modes.json");
+ const inventory = json("contracts/native-business-account-modes.json");
+ const languages = ["typescript", "go", "python", "php", "rust", "dotnet"];
+ assert.match(pin.commit, /^[a-f0-9]{40}$/);
+ assert.match(pin.sources.messaging.sourceSha256, /^[a-f0-9]{64}$/);
+ assert.equal(pin.releaseStatus, "source-only");
+ assert.equal(inventory.sourceCommit, pin.commit);
+ assert.equal(inventory.published, false);
+ assert.equal(inventory.baselineUnchanged, true);
+ assert.equal(
+ json("contracts/source.json").commit,
+ "f180dc1ee2bd45dbecf01702f73bdd75c664634b",
+ );
+ const schemas = pin.sources.messaging.components.schemas;
+ assert.deepEqual(
+ schemas.TestingAccountModeRequest.properties.accountType.enum,
+ ["whatsapp_app", "business_app", "meta_cloud", "meta_coexistence"],
+ );
+ assert.deepEqual(
+ schemas.TestingAccountModeRequest.properties.primaryPlatform.enum,
+ ["android", "ios"],
+ );
+ assert.ok(schemas.TestingAccountModeRequest.required.includes("accountType"));
+ assert.deepEqual(schemas.BusinessProfile.properties.encryption.enum, [
+ "end_to_end",
+ "hybrid",
+ "not_end_to_end",
+ ]);
+ assert.ok(!schemas.BusinessProfile.required.includes("encryption"));
+ assert.equal(inventory.operations.length, 1);
+ assert.equal(inventory.operations[0].operationId, "setTestingAccountMode");
+ assert.equal(inventory.operations[0].method, "PUT");
+ assert.equal(
+ inventory.operations[0].path,
+ "/messaging/{session}/phone/account-mode",
+ );
+ for (const operation of inventory.operations) {
+ assert.equal(
+ pin.sources.messaging.paths[operation.path][
+ operation.method.toLowerCase()
+ ].operationId,
+ operation.operationId,
+ );
+ assert.deepEqual(
+ Object.keys(operation.languages).sort(),
+ [...languages].sort(),
+ );
+ for (const language of languages) {
+ const entry = operation.languages[language];
+ assert.ok(entry.method.length);
+ const test = text(`packages/${language}/${entry.test}`);
+ assert.ok(
+ test.includes("account-mode"),
+ language + " is missing a native wire fixture",
+ );
+ if (language !== "typescript")
+ assert.equal(
+ json(`packages/${language}/coverage.json`).supplements
+ .businessAccountModes.language,
+ language,
+ );
+ }
+ }
+ const fieldGroups = inventory.fields ?? {};
+ assert.deepEqual(Object.keys(fieldGroups).sort(), [
+ "businessProfileEncryption",
+ "quickLinkTesting",
+ ]);
+ const operationIds = new Set(
+ Object.values(pin.sources.messaging.paths).flatMap((methods) =>
+ Object.values(methods).map((operation) => operation.operationId),
+ ),
+ );
+ const quickLink = fieldGroups.quickLinkTesting;
+ assert.ok(operationIds.has(quickLink.operationId));
+ assert.equal(
+ quickLink.operationId,
+ "createQuickLink",
+ "QuickLink testing fields belong to createQuickLink",
+ );
+ assert.deepEqual(quickLink.fields, ["accountType", "primaryPlatform"]);
+ const testingFields =
+ schemas.QuickLinkConfiguration.properties.testing.properties.configuration
+ .properties;
+ for (const field of quickLink.fields)
+ assert.ok(
+ testingFields[field],
+ `QuickLink testing field ${field} is not pinned`,
+ );
+ const encryption = fieldGroups.businessProfileEncryption;
+ assert.ok(operationIds.has(encryption.operationId));
+ assert.equal(
+ encryption.operationId,
+ "getBusinessProfile",
+ "Business profile encryption belongs to getBusinessProfile",
+ );
+ assert.equal(encryption.optional, true);
+ assert.deepEqual(
+ encryption.enum,
+ schemas.BusinessProfile.properties.encryption.enum,
+ );
+ for (const [group, needles] of [
+ [quickLink, quickLink.fields],
+ [encryption, ["encryption"]],
+ ])
+ for (const language of languages) {
+ const entry = group.languages?.[language];
+ assert.ok(entry?.test, `${language} is missing field evidence`);
+ const source = text(`packages/${language}/${entry.test}`);
+ for (const needle of needles)
+ assert.ok(
+ source.includes(needle),
+ `${language} evidence does not cover ${needle}`,
+ );
+ }
+ assert.equal(
+ json("contracts/coverage.json").supplements.businessAccountModes.inventory,
+ "contracts/native-business-account-modes.json",
+ );
+ console.log(
+ "Business supplement: one operation, QuickLink mode/platform and optional encryption fields attributed across six SDKs; baseline unchanged.",
+ );
+}
+if (process.argv[1] === fileURLToPath(import.meta.url))
+ checkBusinessAccountModes();
diff --git a/scripts/check-business-account-modes.test.mjs b/scripts/check-business-account-modes.test.mjs
new file mode 100644
index 000000000..e2d9e9f65
--- /dev/null
+++ b/scripts/check-business-account-modes.test.mjs
@@ -0,0 +1,92 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { checkBusinessAccountModes } from "./check-business-account-modes.mjs";
+const root = resolve(import.meta.dirname, "..");
+const read = (file) => readFileSync(resolve(root, file), "utf8");
+const load = (file) => JSON.parse(read(file));
+function run(edit = () => {}, evidence = (_file, source) => source) {
+ const cache = new Map();
+ const json = (file) => {
+ if (!cache.has(file)) cache.set(file, structuredClone(load(file)));
+ return cache.get(file);
+ };
+ edit(json);
+ return () =>
+ checkBusinessAccountModes({
+ json,
+ text: (file) => evidence(file, read(file)),
+ });
+}
+const inventory = "contracts/native-business-account-modes.json";
+const pin = "contracts/business-account-modes.json";
+test("accepts the committed field and operation attribution", () => {
+ assert.doesNotThrow(run());
+});
+test("fails when the field attribution is removed", () => {
+ assert.throws(run((json) => delete json(inventory).fields.quickLinkTesting));
+ assert.throws(
+ run((json) => delete json(inventory).fields.businessProfileEncryption),
+ );
+ assert.throws(run((json) => delete json(inventory).fields));
+});
+test("fails when a pinned schema property is removed", () => {
+ assert.throws(
+ run(
+ (json) =>
+ delete json(pin).sources.messaging.components.schemas
+ .QuickLinkConfiguration.properties.testing.properties.configuration
+ .properties.primaryPlatform,
+ ),
+ );
+ assert.throws(
+ run(
+ (json) =>
+ delete json(pin).sources.messaging.components.schemas.BusinessProfile
+ .properties.encryption,
+ ),
+ );
+});
+test("fails when a language loses its field evidence", () => {
+ assert.throws(
+ run(undefined, (file, source) =>
+ file === "packages/go/business_account_modes_test.go"
+ ? source
+ .replaceAll("primaryPlatform", "x")
+ .replaceAll("encryption", "y")
+ : source,
+ ),
+ );
+ assert.throws(
+ run(
+ (json) => delete json(inventory).fields.quickLinkTesting.languages.rust,
+ ),
+ );
+});
+test("fails when the inventory names a different pinned operation", () => {
+ assert.throws(
+ run((json) => {
+ const operation = json(inventory).operations[0];
+ operation.operationId = "createQuickLink";
+ operation.method = "POST";
+ operation.path = Object.entries(json(pin).sources.messaging.paths).find(
+ ([, item]) => item.post?.operationId === "createQuickLink",
+ )[0];
+ }),
+ );
+});
+test("fails when a field group names another pinned operation", () => {
+ assert.throws(
+ run((json) => {
+ json(inventory).fields.quickLinkTesting.operationId =
+ "setTestingAccountMode";
+ }),
+ );
+ assert.throws(
+ run((json) => {
+ json(inventory).fields.businessProfileEncryption.operationId =
+ "createQuickLink";
+ }),
+ );
+});
diff --git a/scripts/check-native-coverage.mjs b/scripts/check-native-coverage.mjs
index d933b390d..08814fa01 100644
--- a/scripts/check-native-coverage.mjs
+++ b/scripts/check-native-coverage.mjs
@@ -1,3 +1,4 @@
+import { checkBusinessAccountModes } from "./check-business-account-modes.mjs";
import "./check-calls-simultaneous-calls.mjs";
import { checkOfficialRound2 } from "./check-official-round2.mjs";
import assert from "node:assert/strict";
@@ -92,6 +93,7 @@ if (!requested) {
if (!requested) checkOfficialRound2();
+if (!requested) checkBusinessAccountModes();
const interactive = checkInteractiveSupplement(root);
console.log(
`Interactive supplement: ${interactive.fields} pinned field groups and ${interactive.wireGroups} wire groups attributed in ${interactive.languages} languages; execution and publication remain separate.`,
diff --git a/scripts/doc-snippets/recipes.mjs b/scripts/doc-snippets/recipes.mjs
index e3b822d66..79fbda440 100644
--- a/scripts/doc-snippets/recipes.mjs
+++ b/scripts/doc-snippets/recipes.mjs
@@ -1,7 +1,7 @@
// Requests come from the pinned OpenAPI and existing native wire fixtures.
// Calls are handwritten in the language modules. Never derive arguments from
// contracts/coverage.json's display-only method names.
-export const sourceCommit = "641230d38744d862cbf66ae3af56fbfb203e1e73";
+export const sourceCommit = "44add8e5f4a10124df5b60bd6862f4e721305b88";
export const apiVersion = "2026-09-22";
export const languages = [
"typescript",
diff --git a/scripts/sync-business-account-modes.mjs b/scripts/sync-business-account-modes.mjs
new file mode 100644
index 000000000..200403dbd
--- /dev/null
+++ b/scripts/sync-business-account-modes.mjs
@@ -0,0 +1,102 @@
+import { format, resolveConfig } from "prettier";
+import { createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+import { readFileSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const operations = [
+ "setTestingAccountMode",
+ "createQuickLink",
+ "getBusinessProfile",
+];
+const sourcePath = "apps/api/docs/openapi.json";
+const output = resolve(
+ import.meta.dirname,
+ "../contracts/business-account-modes.json",
+);
+
+export function extractBusinessContract(raw, commit) {
+ if (!/^[a-f0-9]{40}$/.test(commit))
+ throw new Error("An exact API commit is required");
+ const document = JSON.parse(raw);
+ const paths = {};
+ const found = new Set();
+ for (const [path, methods] of Object.entries(document.paths)) {
+ for (const [method, operation] of Object.entries(methods)) {
+ if (!operations.includes(operation?.operationId)) continue;
+ if (found.has(operation.operationId))
+ throw new Error("Duplicate operationId");
+ found.add(operation.operationId);
+ (paths[path] ??= {})[method] = operation;
+ }
+ }
+ if (found.size !== operations.length)
+ throw new Error("Business contract operations are missing");
+ const components = {};
+ const visited = new Set();
+ function visit(value) {
+ if (!value || typeof value !== "object") return;
+ if (typeof value.$ref === "string") {
+ const match = /^#\/components\/([^/]+)\/([^/]+)$/.exec(value.$ref);
+ if (!match) throw new Error(`Unsupported reference ${value.$ref}`);
+ if (!visited.has(value.$ref)) {
+ visited.add(value.$ref);
+ const target = document.components?.[match[1]]?.[match[2]];
+ if (!target) throw new Error(`Missing reference ${value.$ref}`);
+ (components[match[1]] ??= {})[match[2]] = target;
+ visit(target);
+ }
+ }
+ for (const nested of Object.values(value)) visit(nested);
+ }
+ visit(paths);
+ return {
+ repository: "polymorfa/polymorfa",
+ commit,
+ releaseStatus: "source-only",
+ sources: {
+ messaging: {
+ sourcePath,
+ sourceSha256: createHash("sha256").update(raw).digest("hex"),
+ paths,
+ components,
+ },
+ },
+ };
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const args = process.argv.slice(2);
+ const apiRoot = args[args.indexOf("--api-root") + 1];
+ const commit = args[args.indexOf("--commit") + 1];
+ if (
+ !args.includes("--api-root") ||
+ !args.includes("--commit") ||
+ !apiRoot ||
+ !commit
+ )
+ throw new Error(
+ "Use --api-root --commit [--check]",
+ );
+ if (!/^[a-f0-9]{40}$/.test(commit))
+ throw new Error("An exact API commit is required");
+ const head = execFileSync("git", ["-C", apiRoot, "rev-parse", "HEAD"], {
+ encoding: "utf8",
+ }).trim();
+ if (head !== commit)
+ throw new Error("API source HEAD does not match the requested commit");
+ const raw = execFileSync(
+ "git",
+ ["-C", apiRoot, "show", `${commit}:${sourcePath}`],
+ { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 },
+ );
+ const bytes = await format(
+ JSON.stringify(extractBusinessContract(raw, commit)),
+ { ...(await resolveConfig(output)), filepath: output },
+ );
+ if (args.includes("--check")) {
+ if (readFileSync(output, "utf8") !== bytes)
+ throw new Error("Business contract drifted");
+ } else writeFileSync(output, bytes);
+}
diff --git a/scripts/sync-business-account-modes.test.mjs b/scripts/sync-business-account-modes.test.mjs
new file mode 100644
index 000000000..338ac07f9
--- /dev/null
+++ b/scripts/sync-business-account-modes.test.mjs
@@ -0,0 +1,81 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { extractBusinessContract } from "./sync-business-account-modes.mjs";
+const sha = "a".repeat(40);
+function fixture() {
+ return {
+ paths: {
+ "/mode": {
+ put: {
+ operationId: "setTestingAccountMode",
+ responses: { 200: { $ref: "#/components/schemas/Mode" } },
+ },
+ },
+ "/links": { post: { operationId: "createQuickLink" } },
+ "/profile": { get: { operationId: "getBusinessProfile" } },
+ "/unrelated": { get: { operationId: "other" } },
+ },
+ components: {
+ schemas: {
+ Mode: {
+ type: "object",
+ properties: {
+ recursive: { $ref: "#/components/schemas/Mode" },
+ platform: { $ref: "#/components/schemas/Platform" },
+ },
+ },
+ Platform: { enum: ["android", "ios"] },
+ Unrelated: { type: "string" },
+ },
+ },
+ };
+}
+test("projects only the three bound operations and their transitive references", () => {
+ const c = extractBusinessContract(JSON.stringify(fixture()), sha);
+ assert.deepEqual(Object.keys(c.sources.messaging.paths), [
+ "/mode",
+ "/links",
+ "/profile",
+ ]);
+ assert.deepEqual(Object.keys(c.sources.messaging.components.schemas), [
+ "Mode",
+ "Platform",
+ ]);
+ assert.equal(c.commit, sha);
+ assert.equal(c.releaseStatus, "source-only");
+ assert.match(c.sources.messaging.sourceSha256, /^[a-f0-9]{64}$/);
+});
+test("fails closed on an incomplete operation set", () => {
+ const c = fixture();
+ delete c.paths["/mode"];
+ assert.throws(
+ () => extractBusinessContract(JSON.stringify(c), sha),
+ /missing/,
+ );
+});
+test("rejects ambiguous operation identities", () => {
+ const c = fixture();
+ c.paths["/other"] = { put: { operationId: "setTestingAccountMode" } };
+ assert.throws(
+ () => extractBusinessContract(JSON.stringify(c), sha),
+ /Duplicate/,
+ );
+});
+test("rejects an unresolvable or external reference", () => {
+ for (const ref of [
+ "#/components/schemas/Missing",
+ "https://example.test/schema",
+ ]) {
+ const c = fixture();
+ c.components.schemas.Mode.properties.recursive.$ref = ref;
+ assert.throws(
+ () => extractBusinessContract(JSON.stringify(c), sha),
+ /reference/,
+ );
+ }
+});
+test("requires an immutable full source commit", () =>
+ assert.throws(
+ () => extractBusinessContract(JSON.stringify(fixture()), "main"),
+ /exact/,
+ ));