-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathembedded-agent-subscribe.tools.ts
More file actions
1015 lines (966 loc) · 32.4 KB
/
Copy pathembedded-agent-subscribe.tools.ts
File metadata and controls
1015 lines (966 loc) · 32.4 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
/**
* Sanitizes, extracts, and classifies embedded-agent tool execution results.
*/
import { asOptionalRecord as readRecord } from "@openclaw/normalization-core/record-coerce";
import {
normalizeOptionalLowercaseString,
normalizeOptionalString,
normalizeOptionalStringifiedId,
readStringValue,
} from "@openclaw/normalization-core/string-coerce";
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
import { getChannelPlugin, normalizeChannelId } from "../channels/plugins/index.js";
import type { ChannelMessageActionName } from "../channels/plugins/types.public.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { normalizeTargetForProvider } from "../infra/outbound/target-normalization.js";
import { normalizeInteractiveReply, normalizeMessagePresentation } from "../interactive/payload.js";
import { redactSensitiveFieldValue, redactToolPayloadText } from "../logging/redact.js";
import { truncateUtf16Safe } from "../utils.js";
import { collectTextContentBlocks } from "./content-blocks.js";
import { isMessagingToolTargetEvidenceAction } from "./embedded-agent-messaging.js";
import type {
MessagingToolSend,
MessagingToolSourceReplyPayload,
} from "./embedded-agent-messaging.types.js";
import { normalizeToolName } from "./tool-policy.js";
import { readToolResultDetails, readToolResultStatus } from "./tool-result-error.js";
export { isToolResultError } from "./tool-result-error.js";
const TOOL_RESULT_MAX_CHARS = 8000;
const TOOL_ERROR_MAX_CHARS = 400;
const TOOL_DENIAL_ERROR_CODES = ["SYSTEM_RUN_DENIED", "INVALID_REQUEST"] as const;
function truncateToolText(text: string): string {
if (text.length <= TOOL_RESULT_MAX_CHARS) {
return text;
}
return `${truncateUtf16Safe(text, TOOL_RESULT_MAX_CHARS)}\n…(truncated)…`;
}
function normalizeToolErrorText(text: string): string | undefined {
const trimmed = text.trim();
if (!trimmed) {
return undefined;
}
const firstLine = trimmed.split(/\r?\n/)[0]?.trim() ?? "";
if (!firstLine) {
return undefined;
}
return firstLine.length > TOOL_ERROR_MAX_CHARS
? `${truncateUtf16Safe(firstLine, TOOL_ERROR_MAX_CHARS)}…`
: firstLine;
}
function isErrorLikeStatus(status: string): boolean {
const normalized = normalizeOptionalLowercaseString(status);
if (!normalized) {
return false;
}
if (
normalized === "0" ||
normalized === "ok" ||
normalized === "success" ||
normalized === "completed" ||
normalized === "running"
) {
return false;
}
return /error|fail|timeout|timed[_\s-]?out|denied|cancel|invalid|forbidden/.test(normalized);
}
function readErrorCandidate(value: unknown): string | undefined {
if (typeof value === "string") {
return normalizeToolErrorText(value);
}
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
if (typeof record.message === "string") {
return normalizeToolErrorText(record.message);
}
if (typeof record.error === "string") {
return normalizeToolErrorText(record.error);
}
return undefined;
}
function extractErrorField(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
const direct = extractDirectErrorField(record);
if (direct) {
return direct;
}
const status = normalizeOptionalString(record.status) ?? "";
if (!status || !isErrorLikeStatus(status)) {
return undefined;
}
return normalizeToolErrorText(status);
}
function extractDirectErrorField(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
return (
readErrorCandidate(record.error) ??
readErrorCandidate(record.message) ??
readErrorCandidate(record.reason)
);
}
function readErrorCodeField(value: unknown): string | undefined {
return typeof value === "string" ? normalizeOptionalString(value) : undefined;
}
function readDenialErrorCodeFromMessage(value: unknown): string | undefined {
const message = typeof value === "string" ? normalizeOptionalString(value) : undefined;
if (!message) {
return undefined;
}
for (const code of TOOL_DENIAL_ERROR_CODES) {
if (message === code || message.startsWith(`${code}:`)) {
return code;
}
}
return undefined;
}
function readNestedErrorCodeField(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
return (
readDenialErrorCodeFromMessage(record.message) ??
readDenialErrorCodeFromMessage(record.error) ??
readErrorCodeField(record.code) ??
readErrorCodeField(record.gatewayCode)
);
}
function extractDirectErrorCodeField(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
return (
readNestedErrorCodeField(record.error) ??
readNestedErrorCodeField(record.nodeError) ??
readErrorCodeField(record.code) ??
readErrorCodeField(record.gatewayCode)
);
}
export function buildToolLifecycleErrorResult(error: unknown): {
details: Record<string, unknown>;
} {
const errorRecord = readRecord(error);
const rawDetails = readRecord(errorRecord?.details);
const nodeError = readRecord(rawDetails?.nodeError);
const gatewayCode =
readErrorCodeField(errorRecord?.gatewayCode) ?? readErrorCodeField(errorRecord?.code);
const message = error instanceof Error ? error.message : String(error);
return {
details: {
status: "error",
error: message,
...(gatewayCode ? { gatewayCode } : {}),
...(nodeError ? { nodeError } : {}),
},
};
}
function extractAggregatedErrorField(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as Record<string, unknown>;
return readErrorCandidate(record.aggregated);
}
function redactStringsDeep(value: unknown, seen = new WeakSet<object>()): unknown {
if (typeof value === "string") {
return redactToolPayloadText(value);
}
if (Array.isArray(value)) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
return value.map((item) => redactStringsDeep(item, seen));
}
if (value && typeof value === "object") {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
const out: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
out[key] =
typeof child === "string"
? redactSensitiveFieldValue(key, child)
: redactStringsDeep(child, seen);
}
return out;
}
return value;
}
export function sanitizeToolArgs(args: unknown): unknown {
return redactStringsDeep(args);
}
export function sanitizeToolResult(result: unknown): unknown {
if (typeof result === "string") {
return redactToolPayloadText(result);
}
if (Array.isArray(result)) {
return redactStringsDeep(result);
}
if (!result || typeof result !== "object") {
return result;
}
const record = result as Record<string, unknown>;
// Strip image data first so the deep redaction pass doesn't waste work
// scanning base64 payloads (and so we capture the original byte counts).
const preCleaned: Record<string, unknown> = { ...record };
const originalContent = Array.isArray(record.content) ? record.content : null;
if (originalContent) {
preCleaned.content = originalContent.map((item) => {
if (!item || typeof item !== "object") {
return item;
}
const entry = item as Record<string, unknown>;
if (readStringValue(entry.type) === "image") {
const data = readStringValue(entry.data);
const bytes = data ? data.length : undefined;
const cleaned = { ...entry };
delete cleaned.data;
return Object.assign({}, cleaned, { bytes, omitted: true });
}
return entry;
});
}
// Deep-redact the entire result so any top-level or nested string is
// protected, not just `details` and text content blocks.
const baseline = redactStringsDeep(preCleaned) as Record<string, unknown>;
const out: Record<string, unknown> = { ...baseline };
const content = Array.isArray(baseline.content) ? baseline.content : null;
if (content) {
out.content = content.map((item) => {
if (!item || typeof item !== "object") {
return item;
}
const entry = item as Record<string, unknown>;
if (readStringValue(entry.type) === "text" && typeof entry.text === "string") {
return Object.assign({}, entry, { text: truncateToolText(entry.text) });
}
return entry;
});
}
return out;
}
export function extractToolResultText(result: unknown): string | undefined {
if (!result || typeof result !== "object") {
return undefined;
}
const record = result as Record<string, unknown>;
const texts = collectTextContentBlocks(record.content)
.map((item) => {
const trimmed = item.trim();
return trimmed ? trimmed : undefined;
})
.filter((value): value is string => Boolean(value));
if (texts.length > 0) {
return texts.join("\n");
}
// Fallback: serialize structured non-image blocks so tool results with
// JSON/resource content produce visible text instead of collapsing to an
// attachment placeholder (#97267).
const content = record.content;
if (Array.isArray(content)) {
const fallbackParts: string[] = [];
for (const block of content) {
if (!block || typeof block !== "object") {
continue;
}
const b = block as Record<string, unknown>;
if (b.type === "text" || b.type === "image") {
continue;
}
try {
fallbackParts.push(JSON.stringify(block));
} catch {
// skip unserializable blocks
}
}
if (fallbackParts.length > 0) {
const joined = fallbackParts.join("\n");
return truncateToolText(joined);
}
}
return undefined;
}
function pushUniqueMessagingMediaUrl(urls: string[], seen: Set<string>, value: unknown): void {
if (typeof value !== "string") {
return;
}
const normalized = value.trim();
if (!normalized || seen.has(normalized)) {
return;
}
seen.add(normalized);
urls.push(normalized);
}
/** Collects messaging attachment references from tool-call arguments or result records. */
export function collectMessagingMediaUrlsFromRecord(record: Record<string, unknown>): string[] {
const urls: string[] = [];
const seen = new Set<string>();
const pushAttachment = (value: unknown) => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return;
}
const attachment = value as Record<string, unknown>;
for (const candidate of [
attachment.media,
attachment.mediaUrl,
attachment.path,
attachment.filePath,
attachment.fileUrl,
attachment.url,
]) {
pushUniqueMessagingMediaUrl(urls, seen, candidate);
}
};
for (const candidate of [
record.media,
record.mediaUrl,
record.path,
record.filePath,
record.fileUrl,
]) {
pushUniqueMessagingMediaUrl(urls, seen, candidate);
}
if (Array.isArray(record.mediaUrls)) {
for (const mediaUrl of record.mediaUrls) {
pushUniqueMessagingMediaUrl(urls, seen, mediaUrl);
}
}
if (Array.isArray(record.attachments)) {
for (const attachment of record.attachments) {
pushAttachment(attachment);
}
}
return urls;
}
/** Collects messaging attachment references from a completed tool result. */
export function collectMessagingMediaUrlsFromToolResult(result: unknown): string[] {
const urls: string[] = [];
const seen = new Set<string>();
const appendFromRecord = (value: unknown) => {
if (!value || typeof value !== "object") {
return;
}
for (const url of collectMessagingMediaUrlsFromRecord(value as Record<string, unknown>)) {
if (!seen.has(url)) {
seen.add(url);
urls.push(url);
}
}
};
appendFromRecord(result);
if (result && typeof result === "object") {
appendFromRecord((result as Record<string, unknown>).details);
}
const outputText = extractToolResultText(result);
if (outputText) {
try {
appendFromRecord(JSON.parse(outputText));
} catch {
// Ignore non-JSON tool output.
}
}
return urls;
}
/** Extract an internal source-reply payload from a completed message tool result. */
export function extractMessagingToolSourceReplyPayload(
result: unknown,
): MessagingToolSourceReplyPayload | undefined {
const details = readToolResultDetails(result);
if (!details || details.sourceReplySink !== "internal-ui") {
return undefined;
}
const status = normalizeOptionalLowercaseString(details.deliveryStatus);
if (status && status !== "sent") {
return undefined;
}
const sourceReply = readRecord(details.sourceReply) ?? details;
const payload: MessagingToolSourceReplyPayload = {};
const text = readStringValue(sourceReply.text) ?? readStringValue(details.message);
if (text) {
payload.text = text;
}
const mediaUrl = readStringValue(sourceReply.mediaUrl) ?? readStringValue(details.mediaUrl);
if (mediaUrl) {
payload.mediaUrl = mediaUrl;
}
const rawMediaUrls = Array.isArray(sourceReply.mediaUrls)
? sourceReply.mediaUrls
: Array.isArray(details.mediaUrls)
? details.mediaUrls
: [];
const mediaUrls = uniqueStrings(
rawMediaUrls.filter((value): value is string => typeof value === "string"),
);
if (mediaUrls.length > 0) {
payload.mediaUrls = mediaUrls;
}
if (sourceReply.audioAsVoice === true || details.audioAsVoice === true) {
payload.audioAsVoice = true;
}
const presentation = normalizeMessagePresentation(sourceReply.presentation);
if (presentation) {
payload.presentation = presentation;
}
const interactive = normalizeInteractiveReply(sourceReply.interactive);
if (interactive) {
payload.interactive = interactive;
}
const channelData = readRecord(sourceReply.channelData);
if (channelData) {
payload.channelData = { ...channelData };
}
const idempotencyKey =
readStringValue(sourceReply.idempotencyKey) ?? readStringValue(details.idempotencyKey);
if (idempotencyKey) {
payload.idempotencyKey = idempotencyKey;
}
return Object.keys(payload).length > 0 ? payload : undefined;
}
// Core tool names that are allowed to emit trusted local media artifacts.
// Plugin tools must be explicitly passed as trusted run-local names by the caller.
const TRUSTED_TOOL_RESULT_MEDIA = new Set([
"agents_list",
"apply_patch",
"browser",
"canvas",
"cron",
"edit",
"exec",
"gateway",
"image",
"image_generate",
"memory_get",
"memory_search",
"message",
"music_generate",
"nodes",
"process",
"read",
"session_status",
"sessions_history",
"sessions_list",
"sessions_send",
"sessions_spawn",
"subagents",
"tts",
"video_generate",
"web_fetch",
"web_search",
"x_search",
"write",
]);
const HTTP_URL_RE = /^https?:\/\//i;
function isCoreToolResultMediaTrustedName(toolName?: string): boolean {
if (!toolName) {
return false;
}
return TRUSTED_TOOL_RESULT_MEDIA.has(normalizeToolName(toolName));
}
function isExternalToolResult(result: unknown): boolean {
const details = readToolResultDetails(result);
if (!details) {
return false;
}
return typeof details.mcpServer === "string" || typeof details.mcpTool === "string";
}
export function isToolResultMediaTrusted(
toolName?: string,
result?: unknown,
trustedLocalMediaToolNames?: ReadonlySet<string>,
): boolean {
if (!toolName || isExternalToolResult(result)) {
return false;
}
const registeredName = toolName.trim();
if (registeredName && trustedLocalMediaToolNames?.has(registeredName) === true) {
return true;
}
return isCoreToolResultMediaTrustedName(toolName);
}
function isTrustedOwnedTtsLocalMedia(
toolName: string | undefined,
result: unknown,
trustedLocalMediaToolNames?: ReadonlySet<string>,
): boolean {
if (
!toolName ||
!isToolResultMediaTrusted(toolName, result, trustedLocalMediaToolNames) ||
normalizeToolName(toolName) !== "tts"
) {
return false;
}
const media = readToolResultDetails(result)?.media;
if (!media || typeof media !== "object" || Array.isArray(media)) {
return false;
}
return (media as Record<string, unknown>).trustedLocalMedia === true;
}
export function filterToolResultMediaUrls(
toolName: string | undefined,
mediaUrls: string[],
result?: unknown,
trustedLocalMediaToolNames?: ReadonlySet<string>,
): string[] {
if (mediaUrls.length === 0) {
return mediaUrls;
}
const trustedOwnedTtsLocalMedia = isTrustedOwnedTtsLocalMedia(
toolName,
result,
trustedLocalMediaToolNames,
);
if (isToolResultMediaTrusted(toolName, result, trustedLocalMediaToolNames)) {
// When the current run provides its exact trusted local-media tool names,
// require the raw emitted tool name to match one of them before allowing
// local media paths.
// This blocks normalized aliases and case-variant collisions such as
// "Bash" -> "bash" or "Web_Search" -> "web_search" from inheriting a
// registered tool's media trust. TTS-generated local files carry a
// separate trusted-media flag from the owned tool result, so they can
// survive runs whose exact trusted set omitted the raw tts name.
if (trustedLocalMediaToolNames !== undefined) {
if (!trustedOwnedTtsLocalMedia) {
const registeredName = toolName?.trim();
if (!registeredName || !trustedLocalMediaToolNames.has(registeredName)) {
return mediaUrls.filter((url) => HTTP_URL_RE.test(url.trim()));
}
}
}
return mediaUrls;
}
return mediaUrls.filter((url) => HTTP_URL_RE.test(url.trim()));
}
/**
* Extract media file paths from a tool result.
*
* Strategy (first match wins):
* 1. Read structured `details.media` attachments from tool details.
* 2. Fall back to `details.path` when image content exists (legacy imageResult).
*
* Returns an empty array when no media is found (e.g. embedded `read` tool
* returns base64 image data but no file path; those need a different delivery
* path like saving to a temp file).
*/
type ToolResultMediaArtifact = {
mediaUrls: string[];
audioAsVoice?: boolean;
trustedLocalMedia?: boolean;
};
function readToolResultDetailsMedia(
result: Record<string, unknown>,
): Record<string, unknown> | undefined {
const details = readToolResultDetails(result);
const media =
details?.media && typeof details.media === "object" && !Array.isArray(details.media)
? (details.media as Record<string, unknown>)
: undefined;
return media;
}
function collectStructuredMediaUrls(media: Record<string, unknown>): string[] {
const urls: string[] = [];
const pushString = (value: unknown) => {
if (typeof value !== "string") {
return;
}
const normalized = value.trim();
if (normalized) {
urls.push(normalized);
}
};
const pushAttachment = (value: unknown) => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return;
}
const attachment = value as Record<string, unknown>;
pushString(attachment.media);
pushString(attachment.path);
pushString(attachment.url);
pushString(attachment.mediaUrl);
pushString(attachment.filePath);
pushString(attachment.fileUrl);
};
pushString(media.media);
pushString(media.path);
pushString(media.url);
pushString(media.mediaUrl);
pushString(media.filePath);
pushString(media.fileUrl);
if (Array.isArray(media.mediaUrls)) {
for (const value of media.mediaUrls) {
pushString(value);
}
}
if (Array.isArray(media.attachments)) {
for (const attachment of media.attachments) {
pushAttachment(attachment);
}
}
return uniqueStrings(urls);
}
function isNonOutboundToolResultMedia(media: Record<string, unknown>): boolean {
return media.outbound === false;
}
function hasImageContentBlock(content: unknown[]): boolean {
for (const item of content) {
if (!item || typeof item !== "object") {
continue;
}
const entry = item as Record<string, unknown>;
if (entry.type === "image") {
return true;
}
}
return false;
}
export function extractToolResultMediaArtifact(
result: unknown,
): ToolResultMediaArtifact | undefined {
if (!result || typeof result !== "object") {
return undefined;
}
const record = result as Record<string, unknown>;
const detailsMedia = readToolResultDetailsMedia(record);
if (detailsMedia) {
if (isNonOutboundToolResultMedia(detailsMedia)) {
return undefined;
}
const mediaUrls = collectStructuredMediaUrls(detailsMedia);
if (mediaUrls.length > 0) {
return {
mediaUrls,
...(detailsMedia.audioAsVoice === true ? { audioAsVoice: true } : {}),
...(detailsMedia.trustedLocalMedia === true ? { trustedLocalMedia: true } : {}),
};
}
}
const content = Array.isArray(record.content) ? record.content : null;
if (!content) {
return undefined;
}
// Fall back to legacy details.path when image content exists but no
// structured media details.
if (hasImageContentBlock(content)) {
const details = record.details as Record<string, unknown> | undefined;
const p = normalizeOptionalString(details?.path) ?? "";
if (p) {
return { mediaUrls: [p] };
}
}
return undefined;
}
export function extractToolErrorCode(result: unknown): string | undefined {
if (!result || typeof result !== "object") {
return undefined;
}
const record = result as Record<string, unknown>;
return extractDirectErrorCodeField(record.details) ?? extractDirectErrorCodeField(record);
}
export function isToolResultTimedOut(result: unknown): boolean {
const normalizedStatus = readToolResultStatus(result);
if (normalizedStatus === "timeout") {
return true;
}
return readToolResultDetails(result)?.timedOut === true;
}
export function extractToolErrorMessage(result: unknown): string | undefined {
if (!result || typeof result !== "object") {
return undefined;
}
const record = result as Record<string, unknown>;
const fromDetails = extractDirectErrorField(record.details);
if (fromDetails) {
return fromDetails;
}
const fromDetailsAggregated = extractAggregatedErrorField(record.details);
if (fromDetailsAggregated) {
return fromDetailsAggregated;
}
const fromRoot = extractDirectErrorField(record);
if (fromRoot) {
return fromRoot;
}
const text = extractToolResultText(result);
if (text) {
try {
const parsed = JSON.parse(text) as unknown;
const fromJson = extractErrorField(parsed);
if (fromJson) {
return fromJson;
}
} catch {
// Fall through to status/text fallback.
}
}
const fromDetailsStatus = extractErrorField(record.details);
if (fromDetailsStatus) {
return fromDetailsStatus;
}
const fromRootStatus = extractErrorField(record);
if (fromRootStatus) {
return fromRootStatus;
}
return text ? normalizeToolErrorText(text) : undefined;
}
function resolveMessageToolTarget(params: {
action: string;
args: Record<string, unknown>;
providerId: string | null;
currentChannelId?: string;
currentMessagingTarget?: string;
}): string | undefined {
const directTarget =
normalizeOptionalString(params.args.target) ??
normalizeOptionalString(params.args.to) ??
normalizeOptionalString(params.args.channelId);
if (directTarget) {
return directTarget;
}
const aliases = params.providerId
? getChannelPlugin(params.providerId)?.actions?.messageActionTargetAliases?.[
params.action as ChannelMessageActionName
]?.deliveryTargetAliases
: undefined;
for (const alias of aliases ?? []) {
const aliasTarget = normalizeOptionalStringifiedId(params.args[alias]);
if (aliasTarget) {
return aliasTarget;
}
}
return params.currentMessagingTarget ?? params.currentChannelId;
}
function resolveMessagingToolThreadEvidence(params: {
providerId: string;
to: string;
accountId?: string;
threadId?: string;
replyToId?: string;
allowImplicitThread: boolean;
threadSuppressed: boolean;
options?: {
config?: OpenClawConfig;
currentChannelId?: string;
currentMessagingTarget?: string;
currentThreadId?: string;
currentMessageId?: string | number;
replyToMode?: "off" | "first" | "all" | "batched";
hasRepliedRef?: { value: boolean };
};
}): Pick<MessagingToolSend, "threadId" | "threadImplicit" | "threadSuppressed"> {
const threading = getChannelPlugin(params.providerId)?.threading;
const autoThreadResolver = params.allowImplicitThread
? threading?.resolveAutoThreadId
: undefined;
const replyTransport = params.replyToId
? threading?.resolveReplyTransport?.({
cfg: params.options?.config ?? {},
accountId: params.accountId,
threadId: params.threadId,
replyToId: params.replyToId,
})
: undefined;
const transportThreadId = normalizeOptionalStringifiedId(replyTransport?.threadId);
const replyToThreadId =
replyTransport?.threadId === null
? normalizeOptionalString(replyTransport.replyToId)
: undefined;
const explicitThreadId = transportThreadId ?? replyToThreadId ?? params.threadId;
const currentChannelId = normalizeOptionalString(params.options?.currentChannelId);
const currentMessagingTarget = normalizeOptionalString(params.options?.currentMessagingTarget);
const currentThreadId = normalizeOptionalString(params.options?.currentThreadId);
const replyToMode = params.options?.replyToMode ?? (currentThreadId ? "all" : undefined);
const canResolveCurrentThread = Boolean(
(currentChannelId || currentMessagingTarget) && currentThreadId,
);
const resolvedCurrentThreadId =
!explicitThreadId && !params.threadSuppressed && autoThreadResolver && canResolveCurrentThread
? autoThreadResolver({
cfg: params.options?.config ?? {},
accountId: params.accountId,
to: params.to,
replyToId: params.replyToId,
toolContext: {
currentChannelId,
currentMessagingTarget,
currentThreadTs: currentThreadId,
currentMessageId: params.options?.currentMessageId,
replyToMode,
hasRepliedRef: params.options?.hasRepliedRef,
},
})
: undefined;
const threadImplicit =
!explicitThreadId &&
!params.threadSuppressed &&
Boolean(autoThreadResolver) &&
(!canResolveCurrentThread || Boolean(resolvedCurrentThreadId));
return {
...((explicitThreadId ?? resolvedCurrentThreadId)
? { threadId: explicitThreadId ?? resolvedCurrentThreadId }
: {}),
...(threadImplicit ? { threadImplicit: true } : {}),
...(params.threadSuppressed ? { threadSuppressed: true } : {}),
};
}
export function extractMessagingToolSend(
toolName: string,
args: Record<string, unknown>,
options?: {
config?: OpenClawConfig;
currentChannelId?: string;
currentMessagingTarget?: string;
currentThreadId?: string;
currentMessageId?: string | number;
replyToMode?: "off" | "first" | "all" | "batched";
hasRepliedRef?: { value: boolean };
},
): MessagingToolSend | undefined {
// Provider docking: new provider tools must implement plugin.actions.extractToolSend.
const action = normalizeOptionalString(args.action) ?? "";
const accountId = normalizeOptionalString(args.accountId);
if (toolName === "message") {
if (!isMessagingToolTargetEvidenceAction(toolName, args)) {
return undefined;
}
const providerRaw = normalizeOptionalString(args.provider) ?? "";
const channelRaw = normalizeOptionalString(args.channel) ?? "";
const providerHint = providerRaw || channelRaw;
const providerId = providerHint ? normalizeChannelId(providerHint) : null;
const toRaw = resolveMessageToolTarget({
action,
args,
providerId,
currentChannelId: options?.currentChannelId,
currentMessagingTarget: options?.currentMessagingTarget,
});
if (!toRaw) {
return undefined;
}
const provider = providerId ?? normalizeOptionalLowercaseString(providerHint) ?? "message";
const to = normalizeTargetForProvider(provider, toRaw);
const pluginExtractionArgs = { ...args, to: toRaw };
const pluginExtracted = providerId
? getChannelPlugin(providerId)?.actions?.extractToolSend?.({ args: pluginExtractionArgs })
: null;
const resolvedAccountId = normalizeOptionalString(pluginExtracted?.accountId) ?? accountId;
const threadId =
normalizeOptionalString(pluginExtracted?.threadId) ?? normalizeOptionalString(args.threadId);
const replyToId = normalizeOptionalString(args.replyTo);
// Normal sends use prepared core delivery, where provider transport owns
// reply/thread precedence. Other send-like actions use plugin dispatch.
const outboundReplyToId = action === "send" ? replyToId : undefined;
const threadSuppressed =
pluginExtracted?.threadSuppressed === true ||
args.topLevel === true ||
args.threadId === null;
return to
? {
tool: toolName,
provider,
accountId: resolvedAccountId,
to,
...(providerId
? resolveMessagingToolThreadEvidence({
providerId,
to,
accountId: resolvedAccountId,
threadId,
replyToId: outboundReplyToId,
allowImplicitThread: pluginExtracted
? pluginExtracted.threadImplicit === true
: true,
threadSuppressed,
options,
})
: {
...(threadId ? { threadId } : {}),
...(threadSuppressed ? { threadSuppressed: true } : {}),
}),
}
: undefined;
}
const providerId = normalizeChannelId(toolName);
if (!providerId) {
return undefined;
}
const plugin = getChannelPlugin(providerId);
const extracted = plugin?.actions?.extractToolSend?.({ args });
if (!extracted?.to) {
return undefined;
}
const to = normalizeTargetForProvider(providerId, extracted.to);
const threadId = normalizeOptionalString(extracted.threadId);
const threadSuppressed = extracted.threadSuppressed === true;
const extractedAccountId = normalizeOptionalString(extracted.accountId) ?? accountId;
const nativeReplyToMode = options?.replyToMode;
const nativeSingleUseMode = nativeReplyToMode === "first" || nativeReplyToMode === "batched";
const canResolveNativeImplicitThread =
extracted.threadImplicit === true &&
nativeReplyToMode !== undefined &&
(!nativeSingleUseMode || options?.hasRepliedRef !== undefined);
return to
? {
tool: toolName,
provider: providerId,
accountId: extractedAccountId,
to,
...resolveMessagingToolThreadEvidence({
providerId,
to,
accountId: extractedAccountId,
threadId,
allowImplicitThread: canResolveNativeImplicitThread,
threadSuppressed,
options,
}),
}
: undefined;
}
/** Reconciles pending send evidence with the provider's successful action result. */
export function extractMessagingToolSendResult(
pending: MessagingToolSend,
result: unknown,
): MessagingToolSend {
const providerId = normalizeChannelId(pending.provider);
const extracted = providerId
? getChannelPlugin(providerId)?.actions?.extractToolSendResult?.({
result,
send: {
to: pending.to ?? "",
accountId: pending.accountId,
threadId: pending.threadId,
threadImplicit: pending.threadImplicit,
threadSuppressed: pending.threadSuppressed,
},
})
: null;
if (!extracted?.to) {
return pending;
}
const extractedThreadId = normalizeOptionalString(extracted.threadId);
const providerReportedThread =
extractedThreadId != null ||