- IAgentTool.ReadsForeignContent: Werkzeuge mit Aussenkontakt erklaeren sich selbst (WebFetch, WebMonitor, DirectAPI, Mail, RocketChat, Telegram, TelegramClient, SocialMediaManager, FTP, Database); AgentConfig.TreatAsForeignReader kann nur verschaerfen - ReportingLine: Stufe aus den Werkzeugen, "wer steht darueber", Pruefung des Wegs nach oben (nie Aenderungen an Aufgaben darueber, nur eine Ebene hoch, Fremdinhalt-Stufe gar kein Freitext) und Rahmung als untrusted_content - Engine: Nachricht und Spawn nach oben geprueft, Text der Fremdinhalt-Stufe kommt gerahmt an - Taskboard: task_create/update/comment, reopen und die Dubletten-Notiz folgen dem Berichtsweg - Dispatcher: Aufgaben von Agenten der Fremdinhalt-Stufe gehen gerahmt in den Lauf - TaskReports: Erledigt-Signal und Systemmeldung (in Pruefung, blockiert, abgebrochen) an den Auftraggeber, je Zustand einmal, gesammelt in einer offenen Aufgabe je Empfaenger - OrgBriefing nennt den Berichtsweg; WebUI zeigt Stufe und Schalter am Agenten Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
344 lines
14 KiB
C#
344 lines
14 KiB
C#
using System.Text.Json;
|
|
using ClawdDotNet.Core.Tools;
|
|
using MailKit;
|
|
using MailKit.Net.Imap;
|
|
using MailKit.Net.Smtp;
|
|
using MailKit.Search;
|
|
using Microsoft.Extensions.Logging;
|
|
using MimeKit;
|
|
|
|
using ClawdDotNet.Core.State;
|
|
|
|
namespace ClawdDotNet.Tools.Mail;
|
|
|
|
public sealed class MailTool : IAgentTool, IToolJobProvider
|
|
{
|
|
public string Name => "Mail";
|
|
|
|
/// <summary>#715: Brings text from outside into the context — mails from anyone.</summary>
|
|
public bool ReadsForeignContent => true;
|
|
|
|
public string Description => "Allows sending and receiving emails via SMTP and IMAP.";
|
|
|
|
public JsonElement InputSchema { get; } = JsonDocument.Parse("""
|
|
{
|
|
"type": "object",
|
|
"properties": {
|
|
"action": {
|
|
"type": "string",
|
|
"enum": ["send", "read_inbox", "read_message", "mark_read"],
|
|
"description": "The action to perform"
|
|
},
|
|
"to": {
|
|
"type": "string",
|
|
"description": "Recipient email (only for send)"
|
|
},
|
|
"subject": {
|
|
"type": "string",
|
|
"description": "Subject (only for send)"
|
|
},
|
|
"body": {
|
|
"type": "string",
|
|
"description": "Body of the email (only for send)"
|
|
},
|
|
"limit": {
|
|
"type": "integer",
|
|
"description": "Maximum number of emails to retrieve (only for read_inbox)"
|
|
},
|
|
"messageId": {
|
|
"type": "string",
|
|
"description": "The message ID (for read_message or mark_read)"
|
|
}
|
|
},
|
|
"required": ["action"]
|
|
}
|
|
""").RootElement.Clone();
|
|
|
|
public async Task<ToolResult> ExecuteAsync(
|
|
JsonElement input,
|
|
AgentToolContext context,
|
|
CancellationToken ct)
|
|
{
|
|
var action = input.GetProperty("action").GetString()
|
|
?? throw new ArgumentException("'action' is required");
|
|
|
|
try
|
|
{
|
|
return action switch
|
|
{
|
|
"send" => await HandleSendAsync(input, context, ct),
|
|
"read_inbox" => await HandleReadInboxAsync(input, context, ct),
|
|
"read_message" => await HandleReadMessageAsync(input, context, ct),
|
|
"mark_read" => await HandleMarkReadAsync(input, context, ct),
|
|
_ => ToolResult.Fail($"Unknown action: {action}")
|
|
};
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
context.Logger.LogError(ex, "Error during Mail action {Action}", action);
|
|
return ToolResult.Fail($"Error: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private async Task<ToolResult> HandleSendAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
var to = input.TryGetProperty("to", out var t) ? t.GetString() : null;
|
|
var subject = (input.TryGetProperty("subject", out var s) ? s.GetString() : null) ?? "(No Subject)";
|
|
var body = (input.TryGetProperty("body", out var b) ? b.GetString() : null) ?? "";
|
|
|
|
if (string.IsNullOrWhiteSpace(to)) return ToolResult.Fail("'to' is required.");
|
|
|
|
// Sicherheitsprüfung: Erlaubte Empfänger
|
|
if (!IsRecipientAllowed(to, context))
|
|
{
|
|
return ToolResult.Fail($"Security error: Sending to '{to}' is not allowed.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "smtpHost", "smtpPort", 587, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
var message = new MimeMessage();
|
|
message.From.Add(new MailboxAddress("ClawdDotNet", access.UserName));
|
|
message.To.Add(MailboxAddress.Parse(to));
|
|
message.Subject = subject;
|
|
message.Body = new TextPart("plain") { Text = body };
|
|
|
|
using var client = new SmtpClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
await client.SendAsync(message, ct);
|
|
await client.DisconnectAsync(true, ct);
|
|
|
|
return ToolResult.Ok($"Email successfully sent to {to}.");
|
|
}
|
|
|
|
private async Task<ToolResult> HandleReadInboxAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
var limit = input.TryGetProperty("limit", out var l) ? l.GetInt32() : 10;
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
var messages = new List<object>();
|
|
|
|
for (int i = client.Inbox!.Count - 1; i >= Math.Max(0, client.Inbox!.Count - limit); i--)
|
|
{
|
|
var msg = await client.Inbox!.GetMessageAsync(i, ct);
|
|
messages.Add(new
|
|
{
|
|
Id = i.ToString(),
|
|
Date = msg.Date,
|
|
From = msg.From.ToString(),
|
|
Subject = msg.Subject
|
|
});
|
|
}
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok(JsonSerializer.Serialize(messages, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
|
|
private async Task<ToolResult> HandleReadMessageAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
|
|
{
|
|
return ToolResult.Fail("'messageId' (index) is required.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
var msg = await client.Inbox!.GetMessageAsync(index, ct);
|
|
|
|
var result = new
|
|
{
|
|
Id = index.ToString(),
|
|
Date = msg.Date,
|
|
From = msg.From.ToString(),
|
|
Subject = msg.Subject,
|
|
Body = msg.TextBody
|
|
};
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
|
|
private async Task<ToolResult> HandleMarkReadAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
|
|
{
|
|
return ToolResult.Fail("'messageId' (index) is required.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadWrite, ct);
|
|
await client.Inbox!.AddFlagsAsync(index, MessageFlags.Seen, true, ct);
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok($"Message {index} marked as read.");
|
|
}
|
|
|
|
/// <summary>Ein Zugang: Server, Port und Anmeldedaten — vollständig oder gar nicht.</summary>
|
|
private readonly record struct MailAccess(string Host, int Port, string UserName, string Password);
|
|
|
|
/// <summary>
|
|
/// Liest Server und Anmeldedaten aus der Werkzeug-Konfiguration.
|
|
///
|
|
/// <para>Vorher standen die Werte an vier Stellen einzeln im Aufruf:
|
|
/// <c>config["smtpHost"]?.ToString()</c>. Das ging auf zwei Arten schief. Fehlte der
|
|
/// Schlüssel ganz, warf der Indexer eine <c>KeyNotFoundException</c>; war er leer,
|
|
/// ging <c>null</c> an MailKit — worauf der Compiler mit fünfzehn
|
|
/// Nullable-Warnungen hinwies. Beim Agenten kam beides als dieselbe unbrauchbare
|
|
/// Zeile an: „Fehler: …".</para>
|
|
///
|
|
/// <para>Hier fällt stattdessen die Antwort aus, die weiterhilft: welcher Schlüssel
|
|
/// fehlt. Der Port bleibt weich — dafür gibt es sinnvolle Vorgaben; Server und
|
|
/// Anmeldedaten kann niemand raten.</para>
|
|
/// </summary>
|
|
private static bool TryReadAccess(
|
|
AgentToolContext context, string hostKey, string portKey, int defaultPort,
|
|
out MailAccess access, out string error)
|
|
{
|
|
access = default;
|
|
|
|
var host = ReadSetting(context, hostKey);
|
|
var user = ReadSetting(context, "username");
|
|
var password = ReadSetting(context, "password");
|
|
|
|
var missing = new List<string>();
|
|
if (string.IsNullOrWhiteSpace(host)) missing.Add(hostKey);
|
|
if (string.IsNullOrWhiteSpace(user)) missing.Add("username");
|
|
if (string.IsNullOrWhiteSpace(password)) missing.Add("password");
|
|
|
|
if (missing.Count > 0)
|
|
{
|
|
error = "The mail tool is not fully configured. " +
|
|
$"Missing in tool configuration: {string.Join(", ", missing)}.";
|
|
return false;
|
|
}
|
|
|
|
access = new MailAccess(host!, ReadPort(context, portKey, defaultPort), user!, password!);
|
|
error = "";
|
|
return true;
|
|
}
|
|
|
|
private static string? ReadSetting(AgentToolContext context, string key)
|
|
=> context.ToolConfig.TryGetValue(key, out var value) ? value?.ToString() : null;
|
|
|
|
private static int ReadPort(AgentToolContext context, string key, int fallback)
|
|
=> context.ToolConfig.TryGetValue(key, out var value)
|
|
&& value is JsonElement { ValueKind: JsonValueKind.Number } je
|
|
&& je.TryGetInt32(out var port)
|
|
? port
|
|
: fallback;
|
|
|
|
private bool IsRecipientAllowed(string email, AgentToolContext context)
|
|
{
|
|
if (!context.ToolConfig.TryGetValue("allowedRecipients", out var val) || val is not JsonElement je)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var allowed = je.EnumerateArray().Select(x => x.GetString()?.ToLowerInvariant()).ToList();
|
|
return allowed.Contains(email.ToLowerInvariant());
|
|
}
|
|
|
|
public IReadOnlyList<ToolJobDefinition> GetJobDefinitions() =>
|
|
[
|
|
new("mail_check_unread", "Mail Check", "Periodically checks for new unread emails")
|
|
];
|
|
|
|
public async Task<ToolJobResult> ExecuteJobAsync(
|
|
string jobTypeId,
|
|
IReadOnlyDictionary<string, object?> toolConfig,
|
|
IStateStore stateStore,
|
|
ILogger logger,
|
|
CancellationToken ct,
|
|
string? agentId = null,
|
|
string? workspacePath = null)
|
|
{
|
|
if (jobTypeId != "mail_check_unread")
|
|
return ToolJobResult.NoAction($"Unknown job: {jobTypeId}");
|
|
|
|
try
|
|
{
|
|
using var client = new ImapClient();
|
|
var imapHost = toolConfig.TryGetValue("imapHost", out var h) ? h?.ToString() : null;
|
|
var imapPort = toolConfig.TryGetValue("imapPort", out var p) ? (p is long l ? (int)l : (p is int i ? i : 993)) : 993;
|
|
var username = toolConfig.TryGetValue("username", out var u) ? u?.ToString() : null;
|
|
var password = toolConfig.TryGetValue("password", out var pw) ? pw?.ToString() : null;
|
|
|
|
if (string.IsNullOrWhiteSpace(imapHost) || string.IsNullOrWhiteSpace(username))
|
|
return ToolJobResult.NoAction("Mail configuration incomplete");
|
|
|
|
await client.ConnectAsync(imapHost, imapPort, true, ct);
|
|
await client.AuthenticateAsync(username ?? "", password ?? "", ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
|
|
// Wir suchen nach ungelesenen Nachrichten
|
|
var uids = await client.Inbox!.SearchAsync(SearchQuery.NotSeen, ct);
|
|
|
|
if (uids.Count == 0)
|
|
{
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolJobResult.NoAction("No new unread emails");
|
|
}
|
|
|
|
// Um zu vermeiden, dass wir bei jedem Tick für die gleichen Mails wecken,
|
|
// speichern wir die höchste UID, die wir bereits gemeldet haben.
|
|
var lastUidStr = await stateStore.GetAsync("mail_last_notified_uid", ct);
|
|
uint lastUid = uint.TryParse(lastUidStr, out var lu) ? lu : 0;
|
|
|
|
var newUids = uids.Where(uid => uid.Id > lastUid).OrderBy(uid => uid.Id).ToList();
|
|
|
|
if (newUids.Count == 0)
|
|
{
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolJobResult.NoAction("No new emails since last check");
|
|
}
|
|
|
|
// Die neuesten Nachrichten abrufen für die Zusammenfassung
|
|
var summary = new List<string>();
|
|
foreach (var uid in newUids.Take(5))
|
|
{
|
|
var msg = await client.Inbox!.GetMessageAsync(uid, ct);
|
|
summary.Add($"- From: {msg.From}, Subject: {msg.Subject}");
|
|
}
|
|
|
|
if (newUids.Count > 5) summary.Add($"- ... and {newUids.Count - 5} more");
|
|
|
|
// Höchste UID speichern
|
|
var maxUid = newUids.Max(u => u.Id);
|
|
await stateStore.SetAsync("mail_last_notified_uid", maxUid.ToString(), ct);
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
|
|
return ToolJobResult.Wake(
|
|
$"You have received {newUids.Count} new unread email(s):\n" + string.Join("\n", summary),
|
|
logSummary: $"{newUids.Count} new email(s) found"
|
|
);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error in Mail background job");
|
|
return ToolJobResult.NoAction($"Error: {ex.Message}");
|
|
}
|
|
}
|
|
}
|