@@ -121,40 +121,63 @@ pub(crate) struct Gate<'a> {
121121 error_seen : bool ,
122122 /// Where this month's spending is kept (`.gitagent/state.json`).
123123 state_file : Option < PathBuf > ,
124+ /// Payments counted when their call was let through, by call id; a
125+ /// call that then fails is taken off again.
126+ reserved : std:: sync:: Mutex < std:: collections:: HashMap < String , u64 > > ,
124127}
125128
129+ /// Held while this month's spending is read and rewritten, so payments
130+ /// running at the same time (a plan's tasks) cannot both pass the cap.
131+ static SPENDING : std:: sync:: Mutex < ( ) > = std:: sync:: Mutex :: new ( ( ) ) ;
132+
126133/// A payment a tool call makes: the amount in cents and its category.
127134pub ( crate ) struct Payment {
128135 pub cents : u64 ,
129136 pub category : Option < String > ,
130137}
131138
132139/// The payment a call makes, read from `amount_cents` (or `amount`, in
133- /// whole units) and `category` in its arguments.
134- pub ( crate ) fn payment_of ( call : & ToolCall ) -> Option < Payment > {
140+ /// whole units) and `category` in its arguments. `None` when the call names
141+ /// no amount; an error when it names one that cannot be read, which the
142+ /// spending rules treat as a block rather than as no payment.
143+ pub ( crate ) fn payment_of ( call : & ToolCall ) -> Option < Result < Payment , String > > {
135144 let args = & call. arguments ;
136145 let cents = match ( args. get ( "amount_cents" ) , args. get ( "amount" ) ) {
137- ( Some ( c) , _) => c
138- . as_u64 ( )
139- . or_else ( || c. as_str ( ) . and_then ( |s| s. parse ( ) . ok ( ) ) ) ?,
140- ( None , Some ( a) ) => {
141- let units = a
142- . as_f64 ( )
143- . or_else ( || a. as_str ( ) . and_then ( |s| s. parse ( ) . ok ( ) ) ) ?;
144- if units < 0.0 {
145- return None ;
146- }
147- ( units * 100.0 ) . round ( ) as u64
148- }
146+ ( Some ( c) , _) => cents_of ( c, 1.0 ) ,
147+ ( None , Some ( a) ) => cents_of ( a, 100.0 ) ,
149148 ( None , None ) => return None ,
150149 } ;
151- Some ( Payment {
152- cents,
153- category : args
154- . get ( "category" )
155- . and_then ( Value :: as_str)
156- . map ( str:: to_string) ,
157- } )
150+ Some (
151+ cents
152+ . map ( |cents| Payment {
153+ cents,
154+ category : args
155+ . get ( "category" )
156+ . and_then ( Value :: as_str)
157+ . map ( str:: to_string) ,
158+ } )
159+ . ok_or_else ( || "the payment's amount could not be read" . to_string ( ) ) ,
160+ )
161+ }
162+
163+ /// An amount in cents from a number or a string such as `"1,500.00"` or
164+ /// `"$15"`, scaled by `scale`; `None` when negative, fractional cents or
165+ /// not a number.
166+ fn cents_of ( v : & Value , scale : f64 ) -> Option < u64 > {
167+ let n = v. as_f64 ( ) . or_else ( || {
168+ v. as_str ( ) . and_then ( |s| {
169+ s. trim ( )
170+ . trim_start_matches ( '$' )
171+ . replace ( ',' , "" )
172+ . parse :: < f64 > ( )
173+ . ok ( )
174+ } )
175+ } ) ?;
176+ let cents = n * scale;
177+ if !cents. is_finite ( ) || cents < 0.0 || ( scale == 1.0 && cents. fract ( ) != 0.0 ) {
178+ return None ;
179+ }
180+ Some ( cents. round ( ) as u64 )
158181}
159182
160183impl < ' a > Gate < ' a > {
@@ -182,6 +205,7 @@ impl<'a> Gate<'a> {
182205 kill_file,
183206 error_seen : false ,
184207 state_file,
208+ reserved : Default :: default ( ) ,
185209 }
186210 }
187211
@@ -197,24 +221,33 @@ impl<'a> Gate<'a> {
197221 }
198222
199223 /// Notes a call's result: for the `error_detected` trigger, and a
200- /// payment that went through counts toward the month's spending.
224+ /// payment counted by [`Gate::block_reason`] whose call failed, was
225+ /// denied or was blocked is taken off the month's spending again.
201226 pub fn observe ( & mut self , call : & ToolCall , is_error : bool ) {
202227 self . error_seen |= is_error;
203- if is_error || self . spec . supervision . finance . is_none ( ) {
204- return ;
205- }
206- if let Some ( p) = payment_of ( call) {
228+ let reserved = self
229+ . reserved
230+ . lock ( )
231+ . unwrap_or_else ( |e| e. into_inner ( ) )
232+ . remove ( & call. id ) ;
233+ if let ( Some ( cents) , true ) = ( reserved, is_error) {
234+ let _held = SPENDING . lock ( ) . unwrap_or_else ( |e| e. into_inner ( ) ) ;
207235 let month = this_month ( ) ;
208- let mut state = self . state ( ) ;
209- let spent = state[ "spending" ] [ & month] . as_u64 ( ) . unwrap_or ( 0 ) ;
210- state[ "spending" ] [ & month] = json ! ( spent + p. cents) ;
211- if let Some ( path) = & self . state_file {
212- if let Some ( dir) = path. parent ( ) {
213- let _ = std:: fs:: create_dir_all ( dir) ;
214- }
215- let _ = std:: fs:: write ( path, state. to_string ( ) ) ;
216- }
236+ let spent = self . state ( ) [ "spending" ] [ & month] . as_u64 ( ) . unwrap_or ( 0 ) ;
237+ self . write_spent ( & month, spent. saturating_sub ( cents) ) ;
238+ }
239+ }
240+
241+ fn write_spent ( & self , month : & str , cents : u64 ) {
242+ let Some ( path) = & self . state_file else {
243+ return ;
244+ } ;
245+ let mut state = self . state ( ) ;
246+ state[ "spending" ] [ month] = json ! ( cents) ;
247+ if let Some ( dir) = path. parent ( ) {
248+ let _ = std:: fs:: create_dir_all ( dir) ;
217249 }
250+ let _ = std:: fs:: write ( path, state. to_string ( ) ) ;
218251 }
219252
220253 fn state ( & self ) -> Value {
@@ -226,7 +259,10 @@ impl<'a> Gate<'a> {
226259 }
227260
228261 /// Why the call may not run at all, if so: a handoff whose roles the
229- /// agent does not hold, or a payment outside the spending rules.
262+ /// agent does not hold, or a payment outside the spending rules. A
263+ /// payment that passes is counted toward the month at once, so calls
264+ /// running at the same time see it; [`Gate::observe`] takes it off again
265+ /// if the call does not go through.
230266 pub fn block_reason ( & self , call : & ToolCall ) -> Option < String > {
231267 let sup = & self . spec . supervision ;
232268 let agent = self
@@ -255,6 +291,10 @@ impl<'a> Gate<'a> {
255291 let ( Some ( f) , Some ( p) ) = ( & sup. finance , payment_of ( call) ) else {
256292 return None ;
257293 } ;
294+ let p = match p {
295+ Ok ( p) => p,
296+ Err ( why) => return Some ( format ! ( "{why} (financial governance)" ) ) ,
297+ } ;
258298 if let Some ( c) = & p. category {
259299 if f. blocked_categories . iter ( ) . any ( |b| b == c) {
260300 return Some ( format ! (
@@ -279,8 +319,10 @@ impl<'a> Gate<'a> {
279319 f. max_per_transaction_cents. unwrap_or_default( )
280320 ) ) ;
281321 }
322+ let _held = SPENDING . lock ( ) . unwrap_or_else ( |e| e. into_inner ( ) ) ;
323+ let month = this_month ( ) ;
324+ let spent = self . state ( ) [ "spending" ] [ & month] . as_u64 ( ) . unwrap_or ( 0 ) ;
282325 if let Some ( cap) = f. max_monthly_cents {
283- let spent = self . state ( ) [ "spending" ] [ this_month ( ) ] . as_u64 ( ) . unwrap_or ( 0 ) ;
284326 if spent + p. cents > cap {
285327 return Some ( format ! (
286328 "{} cents would take this month's spending to {} of the {cap} allowed (financial governance)" ,
@@ -289,13 +331,21 @@ impl<'a> Gate<'a> {
289331 ) ) ;
290332 }
291333 }
334+ self . write_spent ( & month, spent + p. cents ) ;
335+ self . reserved
336+ . lock ( )
337+ . unwrap_or_else ( |e| e. into_inner ( ) )
338+ . insert ( call. id . clone ( ) , p. cents ) ;
292339 None
293340 }
294341
295342 /// Whether a request that nobody answers in time counts as approved
296343 /// (a payment with `auto_deny_on_timeout: false`).
297344 pub fn approve_on_timeout ( & self , call : & ToolCall ) -> bool {
298- match ( & self . spec . supervision . finance , payment_of ( call) ) {
345+ match (
346+ & self . spec . supervision . finance ,
347+ payment_of ( call) . and_then ( Result :: ok) ,
348+ ) {
299349 ( Some ( f) , Some ( _) ) => !f. auto_deny_on_timeout ,
300350 _ => false ,
301351 }
@@ -338,7 +388,7 @@ impl<'a> Gate<'a> {
338388 ) ) ;
339389 }
340390 }
341- if let ( Some ( f) , Some ( p ) ) = ( & sup. finance , payment_of ( call) ) {
391+ if let ( Some ( f) , Some ( Ok ( p ) ) ) = ( & sup. finance , payment_of ( call) ) {
342392 if f. require_above_cents . is_some_and ( |t| p. cents > t) {
343393 return Some ( format ! (
344394 "a payment of {} cents is over {} (financial governance)" ,
0 commit comments