artifactize-provider 0.27.1

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! A model conversation with caller-supplied tools and observations.

use std::{collections::HashSet, future::Future};

/// Request and tool types for callers of this driver.
pub use rig_core::{
    completion::{CompletionRequest, ToolDefinition},
    message::{ToolCall, ToolResultContent},
};
use rig_core::{
    completion::{CompletionResponse, FinishReason},
    message::{AssistantContent, CallId, Message, ProviderCallId, ToolResult},
};
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;

use crate::secret::{Inventory, append_scalar_values};

use super::{Attempt, Client, Code, Failure, ModelId, Turn, delivery::Delivery, protection};

pub const NO_CALLABLE_TOOL: &str = "Provider ended with tool calls but supplied no callable tool.";
pub const TOKEN_BUDGET: &str = "Provider token budget exceeded.";
pub const TOOL_BUDGET: &str = "Provider tool-call budget exceeded.";

pub struct Options<'a> {
    pub model: &'a ModelId,
    pub deadline: Instant,
    pub cancellation: &'a CancellationToken,
    pub max_tokens: Option<u64>,
    pub max_tool_calls: Option<u64>,
}

/// A model turn sends requests until it answers. Budgets and call IDs persist when the caller
/// asks a subsequent question using the same driver.
pub struct Driver<'a> {
    client: &'a Client,
    options: Options<'a>,
    number: usize,
    tokens: u64,
    calls: u64,
    call_ids: HashSet<CallId>,
}

#[derive(Clone, Copy)]
pub struct ToolContext<'a> {
    pub deadline: Instant,
    pub cancellation: &'a CancellationToken,
}

pub struct Outcome {
    pub content: Vec<ToolResultContent>,
    pub failed: bool,
}

pub enum Event<'a> {
    Delivery(Delivery),
    Attempt(Attempt),
    Output {
        turn: usize,
        response: &'a CompletionResponse,
    },
    Tool {
        turn: usize,
        result: &'a ToolResult,
        failed: bool,
        batch_size: usize,
    },
    ToolBatch {
        turn: usize,
        results: &'a Message,
        failed: &'a [bool],
    },
}

pub trait Handler {
    fn event(&mut self, event: Event<'_>);

    /// Adjust caller context before replaying tool results, without handling provider details.
    fn before_tool_replies(&mut self, _request: &mut CompletionRequest) {}

    /// The caller's result text for an unoffered tool. No executor is called.
    fn unavailable(&self, name: &str) -> String {
        format!("Unknown tool {name:?}.")
    }

    /// A tool may need caller-specific cancellation or commit semantics. The driver checks
    /// cancellation and deadline before dispatch and again before the next tool or request.
    fn invoke(
        &mut self,
        call: &ToolCall,
        context: ToolContext<'_>,
    ) -> impl Future<Output = Result<Outcome, Failure>> + Send;
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Tools {
    Offered,
    Disabled,
}

pub enum Answer {
    Final(Box<CompletionResponse>),
    ToolsDisabled,
}

impl<'a> Driver<'a> {
    pub fn new(client: &'a Client, options: Options<'a>) -> Self {
        Self {
            client,
            options,
            number: 0,
            tokens: 0,
            calls: 0,
            call_ids: HashSet::new(),
        }
    }

    /// The next provider request's sequence number (also the destination of newly added input).
    pub fn next_number(&self) -> usize {
        self.number + 1
    }

    pub async fn run(
        &mut self,
        request: &mut CompletionRequest,
        tools: Tools,
        handler: &mut impl Handler,
    ) -> Result<Answer, Failure> {
        self.run_turn(request, tools, handler)
            .await
            .map_err(|failure| self.client.scrub_failure(failure))
    }

    async fn run_turn(
        &mut self,
        request: &mut CompletionRequest,
        tools: Tools,
        handler: &mut impl Handler,
    ) -> Result<Answer, Failure> {
        loop {
            let response = self.next(request, handler).await?;
            let calls = response
                .choice
                .iter()
                .filter_map(|part| match part {
                    AssistantContent::ToolCall(call) => Some(call.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>();
            if calls.is_empty() {
                return if response.finish_reason() == Some(FinishReason::Stop) {
                    Ok(Answer::Final(Box::new(response)))
                } else {
                    Err(Failure::new(Code::ProviderError, NO_CALLABLE_TOOL))
                };
            }
            if tools == Tools::Disabled {
                return Ok(Answer::ToolsDisabled);
            }
            handler.before_tool_replies(request);
            request.chat_history.push(Message::Assistant {
                id: response.message_id,
                content: response.choice,
            });
            let results = self.call_tools(request, calls, handler).await?;
            request.chat_history.push(results);
        }
    }

    async fn next(
        &mut self,
        request: &CompletionRequest,
        handler: &mut impl Handler,
    ) -> Result<CompletionResponse, Failure> {
        self.number += 1;
        let mut attempts = Vec::new();
        let response = self
            .client
            .turn_observed(
                request,
                Turn {
                    number: self.number,
                    model: self.options.model,
                    deadline: self.options.deadline,
                    cancellation: self.options.cancellation,
                    max_tokens: self.options.max_tokens,
                    tokens_used: &mut self.tokens,
                },
                &mut attempts,
                &mut |event| handler.event(Event::Delivery(event)),
            )
            .await;
        for attempt in attempts {
            handler.event(Event::Attempt(attempt));
        }
        let response = response?;
        self.check_deadline()?;
        handler.event(Event::Output {
            turn: self.number,
            response: &response,
        });
        if self
            .options
            .max_tokens
            .is_some_and(|limit| self.tokens > limit)
        {
            return Err(Failure::new(Code::BudgetExceeded, TOKEN_BUDGET));
        }
        Ok(response)
    }

    async fn call_tools(
        &mut self,
        request: &CompletionRequest,
        calls: Vec<ToolCall>,
        handler: &mut impl Handler,
    ) -> Result<Message, Failure> {
        use crate::auth::codex::import_stamp;
        let import_changed = || {
            Failure::new(
                Code::Configuration,
                "Imported credentials changed during tool execution; tool output was withheld.",
            )
        };
        let import = import_stamp().map_err(|_| import_changed())?;
        let mut results = Vec::new();
        let mut failed = Vec::new();
        let mut stopped = None;
        let turn = self.next_number();
        let batch_size = calls.len();
        // A response never makes tool calls concurrent or admits a tool the caller did not offer.
        for call in calls {
            let result = self.call_tool(request, &call, handler).await;
            match result {
                Ok(Outcome {
                    content,
                    failed: is_error,
                }) => {
                    results.push(call.result(content));
                    failed.push(is_error);
                }
                Err(failure) => {
                    stopped = Some(failure);
                    break;
                }
            }
            if let Err(failure) = self.check_deadline() {
                stopped = Some(failure);
                break;
            }
        }
        if import_stamp().map_err(|_| import_changed())? != import {
            return Err(import_changed());
        }
        let inventory = self.client.inventory();
        scrub_results(&inventory, &mut results)
            .map_err(|_| Failure::new(Code::Configuration, "Cannot sanitize tool results."))?;
        // Individual events are emitted only once the joined text is clean. Otherwise
        // two tools could disclose the two halves of a credential in separate events.
        for (result, &failed) in results.iter().zip(&failed) {
            handler.event(Event::Tool {
                turn,
                result,
                failed,
                batch_size,
            });
        }
        let message = Message::tool_results(results);
        if !failed.is_empty() {
            handler.event(Event::ToolBatch {
                turn,
                results: &message,
                failed: &failed,
            });
        }
        match stopped {
            Some(failure) => Err(failure),
            None => Ok(message),
        }
    }

    async fn call_tool(
        &mut self,
        request: &CompletionRequest,
        call: &ToolCall,
        handler: &mut impl Handler,
    ) -> Result<Outcome, Failure> {
        self.check_deadline()?;
        self.calls = self.calls.saturating_add(1);
        if self
            .options
            .max_tool_calls
            .is_some_and(|limit| self.calls > limit)
        {
            return Err(Failure::new(Code::BudgetExceeded, TOOL_BUDGET));
        }
        // An OpenAI Responses output-item ID is not its tool-result correlation ID.
        let identity = match &call.id {
            CallId::Provider(provider) => ProviderCallId::new(provider.call_id.clone())
                .expect("validated call ID")
                .into(),
            CallId::Local(local) => (*local).into(),
        };
        if !self.call_ids.insert(identity) {
            return Err(Failure::new(
                Code::ProviderError,
                "Provider repeated a tool-call ID; no further tools were executed.",
            ));
        }
        let name = call.function.name.as_str();
        if request.tools.iter().any(|tool| tool.name == name) {
            let mut checked = call.clone();
            let inventory = self.client.inventory();
            if protection::protected_arguments(&call.function.arguments, &inventory)
                || inventory.scrub_typed(&mut checked).unwrap_or(true)
            {
                return Err(Failure::new(
                    Code::ProviderError,
                    "Provider supplied a tool call containing a protected credential.",
                ));
            }
            handler
                .invoke(
                    call,
                    ToolContext {
                        deadline: self.options.deadline,
                        cancellation: self.options.cancellation,
                    },
                )
                .await
        } else {
            Ok(Outcome {
                content: vec![ToolResultContent::text(handler.unavailable(name))],
                failed: true,
            })
        }
    }

    fn check_deadline(&self) -> Result<(), Failure> {
        if self.options.cancellation.is_cancelled() {
            return Err(Failure::cancelled());
        }
        if Instant::now() >= self.options.deadline {
            return Err(Failure::timeout());
        }
        Ok(())
    }
}

fn scrub_results(
    inventory: &Inventory,
    results: &mut [ToolResult],
) -> Result<(), serde_json::Error> {
    if inventory.is_empty() {
        return Ok(());
    }
    if joined_results_contain_secret(inventory, results) {
        for result in &mut *results {
            result.content = vec![ToolResultContent::text("")];
        }
    }
    inventory.scrub_joined(
        &mut results
            .iter_mut()
            .flat_map(|result| result.content.iter_mut())
            .filter_map(|item| match item {
                ToolResultContent::Text(text) => Some(&mut text.text),
                _ => None,
            })
            .collect::<Vec<_>>(),
    );
    for result in &mut *results {
        inventory.scrub_typed(result)?;
    }
    if joined_results_contain_secret(inventory, results) {
        for result in results {
            result.content = vec![ToolResultContent::text("")];
        }
    }
    Ok(())
}

fn joined_results_contain_secret(inventory: &Inventory, results: &[ToolResult]) -> bool {
    let items = results.iter().flat_map(|result| &result.content);
    // A text-only batch goes through the line-preserving text scrubber. When a
    // spelling crosses structured content, don't rewrite its values as prose.
    if items.clone().all(
        |item| matches!(item, ToolResultContent::Text(text) if text.additional_params.is_none()),
    ) {
        return false;
    }
    let mut ordered = String::new();
    let mut payload = String::new();
    let mut structured = String::new();
    for item in items {
        let start = payload.len();
        let params = match item {
            ToolResultContent::Text(text) => {
                payload.push_str(&text.text);
                text.additional_params.as_ref()
            }
            ToolResultContent::Image(image) => {
                let text = protection::image_text(image);
                payload.push_str(text);
                structured.push_str(text);
                image.additional_params.as_ref()
            }
            ToolResultContent::Json { value } => {
                append_scalar_values(value, &mut payload);
                structured.push_str(&payload[start..]);
                None
            }
        };
        ordered.push_str(&payload[start..]);
        if let Some(params) = params {
            let start = structured.len();
            for value in params.as_map().values() {
                append_scalar_values(value, &mut structured);
            }
            ordered.push_str(&structured[start..]);
        }
    }
    inventory.contains(&ordered) || inventory.contains(&payload) || inventory.contains(&structured)
}

pub fn text(response: &CompletionResponse) -> String {
    response
        .choice
        .iter()
        .filter_map(|part| match part {
            AssistantContent::Text(text) => Some(text.text.as_str()),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests;