vv-agent 0.8.0

VectorVein agent runtime, SDK, CLI, tools, and workspace backends
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashSet};
use std::fmt;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::types::{CompletionReason, CycleRecord, Message, Metadata, TaskTokenUsage};

pub const AFTER_CYCLE_CONTROL_STATE_KEY: &str = "_vv_agent_after_cycle_control";
pub const AFTER_CYCLE_CONTROL_SCHEMA: &str = "vv-agent.after-cycle-control.v1";
pub const MAX_STEERING_MESSAGES: usize = 32;
pub const MAX_STEERING_MESSAGE_UTF8_BYTES: usize = 16_384;
pub const MAX_TOTAL_STEERING_UTF8_BYTES: usize = 65_536;
pub const MAX_DISALLOW_TOOLS: usize = 1_024;
pub const MAX_TOOL_NAME_UTF8_BYTES: usize = 256;
pub const MAX_STOP_CODE_ASCII_BYTES: usize = 128;
pub const MAX_STOP_MESSAGE_UTF8_BYTES: usize = 4_096;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AfterCycleAction {
    Continue,
    Steer,
    StopNonSuccess,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NativeCycleOutcomeKind {
    Continue,
    Completed,
    WaitUser,
    MaxCycles,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NativeCycleOutcome {
    pub kind: NativeCycleOutcomeKind,
    pub completion_reason: Option<CompletionReason>,
    pub completion_tool_name: Option<String>,
    pub steer_allowed: bool,
}

impl NativeCycleOutcome {
    pub fn continuing() -> Self {
        Self {
            kind: NativeCycleOutcomeKind::Continue,
            completion_reason: None,
            completion_tool_name: None,
            steer_allowed: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AfterCycleSnapshot {
    pub task_id: String,
    pub cycle_index: u32,
    pub max_cycles: u32,
    pub remaining_cycles: u32,
    pub cycle: CycleRecord,
    pub messages: Vec<Message>,
    pub shared_state: Metadata,
    pub cumulative_token_usage: TaskTokenUsage,
    pub available_tool_names: Vec<String>,
    pub disallowed_tool_names: Vec<String>,
    pub native_outcome: NativeCycleOutcome,
}

impl AfterCycleSnapshot {
    #[allow(clippy::too_many_arguments)]
    pub fn capture(
        task_id: impl Into<String>,
        cycle_index: u32,
        max_cycles: u32,
        cycle: &CycleRecord,
        messages: &[Message],
        shared_state: &Metadata,
        cumulative_token_usage: TaskTokenUsage,
        available_tool_names: Vec<String>,
        disallowed_tool_names: Vec<String>,
        native_outcome: NativeCycleOutcome,
    ) -> Self {
        Self {
            task_id: task_id.into(),
            cycle_index,
            max_cycles,
            remaining_cycles: max_cycles.saturating_sub(cycle_index),
            cycle: cycle.clone(),
            messages: messages.to_vec(),
            shared_state: shared_state.clone(),
            cumulative_token_usage,
            available_tool_names,
            disallowed_tool_names,
            native_outcome,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AfterCycleStop {
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AfterCycleDecision {
    pub action: AfterCycleAction,
    pub steering_messages: Vec<String>,
    pub disallow_tools: Vec<String>,
    pub stop: Option<AfterCycleStop>,
}

impl Default for AfterCycleDecision {
    fn default() -> Self {
        Self::continue_run()
    }
}

impl AfterCycleDecision {
    pub fn continue_run() -> Self {
        Self {
            action: AfterCycleAction::Continue,
            steering_messages: Vec::new(),
            disallow_tools: Vec::new(),
            stop: None,
        }
    }

    pub fn continue_with_disallowed_tools(
        tools: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, AfterCycleDecisionError> {
        let decision = Self {
            disallow_tools: tools.into_iter().map(Into::into).collect(),
            ..Self::continue_run()
        };
        decision.validate()?;
        Ok(decision)
    }

    pub fn steer(
        messages: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, AfterCycleDecisionError> {
        Self::steer_with_disallowed_tools(messages, Vec::<String>::new())
    }

    pub fn steer_with_disallowed_tools(
        messages: impl IntoIterator<Item = impl Into<String>>,
        tools: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, AfterCycleDecisionError> {
        let decision = Self {
            action: AfterCycleAction::Steer,
            steering_messages: messages.into_iter().map(Into::into).collect(),
            disallow_tools: tools.into_iter().map(Into::into).collect(),
            stop: None,
        };
        decision.validate()?;
        Ok(decision)
    }

    pub fn stop_non_success(
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Result<Self, AfterCycleDecisionError> {
        let decision = Self {
            action: AfterCycleAction::StopNonSuccess,
            steering_messages: Vec::new(),
            disallow_tools: Vec::new(),
            stop: Some(AfterCycleStop {
                code: code.into(),
                message: message.into(),
            }),
        };
        decision.validate()?;
        Ok(decision)
    }

    pub fn validate(&self) -> Result<(), AfterCycleDecisionError> {
        if self.steering_messages.len() > MAX_STEERING_MESSAGES {
            return Err(AfterCycleDecisionError::new(
                "after-cycle steering message count exceeds the limit",
            ));
        }
        let mut total_bytes = 0_usize;
        for message in &self.steering_messages {
            validate_bounded_text(
                message,
                "after-cycle steering message",
                MAX_STEERING_MESSAGE_UTF8_BYTES,
            )?;
            total_bytes = total_bytes.saturating_add(message.len());
        }
        if total_bytes > MAX_TOTAL_STEERING_UTF8_BYTES {
            return Err(AfterCycleDecisionError::new(
                "after-cycle steering messages exceed the total byte limit",
            ));
        }
        if self.disallow_tools.len() > MAX_DISALLOW_TOOLS {
            return Err(AfterCycleDecisionError::new(
                "after-cycle disallowed tool count exceeds the limit",
            ));
        }
        let mut seen = HashSet::new();
        for tool_name in &self.disallow_tools {
            validate_bounded_text(
                tool_name,
                "after-cycle disallowed tool name",
                MAX_TOOL_NAME_UTF8_BYTES,
            )?;
            if !seen.insert(tool_name) {
                return Err(AfterCycleDecisionError::new(
                    "after-cycle disallowed tools must be unique",
                ));
            }
        }
        match self.action {
            AfterCycleAction::Continue => {
                if !self.steering_messages.is_empty() || self.stop.is_some() {
                    return Err(AfterCycleDecisionError::new(
                        "continue cannot include steering messages or a stop payload",
                    ));
                }
            }
            AfterCycleAction::Steer => {
                if self.steering_messages.is_empty() || self.stop.is_some() {
                    return Err(AfterCycleDecisionError::new(
                        "steer requires messages and cannot include a stop payload",
                    ));
                }
            }
            AfterCycleAction::StopNonSuccess => {
                if !self.steering_messages.is_empty()
                    || !self.disallow_tools.is_empty()
                    || self.stop.is_none()
                {
                    return Err(AfterCycleDecisionError::new(
                        "stop_non_success requires only a typed stop payload",
                    ));
                }
                let stop = self.stop.as_ref().expect("checked stop payload");
                validate_stop_code(&stop.code)?;
                validate_bounded_text(
                    &stop.message,
                    "after-cycle stop message",
                    MAX_STOP_MESSAGE_UTF8_BYTES,
                )?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AfterCycleDecisionError {
    message: String,
}

impl AfterCycleDecisionError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for AfterCycleDecisionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for AfterCycleDecisionError {}

pub trait AfterCycleHook: Send + Sync {
    fn after_cycle(
        &self,
        snapshot: &AfterCycleSnapshot,
    ) -> Result<Option<AfterCycleDecision>, String>;
}

impl<F> AfterCycleHook for F
where
    F: Fn(&AfterCycleSnapshot) -> Result<Option<AfterCycleDecision>, String> + Send + Sync,
{
    fn after_cycle(
        &self,
        snapshot: &AfterCycleSnapshot,
    ) -> Result<Option<AfterCycleDecision>, String> {
        self(snapshot)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AfterCycleHookError {
    pub code: &'static str,
    message: String,
}

impl AfterCycleHookError {
    fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

impl fmt::Display for AfterCycleHookError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for AfterCycleHookError {}

#[derive(Clone, Default)]
pub struct AfterCycleHookManager {
    hooks: Vec<Arc<dyn AfterCycleHook>>,
}

impl AfterCycleHookManager {
    pub fn new(hooks: Vec<Arc<dyn AfterCycleHook>>) -> Self {
        Self { hooks }
    }

    pub fn has_hooks(&self) -> bool {
        !self.hooks.is_empty()
    }

    pub fn apply(
        &self,
        snapshot: &AfterCycleSnapshot,
    ) -> Result<AfterCycleDecision, AfterCycleHookError> {
        let mut steering_messages = Vec::new();
        let mut disallow_tools = Vec::new();
        let mut seen_tools = HashSet::new();
        for hook in &self.hooks {
            let outcome = catch_unwind(AssertUnwindSafe(|| hook.after_cycle(snapshot)))
                .map_err(|_| {
                    AfterCycleHookError::new("after_cycle_hook_failed", "after-cycle hook panicked")
                })?
                .map_err(|error| {
                    AfterCycleHookError::new(
                        "after_cycle_hook_failed",
                        format!("after-cycle hook failed: {error}"),
                    )
                })?;
            let Some(decision) = outcome else {
                continue;
            };
            decision.validate().map_err(|error| {
                AfterCycleHookError::new(
                    "after_cycle_decision_invalid",
                    format!("after-cycle hook returned an invalid decision: {error}"),
                )
            })?;
            for tool_name in &decision.disallow_tools {
                if seen_tools.insert(tool_name.clone()) {
                    disallow_tools.push(tool_name.clone());
                }
            }
            if decision.action == AfterCycleAction::StopNonSuccess {
                return Ok(decision);
            }
            if decision.action == AfterCycleAction::Steer {
                steering_messages.extend(decision.steering_messages);
            }
        }
        let composed = if steering_messages.is_empty() {
            AfterCycleDecision::continue_with_disallowed_tools(disallow_tools)
        } else {
            AfterCycleDecision::steer_with_disallowed_tools(steering_messages, disallow_tools)
        };
        composed.map_err(|error| {
            AfterCycleHookError::new(
                "after_cycle_decision_invalid",
                format!("composed after-cycle decision is invalid: {error}"),
            )
        })
    }
}

pub fn read_after_cycle_disallowed_tools(
    shared_state: &Metadata,
) -> Result<Vec<String>, AfterCycleHookError> {
    let Some(raw) = shared_state.get(AFTER_CYCLE_CONTROL_STATE_KEY) else {
        return Ok(Vec::new());
    };
    let object = raw
        .as_object()
        .ok_or_else(|| control_state_error("after-cycle control state must be an object"))?;
    let expected = BTreeSet::from(["schema_version", "disallowed_tools"]);
    let actual = object.keys().map(String::as_str).collect::<BTreeSet<_>>();
    if actual != expected {
        return Err(control_state_error(
            "after-cycle control state has missing or unknown fields",
        ));
    }
    if object.get("schema_version").and_then(Value::as_str) != Some(AFTER_CYCLE_CONTROL_SCHEMA) {
        return Err(control_state_error(
            "after-cycle control state schema is unsupported",
        ));
    }
    let values = object
        .get("disallowed_tools")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            control_state_error("after-cycle control disallowed_tools must be an array")
        })?
        .iter()
        .map(|value| {
            value.as_str().map(str::to_string).ok_or_else(|| {
                control_state_error("after-cycle control disallowed_tools must contain strings")
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    AfterCycleDecision::continue_with_disallowed_tools(values.clone())
        .map_err(|error| control_state_error(error.to_string()))?;
    let mut ordered = values.clone();
    ordered.sort_by(|left, right| utf16_cmp(left, right));
    if values != ordered {
        return Err(control_state_error(
            "after-cycle control disallowed_tools must be sorted and unique",
        ));
    }
    Ok(ordered)
}

pub fn persist_after_cycle_disallowed_tools(
    shared_state: &mut Metadata,
    additional_tools: &[String],
) -> Result<Vec<String>, AfterCycleHookError> {
    let mut values = read_after_cycle_disallowed_tools(shared_state)?;
    values.extend(additional_tools.iter().cloned());
    values.sort_by(|left, right| utf16_cmp(left, right));
    values.dedup();
    if values.is_empty() {
        return Ok(values);
    }
    AfterCycleDecision::continue_with_disallowed_tools(values.clone())
        .map_err(|error| control_state_error(error.to_string()))?;
    shared_state.insert(
        AFTER_CYCLE_CONTROL_STATE_KEY.to_string(),
        json!({
            "schema_version": AFTER_CYCLE_CONTROL_SCHEMA,
            "disallowed_tools": values,
        }),
    );
    Ok(values)
}

pub(crate) fn utf16_cmp(left: &str, right: &str) -> Ordering {
    left.encode_utf16().cmp(right.encode_utf16())
}

fn validate_bounded_text(
    value: &str,
    field_name: &str,
    max_bytes: usize,
) -> Result<(), AfterCycleDecisionError> {
    if value.trim().is_empty() {
        return Err(AfterCycleDecisionError::new(format!(
            "{field_name} must be a non-empty string"
        )));
    }
    if value.len() > max_bytes {
        return Err(AfterCycleDecisionError::new(format!(
            "{field_name} exceeds {max_bytes} UTF-8 bytes"
        )));
    }
    Ok(())
}

fn validate_stop_code(code: &str) -> Result<(), AfterCycleDecisionError> {
    let valid = code.is_ascii()
        && !code.is_empty()
        && code.len() <= MAX_STOP_CODE_ASCII_BYTES
        && code.as_bytes()[0].is_ascii_lowercase()
        && code.bytes().all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_.-".contains(&byte)
        });
    if !valid {
        return Err(AfterCycleDecisionError::new(
            "after-cycle stop code is invalid",
        ));
    }
    Ok(())
}

fn control_state_error(message: impl Into<String>) -> AfterCycleHookError {
    AfterCycleHookError::new("after_cycle_control_state_invalid", message)
}