1use std::sync::Arc;
16
17use adk_auth::{ContextScopeResolver, ScopeGuard};
18use adk_core::principal::SubjectRef;
19use adk_core::{
20 AdkError, ApprovalScope, ErrorCategory, ErrorComponent, PolicyCall, PolicyDecision, Result,
21 Tool, ToolConfirmationDecision, ToolConfirmationRequest, ToolContext, ToolEffect, ToolGate,
22 ToolOrigin, ToolPolicyRequest,
23};
24use async_trait::async_trait;
25use serde::Deserialize;
26use serde_json::{Value, json};
27
28use super::engine::{PaymentRequest, Wallet, WalletCaller};
29use super::policy::{Payee, SpendCategory, category_name};
30use super::store::PaymentRecord;
31use crate::auth::PAYMENT_EXECUTE_SCOPES;
32
33pub const WALLET_PAY_TOOL: &str = "wallet_pay";
35pub const WALLET_STATUS_TOOL: &str = "wallet_status";
37
38#[derive(Debug, Deserialize)]
39#[serde(rename_all = "camelCase", deny_unknown_fields)]
40struct PayArgs {
41 category: SpendCategory,
42 payee: Payee,
43 amount: u64,
44 currency: String,
45 description: String,
46 #[serde(default)]
47 rail_data: Option<Value>,
48}
49
50fn parse_pay_args(args: Value) -> Result<PayArgs> {
51 serde_json::from_value(args).map_err(|error| {
52 AdkError::new(
53 ErrorComponent::Tool,
54 ErrorCategory::InvalidInput,
55 "wallet.tools.invalid_args",
56 format!(
57 "invalid arguments for `{WALLET_PAY_TOOL}`: {error}. It takes category, payee, \
58 amount, currency, description and railData only"
59 ),
60 )
61 })
62}
63
64fn settled_response(record: &PaymentRecord) -> Value {
65 json!({
66 "status": "settled",
67 "paymentId": record.id,
68 "category": category_name(record.category),
69 "payee": record.payee.id,
70 "amount": record.amount,
71 "currency": record.currency,
72 "ownerApproved": record.owner_approved(),
73 "proof": record.settlement.as_ref().and_then(|settlement| settlement.proof.clone()),
74 })
75}
76
77struct WalletPayTool {
78 wallet: Wallet,
79}
80
81impl WalletPayTool {
82 async fn on_held(
84 &self,
85 ctx: &Arc<dyn ToolContext>,
86 args: Value,
87 key: &str,
88 record: PaymentRecord,
89 caller: &WalletCaller,
90 ) -> Result<Value> {
91 let acting = ctx.acting_context();
92 let request = ToolConfirmationRequest {
93 tool_name: WALLET_PAY_TOOL.to_string(),
94 function_call_id: Some(ctx.function_call_id().to_string()),
95 args: args.clone(),
96 acting: Some(Box::new(acting.clone())),
97 origin: Some(ToolOrigin::of(self)),
98 evidence: Vec::new(),
99 };
100 let reason = record.hold.as_ref().map(ToString::to_string).unwrap_or_default();
101 if let Some(config) = ctx.run_config() {
102 let gate = ToolGate::new(
103 config,
104 ctx.agent_name(),
105 ctx.invocation_id(),
106 ApprovalScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id()),
107 )
108 .with_acting_context(acting.clone());
109 let why = format!(
110 "Tool '{WALLET_PAY_TOOL}' requires confirmation: payment held for the owner ({reason})"
111 );
112 if let Some(approval) = adk_core::confirm_tool_call(&gate, &request, &why).await? {
113 let subject =
114 acting.on_behalf_of.clone().unwrap_or_else(|| SubjectRef::human(ctx.user_id()));
115 return match approval.decision {
116 ToolConfirmationDecision::Deny => {
117 let record = self
118 .wallet
119 .decide_governed(&record.id, false, subject, approval.message, caller)
120 .await?;
121 Ok(json!({
122 "status": "rejected",
123 "paymentId": record.id,
124 "message": record.decision.and_then(|decision| decision.message),
125 }))
126 }
127 ToolConfirmationDecision::Approve => match approval.edited_args {
128 Some(edited) if edited != args => {
129 self.wallet
130 .decide_governed(
131 &record.id,
132 false,
133 subject.clone(),
134 Some("replaced by the approver's edited payment".to_string()),
135 caller,
136 )
137 .await?;
138 self.pay_edited(ctx, edited, key, subject, approval.message, caller)
139 .await
140 }
141 _ => {
142 let record = self
143 .wallet
144 .decide_governed(
145 &record.id,
146 true,
147 subject,
148 approval.message,
149 caller,
150 )
151 .await?;
152 Ok(settled_response(&record))
153 }
154 },
155 };
156 }
157 }
158 let mut actions = ctx.actions();
159 actions.tool_confirmation = Some(request);
160 ctx.set_actions(actions);
161 Ok(json!({
162 "status": "held",
163 "paymentId": record.id,
164 "reason": reason,
165 "message": "the payment waits for the owner's decision",
166 }))
167 }
168
169 async fn pay_edited(
172 &self,
173 ctx: &Arc<dyn ToolContext>,
174 edited: Value,
175 key: &str,
176 subject: SubjectRef,
177 message: Option<String>,
178 caller: &WalletCaller,
179 ) -> Result<Value> {
180 if let Some(policy) = ctx.run_config().and_then(|config| config.tool_policy.clone()) {
181 let request = ToolPolicyRequest::new(WALLET_PAY_TOOL, edited.clone())
182 .with_effect(self.effect())
183 .with_agent_name(ctx.agent_name())
184 .with_identity(ctx.app_name(), ctx.user_id(), ctx.session_id())
185 .with_invocation_id(ctx.invocation_id())
186 .with_acting_context(ctx.acting_context());
187 let origin = ToolOrigin::of(self);
188 let call = PolicyCall::new()
189 .with_origin(&origin)
190 .with_function_call_id(ctx.function_call_id());
191 if let PolicyDecision::Deny { reason } = policy.evaluate_call(&request, &call).await {
192 return Err(AdkError::new(
193 ErrorComponent::Tool,
194 ErrorCategory::Forbidden,
195 "wallet.tools.edited_args_denied",
196 format!("the approver's edited payment is denied by policy: {reason}"),
197 ));
198 }
199 }
200 let args = parse_pay_args(edited)?;
201 let request = pay_request(format!("{key}/edited"), args);
202 match self.wallet.pay(request, caller).await? {
203 super::engine::PaymentOutcome::Settled(record) => Ok(settled_response(&record)),
204 super::engine::PaymentOutcome::Held(record) => {
205 let record =
206 self.wallet.decide_governed(&record.id, true, subject, message, caller).await?;
207 Ok(settled_response(&record))
208 }
209 }
210 }
211}
212
213fn pay_request(key: String, args: PayArgs) -> PaymentRequest {
214 let request = PaymentRequest::new(key, args.category, args.payee, args.amount, &args.currency)
215 .with_description(args.description);
216 match args.rail_data {
217 Some(data) => request.with_rail_data(data),
218 None => request,
219 }
220}
221
222#[async_trait]
223impl Tool for WalletPayTool {
224 fn name(&self) -> &str {
225 WALLET_PAY_TOOL
226 }
227
228 fn description(&self) -> &str {
229 "Pay from the site's owner-funded wallet within the owner's mandate for one spending \
230 category. A payment over the mandate's per-payment limit or the category's cap waits \
231 for the owner. Limits, payees and payment methods are the owner's; no tool changes them."
232 }
233
234 fn parameters_schema(&self) -> Option<Value> {
235 Some(json!({
236 "type": "object",
237 "additionalProperties": false,
238 "properties": {
239 "category": {
240 "type": "string",
241 "enum": ["hosting", "models", "advertising", "domains", "other"]
242 },
243 "payee": {
244 "type": "object",
245 "additionalProperties": false,
246 "properties": {
247 "id": { "type": "string", "description": "The payee's id on the rail" },
248 "name": { "type": "string" },
249 "domain": { "type": "string" }
250 },
251 "required": ["id"]
252 },
253 "amount": {
254 "type": "integer",
255 "minimum": 1,
256 "description": "Amount in minor units of the currency, such as cents"
257 },
258 "currency": { "type": "string", "description": "ISO 4217 code, the wallet's" },
259 "description": { "type": "string", "description": "What the payment is for" },
260 "railData": {
261 "type": "object",
262 "description": "The rail's data: the merchant's AP2 cart mandate, or the metered resource's payment challenge"
263 }
264 },
265 "required": ["category", "payee", "amount", "currency", "description"]
266 }))
267 }
268
269 fn required_scopes(&self) -> &[&str] {
270 PAYMENT_EXECUTE_SCOPES
271 }
272
273 fn effect(&self) -> ToolEffect {
274 ToolEffect::NonIdempotent
275 }
276
277 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
278 let parsed = parse_pay_args(args.clone())?;
279 let key = format!(
282 "{}/{}/{}/{}",
283 ctx.app_name(),
284 ctx.user_id(),
285 ctx.session_id(),
286 ctx.function_call_id()
287 );
288 let caller = WalletCaller::from_context(ctx.as_ref());
289 match self.wallet.pay(pay_request(key.clone(), parsed), &caller).await? {
290 super::engine::PaymentOutcome::Settled(record) => Ok(settled_response(&record)),
291 super::engine::PaymentOutcome::Held(record) => {
292 self.on_held(&ctx, args, &key, record, &caller).await
293 }
294 }
295 }
296}
297
298struct WalletStatusTool {
299 wallet: Wallet,
300}
301
302#[async_trait]
303impl Tool for WalletStatusTool {
304 fn name(&self) -> &str {
305 WALLET_STATUS_TOOL
306 }
307
308 fn description(&self) -> &str {
309 "Read the site wallet: each category's cap, spend this period, remaining budget, \
310 rail, allowed payees and pause, the payments waiting for the owner, and the balance."
311 }
312
313 fn parameters_schema(&self) -> Option<Value> {
314 Some(json!({ "type": "object", "properties": {}, "additionalProperties": false }))
315 }
316
317 fn effect(&self) -> ToolEffect {
318 ToolEffect::ReadOnly
319 }
320
321 fn is_read_only(&self) -> bool {
322 true
323 }
324
325 fn is_concurrency_safe(&self) -> bool {
326 true
327 }
328
329 async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
330 let held: Vec<Value> = self
331 .wallet
332 .held()
333 .await?
334 .iter()
335 .map(|record| {
336 json!({
337 "paymentId": record.id,
338 "category": category_name(record.category),
339 "payee": record.payee.id,
340 "amount": record.amount,
341 "reason": record.hold.as_ref().map(ToString::to_string),
342 })
343 })
344 .collect();
345 Ok(json!({
346 "currency": self.wallet.policy().currency,
347 "period": self.wallet.policy().period,
348 "balance": self.wallet.balance().await?,
349 "categories": self.wallet.status().await?,
350 "held": held,
351 }))
352 }
353}
354
355pub fn wallet_pay_tool(wallet: Wallet) -> impl Tool {
358 WalletPayTool { wallet }
359}
360
361pub fn wallet_status_tool(wallet: Wallet) -> impl Tool {
363 WalletStatusTool { wallet }
364}
365
366pub struct WalletToolset {
375 wallet: Wallet,
376 scope_guard: Option<ScopeGuard>,
377}
378
379impl WalletToolset {
380 pub fn new(wallet: Wallet) -> Self {
382 Self { wallet, scope_guard: None }
383 }
384
385 #[must_use]
387 pub fn with_scope_guard(mut self, guard: ScopeGuard) -> Self {
388 self.scope_guard = Some(guard);
389 self
390 }
391
392 pub fn tools(self) -> Vec<Arc<dyn Tool>> {
394 let tools: Vec<Arc<dyn Tool>> = vec![
395 Arc::new(wallet_pay_tool(self.wallet.clone())),
396 Arc::new(wallet_status_tool(self.wallet)),
397 ];
398 let guard = self.scope_guard.unwrap_or_else(|| ScopeGuard::new(ContextScopeResolver));
399 guard.protect_all(tools)
400 }
401}