enki-next 0.5.78

Enki's Rust agent runtime, workflow engine, and shared core abstractions.
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
use crate::agent::AgentDefinition;
use crate::agent::core::Agent;
use crate::llm::{
    ChatMessage, LlmConfig, LlmError, LlmProvider, LlmResponse, Result as LlmResult, ToolDefinition,
};
use crate::tooling::types::{
    Tool, ToolContext, ToolRegistry, ToolRegistryBuilder, parse_tool_args,
};
use async_trait::async_trait;
use futures::stream;
use serde::Deserialize;
use serde_json::Value;
use serde_json::json;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Clone)]
struct RecordingLlm {
    responses: Arc<Mutex<VecDeque<LlmResponse>>>,
    calls: Arc<Mutex<Vec<Vec<ChatMessage>>>>,
    tool_calls: Arc<Mutex<Vec<Vec<ToolDefinition>>>>,
}

impl RecordingLlm {
    fn new(responses: Vec<LlmResponse>) -> Self {
        Self {
            responses: Arc::new(Mutex::new(responses.into())),
            calls: Arc::new(Mutex::new(Vec::new())),
            tool_calls: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn calls(&self) -> Vec<Vec<ChatMessage>> {
        self.calls.lock().unwrap().clone()
    }

    fn requested_tools(&self) -> Vec<Vec<ToolDefinition>> {
        self.tool_calls.lock().unwrap().clone()
    }
}

#[async_trait]
impl LlmProvider for RecordingLlm {
    async fn complete(
        &self,
        _messages: &[ChatMessage],
        _config: &LlmConfig,
    ) -> LlmResult<LlmResponse> {
        Err(LlmError::Provider("not used".to_string()))
    }

    async fn complete_stream(
        &self,
        _messages: &[ChatMessage],
        _config: &LlmConfig,
    ) -> LlmResult<crate::llm::ResponseStream> {
        Ok(Box::pin(stream::empty()))
    }

    async fn complete_with_tools(
        &self,
        messages: &[ChatMessage],
        tools: &[ToolDefinition],
        _config: &LlmConfig,
    ) -> LlmResult<LlmResponse> {
        self.calls.lock().unwrap().push(messages.to_vec());
        self.tool_calls.lock().unwrap().push(tools.to_vec());
        self.responses
            .lock()
            .unwrap()
            .pop_front()
            .ok_or_else(|| LlmError::Provider("missing response".to_string()))
    }

    fn name(&self) -> &'static str {
        "recording"
    }

    fn available_models(&self) -> Vec<&'static str> {
        vec!["recording"]
    }
}

fn temp_home(label: &str) -> PathBuf {
    let path = std::env::temp_dir().join(format!(
        "core-next-agent-tests-{label}-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or_default()
    ));
    std::fs::create_dir_all(&path).unwrap();
    path
}

#[derive(Deserialize)]
struct EchoParams {
    value: String,
}

struct EchoTool;

#[async_trait(?Send)]
impl Tool for EchoTool {
    fn name(&self) -> &str {
        "echo"
    }

    fn description(&self) -> &str {
        "Echo a value"
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "value": { "type": "string" }
            },
            "required": ["value"]
        })
    }

    async fn execute(&self, args: &Value, _ctx: &ToolContext) -> String {
        let params: EchoParams = match parse_tool_args(args) {
            Ok(params) => params,
            Err(error) => return format!("Error: failed to parse tool arguments: {error}"),
        };

        format!("echo:{}", params.value)
    }
}

#[test]
fn extracts_tool_call_from_mixed_content() {
    let assistant_message = json!({
        "role": "assistant",
        "content": "I'll save the note for you.\n\n{\"tool\":\"write_file\",\"args\":{\"path\":\"note.md\",\"content\":\"hello\"}}\n\nDone."
    });

    let tool_call =
        Agent::extract_embedded_tool_call(assistant_message["content"].as_str().unwrap());

    assert_eq!(
        tool_call,
        Some((
            "write_file".to_string(),
            json!({
                "path": "note.md",
                "content": "hello"
            })
        ))
    );
}

#[test]
fn ignores_non_tool_json_objects() {
    let content = "Summary: {\"ok\":true}\n{\"tool\":\"exec\",\"args\":{\"cmd\":\"pwd\"}}";

    let tool_call = Agent::extract_embedded_tool_call(content);

    assert_eq!(
        tool_call,
        Some((
            "exec".to_string(),
            json!({
                "cmd": "pwd"
            })
        ))
    );
}

#[test]
fn repairs_tool_call_with_missing_closing_brace() {
    // Small LLMs sometimes drop the final `}` after long content strings
    let content = r##"I'll write the note.

{"tool": "write_file", "args": {"path": "note.md", "content": "# Hello World"}"##;

    let tool_call = Agent::extract_embedded_tool_call(content);

    assert_eq!(
        tool_call,
        Some((
            "write_file".to_string(),
            json!({
                "path": "note.md",
                "content": "# Hello World"
            })
        ))
    );
}

#[test]
fn extracts_tool_call_from_code_fence() {
    let content = "Here is the tool call:\n\n```json\n{\"tool\": \"write_file\", \"args\": {\"path\": \"note.md\", \"content\": \"hello\"}}\n```\n\nDone.";

    let tool_call = Agent::extract_embedded_tool_call(content);

    assert_eq!(
        tool_call,
        Some((
            "write_file".to_string(),
            json!({
                "path": "note.md",
                "content": "hello"
            })
        ))
    );
}

#[test]
fn system_prompt_uses_default_agentic_loop_when_no_override_is_present() {
    let (preamble, agentic_loop) = Agent::split_system_prompt_preamble("Keep responses concise.");

    assert_eq!(preamble, "Keep responses concise.");
    assert!(agentic_loop.contains("Process each incoming user message as a loop"));
}

#[test]
fn system_prompt_extracts_custom_agentic_loop_from_preamble() {
    let (preamble, agentic_loop) = Agent::split_system_prompt_preamble(
        "Keep responses concise.\n<enki:agentic-loop>\n- Think briefly.\n- Call tools only after planning.\n</enki:agentic-loop>",
    );

    assert_eq!(preamble, "Keep responses concise.");
    assert_eq!(
        agentic_loop,
        "- Think briefly.\n- Call tools only after planning."
    );
}

#[tokio::test]
async fn reloads_previous_session_messages_before_next_request() {
    let home = temp_home("resume");
    let llm = RecordingLlm::new(vec![
        LlmResponse {
            content: "First answer".to_string(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
        LlmResponse {
            content: "Second answer".to_string(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
    ]);

    let agent = Agent::with_definition_executor_llm_and_workspace(
        AgentDefinition::default(),
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home.clone()),
    )
    .await
    .unwrap();

    assert_eq!(agent.run("session-a", "hello").await, "First answer");
    assert_eq!(agent.run("session-a", "follow up").await, "Second answer");

    let calls = llm.calls();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[1].len(), 4);
    assert_eq!(calls[1][1].content, "hello");
    assert_eq!(calls[1][2].content, "First answer");
    assert_eq!(calls[1][3].content, "follow up");
}

#[tokio::test]
async fn persists_terminal_error_to_session_transcript() {
    let home = temp_home("error");
    let llm = RecordingLlm::new(Vec::new());

    let agent = Agent::with_definition_executor_llm_and_workspace(
        AgentDefinition::default(),
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm)),
        None,
        Some(home.clone()),
    )
    .await
    .unwrap();

    let result = agent.run("session-a", "hello").await;
    assert_eq!(result, "LLM error: Provider error: missing response");

    let session_file = home
        .join(".atomiagent")
        .join("agents")
        .join("personal-assistant")
        .join("sessions")
        .join("session-a.json");
    let raw = std::fs::read_to_string(session_file).unwrap();
    let transcript: Vec<serde_json::Value> = serde_json::from_str(&raw).unwrap();

    let last = transcript.last().unwrap();
    assert_eq!(
        last["payload"]["content"].as_str().unwrap(),
        "LLM error: Provider error: missing response"
    );
}

#[tokio::test]
async fn exposes_builtin_tools_by_default() {
    let home = temp_home("builtin-tools-default");
    let llm = RecordingLlm::new(vec![LlmResponse {
        content: "Builtin tools enabled".to_string(),
        usage: None,
        tool_calls: Vec::new(),
        model: "recording".to_string(),
        finish_reason: Some("stop".to_string()),
    }]);

    let agent = Agent::with_definition_executor_llm_and_workspace(
        AgentDefinition::default(),
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home),
    )
    .await
    .unwrap();

    assert_eq!(
        agent.run("session-a", "hello").await,
        "Builtin tools enabled"
    );

    let requested_tools = llm.requested_tools();
    assert_eq!(requested_tools.len(), 1);
    let tool_names = requested_tools[0]
        .iter()
        .map(|tool| tool.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(tool_names, vec!["exec", "read_file", "write_file"]);
}

#[tokio::test]
async fn custom_tool_registry_is_merged_with_builtin_tools() {
    let home = temp_home("builtin-tools-merge");
    let llm = RecordingLlm::new(vec![LlmResponse {
        content: "Merged tools enabled".to_string(),
        usage: None,
        tool_calls: Vec::new(),
        model: "recording".to_string(),
        finish_reason: Some("stop".to_string()),
    }]);

    let tool_registry = ToolRegistryBuilder::new().register(EchoTool).build();

    let agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
        AgentDefinition::default(),
        tool_registry,
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home),
    )
    .await
    .unwrap();

    assert_eq!(
        agent.run("session-a", "hello").await,
        "Merged tools enabled"
    );

    let requested_tools = llm.requested_tools();
    assert_eq!(requested_tools.len(), 1);
    let tool_names = requested_tools[0]
        .iter()
        .map(|tool| tool.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(tool_names, vec!["echo", "exec", "read_file", "write_file"]);
}

#[tokio::test]
async fn tool_registry_can_be_connected_after_agent_construction() {
    let home = temp_home("dynamic-tool-registry");
    let llm = RecordingLlm::new(vec![LlmResponse {
        content: "Dynamic tools enabled".to_string(),
        usage: None,
        tool_calls: Vec::new(),
        model: "recording".to_string(),
        finish_reason: Some("stop".to_string()),
    }]);

    let mut agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
        AgentDefinition::default(),
        ToolRegistry::new(),
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home),
    )
    .await
    .unwrap();

    let registry = ToolRegistryBuilder::new().register(EchoTool).build();
    agent.connect_tool_registry(registry.clone());

    assert!(
        agent
            .tool_registry
            .tool_names()
            .contains(&"echo".to_string())
    );
    assert_eq!(
        agent.run("session-a", "hello").await,
        "Dynamic tools enabled"
    );

    let requested_tools = llm.requested_tools();
    assert_eq!(requested_tools.len(), 1);
    let tool_names = requested_tools[0]
        .iter()
        .map(|tool| tool.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(tool_names, vec!["echo", "exec", "read_file", "write_file"]);
}

#[tokio::test]
async fn executes_function_tools_from_native_stringified_arguments() {
    let home = temp_home("function-tool");
    let llm = RecordingLlm::new(vec![
        LlmResponse {
            content: String::new(),
            usage: None,
            tool_calls: vec![
                json!({
                    "id": "call-1",
                    "function": {
                        "name": "echo",
                        "arguments": "{\"value\":\"hello\"}"
                    }
                })
                .to_string(),
            ],
            model: "recording".to_string(),
            finish_reason: Some("tool_calls".to_string()),
        },
        LlmResponse {
            content: "done".to_string(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
    ]);

    let tool_registry = ToolRegistryBuilder::new().register(EchoTool).build();

    let agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
        AgentDefinition::default(),
        tool_registry,
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home),
    )
    .await
    .unwrap();

    assert_eq!(agent.run("session-a", "hello").await, "done");

    let calls = llm.calls();
    assert_eq!(calls.len(), 2);
    assert_eq!(calls[1][3].content, "echo:hello");
    assert_eq!(calls[1][3].tool_call_id.as_deref(), Some("call-1"));
}

#[tokio::test]
async fn detailed_run_traces_tool_call_minor_steps() {
    let home = temp_home("trace-tool-steps");
    let llm = RecordingLlm::new(vec![
        LlmResponse {
            content: String::new(),
            usage: None,
            tool_calls: vec![
                json!({
                    "id": "call-1",
                    "function": {
                        "name": "echo",
                        "arguments": "{\"value\":\"hello\"}"
                    }
                })
                .to_string(),
            ],
            model: "recording".to_string(),
            finish_reason: Some("tool_calls".to_string()),
        },
        LlmResponse {
            content: "done".to_string(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
    ]);

    let tool_registry = ToolRegistryBuilder::new().register(EchoTool).build();

    let agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
        AgentDefinition::default(),
        tool_registry,
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm)),
        None,
        Some(home),
    )
    .await
    .unwrap();

    let result = agent.run_detailed("session-a", "hello", None).await;

    assert_eq!(result.content, "done");
    assert!(result.steps.iter().any(|step| {
        step.kind == "tool_call"
            && step.detail.contains("echo")
            && step.detail.contains("{\"value\":\"hello\"}")
    }));
    assert!(result.steps.iter().any(|step| {
        step.kind == "tool_result"
            && step.detail.contains("echo")
            && step.detail.contains("echo:hello")
    }));
}

#[tokio::test]
async fn retries_when_model_returns_empty_final_response_after_tool_call() {
    let home = temp_home("empty-final-retry");
    let llm = RecordingLlm::new(vec![
        LlmResponse {
            content: String::new(),
            usage: None,
            tool_calls: vec![
                json!({
                    "id": "call-1",
                    "function": {
                        "name": "echo",
                        "arguments": "{\"value\":\"hello\"}"
                    }
                })
                .to_string(),
            ],
            model: "recording".to_string(),
            finish_reason: Some("tool_calls".to_string()),
        },
        LlmResponse {
            content: String::new(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
        LlmResponse {
            content: "done".to_string(),
            usage: None,
            tool_calls: Vec::new(),
            model: "recording".to_string(),
            finish_reason: Some("stop".to_string()),
        },
    ]);

    let tool_registry = ToolRegistryBuilder::new().register(EchoTool).build();

    let agent = Agent::with_definition_tool_registry_executor_llm_and_workspace(
        AgentDefinition::default(),
        tool_registry,
        Box::new(crate::tooling::tool_calling::RegistryToolExecutor),
        Some(Box::new(llm.clone())),
        None,
        Some(home),
    )
    .await
    .unwrap();

    let result = agent.run_detailed("session-a", "hello", None).await;

    assert_eq!(result.content, "done");
    assert!(result.steps.iter().any(|step| {
        step.kind == "retry"
            && step
                .detail
                .contains("Model returned an empty response with no tool calls.")
    }));
    assert_eq!(llm.calls().len(), 3);
}