-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathOpenClawGatewayClient.cs
More file actions
1615 lines (1424 loc) · 56.1 KB
/
OpenClawGatewayClient.cs
File metadata and controls
1615 lines (1424 loc) · 56.1 KB
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace OpenClaw.Shared;
public class OpenClawGatewayClient : WebSocketClientBase
{
// Tracked state
private readonly Dictionary<string, SessionInfo> _sessions = new();
private readonly Dictionary<string, GatewayNodeInfo> _nodes = new();
private GatewayUsageInfo? _usage;
private GatewayUsageStatusInfo? _usageStatus;
private GatewayCostUsageInfo? _usageCost;
private readonly Dictionary<string, string> _pendingRequestMethods = new();
private readonly object _pendingRequestLock = new();
private readonly object _sessionsLock = new();
private readonly object _nodesLock = new();
private bool _usageStatusUnsupported;
private bool _usageCostUnsupported;
private bool _sessionPreviewUnsupported;
private bool _nodeListUnsupported;
private bool _preferStructuredCategories = true;
/// <summary>
/// Controls whether structured notification metadata (Intent, Channel) takes priority
/// over keyword-based classification. Mirrors the <c>PreferStructuredCategories</c>
/// setting. Call after construction and whenever settings change.
/// </summary>
public void SetPreferStructuredCategories(bool value)
{
_preferStructuredCategories = value;
}
private void ResetUnsupportedMethodFlags()
{
_usageStatusUnsupported = false;
_usageCostUnsupported = false;
_sessionPreviewUnsupported = false;
_nodeListUnsupported = false;
}
protected override int ReceiveBufferSize => 16384;
protected override string ClientRole => "gateway";
protected override Task ProcessMessageAsync(string json)
{
ProcessMessage(json);
return Task.CompletedTask;
}
protected override Task OnConnectedAsync()
{
ResetUnsupportedMethodFlags();
return Task.CompletedTask;
}
protected override void OnDisconnected()
{
ClearPendingRequests();
}
protected override void OnDisposing()
{
ClearPendingRequests();
}
// Events
public event EventHandler<OpenClawNotification>? NotificationReceived;
public event EventHandler<AgentActivity>? ActivityChanged;
public event EventHandler<ChannelHealth[]>? ChannelHealthUpdated;
public event EventHandler<SessionInfo[]>? SessionsUpdated;
public event EventHandler<GatewayUsageInfo>? UsageUpdated;
public event EventHandler<GatewayUsageStatusInfo>? UsageStatusUpdated;
public event EventHandler<GatewayCostUsageInfo>? UsageCostUpdated;
public event EventHandler<GatewayNodeInfo[]>? NodesUpdated;
public event EventHandler<SessionsPreviewPayloadInfo>? SessionPreviewUpdated;
public event EventHandler<SessionCommandResult>? SessionCommandCompleted;
public OpenClawGatewayClient(string gatewayUrl, string token, IOpenClawLogger? logger = null)
: base(gatewayUrl, token, logger)
{
}
public async Task DisconnectAsync()
{
if (IsConnected)
{
try
{
await CloseWebSocketAsync();
}
catch (Exception ex)
{
_logger.Warn($"Error during disconnect: {ex.Message}");
}
}
ClearPendingRequests();
RaiseStatusChanged(ConnectionStatus.Disconnected);
_logger.Info("Disconnected");
}
public async Task CheckHealthAsync()
{
if (!IsConnected)
{
await ReconnectWithBackoffAsync();
return;
}
try
{
var req = new
{
type = "req",
id = Guid.NewGuid().ToString(),
method = "health",
@params = new { deep = true }
};
await SendRawAsync(JsonSerializer.Serialize(req));
}
catch (Exception ex)
{
_logger.Error("Health check failed", ex);
RaiseStatusChanged(ConnectionStatus.Error);
await ReconnectWithBackoffAsync();
}
}
public async Task SendChatMessageAsync(string message)
{
if (!IsConnected)
throw new InvalidOperationException("Gateway connection is not open");
var req = new
{
type = "req",
id = Guid.NewGuid().ToString(),
method = "chat.send",
@params = new { message }
};
await SendRawAsync(JsonSerializer.Serialize(req));
_logger.Info($"Sent chat message ({message.Length} chars)");
}
/// <summary>Request session list from gateway.</summary>
public async Task RequestSessionsAsync()
{
await SendTrackedRequestAsync("sessions.list");
}
/// <summary>Request usage/context info from gateway (may not be supported on all gateways).</summary>
public async Task RequestUsageAsync()
{
if (!IsConnected) return;
try
{
if (_usageStatusUnsupported)
{
await RequestLegacyUsageAsync();
return;
}
await RequestUsageStatusAsync();
if (!_usageCostUnsupported)
{
await RequestUsageCostAsync(days: 30);
}
}
catch (Exception ex)
{
_logger.Warn($"Usage request failed: {ex.Message}");
}
}
/// <summary>Request connected node inventory from gateway.</summary>
public async Task RequestNodesAsync()
{
if (_nodeListUnsupported) return;
await SendTrackedRequestAsync("node.list");
}
public async Task RequestUsageStatusAsync()
{
await SendTrackedRequestAsync("usage.status");
}
public async Task RequestUsageCostAsync(int days = 30)
{
if (days <= 0) days = 30;
await SendTrackedRequestAsync("usage.cost", new { days });
}
public async Task RequestSessionPreviewAsync(string[] keys, int limit = 12, int maxChars = 240)
{
if (_sessionPreviewUnsupported) return;
if (keys.Length == 0) return;
if (limit <= 0) limit = 1;
if (maxChars < 20) maxChars = 20;
await SendTrackedRequestAsync("sessions.preview", new
{
keys,
limit,
maxChars
});
}
public Task<bool> PatchSessionAsync(string key, string? thinkingLevel = null, string? verboseLevel = null)
{
if (string.IsNullOrWhiteSpace(key)) return Task.FromResult(false);
var payload = new Dictionary<string, object?>
{
["key"] = key
};
if (thinkingLevel is not null)
payload["thinkingLevel"] = thinkingLevel;
if (verboseLevel is not null)
payload["verboseLevel"] = verboseLevel;
return TrySendTrackedRequestAsync("sessions.patch", payload);
}
public Task<bool> ResetSessionAsync(string key)
{
if (string.IsNullOrWhiteSpace(key)) return Task.FromResult(false);
return TrySendTrackedRequestAsync("sessions.reset", new { key });
}
public Task<bool> DeleteSessionAsync(string key, bool deleteTranscript = true)
{
if (string.IsNullOrWhiteSpace(key)) return Task.FromResult(false);
return TrySendTrackedRequestAsync("sessions.delete", new { key, deleteTranscript });
}
public Task<bool> CompactSessionAsync(string key, int maxLines = 400)
{
if (string.IsNullOrWhiteSpace(key)) return Task.FromResult(false);
if (maxLines <= 0) maxLines = 400;
return TrySendTrackedRequestAsync("sessions.compact", new { key, maxLines });
}
/// <summary>Start a channel (telegram, whatsapp, etc).</summary>
public async Task<bool> StartChannelAsync(string channelName)
{
if (!IsConnected) return false;
try
{
var req = new
{
type = "req",
id = Guid.NewGuid().ToString(),
method = "channel.start",
@params = new { channel = channelName }
};
await SendRawAsync(JsonSerializer.Serialize(req));
_logger.Info($"Sent channel.start for {channelName}");
return true;
}
catch (Exception ex)
{
_logger.Error($"Failed to start channel {channelName}", ex);
return false;
}
}
/// <summary>Stop a channel (telegram, whatsapp, etc).</summary>
public async Task<bool> StopChannelAsync(string channelName)
{
if (!IsConnected) return false;
try
{
var req = new
{
type = "req",
id = Guid.NewGuid().ToString(),
method = "channel.stop",
@params = new { channel = channelName }
};
await SendRawAsync(JsonSerializer.Serialize(req));
_logger.Info($"Sent channel.stop for {channelName}");
return true;
}
catch (Exception ex)
{
_logger.Error($"Failed to stop channel {channelName}", ex);
return false;
}
}
private async Task SendConnectMessageAsync(string? nonce = null)
{
// Use "cli" client ID for native apps - no browser security checks
var msg = new
{
type = "req",
id = Guid.NewGuid().ToString(),
method = "connect",
@params = new
{
minProtocol = 3,
maxProtocol = 3,
client = new
{
id = "cli", // Native client ID
version = "1.0.0",
platform = "windows",
mode = "cli",
displayName = "OpenClaw Windows Tray"
},
role = "operator",
scopes = new[] { "operator.admin", "operator.approvals", "operator.pairing" },
caps = Array.Empty<string>(),
commands = Array.Empty<string>(),
permissions = new { },
auth = new { token = _token },
locale = "en-US",
userAgent = "openclaw-windows-tray/1.0.0"
}
};
await SendRawAsync(JsonSerializer.Serialize(msg));
}
private async Task SendTrackedRequestAsync(string method, object? parameters = null)
{
if (!IsConnected) return;
var requestId = Guid.NewGuid().ToString();
TrackPendingRequest(requestId, method);
try
{
await SendRawAsync(SerializeRequest(requestId, method, parameters));
}
catch
{
RemovePendingRequest(requestId);
throw;
}
}
private async Task<bool> TrySendTrackedRequestAsync(string method, object? parameters = null)
{
try
{
await SendTrackedRequestAsync(method, parameters);
return true;
}
catch (Exception ex)
{
_logger.Warn($"{method} request failed: {ex.Message}");
return false;
}
}
private async Task RequestLegacyUsageAsync()
{
try
{
await SendTrackedRequestAsync("usage");
}
catch (Exception ex)
{
_logger.Warn($"Legacy usage request failed: {ex.Message}");
}
}
private static string SerializeRequest(string requestId, string method, object? parameters)
{
if (parameters is null)
{
return JsonSerializer.Serialize(new { type = "req", id = requestId, method });
}
return JsonSerializer.Serialize(new { type = "req", id = requestId, method, @params = parameters });
}
private void TrackPendingRequest(string requestId, string method)
{
lock (_pendingRequestLock)
{
_pendingRequestMethods[requestId] = method;
}
}
private void RemovePendingRequest(string requestId)
{
lock (_pendingRequestLock)
{
_pendingRequestMethods.Remove(requestId);
}
}
private string? TakePendingRequestMethod(string? requestId)
{
if (string.IsNullOrWhiteSpace(requestId)) return null;
lock (_pendingRequestLock)
{
if (!_pendingRequestMethods.TryGetValue(requestId, out var method)) return null;
_pendingRequestMethods.Remove(requestId);
return method;
}
}
private void ClearPendingRequests()
{
lock (_pendingRequestLock)
{
_pendingRequestMethods.Clear();
}
}
// --- Message processing ---
private void ProcessMessage(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (!root.TryGetProperty("type", out var typeProp)) return;
var type = typeProp.GetString();
switch (type)
{
case "res":
HandleResponse(root);
break;
case "event":
HandleEvent(root);
break;
}
}
catch (JsonException ex)
{
_logger.Warn($"JSON parse error: {ex.Message}");
}
catch (Exception ex)
{
_logger.Error("Message processing error", ex);
}
}
private void HandleResponse(JsonElement root)
{
string? requestMethod = null;
if (root.TryGetProperty("id", out var idProp))
{
requestMethod = TakePendingRequestMethod(idProp.GetString());
}
if (root.TryGetProperty("ok", out var okProp) &&
okProp.ValueKind == JsonValueKind.False)
{
HandleRequestError(requestMethod, root);
return;
}
if (!root.TryGetProperty("payload", out var payload)) return;
if (!string.IsNullOrEmpty(requestMethod) && HandleKnownResponse(requestMethod!, payload))
{
return;
}
// Handle hello-ok
if (payload.TryGetProperty("type", out var t) && t.GetString() == "hello-ok")
{
_logger.Info("Handshake complete (hello-ok)");
RaiseStatusChanged(ConnectionStatus.Connected);
// Request initial state after handshake
_ = Task.Run(async () =>
{
await Task.Delay(500);
await CheckHealthAsync();
await RequestSessionsAsync();
await RequestUsageAsync();
await RequestNodesAsync();
});
}
// Handle health response — channels
if (payload.TryGetProperty("channels", out var channels))
{
ParseChannelHealth(channels);
}
// Handle sessions response
if (payload.TryGetProperty("sessions", out var sessions))
{
ParseSessions(sessions);
}
// Handle usage response
if (payload.TryGetProperty("usage", out var usage))
{
ParseUsage(usage);
}
if (payload.TryGetProperty("nodes", out var nodes))
{
ParseNodeList(nodes);
}
}
private bool HandleKnownResponse(string method, JsonElement payload)
{
switch (method)
{
case "health":
if (payload.TryGetProperty("channels", out var channels))
ParseChannelHealth(channels);
return true;
case "sessions.list":
if (TryGetSessionsPayload(payload, out var sessionsPayload))
ParseSessions(sessionsPayload);
return true;
case "usage":
ParseUsage(payload);
return true;
case "usage.status":
ParseUsageStatus(payload);
return true;
case "usage.cost":
ParseUsageCost(payload);
return true;
case "node.list":
if (TryGetNodesPayload(payload, out var nodesPayload))
ParseNodeList(nodesPayload);
return true;
case "sessions.preview":
ParseSessionsPreview(payload);
return true;
case "sessions.patch":
case "sessions.reset":
case "sessions.delete":
case "sessions.compact":
ParseSessionCommandResult(method, payload);
return true;
default:
return false;
}
}
private void HandleRequestError(string? method, JsonElement root)
{
var message = TryGetErrorMessage(root) ?? "request failed";
if (string.IsNullOrEmpty(method))
{
_logger.Warn($"Gateway request failed: {message}");
return;
}
if (IsUnknownMethodError(message))
{
switch (method)
{
case "usage.status":
_usageStatusUnsupported = true;
_logger.Warn("usage.status unsupported on gateway; falling back to usage");
_ = RequestLegacyUsageAsync();
return;
case "usage.cost":
_usageCostUnsupported = true;
_logger.Warn("usage.cost unsupported on gateway");
return;
case "sessions.preview":
_sessionPreviewUnsupported = true;
_logger.Warn("sessions.preview unsupported on gateway");
return;
case "node.list":
_nodeListUnsupported = true;
_logger.Warn("node.list unsupported on gateway");
return;
}
}
if (IsSessionCommandMethod(method))
{
SessionCommandCompleted?.Invoke(this, new SessionCommandResult
{
Method = method,
Ok = false,
Error = message
});
}
_logger.Warn($"{method} failed: {message}");
}
private static bool TryGetSessionsPayload(JsonElement payload, out JsonElement sessions)
{
if (payload.ValueKind == JsonValueKind.Object &&
payload.TryGetProperty("sessions", out sessions))
{
return true;
}
if (payload.ValueKind == JsonValueKind.Object || payload.ValueKind == JsonValueKind.Array)
{
sessions = payload;
return true;
}
sessions = default;
return false;
}
private static bool TryGetNodesPayload(JsonElement payload, out JsonElement nodes)
{
if (payload.ValueKind == JsonValueKind.Object &&
payload.TryGetProperty("nodes", out nodes))
{
return true;
}
if (payload.ValueKind == JsonValueKind.Array || payload.ValueKind == JsonValueKind.Object)
{
nodes = payload;
return true;
}
nodes = default;
return false;
}
private static string? TryGetErrorMessage(JsonElement root)
{
if (!root.TryGetProperty("error", out var error)) return null;
if (error.ValueKind == JsonValueKind.String) return error.GetString();
if (error.ValueKind != JsonValueKind.Object) return null;
if (error.TryGetProperty("message", out var message) && message.ValueKind == JsonValueKind.String)
return message.GetString();
return null;
}
private static bool IsUnknownMethodError(string errorMessage)
{
return errorMessage.Contains("unknown method", StringComparison.OrdinalIgnoreCase);
}
private static bool IsSessionCommandMethod(string method)
{
return method is "sessions.patch" or "sessions.reset" or "sessions.delete" or "sessions.compact";
}
private void HandleEvent(JsonElement root)
{
if (!root.TryGetProperty("event", out var eventProp)) return;
var eventType = eventProp.GetString();
switch (eventType)
{
case "connect.challenge":
HandleConnectChallenge(root);
break;
case "agent":
HandleAgentEvent(root);
break;
case "health":
if (root.TryGetProperty("payload", out var hp) &&
hp.TryGetProperty("channels", out var ch))
ParseChannelHealth(ch);
break;
case "chat":
HandleChatEvent(root);
break;
case "session":
HandleSessionEvent(root);
break;
}
}
private void HandleConnectChallenge(JsonElement root)
{
string? nonce = null;
if (root.TryGetProperty("payload", out var payload) &&
payload.TryGetProperty("nonce", out var nonceProp))
{
nonce = nonceProp.GetString();
}
_logger.Info($"Received challenge, nonce: {nonce}");
_ = SendConnectMessageAsync(nonce);
}
private void HandleAgentEvent(JsonElement root)
{
if (!root.TryGetProperty("payload", out var payload)) return;
// Determine session
var sessionKey = "unknown";
if (root.TryGetProperty("sessionKey", out var sk))
sessionKey = sk.GetString() ?? "unknown";
var isMain = sessionKey == "main" || sessionKey.Contains(":main:");
// Parse activity from stream field
if (payload.TryGetProperty("stream", out var streamProp))
{
var stream = streamProp.GetString();
if (stream == "job")
{
HandleJobEvent(payload, sessionKey, isMain);
}
else if (stream == "tool")
{
HandleToolEvent(payload, sessionKey, isMain);
}
}
// Check for notification content
if (payload.TryGetProperty("content", out var content))
{
var text = content.GetString() ?? "";
if (!string.IsNullOrEmpty(text))
{
EmitNotification(text);
}
}
}
private void HandleJobEvent(JsonElement payload, string sessionKey, bool isMain)
{
var state = "unknown";
if (payload.TryGetProperty("data", out var data) &&
data.TryGetProperty("state", out var stateProp))
state = stateProp.GetString() ?? "unknown";
var activity = new AgentActivity
{
SessionKey = sessionKey,
IsMain = isMain,
Kind = ActivityKind.Job,
State = state,
Label = $"Job: {state}"
};
if (state == "done" || state == "error")
activity.Kind = ActivityKind.Idle;
_logger.Info($"Agent activity: {activity.Label} (session: {sessionKey})");
ActivityChanged?.Invoke(this, activity);
// Update tracked session
UpdateTrackedSession(sessionKey, isMain, state == "done" || state == "error" ? null : $"Job: {state}");
}
private void HandleToolEvent(JsonElement payload, string sessionKey, bool isMain)
{
var phase = "";
var toolName = "";
var label = "";
if (payload.TryGetProperty("data", out var data))
{
if (data.TryGetProperty("phase", out var phaseProp))
phase = phaseProp.GetString() ?? "";
if (data.TryGetProperty("name", out var nameProp))
toolName = nameProp.GetString() ?? "";
// Extract detail from args
if (data.TryGetProperty("args", out var args))
{
if (args.TryGetProperty("command", out var cmd))
label = TruncateLabel(cmd.GetString()?.Split('\n')[0] ?? "");
else if (args.TryGetProperty("path", out var path))
label = ShortenPath(path.GetString() ?? "");
else if (args.TryGetProperty("file_path", out var filePath))
label = ShortenPath(filePath.GetString() ?? "");
else if (args.TryGetProperty("query", out var query))
label = TruncateLabel(query.GetString() ?? "");
else if (args.TryGetProperty("url", out var url))
label = TruncateLabel(url.GetString() ?? "");
}
}
if (string.IsNullOrEmpty(label))
label = toolName;
var kind = ClassifyTool(toolName);
// On tool result, briefly show then go idle
if (phase == "result")
kind = ActivityKind.Idle;
var activity = new AgentActivity
{
SessionKey = sessionKey,
IsMain = isMain,
Kind = kind,
State = phase,
ToolName = toolName,
Label = label
};
_logger.Info($"Tool: {toolName} ({phase}) — {label}");
ActivityChanged?.Invoke(this, activity);
// Update tracked session
if (kind != ActivityKind.Idle)
{
UpdateTrackedSession(sessionKey, isMain, $"{activity.Glyph} {label}");
}
}
private void HandleChatEvent(JsonElement root)
{
_logger.Debug($"Chat event received: {root.GetRawText().Substring(0, Math.Min(200, root.GetRawText().Length))}");
if (!root.TryGetProperty("payload", out var payload)) return;
// Try new format: payload.message.role + payload.message.content[].text
if (payload.TryGetProperty("message", out var message))
{
if (message.TryGetProperty("role", out var role) && role.GetString() == "assistant")
{
// Extract text from content array
if (message.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.Array)
{
foreach (var item in content.EnumerateArray())
{
if (item.TryGetProperty("type", out var type) && type.GetString() == "text" &&
item.TryGetProperty("text", out var textProp))
{
var text = textProp.GetString() ?? "";
if (!string.IsNullOrEmpty(text) &&
payload.TryGetProperty("state", out var state) &&
state.GetString() == "final")
{
_logger.Info($"Assistant response: {text.Substring(0, Math.Min(100, text.Length))}...");
EmitChatNotification(text);
}
}
}
}
}
}
// Legacy format: payload.text + payload.role
else if (payload.TryGetProperty("text", out var textProp))
{
var text = textProp.GetString() ?? "";
if (payload.TryGetProperty("role", out var role) &&
role.GetString() == "assistant" &&
!string.IsNullOrEmpty(text))
{
_logger.Info($"Assistant response (legacy): {text.Substring(0, Math.Min(100, text.Length))}");
EmitChatNotification(text);
}
}
}
private void EmitChatNotification(string text)
{
var displayText = text.Length > 200 ? text[..200] + "…" : text;
var notification = new OpenClawNotification
{
Message = displayText,
IsChat = true
};
var (title, type) = _categorizer.Classify(notification, preferStructuredCategories: _preferStructuredCategories);
notification.Title = title;
notification.Type = type;
NotificationReceived?.Invoke(this, notification);
}
private void HandleSessionEvent(JsonElement root)
{
// Re-request sessions list when session events come through
_ = RequestSessionsAsync();
}
// --- State tracking ---
private void UpdateTrackedSession(string sessionKey, bool isMain, string? currentActivity)
{
SessionInfo[] snapshot;
lock (_sessionsLock)
{
if (!_sessions.ContainsKey(sessionKey))
{
_sessions[sessionKey] = new SessionInfo
{
Key = sessionKey,
IsMain = isMain,
Status = "active"
};
}
_sessions[sessionKey].CurrentActivity = currentActivity;
_sessions[sessionKey].LastSeen = DateTime.UtcNow;
snapshot = GetSessionListInternal();
}
SessionsUpdated?.Invoke(this, snapshot);
}
public SessionInfo[] GetSessionList()
{
lock (_sessionsLock)
{
return GetSessionListInternal();
}
}
private SessionInfo[] GetSessionListInternal()
{
var list = new List<SessionInfo>(_sessions.Values);
list.Sort((a, b) =>
{
// Main session first, then by last seen
if (a.IsMain != b.IsMain) return a.IsMain ? -1 : 1;
return b.LastSeen.CompareTo(a.LastSeen);
});
return list.ToArray();
}
// --- Parsing helpers ---
private void ParseChannelHealth(JsonElement channels)
{
var healthList = new List<ChannelHealth>();
// Debug: log raw channel data
_logger.Debug($"Raw channel health JSON: {channels.GetRawText()}");
foreach (var prop in channels.EnumerateObject())
{
var ch = new ChannelHealth { Name = prop.Name };
var val = prop.Value;
// Get running status
bool isRunning = false;
bool isConfigured = false;
bool isLinked = false;
bool probeOk = false;
bool hasError = false;
string? tokenSource = null;
if (val.TryGetProperty("running", out var running))
isRunning = running.GetBoolean();
if (val.TryGetProperty("configured", out var configured))
isConfigured = configured.GetBoolean();
if (val.TryGetProperty("linked", out var linked))
{
isLinked = linked.GetBoolean();
ch.IsLinked = isLinked;
}
// Check probe status for webhook-based channels like Telegram
if (val.TryGetProperty("probe", out var probe) && probe.TryGetProperty("ok", out var ok))
probeOk = ok.GetBoolean();
// Check for errors
if (val.TryGetProperty("lastError", out var lastError) && lastError.ValueKind != JsonValueKind.Null)
hasError = true;
// Check token source (for Telegram - if configured, bot token was validated)
if (val.TryGetProperty("tokenSource", out var ts))
tokenSource = ts.GetString();
// Determine status string - unified for parity between channels
// Key insight: if configured=true and no errors, the channel is ready
// - WhatsApp: linked=true means authenticated
// - Telegram: configured=true means bot token was validated
if (val.TryGetProperty("status", out var status))
ch.Status = status.GetString() ?? "unknown";
else if (hasError)
ch.Status = "error";
else if (isRunning)
ch.Status = "running";
else if (isConfigured && (probeOk || isLinked))
ch.Status = "ready"; // Explicitly verified ready
else if (isConfigured && !hasError)
ch.Status = "ready"; // Configured without errors = ready (token was validated at config time)
else
ch.Status = "not configured";
if (val.TryGetProperty("error", out var error))
ch.Error = error.GetString();
if (val.TryGetProperty("authAge", out var authAge))
ch.AuthAge = authAge.GetString();
if (val.TryGetProperty("type", out var chType))
ch.Type = chType.GetString();
healthList.Add(ch);
}
_logger.Info(healthList.Count > 0
? $"Channel health: {string.Join(", ", healthList.ConvertAll(c => $"{c.Name}={c.Status}"))}"
: "Channel health: no channels");
ChannelHealthUpdated?.Invoke(this, healthList.ToArray());
}
private void ParseSessions(JsonElement sessions)
{
try
{