AWP 1.x から 2.0 への移行
AWP 2.0 では 1.x の wire(仕様 3.5 §4.1)が置き換えられます。adk-awp は、1 回のリリース系列の間、デフォルトの awp-v1
feature の背後で 1.x の routes を引き続き提供するため、移行中も 1.x の deployment は変更なしで動作します。このページでは、各 1.x
element を 2.0 の対応する要素に対応付け、business.toml を変換し、引き続き 1.x を提供する deployment のために 1.x の reference を保持します。
注記: 3.0.0 における Rust API の 1.x types への変更(manifest 内の access levels と schemas、
AwpConfigError::Serialize、非推奨の HMAC helpers、HTTP 経由の event delivery)については、 2.x → 3.0 からの移行を参照してください。
変更点
| 領域 | AWP 1.x(awp-v1) | AWP 2.0 |
|---|---|---|
| 発見 | business.toml から構築された、version、siteName、URLs を備えた未署名の /.well-known/awp.json | プロファイル、鍵、すべてのサーフェスへのリンク、最新リリース、ステータス、チャーターダイジェストを含む、ルート署名済みの SiteContract |
| 信頼 | アプリケーションの TrustLevelAssigner によって割り当てられる Anonymous、Known、Partner、Internal。デフォルトではすべてのリクエスターを Anonymous にする | 検証済みの認証情報のみからなる public、known、verified、partner:Web Bot Auth、OAuth、mTLS、所有者が発行した API 鍵 |
| リクエスターの検出 | detect_requester_type(X-AWP-ChannelおよびUser-Agentから) | 分析用のラベル。ティアや上限が変わることはない |
| 機能 | アプリケーションが適用するaccessLevelメタデータを持つエンドポイント | エッジが適用する型付きのCapabilityV2:効果、ティア、スキーマ、同意、価格、承認、冪等性。A2A、MCP、HTTP上で提供される1つの宣言 |
| エージェントメッセージ | アプリケーションハンドラーへのPOST /awp/a2a。AwpTypedMessageカテゴリ | エッジ上のA2A v1.0。バックオフィスへの型付きシグナル |
| イベント | アプリケーションが認証する管理ルート上のサブスクリプション | Web Bot AuthまたはOAuthによって認証され、リクエスターを対象範囲とするサブスクリプション。72時間以内の再生。6回の失敗後に一時停止 |
| ヘルス | Healthy、Degrading、Degraded | 署名済みのSiteStatus:operational、degraded、read_only、maintenance、incident |
| 同意 | 訪問者と目的をキーとするConsentService | スコープとポリシーバージョンを含む署名済みConsentReceipt;失効、エクスポート、消去 |
| 支払い | PaymentIntentとPaymentPolicy。ワークスペース内のいかなるものもこれらを実行しない | adk-paymentsを介した処理と署名済みレシート |
| 所有者の設定 | business.toml、ホットリロード対応 | サイトデータ(site.toml、capabilities.json、public-terms.json)と所有者が署名する憲章 |
1. 1.x の稼働を維持する
変更しない限り何も変わりません。awp_routes(AwpState) は 1.x のルートを 1.x のパスで提供します。バージョン一覧がある場合、1.x のルートで AWP-Version: 2.0, 1.0 を要求するクライアントには 1.0 で応答し、共通するメジャーバージョンを指定しないリクエストには 406 が返されます。
2. business.toml を変換する
adk-rust awp migrate-config business.toml --out my-site
このコマンドは site.toml、capabilities.json、public-terms.json、charter.draft.json、および署名されていない contract.draft.json を書き込み、所有者が確認できるようすべての推論を一覧表示し、ファイルを上書きすることはありません(コマンドラインからのサイトと AWP)。内部では adk_awp::v2::migrate::migrate_config です。
| 1.x | 2.0 |
|---|---|
site_name、domain、business.languages | サイトのSiteRef |
[[capabilities]] | CapabilityV2:GET/HEAD → read_only、PUT/DELETE → idempotent、その他のメソッド → non_idempotent(確認用に記載);access_levelのティア;名前を^[a-z][a-z0-9_]{0,63}$に正規化;JSONスキーマの場合のみスキーマを保持 |
access_level = "internal" | 公開されない;警告に記載される |
[payments] auto_approve_threshold | non_idempotentの機能に対するabove_amountの承認;それなしではalways |
site_description、brand_voice、business.currency、contact、outreach、payments | 草案憲章の使命、文体、予算通貨、連絡先リンク、同意スコープ |
ドメイン、[[products]]、[payments] | サイトの種類:公共部門のドメインはgovernment、製品または支払いを扱うものはecommerce、その他はbusiness |
結果はドラフトです。チャーターは所有者のいないバージョン 0 であり、契約は未署名で、公開用の規約で名前を付ける前に、ポリシーには URL とバージョンが必要です。
[dependencies]
adk-awp = "3.0.0"
awp-types = "3.0.0"
uuid = "1"
use adk_awp::v2::migrate::migrate_config;
use awp_types::{BusinessCapability, BusinessContext, CapabilityEffect, SiteKind, TrustLevel};
use uuid::Uuid;
fn convert() {
let mut ctx = BusinessContext::core("Example Solar", "Solar for Nairobi homes", "example.com");
ctx.capabilities = vec![BusinessCapability {
name: "place-order".into(),
description: "Place an order".into(),
endpoint: "/api/orders".into(),
method: "POST".into(),
access_level: TrustLevel::Known,
input_schema: None,
output_schema: None,
}];
let migration = migrate_config(&ctx, Uuid::nil());
assert_eq!(migration.capabilities[0].name, "place_order");
assert_eq!(migration.capabilities[0].effect, CapabilityEffect::NonIdempotent);
assert_eq!(migration.charter.kind, SiteKind::Business);
for warning in &migration.warnings {
println!("confirm: {warning}");
}
}
3. Serve 2.0
変換済みファイルからサイトとそのエッジを構築します。コンテンツとリリースは
adk-rust site で、機能はエージェント
エッジ上で、それぞれのハンドラー(機能
パックの作成)とともに構築し、キーは adk-rust awp keys rotate と
delegate で構築します。オンボーディングで推論を確認し、所有者がチャーターに署名します
(チャーター)。adk-rust awp verify <domain> が結果を検査します。
4. 1.x を停止する
1.x のルートを必要とするクライアントがなくなったら、デフォルト機能なしで adk-awp をビルドします。
[dependencies]
adk-awp = { version = "3.0.0", default-features = false, features = ["signing"] }
AWP 1.x リファレンス
それを保持するデプロイメント向けに、awp-v1 が提供するものです。
1.x ルートの提供
use std::sync::Arc;
use adk_awp::{AwpA2aHandler, AwpState, BusinessContextLoader, awp_routes};
use async_trait::async_trait;
use awp_types::AwpError;
use axum::http::{HeaderMap, header};
use serde_json::{Value, json};
struct ApplicationA2a {
bearer_token: Arc<str>,
}
#[async_trait]
impl AwpA2aHandler for ApplicationA2a {
async fn handle(&self, headers: HeaderMap, message: Value) -> Result<Value, AwpError> {
let expected = format!("Bearer {}", self.bearer_token);
let authorized = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value == expected);
if !authorized {
return Err(AwpError::Unauthorized("invalid A2A credential".to_string()));
}
// Authorize the requested capability and dispatch to the application agent.
Ok(json!({ "status": "processed", "messageId": message["id"] }))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let loader = BusinessContextLoader::from_file("business.toml".as_ref())?;
let a2a_token: Arc<str> = std::env::var("AWP_A2A_TOKEN")?.into();
let state = AwpState::builder(loader.context_ref())
.a2a_handler(Arc::new(ApplicationA2a { bearer_token: a2a_token }))
.build();
let app = axum::Router::new().merge(awp_routes(state));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3456").await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
)
.await?;
Ok(())
}
AwpA2aHandler がない場合、POST /awp/a2a は 503 を返し、ディスパッチされていない作業を承認することはありません。ConnectInfo は匿名のレート制限バケットを分離するピアアドレスを提供します。これがない場合、未知の呼び出し元は1つのバケットを共有します。
BusinessContextLoader は ArcSwap を通じて business.toml を再読み込みします。
use adk_awp::BusinessContextLoader;
async fn hot_reload() -> Result<(), Box<dyn std::error::Error>> {
let loader = BusinessContextLoader::from_file("business.toml".as_ref())?;
loader.watch("business.toml".into()).await?;
// Changes to business.toml are picked up every 5 seconds.
Ok(())
}
すべての 1.x ルートはバージョンをネゴシエートします。クライアントは AWP-Version: 1.1、または
2.0, 1.0 のようなリストを送信できます。リストにメジャーバージョン 1 が含まれるリクエストは処理が続行され、そのレスポンスには AWP-Version: 1.0 が含まれます。メジャーバージョン 1 を指定しないリクエストは 406 version_mismatch を受け取り、不正な値は 400 となります。
| メソッド | パス | 説明 |
|---|---|---|
| GET | /.well-known/awp.json | business.toml から生成されたディスカバリードキュメント |
| GET | /awp/manifest | JSON-LD capability マニフェスト。各エントリには accessLevel と、そのオプションのスキーマが含まれます |
| GET | /awp/health | ヘルス状態 |
| POST | /awp/a2a | アプリケーション提供のA2Aディスパッチ、64 KiBボディ制限 |
awp_management_routes()は認証レイヤーなしでサブスクリプション管理を返します。マージする前にアプリケーションの認証ミドルウェアを適用してください:
| メソッド | パス | 説明 |
|---|---|---|
| POST | /awp/events/subscribe | Webhook サブスクリプションを作成 |
| GET | /awp/events/subscriptions | サブスクリプションを一覧表示(シークレットは返されません) |
| 削除 | /awp/events/subscriptions/{id} | サブスクリプションを削除 |
/.well-known/awp.json のディスカバリードキュメントは business.toml から生成されます。
{
"version": { "major": 1, "minor": 0 },
"siteName": "My Shop",
"siteDescription": "An online store powered by AWP",
"capabilityManifestUrl": "https://myshop.example.com/awp/manifest",
"a2aEndpointUrl": "https://myshop.example.com/awp/a2a",
"eventsEndpointUrl": "https://myshop.example.com/awp/events/subscribe",
"healthEndpointUrl": "https://myshop.example.com/awp/health",
"supportedTrustLevels": ["anonymous"]
}
/awp/manifest のマニフェストは JSON-LD です。
{
"@context": "https://schema.org",
"@type": "WebAPI",
"name": "My Shop",
"description": "An online store powered by AWP",
"capabilities": [
{
"name": "place_order",
"description": "Place an order",
"endpoint": "/api/orders",
"method": "POST",
"accessLevel": "known",
"inputSchema": "OrderInput",
"outputSchema": "OrderReceipt"
}
]
}
business.toml
| セクション | フィールド | 必須 |
|---|---|---|
| (ルート) | site_name, site_description, domain, contact | はい(contactを除く) |
[business] | name, country, languages, currency, timezone | いいえ |
[brand_voice] | tone, greeting, escalation_message | いいえ |
[[products]] | sku, name, price, inventory, tags, description | いいえ |
[[capabilities]] | name, description, endpoint, method, access_level; 任意の input_schema, output_schema | はい |
[[policies]] | name, description, policy_type | はい |
[channels] | whatsapp, email, website, sms | いいえ |
[payments] | providers, auto_approve_threshold, require_approval_threshold | いいえ |
[support] | escalation_contacts, hours, sla | いいえ |
[content] | topics, auto_draft, publish_delay | いいえ |
[reviews] | platforms、auto_respond_threshold | いいえ |
[outreach] | follow_up_delay、require_consent | いいえ |
信頼レベルとレート制限
| レベル | 割り当て方法 | デフォルトの制限 |
|---|---|---|
Anonymous | 認証情報なし。すべてのリクエストは DefaultTrustAssigner の下で実行 | 30 リクエスト/分 |
Known | 呼び出し元を検証したカスタム TrustLevelAssigner | 120 リクエスト/分 |
Partner | カスタム割り当て機能 | 600 リクエスト/分 |
Internal | カスタム割り当て機能 | 無制限 |
アクセスレベルはマニフェストのメタデータであり、アプリケーションハンドラーがそれを適用します。デプロイメントで検証できるレベルのみをディスカバリーで通知するよう、.supported_trust_levels(...) を設定してください。
InMemoryRateLimiter は信頼レベルごとにスライディングウィンドウを保持します。拒否されたリクエストには 429 と Retry-After が返されます。
use std::collections::HashMap;
use adk_awp::{InMemoryRateLimiter, RateLimitConfig};
use awp_types::TrustLevel;
fn limiter() -> InMemoryRateLimiter {
let mut limits = HashMap::new();
limits.insert(TrustLevel::Anonymous, RateLimitConfig { max_requests: 10, window_secs: 60 });
limits.insert(TrustLevel::Known, RateLimitConfig { max_requests: 100, window_secs: 60 });
InMemoryRateLimiter::with_config(limits)
}
use std::sync::Arc;
use adk_awp::TrustLevelAssigner;
use async_trait::async_trait;
use awp_types::TrustLevel;
use axum::http::{HeaderMap, header};
struct MyTrustAssigner {
bearer_token: Arc<str>,
}
#[async_trait]
impl TrustLevelAssigner for MyTrustAssigner {
async fn assign(&self, headers: &HeaderMap) -> TrustLevel {
let expected = format!("Bearer {}", self.bearer_token);
if headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value == expected)
{
TrustLevel::Known
} else {
TrustLevel::Anonymous
}
}
}
イベント、ヘルス、同意
サブスクリプション管理は特権サーフェスです。認証の背後に awp_management_routes() をマウントしてください。コールバック URLs は絶対 HTTPS URLs でなければならず、ループバック、プライベート、またはリンクローカルアドレスを指定してはなりません。また、署名シークレットには 32~4096 バイトを含める必要があります。
# Subscribe — answers 201 with {"id": "..."}
curl -X POST http://localhost:3456/awp/events/subscribe \
-H "Authorization: Bearer $AWP_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"subscriber": "my-agent",
"callbackUrl": "https://my-agent.example/webhook",
"eventTypes": ["health.changed"],
"secret": "replace-with-at-least-32-random-bytes"
}'
デフォルトの InMemoryEventSubscriptionService はサブスクリプションをメモリ内に保持し、一致する各イベントを adk_core::webhook_delivery::WebhookDelivery 経由で配信します。
- 各配信には Standard Webhooks ヘッダー(
webhook-id、webhook-timestamp、webhook-signature)が含まれ、サブスクリプションシークレットのバイト列をキーとして署名されます。イベント ID はwebhook-idです。 - 失敗した配信は指数バックオフとジッターを使用して再試行され、最後の試行後にデッドレター化されます。リダイレクトには従いません。
- エグレスポリシーは、サブスクリプション時とホスト名の解決時に再度、プレーンな HTTP、ループバック、プライベート、およびリンクローカルの宛先を拒否します。
deliverは配信を開始して直ちに戻ります。deliver_and_waitはサブスクリプションごとにDeliveryReportを返します。with_deliveryは再試行ポリシー、デッドレターシンク、またはエグレスポリシーを設定します。
永続ストレージには EventSubscriptionService を実装してください。受信側は adk_core::webhook::WebhookVerifier(機能 webhooks)を使用して配信を検証します。
use adk_core::webhook::{WebhookHeaders, WebhookSecret, WebhookVerifier};
fn verify(
secret: &str,
id: &str,
timestamp: &str,
signature: &str,
body: &[u8],
) -> Result<(), adk_core::webhook::WebhookError> {
let verifier = WebhookVerifier::new(WebhookSecret::from_bytes(secret.as_bytes().to_vec())?);
let headers = WebhookHeaders { id, timestamp: timestamp.into(), signature };
verifier.verify(&headers, body)?;
Ok(())
}
以前の sha256=<hex_digest> HMAC ペアである adk_awp::sign_payload と verify_signature は非推奨です。組み込みサービスはこの形式を送信しなくなりました。
HealthStateMachine は、検証済みの遷移(Healthy → Degrading、
Degrading → Degraded、Degrading または Degraded → Healthy)により /awp/health を追跡し、
一致するサブスクライバーに health.changed を発行します。それ以外の遷移では AwpError::InvalidRequest を返します。
use std::sync::Arc;
use adk_awp::{HealthStateMachine, InMemoryEventSubscriptionService};
async fn health() -> Result<(), awp_types::AwpError> {
let health = HealthStateMachine::new(Arc::new(InMemoryEventSubscriptionService::new()));
health.report_degrading("database latency high").await?;
health.report_degraded("database unreachable").await?;
health.report_healthy().await?;
Ok(())
}
ConsentService には、メモリ内実装とファイルベース(FileConsentService)実装があります。
FileConsentService は変更ごとに同期済みの一時ファイルへ書き込み、ブロッキングスレッド上でそのファイルを
ターゲットへリネームするため、読み取り側やクラッシュによって不完全なファイルが見えることはありません。ストレージ実装を選択しても、規制への準拠が確立されるわけではありません。
use adk_awp::{ConsentService, InMemoryConsentService};
async fn consent() -> Result<(), awp_types::AwpError> {
let consent = InMemoryConsentService::new();
consent.capture_consent("visitor-123", "analytics").await?;
let granted = consent.check_consent("visitor-123", "analytics").await?;
assert!(granted);
consent.revoke_consent("visitor-123", "analytics").await?;
Ok(())
}
リクエスターの検出、メッセージ、支払いインテント
detect_requester_type は、X-AWP-Channel: agent に対して、または application/json、application/ld+json、application/awp+json のいずれかの
Accept と、エージェントの User-Agent パターン(bot、crawler、spider、agent、gpt、claude、gemini、
perplexity、anthropic、openai)の組み合わせに対して Agent を返します。それ以外の場合は Human です。これらはクレームであり、AWP 2.0 は分析用ラベルとしてのみ使用します。
AwpTypedMessage は、VisitorIntentSignal、ContentGapSignal、PaymentIntent、
SupportEscalation、ReviewSignal、OperationsProposal、InvokeCapability、RenderUi、または
OutboundTrigger のいずれかを保持します。
PaymentIntent は Draft → PendingApproval → Approved → Executing → Settled、Rejected、または
Cancelled へ遷移します。PaymentPolicy::evaluate は、min_trust_for_auto_approve 以上(デフォルトは Known)の呼び出し元からの、
auto_approve_threshold 以下(デフォルトは 5000 cents)の金額を自動承認し、それ以外のすべてについて承認を要求します。
require_approval_threshold(デフォルトは 50,000)はこの判断を変更しません。このワークスペース内のどのクレートも
PaymentIntent を実行しません。別のリポジトリである adk-gateway がそれを使用します。
1.x の例
awp_agentの例では、adk-playground にある business.toml を読み込み、それを基にエージェントを構築し、認証済みの A2A ディスパッチをインストールして、管理ルートを別の認証情報の背後にマウントし、すべてのエンドポイントを実行します。GOOGLE_API_KEY を読み取ります。