everruns-core 0.17.9

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
498
499
500
501
use crate::session_task::{
    NewTaskMessage, SessionTask, SessionTaskUpdate, TaskMessageDirection, TaskMessagePart,
    task_result_path,
};
use crate::tools::{Tool, ToolExecutionResult};
use crate::traits::{SessionFileSystem, SessionStore, ToolContext};
use crate::typed_id::{SessionId, WorkspaceId};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

pub(crate) const RESULT_SCHEMA_SPEC_KEY: &str = "result_schema";
pub(crate) const MESSAGE_SCHEMA_SPEC_KEY: &str = "message_schema";

pub(crate) fn declared_result_schema(task: &SessionTask) -> Option<&Value> {
    task.spec
        .get(RESULT_SCHEMA_SPEC_KEY)
        .filter(|schema| schema.is_object())
}

pub(crate) fn declared_message_schema(task: &SessionTask) -> Option<&Value> {
    task.spec
        .get(MESSAGE_SCHEMA_SPEC_KEY)
        .filter(|schema| schema.is_object())
}

fn normalize_optional_schema(
    arguments: &Value,
    key: &str,
) -> Result<Option<Value>, ToolExecutionResult> {
    let Some(schema) = arguments.get(key).filter(|value| !value.is_null()) else {
        return Ok(None);
    };
    if !schema.is_object() {
        return Err(ToolExecutionResult::tool_error(format!(
            "{key} must be a JSON Schema object when provided."
        )));
    }
    Ok(Some(schema.clone()))
}

pub(crate) fn normalize_result_schema(
    arguments: &Value,
) -> Result<Option<Value>, ToolExecutionResult> {
    normalize_optional_schema(arguments, RESULT_SCHEMA_SPEC_KEY)
}

pub(crate) fn normalize_message_schema(
    arguments: &Value,
) -> Result<Option<Value>, ToolExecutionResult> {
    normalize_optional_schema(arguments, MESSAGE_SCHEMA_SPEC_KEY)
}

fn json_schema_type_matches(expected: &str, value: &Value) -> bool {
    match expected {
        "object" => value.is_object(),
        "array" => value.is_array(),
        "string" => value.is_string(),
        "boolean" => value.is_boolean(),
        "integer" => value.as_i64().is_some() || value.as_u64().is_some(),
        "number" => value.is_number(),
        "null" => value.is_null(),
        _ => true,
    }
}

fn validate_against_schema(schema: &Value, value: &Value, path: &str, errors: &mut Vec<String>) {
    if let Some(enum_values) = schema.get("enum").and_then(Value::as_array)
        && !enum_values.iter().any(|candidate| candidate == value)
    {
        errors.push(format!("{path} is not one of the allowed enum values"));
    }
    if let Some(const_value) = schema.get("const")
        && const_value != value
    {
        errors.push(format!("{path} does not match the required const value"));
    }
    if let Some(type_value) = schema.get("type") {
        let matches = match type_value {
            Value::String(expected) => json_schema_type_matches(expected, value),
            Value::Array(types) => types
                .iter()
                .filter_map(Value::as_str)
                .any(|expected| json_schema_type_matches(expected, value)),
            _ => true,
        };
        if !matches {
            errors.push(format!("{path} has the wrong JSON type"));
            return;
        }
    }
    if let (Some(object), Some(properties)) = (
        value.as_object(),
        schema.get("properties").and_then(Value::as_object),
    ) {
        if let Some(required) = schema.get("required").and_then(Value::as_array) {
            for key in required.iter().filter_map(Value::as_str) {
                if !object.contains_key(key) {
                    errors.push(format!("{path}.{key} is required"));
                }
            }
        }
        if schema.get("additionalProperties") == Some(&Value::Bool(false)) {
            for key in object.keys() {
                if !properties.contains_key(key) {
                    errors.push(format!("{path}.{key} is not allowed"));
                }
            }
        }
        for (key, property_schema) in properties {
            if let Some(property_value) = object.get(key) {
                validate_against_schema(
                    property_schema,
                    property_value,
                    &format!("{path}.{key}"),
                    errors,
                );
            }
        }
    }
    if let (Some(array), Some(item_schema)) = (value.as_array(), schema.get("items")) {
        for (index, item) in array.iter().enumerate() {
            validate_against_schema(item_schema, item, &format!("{path}[{index}]"), errors);
        }
    }
}

pub(crate) fn schema_validation_errors(schema: &Value, value: &Value) -> Vec<String> {
    let mut errors = Vec::new();
    validate_against_schema(schema, value, "$", &mut errors);
    errors
}

const MAX_TASK_SUMMARY_CHARS: usize = 2_048;

pub(crate) fn truncate_summary(text: &str) -> String {
    let mut chars = text.chars();
    let truncated: String = chars.by_ref().take(MAX_TASK_SUMMARY_CHARS).collect();
    if chars.next().is_some() {
        format!("{truncated}\n[truncated]")
    } else {
        truncated
    }
}

pub(crate) async fn task_for_child_session(
    child_session_id: SessionId,
    session_store: &dyn SessionStore,
    task_registry: &dyn crate::session_task::SessionTaskRegistry,
) -> crate::error::Result<Option<(SessionTask, WorkspaceId)>> {
    let Some(child) = session_store.get_session(child_session_id).await? else {
        return Ok(None);
    };
    let Some(parent_session_id) = child.parent_session_id.or(child.forked_from_session_id) else {
        return Ok(None);
    };
    let Some(parent) = session_store.get_session(parent_session_id).await? else {
        return Ok(None);
    };
    let task = task_registry
        .list(parent_session_id, None)
        .await?
        .into_iter()
        .find(|task| task.links.child_session_id == Some(child_session_id));
    Ok(task.map(|task| (task, parent.workspace_id)))
}

pub struct ReportResultTool {
    parent_session_id: SessionId,
    parent_workspace_id: WorkspaceId,
    task_id: String,
    result_schema: Value,
    file_store: Option<Arc<dyn SessionFileSystem>>,
}

impl ReportResultTool {
    pub fn new(
        parent_session_id: SessionId,
        parent_workspace_id: WorkspaceId,
        task_id: String,
        result_schema: Value,
    ) -> Self {
        Self {
            parent_session_id,
            parent_workspace_id,
            task_id,
            result_schema,
            file_store: None,
        }
    }

    pub fn with_file_store(mut self, file_store: Arc<dyn SessionFileSystem>) -> Self {
        self.file_store = Some(file_store);
        self
    }
}

#[async_trait]
impl Tool for ReportResultTool {
    fn name(&self) -> &str {
        "report_result"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Report Result")
    }

    fn description(&self) -> &str {
        "Submit the final structured result for this delegated task. The call arguments must match the declared result schema."
    }

    fn parameters_schema(&self) -> Value {
        self.result_schema.clone()
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "report_result requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let errors = schema_validation_errors(&self.result_schema, &arguments);
        if !errors.is_empty() {
            return ToolExecutionResult::tool_error(format!(
                "report_result arguments do not match result_schema: {}",
                errors.join("; ")
            ));
        }
        let Some(registry) = context.session_task_registry.as_ref() else {
            return ToolExecutionResult::tool_error(
                "report_result requires session_task_registry context",
            );
        };
        let Some(file_store) = self.file_store.as_ref().or(context.file_store.as_ref()) else {
            return ToolExecutionResult::tool_error("report_result requires file_store context");
        };
        let path = task_result_path(&self.task_id);
        let content = match serde_json::to_string_pretty(&arguments) {
            Ok(content) => content,
            Err(error) => return ToolExecutionResult::internal_error(error),
        };
        let parent_workspace_key = SessionId::from_uuid(self.parent_workspace_id.uuid());
        if let Err(error) = file_store
            .write_file(parent_workspace_key, &path, &content, "utf-8")
            .await
        {
            return ToolExecutionResult::internal_error(error);
        }
        if let Err(error) = registry
            .update(
                self.parent_session_id,
                &self.task_id,
                SessionTaskUpdate {
                    result_path: Some(path.clone()),
                    summary: Some(truncate_summary(&content)),
                    ..Default::default()
                },
            )
            .await
        {
            return ToolExecutionResult::internal_error(error);
        }
        ToolExecutionResult::success(json!({
            "status": "recorded",
            "task_id": self.task_id,
            "result_path": path,
        }))
    }

    fn requires_context(&self) -> bool {
        true
    }
}

pub struct ReportTaskProgressTool {
    parent_session_id: SessionId,
    task_id: String,
    message_schema: Value,
}

impl ReportTaskProgressTool {
    pub fn new(parent_session_id: SessionId, task_id: String, message_schema: Value) -> Self {
        Self {
            parent_session_id,
            task_id,
            message_schema,
        }
    }
}

#[async_trait]
impl Tool for ReportTaskProgressTool {
    fn name(&self) -> &str {
        "report_task_progress"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Report Task Progress")
    }

    fn description(&self) -> &str {
        "Post a structured progress message for this delegated task. The call arguments must match the declared message schema."
    }

    fn parameters_schema(&self) -> Value {
        self.message_schema.clone()
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "report_task_progress requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let errors = schema_validation_errors(&self.message_schema, &arguments);
        if !errors.is_empty() {
            return ToolExecutionResult::tool_error(format!(
                "report_task_progress arguments do not match message_schema: {}",
                errors.join("; ")
            ));
        }
        let Some(registry) = context.session_task_registry.as_ref() else {
            return ToolExecutionResult::tool_error(
                "report_task_progress requires session_task_registry context",
            );
        };
        let stored = match registry
            .record_message(
                self.parent_session_id,
                &self.task_id,
                NewTaskMessage {
                    direction: TaskMessageDirection::Outbound,
                    content: vec![TaskMessagePart::Data {
                        data: arguments.clone(),
                    }],
                    in_reply_to: None,
                    expected_attempt: None,
                },
            )
            .await
        {
            Ok(stored) => stored,
            Err(error) => return ToolExecutionResult::internal_error(error),
        };
        ToolExecutionResult::success(json!({
            "status": "posted",
            "task_id": self.task_id,
            "message_id": stored.id,
        }))
    }

    fn requires_context(&self) -> bool {
        true
    }
}

pub async fn report_result_tool_for_child_session(
    child_session_id: SessionId,
    session_store: &dyn SessionStore,
    task_registry: &dyn crate::session_task::SessionTaskRegistry,
) -> crate::error::Result<Option<ReportResultTool>> {
    let Some((task, parent_workspace_id)) =
        task_for_child_session(child_session_id, session_store, task_registry).await?
    else {
        return Ok(None);
    };
    let Some(schema) = declared_result_schema(&task).cloned() else {
        return Ok(None);
    };
    Ok(Some(ReportResultTool::new(
        task.session_id,
        parent_workspace_id,
        task.id,
        schema,
    )))
}

pub async fn report_task_progress_tool_for_child_session(
    child_session_id: SessionId,
    session_store: &dyn SessionStore,
    task_registry: &dyn crate::session_task::SessionTaskRegistry,
) -> crate::error::Result<Option<ReportTaskProgressTool>> {
    let Some((task, _)) =
        task_for_child_session(child_session_id, session_store, task_registry).await?
    else {
        return Ok(None);
    };
    let Some(schema) = declared_message_schema(&task).cloned() else {
        return Ok(None);
    };
    Ok(Some(ReportTaskProgressTool::new(
        task.session_id,
        task.id,
        schema,
    )))
}

pub(crate) async fn result_value_for_task(
    context: &ToolContext,
    task_id: Option<&str>,
) -> Option<Value> {
    let task_id = task_id?;
    let registry = context.session_task_registry.as_ref()?;
    let task = registry
        .get(context.session_id, task_id)
        .await
        .ok()
        .flatten()?;
    declared_result_schema(&task)?;
    let result_path = task.result_path.as_deref()?;
    let file_store = context.file_store.as_ref()?;
    let file = file_store
        .read_file(context.workspace_fs_key(), result_path)
        .await
        .ok()
        .flatten()?;
    serde_json::from_str(file.content.as_deref()?).ok()
}

pub(crate) async fn required_result_is_missing(
    context: &ToolContext,
    task_id: Option<&str>,
) -> bool {
    let Some(task_id) = task_id else {
        return false;
    };
    let Some(registry) = context.session_task_registry.as_ref() else {
        return false;
    };
    registry
        .get(context.session_id, task_id)
        .await
        .ok()
        .flatten()
        .is_some_and(|task| declared_result_schema(&task).is_some() && task.result_path.is_none())
}

pub(crate) async fn write_task_result_value(
    context: &ToolContext,
    task_id: &str,
    value: &Value,
) -> crate::error::Result<Option<String>> {
    let Some(file_store) = context.file_store.as_ref() else {
        return Ok(None);
    };
    let path = task_result_path(task_id);
    let content = serde_json::to_string_pretty(value).map_err(|error| {
        crate::error::AgentLoopError::store(format!("failed to serialize task result: {error}"))
    })?;
    file_store
        .write_file(context.workspace_fs_key(), &path, &content, "utf-8")
        .await?;
    Ok(Some(path))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shared_validator_reports_required_type_and_extra_property_errors() {
        let schema = json!({
            "type": "object",
            "properties": {
                "answer": {"type": "string"},
                "count": {"type": "integer"}
            },
            "required": ["answer", "count"],
            "additionalProperties": false
        });
        let errors =
            schema_validation_errors(&schema, &json!({"count": "not-an-integer", "extra": true}));
        assert!(errors.iter().any(|error| error == "$.answer is required"));
        assert!(
            errors
                .iter()
                .any(|error| error == "$.count has the wrong JSON type")
        );
        assert!(errors.iter().any(|error| error == "$.extra is not allowed"));
    }

    #[test]
    fn shared_schema_normalization_rejects_non_objects() {
        let ToolExecutionResult::ToolError(error) =
            normalize_result_schema(&json!({"result_schema": "object"})).unwrap_err()
        else {
            panic!("expected tool error");
        };
        assert!(error.contains("result_schema must be a JSON Schema object"));
    }
}