-
-
Notifications
You must be signed in to change notification settings - Fork 80.9k
Expand file tree
/
Copy pathsubagent-announce-delivery.ts
More file actions
895 lines (851 loc) · 29.9 KB
/
Copy pathsubagent-announce-delivery.ts
File metadata and controls
895 lines (851 loc) · 29.9 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
import type { OpenClawConfig } from "../config/types.openclaw.js";
import type { ConversationRef } from "../infra/outbound/session-binding-service.js";
import { stringifyRouteThreadId } from "../plugin-sdk/channel-route.js";
import { normalizeAccountId } from "../routing/session-key.js";
import { defaultRuntime } from "../runtime.js";
import { isCronSessionKey } from "../sessions/session-key-utils.js";
import { isNonTerminalAgentRunStatus } from "../shared/agent-run-status.js";
import { normalizeOptionalLowercaseString } from "../shared/string-coerce.js";
import {
mergeDeliveryContext,
normalizeDeliveryContext,
resolveConversationDeliveryTarget,
} from "../utils/delivery-context.js";
import {
INTERNAL_MESSAGE_CHANNEL,
isDeliverableMessageChannel,
isGatewayMessageChannel,
isInternalMessageChannel,
normalizeMessageChannel,
} from "../utils/message-channel.js";
import { mediaUrlsFromGeneratedAttachments } from "./generated-attachments.js";
import type { AgentInternalEvent } from "./internal-events.js";
import {
getAgentCommandDeliveryFailure,
getGatewayAgentResult,
hasDeliveredExpectedMedia,
hasMessagingToolDeliveryEvidence,
hasVisibleAgentPayload,
} from "./pi-embedded-runner/delivery-evidence.js";
import type { EmbeddedPiQueueMessageOptions } from "./pi-embedded-runner/run-state.js";
import type { EmbeddedPiQueueMessageOutcome } from "./pi-embedded-runner/runs.js";
import {
callGateway,
createBoundDeliveryRouter,
dispatchGatewayMethodInProcess,
getGlobalHookRunner,
isEmbeddedPiRunActive,
getRuntimeConfig,
formatEmbeddedPiQueueFailureSummary,
loadSessionStore,
queueEmbeddedPiMessageWithOutcomeAsync,
resolveActiveEmbeddedRunSessionId,
resolveAgentIdFromSessionKey,
resolveConversationIdFromTargets,
resolveExternalBestEffortDeliveryTarget,
resolveQueueSettings,
resolveStorePath,
} from "./subagent-announce-delivery.runtime.js";
import {
runSubagentAnnounceDispatch,
type SubagentAnnounceDeliveryResult,
} from "./subagent-announce-dispatch.js";
import type { DeliveryContext } from "./subagent-announce-origin.js";
import { getSubagentDepthFromSessionStore } from "./subagent-depth.js";
import { resolveRequesterStoreKey } from "./subagent-requester-store-key.js";
import type { SpawnSubagentMode } from "./subagent-spawn.types.js";
const DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS = 120_000;
const MAX_TIMER_SAFE_TIMEOUT_MS = 2_147_000_000;
const AGENT_MEDIATED_COMPLETION_TOOLS = new Set([
"image_generate",
"music_generate",
"video_generate",
]);
type SubagentAnnounceDeliveryDeps = {
dispatchGatewayMethodInProcess: typeof dispatchGatewayMethodInProcess;
getRuntimeConfig: typeof getRuntimeConfig;
getRequesterSessionActivity: (requesterSessionKey: string) => {
sessionId?: string;
isActive: boolean;
};
queueEmbeddedPiMessageWithOutcome: (
sessionId: string,
text: string,
options?: EmbeddedPiQueueMessageOptions,
) => EmbeddedPiQueueMessageOutcome | Promise<EmbeddedPiQueueMessageOutcome>;
};
const defaultSubagentAnnounceDeliveryDeps: SubagentAnnounceDeliveryDeps = {
dispatchGatewayMethodInProcess,
getRuntimeConfig,
getRequesterSessionActivity: (requesterSessionKey: string) => {
const sessionId =
resolveActiveEmbeddedRunSessionId(requesterSessionKey) ??
loadRequesterSessionEntry(requesterSessionKey).entry?.sessionId;
return {
sessionId,
isActive: Boolean(sessionId && isEmbeddedPiRunActive(sessionId)),
};
},
queueEmbeddedPiMessageWithOutcome: queueEmbeddedPiMessageWithOutcomeAsync,
};
let subagentAnnounceDeliveryDeps: SubagentAnnounceDeliveryDeps =
defaultSubagentAnnounceDeliveryDeps;
async function resolveQueueEmbeddedPiMessageOutcome(
sessionId: string,
text: string,
options?: EmbeddedPiQueueMessageOptions,
): Promise<EmbeddedPiQueueMessageOutcome> {
return await subagentAnnounceDeliveryDeps.queueEmbeddedPiMessageWithOutcome(
sessionId,
text,
options,
);
}
async function runAnnounceAgentCall(params: {
agentParams: Record<string, unknown>;
expectFinal?: boolean;
timeoutMs?: number;
}): Promise<unknown> {
return await subagentAnnounceDeliveryDeps.dispatchGatewayMethodInProcess(
"agent",
params.agentParams,
{
expectFinal: params.expectFinal,
timeoutMs: params.timeoutMs,
},
);
}
function formatQueueWakeFailureError(
fallback: string,
outcome: EmbeddedPiQueueMessageOutcome,
): string {
const summary = formatEmbeddedPiQueueFailureSummary(outcome);
return summary ? `${fallback}: ${summary}` : fallback;
}
function resolveBoundConversationOrigin(params: {
bindingConversation: ConversationRef & { parentConversationId?: string };
requesterConversation?: ConversationRef;
requesterOrigin?: DeliveryContext;
}): DeliveryContext {
const conversation = params.bindingConversation;
const conversationId = conversation.conversationId?.trim() ?? "";
const parentConversationId = conversation.parentConversationId?.trim() ?? "";
const requesterConversationId = params.requesterConversation?.conversationId?.trim() ?? "";
const requesterTo = params.requesterOrigin?.to?.trim();
if (
conversation.channel === "matrix" &&
parentConversationId &&
requesterConversationId &&
parentConversationId === requesterConversationId &&
requesterTo
) {
return {
channel: conversation.channel,
accountId: conversation.accountId,
to: requesterTo,
...(conversationId ? { threadId: conversationId } : {}),
};
}
const boundTarget = resolveConversationDeliveryTarget({
channel: conversation.channel,
conversationId,
parentConversationId,
});
const inferredThreadId =
boundTarget.threadId ??
(parentConversationId && parentConversationId !== conversationId
? conversationId
: undefined) ??
(params.requesterOrigin?.threadId != null && params.requesterOrigin.threadId !== ""
? stringifyRouteThreadId(params.requesterOrigin.threadId)
: undefined);
if (
requesterTo &&
conversationId &&
requesterConversationId &&
conversationId.toLowerCase() === requesterConversationId.toLowerCase()
) {
return {
channel: conversation.channel,
accountId: conversation.accountId,
to: requesterTo,
threadId: inferredThreadId,
};
}
return {
channel: conversation.channel,
accountId: conversation.accountId,
to: boundTarget.to,
threadId: inferredThreadId,
};
}
function resolveRequesterSessionActivity(requesterSessionKey: string) {
const activity = subagentAnnounceDeliveryDeps.getRequesterSessionActivity(requesterSessionKey);
if (activity.sessionId || activity.isActive) {
return activity;
}
const { entry } = loadRequesterSessionEntry(requesterSessionKey);
const sessionId = entry?.sessionId;
return {
sessionId,
isActive: Boolean(sessionId && isEmbeddedPiRunActive(sessionId)),
};
}
function resolveDirectAnnounceTransientRetryDelaysMs() {
return process.env.OPENCLAW_TEST_FAST === "1"
? ([8, 16, 32] as const)
: ([5_000, 10_000, 20_000] as const);
}
export function resolveSubagentAnnounceTimeoutMs(cfg: OpenClawConfig): number {
const configured = cfg.agents?.defaults?.subagents?.announceTimeoutMs;
if (typeof configured !== "number" || !Number.isFinite(configured)) {
return DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS;
}
return Math.min(Math.max(1, Math.floor(configured)), MAX_TIMER_SAFE_TIMEOUT_MS);
}
export function isInternalAnnounceRequesterSession(sessionKey: string | undefined): boolean {
return getSubagentDepthFromSessionStore(sessionKey) >= 1 || isCronSessionKey(sessionKey);
}
function summarizeDeliveryError(error: unknown): string {
if (error instanceof Error) {
return error.message || "error";
}
if (typeof error === "string") {
return error;
}
if (error === undefined || error === null) {
return "unknown error";
}
try {
return JSON.stringify(error);
} catch {
return "error";
}
}
const TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS: readonly RegExp[] = [
/\berrorcode=unavailable\b/i,
/\bstatus\s*[:=]\s*"?unavailable\b/i,
/\bUNAVAILABLE\b/,
/no active .* listener/i,
/gateway not connected/i,
/gateway closed \(1006/i,
/gateway timeout/i,
/\ball models failed\b/i,
/\ball profiles unavailable\b/i,
/\boverloaded\b/i,
/\b(econnreset|econnrefused|etimedout|enotfound|ehostunreach|network error)\b/i,
];
const PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS: readonly RegExp[] = [
/unsupported channel/i,
/unknown channel/i,
/chat not found/i,
/user not found/i,
/bot.*not.*member/i,
/bot was blocked by the user/i,
/forbidden: bot was kicked/i,
/recipient is not a valid/i,
/outbound not configured for channel/i,
];
function isTransientAnnounceDeliveryError(error: unknown): boolean {
const message = summarizeDeliveryError(error);
if (!message) {
return false;
}
if (PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message))) {
return false;
}
return TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message));
}
function isPermanentAnnounceDeliveryError(error: unknown): boolean {
const message = summarizeDeliveryError(error);
return Boolean(
message && PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message)),
);
}
async function waitForAnnounceRetryDelay(ms: number, signal?: AbortSignal): Promise<void> {
if (ms <= 0) {
return;
}
if (!signal) {
await new Promise<void>((resolve) => setTimeout(resolve, ms));
return;
}
if (signal.aborted) {
return;
}
await new Promise<void>((resolve) => {
const timer = setTimeout(() => {
signal.removeEventListener("abort", onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer);
signal.removeEventListener("abort", onAbort);
resolve();
};
signal.addEventListener("abort", onAbort, { once: true });
});
}
export async function runAnnounceDeliveryWithRetry<T>(params: {
operation: string;
signal?: AbortSignal;
run: () => Promise<T>;
}): Promise<T> {
const retryDelaysMs = resolveDirectAnnounceTransientRetryDelaysMs();
let retryIndex = 0;
for (;;) {
if (params.signal?.aborted) {
throw new Error("announce delivery aborted");
}
try {
return await params.run();
} catch (err) {
const delayMs = retryDelaysMs[retryIndex];
if (delayMs == null || !isTransientAnnounceDeliveryError(err) || params.signal?.aborted) {
throw err;
}
const nextAttempt = retryIndex + 2;
const maxAttempts = retryDelaysMs.length + 1;
defaultRuntime.log(
`[warn] Subagent announce ${params.operation} transient failure, retrying ${nextAttempt}/${maxAttempts} in ${Math.round(delayMs / 1000)}s: ${summarizeDeliveryError(err)}`,
);
retryIndex += 1;
await waitForAnnounceRetryDelay(delayMs, params.signal);
}
}
}
export async function resolveSubagentCompletionOrigin(params: {
childSessionKey: string;
requesterSessionKey: string;
requesterOrigin?: DeliveryContext;
childRunId?: string;
spawnMode?: SpawnSubagentMode;
expectsCompletionMessage: boolean;
}): Promise<DeliveryContext | undefined> {
const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
const channel = normalizeOptionalLowercaseString(requesterOrigin?.channel);
const to = requesterOrigin?.to?.trim();
const accountId = normalizeAccountId(requesterOrigin?.accountId);
const threadId =
requesterOrigin?.threadId != null && requesterOrigin.threadId !== ""
? stringifyRouteThreadId(requesterOrigin.threadId)
: undefined;
const conversationId =
threadId ||
resolveConversationIdFromTargets({
targets: [to],
}) ||
"";
const requesterConversation: ConversationRef | undefined =
channel && conversationId ? { channel, accountId, conversationId } : undefined;
const router = createBoundDeliveryRouter();
const childRoute = router.resolveDestination({
eventKind: "task_completion",
targetSessionKey: params.childSessionKey,
requester: requesterConversation,
failClosed: true,
});
if (childRoute.mode === "bound" && childRoute.binding) {
return mergeDeliveryContext(
resolveBoundConversationOrigin({
bindingConversation: childRoute.binding.conversation,
requesterConversation,
requesterOrigin,
}),
requesterOrigin,
);
}
const route = router.resolveDestination({
eventKind: "task_completion",
targetSessionKey: params.requesterSessionKey,
requester: requesterConversation,
failClosed: true,
});
if (route.mode === "bound" && route.binding) {
return mergeDeliveryContext(
resolveBoundConversationOrigin({
bindingConversation: route.binding.conversation,
requesterConversation,
requesterOrigin,
}),
requesterOrigin,
);
}
const hookRunner = getGlobalHookRunner();
if (!hookRunner?.hasHooks("subagent_delivery_target")) {
return requesterOrigin;
}
try {
const result = await hookRunner.runSubagentDeliveryTarget(
{
childSessionKey: params.childSessionKey,
requesterSessionKey: params.requesterSessionKey,
requesterOrigin,
childRunId: params.childRunId,
spawnMode: params.spawnMode,
expectsCompletionMessage: params.expectsCompletionMessage,
},
{
runId: params.childRunId,
childSessionKey: params.childSessionKey,
requesterSessionKey: params.requesterSessionKey,
},
);
const hookOrigin = normalizeDeliveryContext(result?.origin);
if (!hookOrigin) {
return requesterOrigin;
}
if (hookOrigin.channel && isInternalMessageChannel(hookOrigin.channel)) {
return requesterOrigin;
}
return mergeDeliveryContext(hookOrigin, requesterOrigin);
} catch {
return requesterOrigin;
}
}
export function loadRequesterSessionEntry(requesterSessionKey: string) {
const cfg = subagentAnnounceDeliveryDeps.getRuntimeConfig();
const canonicalKey = resolveRequesterStoreKey(cfg, requesterSessionKey);
const agentId = resolveAgentIdFromSessionKey(canonicalKey);
const storePath = resolveStorePath(cfg.session?.store, { agentId });
const store = loadSessionStore(storePath);
const entry = store[canonicalKey];
return { cfg, entry, canonicalKey };
}
export function loadSessionEntryByKey(sessionKey: string) {
const cfg = subagentAnnounceDeliveryDeps.getRuntimeConfig();
const agentId = resolveAgentIdFromSessionKey(sessionKey);
const storePath = resolveStorePath(cfg.session?.store, { agentId });
const store = loadSessionStore(storePath);
return store[sessionKey];
}
async function maybeSteerSubagentAnnounce(params: {
requesterSessionKey: string;
steerMessage: string;
signal?: AbortSignal;
}): Promise<"steered" | "none" | "dropped"> {
if (params.signal?.aborted) {
return "none";
}
const { cfg, entry } = loadRequesterSessionEntry(params.requesterSessionKey);
const canonicalKey = resolveRequesterStoreKey(cfg, params.requesterSessionKey);
const { sessionId, isActive } = resolveRequesterSessionActivity(canonicalKey);
if (!sessionId) {
return "none";
}
const queueSettings = resolveQueueSettings({
cfg,
channel: entry?.channel ?? entry?.lastChannel ?? entry?.origin?.provider,
sessionEntry: entry,
});
// Subagent announcements are internal handoffs into an active requester turn.
// Queue modes such as followup/collect apply to user prompts, not this path.
const queueOutcome = await resolveQueueEmbeddedPiMessageOutcome(sessionId, params.steerMessage, {
steeringMode: "all",
...(queueSettings.debounceMs !== undefined ? { debounceMs: queueSettings.debounceMs } : {}),
});
if (queueOutcome.queued) {
return "steered";
}
return isActive ? "dropped" : "none";
}
function hasVisibleGatewayAgentPayload(response: unknown): boolean {
const result = getGatewayAgentResult(response);
return Boolean(
result && (hasVisibleAgentPayload(result) || hasMessagingToolDeliveryEvidence(result)),
);
}
function requiresAgentMediatedCompletionDelivery(params: {
expectsCompletionMessage: boolean;
sourceTool?: string;
}): boolean {
return (
params.expectsCompletionMessage &&
AGENT_MEDIATED_COMPLETION_TOOLS.has(normalizeOptionalLowercaseString(params.sourceTool) ?? "")
);
}
function hasGatewayAgentMessagingToolDelivery(response: unknown): boolean {
const result = getGatewayAgentResult(response);
return Boolean(result && hasMessagingToolDeliveryEvidence(result));
}
function collectExpectedMediaFromInternalEvents(
events: AgentInternalEvent[] | undefined,
): string[] {
if (!events?.length) {
return [];
}
const mediaUrls: string[] = [];
const seen = new Set<string>();
for (const event of events) {
const values = [
...(Array.isArray(event.mediaUrls) ? event.mediaUrls : []),
...mediaUrlsFromGeneratedAttachments(event.attachments),
];
for (const value of values) {
const normalized = typeof value === "string" ? value.trim() : "";
if (!normalized || seen.has(normalized)) {
continue;
}
seen.add(normalized);
mediaUrls.push(normalized);
}
}
return mediaUrls;
}
function hasGatewayAgentDeliveredExpectedMedia(
response: unknown,
expectedMediaUrls: readonly string[],
): boolean {
const result = getGatewayAgentResult(response);
return Boolean(result && hasDeliveredExpectedMedia(result, expectedMediaUrls));
}
function getGatewayAgentCommandDeliveryFailure(response: unknown): string | undefined {
const result = getGatewayAgentResult(response);
return result ? getAgentCommandDeliveryFailure(result) : undefined;
}
function isGatewayAgentRunPending(response: unknown): boolean {
if (!response || typeof response !== "object") {
return false;
}
const status = (response as { status?: unknown }).status;
return isNonTerminalAgentRunStatus(status);
}
function stripNonDeliverableChannelForCompletionOrigin(
context?: DeliveryContext,
): DeliveryContext | undefined {
const normalized = normalizeDeliveryContext(context);
if (!normalized?.channel) {
return normalized;
}
const channel = normalizeMessageChannel(normalized.channel);
if (!channel || isDeliverableMessageChannel(channel)) {
return normalized;
}
const { channel: _channel, ...rest } = normalized;
return normalizeDeliveryContext(rest);
}
async function sendSubagentAnnounceDirectly(params: {
requesterSessionKey: string;
targetRequesterSessionKey: string;
triggerMessage: string;
internalEvents?: AgentInternalEvent[];
expectsCompletionMessage: boolean;
bestEffortDeliver?: boolean;
directIdempotencyKey: string;
completionDirectOrigin?: DeliveryContext;
directOrigin?: DeliveryContext;
requesterSessionOrigin?: DeliveryContext;
sourceSessionKey?: string;
sourceChannel?: string;
sourceTool?: string;
requesterIsSubagent: boolean;
signal?: AbortSignal;
}): Promise<SubagentAnnounceDeliveryResult> {
if (params.signal?.aborted) {
return {
delivered: false,
path: "none",
};
}
const cfg = subagentAnnounceDeliveryDeps.getRuntimeConfig();
const announceTimeoutMs = resolveSubagentAnnounceTimeoutMs(cfg);
const canonicalRequesterSessionKey = resolveRequesterStoreKey(
cfg,
params.targetRequesterSessionKey,
);
try {
const completionDirectOrigin = normalizeDeliveryContext(params.completionDirectOrigin);
const directOrigin = normalizeDeliveryContext(params.directOrigin);
const requesterSessionOrigin = normalizeDeliveryContext(params.requesterSessionOrigin);
// Merge completionDirectOrigin with directOrigin so that missing fields
// (channel, to, accountId) fall back to the originating session's
// lastChannel / lastTo. Without this, a completion origin that carries a
// channel but not a `to` would prevent external delivery.
const externalCompletionDirectOrigin =
stripNonDeliverableChannelForCompletionOrigin(completionDirectOrigin);
const completionExternalFallbackOrigin = mergeDeliveryContext(
directOrigin,
requesterSessionOrigin,
);
const effectiveDirectOrigin = params.expectsCompletionMessage
? mergeDeliveryContext(externalCompletionDirectOrigin, completionExternalFallbackOrigin)
: directOrigin;
const sessionOnlyOrigin = effectiveDirectOrigin?.channel
? effectiveDirectOrigin
: requesterSessionOrigin;
const requesterEntry = loadRequesterSessionEntry(params.targetRequesterSessionKey).entry;
const deliveryTarget = !params.requesterIsSubagent
? resolveExternalBestEffortDeliveryTarget({
channel: effectiveDirectOrigin?.channel,
to: effectiveDirectOrigin?.to,
accountId: effectiveDirectOrigin?.accountId,
threadId: effectiveDirectOrigin?.threadId,
})
: { deliver: false };
const normalizedSessionOnlyOriginChannel = !params.requesterIsSubagent
? normalizeMessageChannel(sessionOnlyOrigin?.channel)
: undefined;
const sessionOnlyOriginChannel =
normalizedSessionOnlyOriginChannel &&
isGatewayMessageChannel(normalizedSessionOnlyOriginChannel)
? normalizedSessionOnlyOriginChannel
: undefined;
const agentMediatedCompletion = requiresAgentMediatedCompletionDelivery({
expectsCompletionMessage: params.expectsCompletionMessage,
sourceTool: params.sourceTool,
});
const expectedMediaUrls = collectExpectedMediaFromInternalEvents(params.internalEvents);
const requiresMessageToolDelivery = agentMediatedCompletion && expectedMediaUrls.length > 0;
const completionSourceReplyDeliveryMode = requiresMessageToolDelivery
? "message_tool_only"
: undefined;
const shouldDeliverAgentFinal = deliveryTarget.deliver && !requiresMessageToolDelivery;
const requesterActivity = resolveRequesterSessionActivity(canonicalRequesterSessionKey);
const requesterQueueSettings = resolveQueueSettings({
cfg,
channel:
requesterEntry?.channel ??
requesterEntry?.lastChannel ??
requesterEntry?.origin?.provider ??
requesterSessionOrigin?.channel ??
directOrigin?.channel,
sessionEntry: requesterEntry,
});
if (params.expectsCompletionMessage && requesterActivity.sessionId) {
const wakeOutcome = await resolveQueueEmbeddedPiMessageOutcome(
requesterActivity.sessionId,
params.triggerMessage,
{
steeringMode: "all",
...(completionSourceReplyDeliveryMode
? { sourceReplyDeliveryMode: completionSourceReplyDeliveryMode }
: {}),
...(requesterQueueSettings.debounceMs !== undefined
? { debounceMs: requesterQueueSettings.debounceMs }
: {}),
},
);
if (wakeOutcome.queued) {
return {
delivered: true,
path: "steered",
};
}
const shouldFallbackToForcedAgentHandoff =
requiresMessageToolDelivery && wakeOutcome.reason === "source_reply_delivery_mode_mismatch";
if (requesterActivity.isActive && !shouldFallbackToForcedAgentHandoff) {
// Active requester sessions should receive completion data through their
// running agent turn. If wake fails, let the dispatch layer steer/retry;
// do not bypass the requester agent with raw child output.
return {
delivered: false,
path: "direct",
error: formatQueueWakeFailureError(
"active requester session could not be woken",
wakeOutcome,
),
};
}
}
if (params.signal?.aborted) {
return {
delivered: false,
path: "none",
};
}
const directAgentParams: Record<string, unknown> = {
sessionKey: canonicalRequesterSessionKey,
message: params.triggerMessage,
deliver: shouldDeliverAgentFinal,
bestEffortDeliver: params.bestEffortDeliver,
internalEvents: params.internalEvents,
channel: shouldDeliverAgentFinal ? deliveryTarget.channel : sessionOnlyOriginChannel,
accountId: shouldDeliverAgentFinal
? deliveryTarget.accountId
: sessionOnlyOriginChannel
? sessionOnlyOrigin?.accountId
: undefined,
to: shouldDeliverAgentFinal
? deliveryTarget.to
: sessionOnlyOriginChannel
? sessionOnlyOrigin?.to
: undefined,
threadId: shouldDeliverAgentFinal
? deliveryTarget.threadId
: sessionOnlyOriginChannel
? sessionOnlyOrigin?.threadId
: undefined,
inputProvenance: {
kind: "inter_session",
sourceSessionKey: params.sourceSessionKey,
sourceChannel: params.sourceChannel ?? INTERNAL_MESSAGE_CHANNEL,
sourceTool: params.sourceTool ?? "subagent_announce",
},
...(completionSourceReplyDeliveryMode
? { sourceReplyDeliveryMode: completionSourceReplyDeliveryMode }
: {}),
idempotencyKey: params.directIdempotencyKey,
};
let directAnnounceResponse: unknown;
try {
directAnnounceResponse = await runAnnounceDeliveryWithRetry({
operation: params.expectsCompletionMessage
? "completion direct announce agent call"
: "direct announce agent call",
signal: params.signal,
run: async () =>
await runAnnounceAgentCall({
agentParams: directAgentParams,
expectFinal: true,
timeoutMs: announceTimeoutMs,
}),
});
} catch (err) {
if (isPermanentAnnounceDeliveryError(err)) {
throw err;
}
// The requester-agent handoff is the delivery contract for background
// completions. A failed handoff should retry/fail visibly instead
// of sending the child result directly to the external channel.
throw err;
}
const directAnnounceStillPending = isGatewayAgentRunPending(directAnnounceResponse);
if (directAnnounceStillPending) {
return {
delivered: true,
path: "direct",
};
}
if (
requiresMessageToolDelivery &&
!hasGatewayAgentMessagingToolDelivery(directAnnounceResponse)
) {
return {
delivered: false,
path: "direct",
error: "completion agent did not deliver through the message tool",
};
}
if (
agentMediatedCompletion &&
expectedMediaUrls.length > 0 &&
!hasGatewayAgentDeliveredExpectedMedia(directAnnounceResponse, expectedMediaUrls)
) {
return {
delivered: false,
path: "direct",
error: "completion agent did not deliver generated media",
};
}
const directDeliveryFailure = shouldDeliverAgentFinal
? getGatewayAgentCommandDeliveryFailure(directAnnounceResponse)
: undefined;
if (directDeliveryFailure) {
return {
delivered: false,
path: "direct",
error: directDeliveryFailure,
};
}
if (
params.expectsCompletionMessage &&
shouldDeliverAgentFinal &&
!hasVisibleGatewayAgentPayload(directAnnounceResponse)
) {
return {
delivered: false,
path: "direct",
error: "completion agent did not produce a visible reply",
};
}
return {
delivered: true,
path: "direct",
};
} catch (err) {
return {
delivered: false,
path: "direct",
error: summarizeDeliveryError(err),
};
}
}
export async function deliverSubagentAnnouncement(params: {
requesterSessionKey: string;
announceId?: string;
triggerMessage: string;
steerMessage: string;
internalEvents?: AgentInternalEvent[];
summaryLine?: string;
requesterSessionOrigin?: DeliveryContext;
requesterOrigin?: DeliveryContext;
completionDirectOrigin?: DeliveryContext;
directOrigin?: DeliveryContext;
sourceSessionKey?: string;
sourceChannel?: string;
sourceTool?: string;
targetRequesterSessionKey: string;
requesterIsSubagent: boolean;
expectsCompletionMessage: boolean;
bestEffortDeliver?: boolean;
directIdempotencyKey: string;
signal?: AbortSignal;
}): Promise<SubagentAnnounceDeliveryResult> {
return await runSubagentAnnounceDispatch({
expectsCompletionMessage: params.expectsCompletionMessage,
signal: params.signal,
steer: async () =>
await maybeSteerSubagentAnnounce({
requesterSessionKey: params.requesterSessionKey,
steerMessage: params.steerMessage,
signal: params.signal,
}),
direct: async () =>
await sendSubagentAnnounceDirectly({
requesterSessionKey: params.requesterSessionKey,
targetRequesterSessionKey: params.targetRequesterSessionKey,
triggerMessage: params.triggerMessage,
internalEvents: params.internalEvents,
directIdempotencyKey: params.directIdempotencyKey,
completionDirectOrigin: params.completionDirectOrigin,
directOrigin: params.directOrigin,
requesterSessionOrigin: params.requesterSessionOrigin,
sourceSessionKey: params.sourceSessionKey,
sourceChannel: params.sourceChannel,
sourceTool: params.sourceTool,
requesterIsSubagent: params.requesterIsSubagent,
expectsCompletionMessage: params.expectsCompletionMessage,
signal: params.signal,
bestEffortDeliver: params.bestEffortDeliver,
}),
});
}
export const __testing = {
setDepsForTest(
overrides?: Partial<SubagentAnnounceDeliveryDeps> & {
callGateway?: typeof callGateway;
},
) {
const callGatewayOverride = overrides?.callGateway;
const dispatchGatewayMethodInProcessOverride =
overrides?.dispatchGatewayMethodInProcess ??
(callGatewayOverride
? ((async (method, agentParams, options) =>
await callGatewayOverride({
method,
params: agentParams,
expectFinal: options?.expectFinal,
timeoutMs: options?.timeoutMs,
})) satisfies typeof dispatchGatewayMethodInProcess)
: undefined);
subagentAnnounceDeliveryDeps = overrides
? {
...defaultSubagentAnnounceDeliveryDeps,
...overrides,
...(dispatchGatewayMethodInProcessOverride
? { dispatchGatewayMethodInProcess: dispatchGatewayMethodInProcessOverride }
: {}),
}
: defaultSubagentAnnounceDeliveryDeps;
},
};