@ouro.bot/cli 0.1.0-alpha.1162 → 0.1.0-alpha.1165
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/changelog.json +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/session-events.js +5 -1
- package/dist/mind/context.js +1 -1
- package/dist/mind/outbound-record.js +1 -1
- package/dist/senses/app-sessions/app-interface.js +4 -4
- package/dist/senses/app-sessions/coordinator.js +3 -3
- package/dist/senses/app-sessions/handoff.js +15 -17
- package/dist/senses/app-sessions/retire.js +1 -1
- package/dist/senses/app-sessions/size-watch.js +1 -1
- package/dist/senses/bluebubbles/index.js +531 -526
- package/dist/senses/teams.js +10 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1545,588 +1545,593 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
|
|
|
1545
1545
|
const friendId = context.friend.id;
|
|
1546
1546
|
const sessPath = resolvedDeps.sessionPath(friendId, "bluebubbles", event.chat.sessionKey);
|
|
1547
1547
|
return await resolvedDeps.withSessionTurnLease(sessPath, async (sessionTurnLease) => {
|
|
1548
|
-
// Messages sent into this chat while another turn held it wait outside the session; they go in first.
|
|
1548
|
+
// Messages sent into this chat while another turn held it wait outside the session; they go in first, and again when this turn ends.
|
|
1549
1549
|
(0, outbound_record_1.drainOutboundRecords)((0, identity_1.getAgentRoot)(), friendId, "bluebubbles", event.chat.sessionKey, sessionTurnLease);
|
|
1550
1550
|
try {
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
catch (error) {
|
|
1554
|
-
(0, runtime_1.emitNervesEvent)({
|
|
1555
|
-
level: "warn",
|
|
1556
|
-
component: "senses",
|
|
1557
|
-
event: "senses.bluebubbles_thread_lane_cleanup_error",
|
|
1558
|
-
message: "failed to inspect obsolete bluebubbles thread-lane sessions",
|
|
1559
|
-
meta: {
|
|
1560
|
-
sessionPath: sessPath,
|
|
1561
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
1562
|
-
},
|
|
1563
|
-
});
|
|
1564
|
-
}
|
|
1565
|
-
// Pre-load session inside the canonical turn lock so same-chat
|
|
1566
|
-
// deliveries cannot race on stale trunk state.
|
|
1567
|
-
const existing = resolvedDeps.loadSession(sessPath);
|
|
1568
|
-
const sessionMessages = existing?.messages && existing.messages.length > 0
|
|
1569
|
-
? structuredClone(existing.messages)
|
|
1570
|
-
: [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(await resolvedDeps.buildSystem("bluebubbles", {}, context)) }];
|
|
1571
|
-
// Record EARLY for audit and crash recovery. This is capture truth, not
|
|
1572
|
-
// a claim that the agent turn completed successfully.
|
|
1573
|
-
const inboundSource = (options.semanticRecovery || source !== "webhook")
|
|
1574
|
-
&& sessionLikelyContainsMessage(event, existing?.messages ?? sessionMessages)
|
|
1575
|
-
? "recovery-bootstrap"
|
|
1576
|
-
: source;
|
|
1577
|
-
(0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, inboundSource);
|
|
1578
|
-
if (inboundSource === "recovery-bootstrap") {
|
|
1579
|
-
(0, runtime_1.emitNervesEvent)({
|
|
1580
|
-
component: "senses",
|
|
1581
|
-
event: "senses.bluebubbles_recovery_skip",
|
|
1582
|
-
message: "skipped bluebubbles recovery because the session already contains the message text",
|
|
1583
|
-
meta: {
|
|
1584
|
-
messageGuid: event.messageGuid,
|
|
1585
|
-
sessionKey: event.chat.sessionKey,
|
|
1586
|
-
source,
|
|
1587
|
-
},
|
|
1588
|
-
});
|
|
1589
|
-
(0, processed_log_1.recordProcessedBlueBubblesMessage)(agentName, event, inboundSource, "session-bootstrap");
|
|
1590
|
-
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "already_processed" };
|
|
1591
|
-
}
|
|
1592
|
-
// The inbound event is canonical truth as soon as its canonical lane is
|
|
1593
|
-
// reserved. Persist it before any supersedable orientation/provider work.
|
|
1594
|
-
const priorMessages = sessionMessages;
|
|
1595
|
-
const userMessage = {
|
|
1596
|
-
role: "user",
|
|
1597
|
-
content: buildInboundContent(event),
|
|
1598
|
-
};
|
|
1599
|
-
resolvedDeps.saveSession(sessPath, [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
|
|
1600
|
-
if (!await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
|
|
1601
|
-
|| !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
|
|
1602
|
-
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
|
|
1603
|
-
}
|
|
1604
|
-
options.lifecycleSignal?.throwIfAborted();
|
|
1605
|
-
const mcpOwner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
|
|
1606
|
-
const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
|
|
1607
|
-
activeTurnId = liveTurnId;
|
|
1608
|
-
const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(mcpOwner) ?? undefined;
|
|
1609
|
-
if (event.chat.isGroup) {
|
|
1610
|
-
await (0, friends_1.upsertGroupContextParticipants)({
|
|
1611
|
-
store,
|
|
1612
|
-
participants: event.chat.participantHandles.map((externalId) => ({
|
|
1613
|
-
provider: "imessage-handle",
|
|
1614
|
-
externalId,
|
|
1615
|
-
})),
|
|
1616
|
-
groupExternalId: resolveGroupExternalId(event),
|
|
1617
|
-
});
|
|
1618
|
-
}
|
|
1619
|
-
// Fetch the text of the message being replied to (if this is a threaded reply)
|
|
1620
|
-
const threadGuid = event.threadOriginatorGuid?.trim();
|
|
1621
|
-
let repliedToText = null;
|
|
1622
|
-
let repliedToAuthor;
|
|
1623
|
-
if (threadGuid) {
|
|
1624
|
-
if (client.getRepliedMessage) {
|
|
1625
|
-
const replied = await client.getRepliedMessage(threadGuid).catch(() => null);
|
|
1626
|
-
repliedToText = replied?.text ?? null;
|
|
1627
|
-
repliedToAuthor = replied ? repliedMessageAuthor(replied, options.orientationEvidence.actor.externalId) : undefined;
|
|
1628
|
-
}
|
|
1629
|
-
else {
|
|
1630
|
-
repliedToText = await client.getMessageText(threadGuid).catch(() => null);
|
|
1631
|
-
}
|
|
1632
|
-
(0, runtime_1.emitNervesEvent)({
|
|
1633
|
-
component: "senses",
|
|
1634
|
-
event: "senses.bluebubbles_reply_context",
|
|
1635
|
-
message: repliedToText ? "fetched replied-to message text" : "could not fetch replied-to message text",
|
|
1636
|
-
meta: { threadGuid, hasText: !!repliedToText },
|
|
1637
|
-
});
|
|
1638
|
-
}
|
|
1639
|
-
// Shutdown can land during MCP/group/reply-context awaits above. Recheck
|
|
1640
|
-
// before the remaining synchronous setup installs its lifecycle listener.
|
|
1641
|
-
options.lifecycleSignal?.throwIfAborted();
|
|
1642
|
-
const orientationFrame = (0, orientation_frame_1.buildOrientationFrame)({
|
|
1643
|
-
channel: "bluebubbles",
|
|
1644
|
-
messages: [...priorMessages, userMessage],
|
|
1645
|
-
currentUserMessages: [userMessage],
|
|
1646
|
-
structuredOutputs: existing?.structuredOutputs ?? [],
|
|
1647
|
-
source: buildBlueBubblesOrientationSource(event, priorMessages, options.orientationEvidence, options.orientationConversationKind, repliedToText, repliedToAuthor),
|
|
1648
|
-
});
|
|
1649
|
-
if (!(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
|
|
1650
|
-
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
|
|
1651
|
-
}
|
|
1652
|
-
const turnStage = createBlueBubblesTurnStage(event.chat.sessionKey);
|
|
1653
|
-
let finalTransportInvoked = false;
|
|
1654
|
-
let finalTransportAccepted = false;
|
|
1655
|
-
let spokeBeforeFinalTransport = false;
|
|
1656
|
-
const outboundRuntimeConfig = (0, config_1.getBlueBubblesConfig)();
|
|
1657
|
-
const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget, event.chat.isGroup, () => {
|
|
1658
|
-
spokeBeforeFinalTransport = true;
|
|
1659
|
-
(0, active_turns_1.noteBlueBubblesActiveTurnVisibleActivity)(agentName, liveTurnId);
|
|
1660
|
-
}, {
|
|
1661
|
-
admitOutbound: async () => (!options.lifecycleSignal?.aborted
|
|
1662
|
-
&& await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
|
|
1663
|
-
&& !options.lifecycleSignal?.aborted),
|
|
1664
|
-
isOutboundCurrent: () => (!options.lifecycleSignal?.aborted
|
|
1665
|
-
&& (0, latest_turn_1.isCurrent)(options.latestTurnCapability)),
|
|
1666
|
-
isOutboundAdmittedNow: () => (!options.lifecycleSignal?.aborted
|
|
1667
|
-
&& (0, latest_turn_1.isDeliveryAdmittedNow)(options.latestTurnCapability)),
|
|
1668
|
-
onFinalTransportInvoked: () => {
|
|
1669
|
-
finalTransportInvoked = true;
|
|
1670
|
-
},
|
|
1671
|
-
onFinalTransportAccepted: () => {
|
|
1672
|
-
finalTransportAccepted = true;
|
|
1673
|
-
},
|
|
1674
|
-
durableOutbound: {
|
|
1675
|
-
agentRoot: (0, identity_1.getAgentRoot)(),
|
|
1676
|
-
idempotencyKey: blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash),
|
|
1677
|
-
attachment: {
|
|
1678
|
-
serverUrl: outboundRuntimeConfig.serverUrl,
|
|
1679
|
-
accountId: outboundRuntimeConfig.accountId,
|
|
1680
|
-
},
|
|
1681
|
-
},
|
|
1682
|
-
});
|
|
1683
|
-
const controller = new AbortController();
|
|
1684
|
-
const lifecycleSignal = options.lifecycleSignal;
|
|
1685
|
-
let rejectLifecycle;
|
|
1686
|
-
const lifecyclePromise = new Promise((_resolve, reject) => {
|
|
1687
|
-
rejectLifecycle = reject;
|
|
1688
|
-
});
|
|
1689
|
-
let resolveSupersession;
|
|
1690
|
-
const supersessionPromise = new Promise((resolve) => {
|
|
1691
|
-
resolveSupersession = resolve;
|
|
1692
|
-
});
|
|
1693
|
-
const cancelForSupersession = () => {
|
|
1694
|
-
callbacks.cancelOutbound("superseded");
|
|
1695
|
-
if (!finalTransportInvoked) {
|
|
1696
|
-
controller.abort(options.latestTurnCapability.signal.reason);
|
|
1697
|
-
resolveSupersession({
|
|
1698
|
-
handled: true,
|
|
1699
|
-
notifiedAgent: false,
|
|
1700
|
-
kind: event.kind,
|
|
1701
|
-
reason: "superseded",
|
|
1702
|
-
});
|
|
1703
|
-
}
|
|
1704
|
-
};
|
|
1705
|
-
options.latestTurnCapability.signal.addEventListener("abort", cancelForSupersession, { once: true });
|
|
1706
|
-
const cancelForShutdown = () => {
|
|
1707
|
-
callbacks.cancelOutbound("shutdown");
|
|
1708
|
-
if (!finalTransportInvoked) {
|
|
1709
|
-
const reason = lifecycleSignal.reason;
|
|
1710
|
-
controller.abort(reason);
|
|
1711
|
-
rejectLifecycle(reason);
|
|
1551
|
+
try {
|
|
1552
|
+
(0, session_cleanup_1.findObsoleteBlueBubblesThreadSessions)(sessPath);
|
|
1712
1553
|
}
|
|
1713
|
-
|
|
1714
|
-
lifecycleSignal?.addEventListener("abort", cancelForShutdown, { once: true });
|
|
1715
|
-
let timeoutTimer;
|
|
1716
|
-
let timeoutPromise;
|
|
1717
|
-
let resolveTimeout;
|
|
1718
|
-
let recoveryTimedOut = false;
|
|
1719
|
-
let activeRunTurn = null;
|
|
1720
|
-
// BB-specific tool context wrappers
|
|
1721
|
-
const summarize = (0, core_1.createSummarize)("human");
|
|
1722
|
-
const bbCapabilities = (0, friends_1.getChannelCapabilities)("bluebubbles");
|
|
1723
|
-
const pendingDir = (0, pending_1.getPendingDir)(resolvedDeps.getAgentName(), friendId, "bluebubbles", event.chat.sessionKey);
|
|
1724
|
-
// Buffer terminal errors so failover can suppress them.
|
|
1725
|
-
// If failover produces a message, the buffered error is skipped.
|
|
1726
|
-
// If failover doesn't fire, the buffered error is replayed.
|
|
1727
|
-
let bufferedTerminalError = null;
|
|
1728
|
-
/* v8 ignore start -- failover-aware error buffering @preserve */
|
|
1729
|
-
const failoverAwareCallbacks = {
|
|
1730
|
-
...callbacks,
|
|
1731
|
-
onError(error, severity) {
|
|
1732
|
-
if (severity === "terminal") {
|
|
1733
|
-
bufferedTerminalError = error;
|
|
1734
|
-
return;
|
|
1735
|
-
}
|
|
1736
|
-
callbacks.onError(error, severity);
|
|
1737
|
-
},
|
|
1738
|
-
};
|
|
1739
|
-
/* v8 ignore stop */
|
|
1740
|
-
try {
|
|
1741
|
-
// ── Compute trust gate context for group/acquaintance rules ─────
|
|
1742
|
-
// These store reads can block on filesystem I/O. Race them against the
|
|
1743
|
-
// runtime lifecycle before constructing the shared pipeline so a closed
|
|
1744
|
-
// worker cannot begin new durable or outward work after the read settles.
|
|
1745
|
-
const trustContext = await Promise.race([
|
|
1746
|
-
Promise.all([
|
|
1747
|
-
checkGroupHasFamilyMember(store, event),
|
|
1748
|
-
event.chat.isGroup
|
|
1749
|
-
? Promise.resolve(false)
|
|
1750
|
-
: checkHasExistingGroupWithFamily(store, context.friend),
|
|
1751
|
-
]),
|
|
1752
|
-
lifecyclePromise,
|
|
1753
|
-
supersessionPromise.then(() => null),
|
|
1754
|
-
]);
|
|
1755
|
-
if (trustContext === null) {
|
|
1756
|
-
return {
|
|
1757
|
-
handled: true,
|
|
1758
|
-
notifiedAgent: false,
|
|
1759
|
-
kind: event.kind,
|
|
1760
|
-
reason: "superseded",
|
|
1761
|
-
};
|
|
1762
|
-
}
|
|
1763
|
-
const [groupHasFamilyMember, hasExistingGroupWithFamily] = trustContext;
|
|
1764
|
-
lifecycleSignal?.throwIfAborted();
|
|
1765
|
-
// ── Call shared pipeline ────────────────────────────────────────
|
|
1766
|
-
const timeoutMs = options.timeoutMs ?? BLUEBUBBLES_TURN_TIMEOUT_MS;
|
|
1767
|
-
timeoutPromise = new Promise((resolve) => {
|
|
1768
|
-
resolveTimeout = resolve;
|
|
1769
|
-
});
|
|
1770
|
-
timeoutTimer = setTimeout(() => {
|
|
1771
|
-
const reason = new BlueBubblesRecoveryTurnTimeoutError(timeoutMs);
|
|
1772
|
-
recoveryTimedOut = true;
|
|
1773
|
-
if (!finalTransportInvoked) {
|
|
1774
|
-
resolveTimeout?.({
|
|
1775
|
-
handled: true,
|
|
1776
|
-
notifiedAgent: false,
|
|
1777
|
-
kind: event.kind,
|
|
1778
|
-
reason: "turn_timeout",
|
|
1779
|
-
});
|
|
1780
|
-
}
|
|
1781
|
-
callbacks.cancelOutbound("turn_timeout");
|
|
1782
|
-
(0, latest_turn_1.cancel)(options.latestTurnCapability, "turn_timeout");
|
|
1783
|
-
if (!finalTransportInvoked)
|
|
1784
|
-
controller.abort(reason);
|
|
1554
|
+
catch (error) {
|
|
1785
1555
|
(0, runtime_1.emitNervesEvent)({
|
|
1786
1556
|
level: "warn",
|
|
1787
1557
|
component: "senses",
|
|
1788
|
-
event: "senses.
|
|
1789
|
-
message: "bluebubbles
|
|
1558
|
+
event: "senses.bluebubbles_thread_lane_cleanup_error",
|
|
1559
|
+
message: "failed to inspect obsolete bluebubbles thread-lane sessions",
|
|
1790
1560
|
meta: {
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
source,
|
|
1794
|
-
timeoutMs,
|
|
1561
|
+
sessionPath: sessPath,
|
|
1562
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
1795
1563
|
},
|
|
1796
1564
|
});
|
|
1565
|
+
}
|
|
1566
|
+
// Pre-load session inside the canonical turn lock so same-chat
|
|
1567
|
+
// deliveries cannot race on stale trunk state.
|
|
1568
|
+
const existing = resolvedDeps.loadSession(sessPath);
|
|
1569
|
+
const sessionMessages = existing?.messages && existing.messages.length > 0
|
|
1570
|
+
? structuredClone(existing.messages)
|
|
1571
|
+
: [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(await resolvedDeps.buildSystem("bluebubbles", {}, context)) }];
|
|
1572
|
+
// Record EARLY for audit and crash recovery. This is capture truth, not
|
|
1573
|
+
// a claim that the agent turn completed successfully.
|
|
1574
|
+
const inboundSource = (options.semanticRecovery || source !== "webhook")
|
|
1575
|
+
&& sessionLikelyContainsMessage(event, existing?.messages ?? sessionMessages)
|
|
1576
|
+
? "recovery-bootstrap"
|
|
1577
|
+
: source;
|
|
1578
|
+
(0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, inboundSource);
|
|
1579
|
+
if (inboundSource === "recovery-bootstrap") {
|
|
1797
1580
|
(0, runtime_1.emitNervesEvent)({
|
|
1798
|
-
level: "warn",
|
|
1799
1581
|
component: "senses",
|
|
1800
|
-
event: "senses.
|
|
1801
|
-
message: "bluebubbles
|
|
1582
|
+
event: "senses.bluebubbles_recovery_skip",
|
|
1583
|
+
message: "skipped bluebubbles recovery because the session already contains the message text",
|
|
1802
1584
|
meta: {
|
|
1803
1585
|
messageGuid: event.messageGuid,
|
|
1804
1586
|
sessionKey: event.chat.sessionKey,
|
|
1805
1587
|
source,
|
|
1806
|
-
timeoutMs,
|
|
1807
1588
|
},
|
|
1808
1589
|
});
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
if (typeof timeoutTimer.unref === "function") {
|
|
1812
|
-
timeoutTimer.unref();
|
|
1590
|
+
(0, processed_log_1.recordProcessedBlueBubblesMessage)(agentName, event, inboundSource, "session-bootstrap");
|
|
1591
|
+
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "already_processed" };
|
|
1813
1592
|
}
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1593
|
+
// The inbound event is canonical truth as soon as its canonical lane is
|
|
1594
|
+
// reserved. Persist it before any supersedable orientation/provider work.
|
|
1595
|
+
const priorMessages = sessionMessages;
|
|
1596
|
+
const userMessage = {
|
|
1597
|
+
role: "user",
|
|
1598
|
+
content: buildInboundContent(event),
|
|
1817
1599
|
};
|
|
1818
|
-
|
|
1600
|
+
resolvedDeps.saveSession(sessPath, [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
|
|
1601
|
+
if (!await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
|
|
1602
|
+
|| !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
|
|
1603
|
+
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
|
|
1604
|
+
}
|
|
1605
|
+
options.lifecycleSignal?.throwIfAborted();
|
|
1606
|
+
const mcpOwner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
|
|
1607
|
+
const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
|
|
1608
|
+
activeTurnId = liveTurnId;
|
|
1609
|
+
const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(mcpOwner) ?? undefined;
|
|
1610
|
+
if (event.chat.isGroup) {
|
|
1611
|
+
await (0, friends_1.upsertGroupContextParticipants)({
|
|
1612
|
+
store,
|
|
1613
|
+
participants: event.chat.participantHandles.map((externalId) => ({
|
|
1614
|
+
provider: "imessage-handle",
|
|
1615
|
+
externalId,
|
|
1616
|
+
})),
|
|
1617
|
+
groupExternalId: resolveGroupExternalId(event),
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1620
|
+
// Fetch the text of the message being replied to (if this is a threaded reply)
|
|
1621
|
+
const threadGuid = event.threadOriginatorGuid?.trim();
|
|
1622
|
+
let repliedToText = null;
|
|
1623
|
+
let repliedToAuthor;
|
|
1624
|
+
if (threadGuid) {
|
|
1625
|
+
if (client.getRepliedMessage) {
|
|
1626
|
+
const replied = await client.getRepliedMessage(threadGuid).catch(() => null);
|
|
1627
|
+
repliedToText = replied?.text ?? null;
|
|
1628
|
+
repliedToAuthor = replied ? repliedMessageAuthor(replied, options.orientationEvidence.actor.externalId) : undefined;
|
|
1629
|
+
}
|
|
1630
|
+
else {
|
|
1631
|
+
repliedToText = await client.getMessageText(threadGuid).catch(() => null);
|
|
1632
|
+
}
|
|
1633
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1634
|
+
component: "senses",
|
|
1635
|
+
event: "senses.bluebubbles_reply_context",
|
|
1636
|
+
message: repliedToText ? "fetched replied-to message text" : "could not fetch replied-to message text",
|
|
1637
|
+
meta: { threadGuid, hasText: !!repliedToText },
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
// Shutdown can land during MCP/group/reply-context awaits above. Recheck
|
|
1641
|
+
// before the remaining synchronous setup installs its lifecycle listener.
|
|
1642
|
+
options.lifecycleSignal?.throwIfAborted();
|
|
1643
|
+
const orientationFrame = (0, orientation_frame_1.buildOrientationFrame)({
|
|
1819
1644
|
channel: "bluebubbles",
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1645
|
+
messages: [...priorMessages, userMessage],
|
|
1646
|
+
currentUserMessages: [userMessage],
|
|
1647
|
+
structuredOutputs: existing?.structuredOutputs ?? [],
|
|
1648
|
+
source: buildBlueBubblesOrientationSource(event, priorMessages, options.orientationEvidence, options.orientationConversationKind, repliedToText, repliedToAuthor),
|
|
1649
|
+
});
|
|
1650
|
+
if (!(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
|
|
1651
|
+
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
|
|
1652
|
+
}
|
|
1653
|
+
const turnStage = createBlueBubblesTurnStage(event.chat.sessionKey);
|
|
1654
|
+
let finalTransportInvoked = false;
|
|
1655
|
+
let finalTransportAccepted = false;
|
|
1656
|
+
let spokeBeforeFinalTransport = false;
|
|
1657
|
+
const outboundRuntimeConfig = (0, config_1.getBlueBubblesConfig)();
|
|
1658
|
+
const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget, event.chat.isGroup, () => {
|
|
1659
|
+
spokeBeforeFinalTransport = true;
|
|
1660
|
+
(0, active_turns_1.noteBlueBubblesActiveTurnVisibleActivity)(agentName, liveTurnId);
|
|
1661
|
+
}, {
|
|
1662
|
+
admitOutbound: async () => (!options.lifecycleSignal?.aborted
|
|
1663
|
+
&& await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
|
|
1664
|
+
&& !options.lifecycleSignal?.aborted),
|
|
1665
|
+
isOutboundCurrent: () => (!options.lifecycleSignal?.aborted
|
|
1666
|
+
&& (0, latest_turn_1.isCurrent)(options.latestTurnCapability)),
|
|
1667
|
+
isOutboundAdmittedNow: () => (!options.lifecycleSignal?.aborted
|
|
1668
|
+
&& (0, latest_turn_1.isDeliveryAdmittedNow)(options.latestTurnCapability)),
|
|
1669
|
+
onFinalTransportInvoked: () => {
|
|
1670
|
+
finalTransportInvoked = true;
|
|
1833
1671
|
},
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1672
|
+
onFinalTransportAccepted: () => {
|
|
1673
|
+
finalTransportAccepted = true;
|
|
1674
|
+
},
|
|
1675
|
+
durableOutbound: {
|
|
1676
|
+
agentRoot: (0, identity_1.getAgentRoot)(),
|
|
1677
|
+
idempotencyKey: blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash),
|
|
1678
|
+
attachment: {
|
|
1679
|
+
serverUrl: outboundRuntimeConfig.serverUrl,
|
|
1680
|
+
accountId: outboundRuntimeConfig.accountId,
|
|
1681
|
+
},
|
|
1682
|
+
},
|
|
1683
|
+
});
|
|
1684
|
+
const controller = new AbortController();
|
|
1685
|
+
const lifecycleSignal = options.lifecycleSignal;
|
|
1686
|
+
let rejectLifecycle;
|
|
1687
|
+
const lifecyclePromise = new Promise((_resolve, reject) => {
|
|
1688
|
+
rejectLifecycle = reject;
|
|
1689
|
+
});
|
|
1690
|
+
let resolveSupersession;
|
|
1691
|
+
const supersessionPromise = new Promise((resolve) => {
|
|
1692
|
+
resolveSupersession = resolve;
|
|
1693
|
+
});
|
|
1694
|
+
const cancelForSupersession = () => {
|
|
1695
|
+
callbacks.cancelOutbound("superseded");
|
|
1696
|
+
if (!finalTransportInvoked) {
|
|
1697
|
+
controller.abort(options.latestTurnCapability.signal.reason);
|
|
1698
|
+
resolveSupersession({
|
|
1699
|
+
handled: true,
|
|
1700
|
+
notifiedAgent: false,
|
|
1701
|
+
kind: event.kind,
|
|
1702
|
+
reason: "superseded",
|
|
1851
1703
|
});
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1704
|
+
}
|
|
1705
|
+
};
|
|
1706
|
+
options.latestTurnCapability.signal.addEventListener("abort", cancelForSupersession, { once: true });
|
|
1707
|
+
const cancelForShutdown = () => {
|
|
1708
|
+
callbacks.cancelOutbound("shutdown");
|
|
1709
|
+
if (!finalTransportInvoked) {
|
|
1710
|
+
const reason = lifecycleSignal.reason;
|
|
1711
|
+
controller.abort(reason);
|
|
1712
|
+
rejectLifecycle(reason);
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
lifecycleSignal?.addEventListener("abort", cancelForShutdown, { once: true });
|
|
1716
|
+
let timeoutTimer;
|
|
1717
|
+
let timeoutPromise;
|
|
1718
|
+
let resolveTimeout;
|
|
1719
|
+
let recoveryTimedOut = false;
|
|
1720
|
+
let activeRunTurn = null;
|
|
1721
|
+
// BB-specific tool context wrappers
|
|
1722
|
+
const summarize = (0, core_1.createSummarize)("human");
|
|
1723
|
+
const bbCapabilities = (0, friends_1.getChannelCapabilities)("bluebubbles");
|
|
1724
|
+
const pendingDir = (0, pending_1.getPendingDir)(resolvedDeps.getAgentName(), friendId, "bluebubbles", event.chat.sessionKey);
|
|
1725
|
+
// Buffer terminal errors so failover can suppress them.
|
|
1726
|
+
// If failover produces a message, the buffered error is skipped.
|
|
1727
|
+
// If failover doesn't fire, the buffered error is replayed.
|
|
1728
|
+
let bufferedTerminalError = null;
|
|
1729
|
+
/* v8 ignore start -- failover-aware error buffering @preserve */
|
|
1730
|
+
const failoverAwareCallbacks = {
|
|
1731
|
+
...callbacks,
|
|
1732
|
+
onError(error, severity) {
|
|
1733
|
+
if (severity === "terminal") {
|
|
1734
|
+
bufferedTerminalError = error;
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
callbacks.onError(error, severity);
|
|
1738
|
+
},
|
|
1739
|
+
};
|
|
1740
|
+
/* v8 ignore stop */
|
|
1741
|
+
try {
|
|
1742
|
+
// ── Compute trust gate context for group/acquaintance rules ─────
|
|
1743
|
+
// These store reads can block on filesystem I/O. Race them against the
|
|
1744
|
+
// runtime lifecycle before constructing the shared pipeline so a closed
|
|
1745
|
+
// worker cannot begin new durable or outward work after the read settles.
|
|
1746
|
+
const trustContext = await Promise.race([
|
|
1747
|
+
Promise.all([
|
|
1748
|
+
checkGroupHasFamilyMember(store, event),
|
|
1749
|
+
event.chat.isGroup
|
|
1750
|
+
? Promise.resolve(false)
|
|
1751
|
+
: checkHasExistingGroupWithFamily(store, context.friend),
|
|
1752
|
+
]),
|
|
1753
|
+
lifecyclePromise,
|
|
1754
|
+
supersessionPromise.then(() => null),
|
|
1755
|
+
]);
|
|
1756
|
+
if (trustContext === null) {
|
|
1858
1757
|
return {
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
],
|
|
1864
|
-
} : {}),
|
|
1865
|
-
...(preparedBlueBubblesContext.messages.length > 0 ? {
|
|
1866
|
-
promptOnlyEvidenceMessages: preparedBlueBubblesContext.messages,
|
|
1867
|
-
} : {}),
|
|
1868
|
-
requiredPromptEvidence: {
|
|
1869
|
-
currentUserMessage,
|
|
1870
|
-
...(verifiedPredecessorMessage ? { verifiedPredecessorMessage } : {}),
|
|
1871
|
-
},
|
|
1758
|
+
handled: true,
|
|
1759
|
+
notifiedAgent: false,
|
|
1760
|
+
kind: event.kind,
|
|
1761
|
+
reason: "superseded",
|
|
1872
1762
|
};
|
|
1873
|
-
}
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1763
|
+
}
|
|
1764
|
+
const [groupHasFamilyMember, hasExistingGroupWithFamily] = trustContext;
|
|
1765
|
+
lifecycleSignal?.throwIfAborted();
|
|
1766
|
+
// ── Call shared pipeline ────────────────────────────────────────
|
|
1767
|
+
const timeoutMs = options.timeoutMs ?? BLUEBUBBLES_TURN_TIMEOUT_MS;
|
|
1768
|
+
timeoutPromise = new Promise((resolve) => {
|
|
1769
|
+
resolveTimeout = resolve;
|
|
1770
|
+
});
|
|
1771
|
+
timeoutTimer = setTimeout(() => {
|
|
1772
|
+
const reason = new BlueBubblesRecoveryTurnTimeoutError(timeoutMs);
|
|
1773
|
+
recoveryTimedOut = true;
|
|
1774
|
+
if (!finalTransportInvoked) {
|
|
1775
|
+
resolveTimeout?.({
|
|
1776
|
+
handled: true,
|
|
1777
|
+
notifiedAgent: false,
|
|
1778
|
+
kind: event.kind,
|
|
1779
|
+
reason: "turn_timeout",
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
callbacks.cancelOutbound("turn_timeout");
|
|
1783
|
+
(0, latest_turn_1.cancel)(options.latestTurnCapability, "turn_timeout");
|
|
1784
|
+
if (!finalTransportInvoked)
|
|
1785
|
+
controller.abort(reason);
|
|
1786
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1787
|
+
level: "warn",
|
|
1788
|
+
component: "senses",
|
|
1789
|
+
event: "senses.bluebubbles_turn_timeout",
|
|
1790
|
+
message: "bluebubbles turn timed out",
|
|
1791
|
+
meta: {
|
|
1792
|
+
messageGuid: event.messageGuid,
|
|
1793
|
+
sessionKey: event.chat.sessionKey,
|
|
1794
|
+
source,
|
|
1795
|
+
timeoutMs,
|
|
1889
1796
|
},
|
|
1797
|
+
});
|
|
1798
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1799
|
+
level: "warn",
|
|
1800
|
+
component: "senses",
|
|
1801
|
+
event: "senses.bluebubbles_timeout_notice_suppressed",
|
|
1802
|
+
message: "bluebubbles timeout notice suppressed from iMessage",
|
|
1803
|
+
meta: {
|
|
1804
|
+
messageGuid: event.messageGuid,
|
|
1805
|
+
sessionKey: event.chat.sessionKey,
|
|
1806
|
+
source,
|
|
1807
|
+
timeoutMs,
|
|
1808
|
+
},
|
|
1809
|
+
});
|
|
1810
|
+
}, timeoutMs);
|
|
1811
|
+
/* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
|
|
1812
|
+
if (typeof timeoutTimer.unref === "function") {
|
|
1813
|
+
timeoutTimer.unref();
|
|
1814
|
+
}
|
|
1815
|
+
let preparedBlueBubblesContext = {
|
|
1816
|
+
messages: [],
|
|
1817
|
+
contextPacketIds: [],
|
|
1818
|
+
};
|
|
1819
|
+
const turnPromise = (0, pipeline_1.handleInboundTurn)({
|
|
1820
|
+
channel: "bluebubbles",
|
|
1821
|
+
sessionKey: event.chat.sessionKey,
|
|
1822
|
+
capabilities: bbCapabilities,
|
|
1823
|
+
messages: [userMessage],
|
|
1824
|
+
continuityIngressTexts: getBlueBubblesContinuityIngressTexts(event),
|
|
1825
|
+
friendResolver: { resolve: () => Promise.resolve(context) },
|
|
1826
|
+
sessionLoader: {
|
|
1827
|
+
loadOrCreate: () => Promise.resolve({
|
|
1828
|
+
messages: sessionMessages,
|
|
1829
|
+
sessionPath: sessPath,
|
|
1830
|
+
state: existing?.state,
|
|
1831
|
+
events: existing?.events,
|
|
1832
|
+
structuredOutputs: existing?.structuredOutputs,
|
|
1833
|
+
}),
|
|
1834
|
+
},
|
|
1835
|
+
pendingDir,
|
|
1836
|
+
friendStore: store,
|
|
1837
|
+
provider: "imessage-handle",
|
|
1838
|
+
externalId: event.sender.externalId,
|
|
1839
|
+
isGroupChat: event.chat.isGroup,
|
|
1840
|
+
groupHasFamilyMember,
|
|
1841
|
+
hasExistingGroupWithFamily,
|
|
1842
|
+
enforceTrustGate: trust_gate_1.enforceTrustGate,
|
|
1843
|
+
drainPending: pending_1.drainPending,
|
|
1844
|
+
drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(resolvedDeps.getAgentName(), deferredFriendId),
|
|
1845
|
+
prepareRunAgentOptions: async ({ messages = [], currentUserMessages = [], runAgentOptions }) => {
|
|
1846
|
+
preparedBlueBubblesContext = await buildBlueBubblesContextMessages({
|
|
1847
|
+
agentName,
|
|
1848
|
+
agentRoot: (0, identity_1.getAgentRoot)(),
|
|
1849
|
+
client,
|
|
1850
|
+
event,
|
|
1851
|
+
knownMessages: messages,
|
|
1852
|
+
});
|
|
1853
|
+
const currentUserMessage = currentUserMessages.findLast((message) => message.role === "user")
|
|
1854
|
+
?? messages.findLast((message) => message.role === "user");
|
|
1855
|
+
if (!currentUserMessage)
|
|
1856
|
+
return undefined;
|
|
1857
|
+
Object.freeze(currentUserMessage);
|
|
1858
|
+
const { verifiedPredecessorMessage } = preparedBlueBubblesContext;
|
|
1859
|
+
return {
|
|
1860
|
+
...(preparedBlueBubblesContext.contextPacketIds.length > 0 ? {
|
|
1861
|
+
contextPacketIds: [
|
|
1862
|
+
...(runAgentOptions.contextPacketIds ?? []),
|
|
1863
|
+
...preparedBlueBubblesContext.contextPacketIds,
|
|
1864
|
+
],
|
|
1865
|
+
} : {}),
|
|
1866
|
+
...(preparedBlueBubblesContext.messages.length > 0 ? {
|
|
1867
|
+
promptOnlyEvidenceMessages: preparedBlueBubblesContext.messages,
|
|
1868
|
+
} : {}),
|
|
1869
|
+
requiredPromptEvidence: {
|
|
1870
|
+
currentUserMessage,
|
|
1871
|
+
...(verifiedPredecessorMessage ? { verifiedPredecessorMessage } : {}),
|
|
1872
|
+
},
|
|
1873
|
+
};
|
|
1874
|
+
},
|
|
1875
|
+
runAgent: async (msgs, cb, channel, sig, opts) => {
|
|
1876
|
+
const { codingFeedback: _omittedCodingFeedback, ...safeToolContext } = opts?.toolContext ?? {};
|
|
1877
|
+
const requiredCurrent = opts?.requiredPromptEvidence?.currentUserMessage;
|
|
1878
|
+
const providerMessages = insertEphemeralContextMessages(msgs.map((message) => message === requiredCurrent ? message : structuredClone(message)), [
|
|
1879
|
+
...preparedBlueBubblesContext.messages,
|
|
1880
|
+
...(preparedBlueBubblesContext.verifiedPredecessorMessage
|
|
1881
|
+
? [preparedBlueBubblesContext.verifiedPredecessorMessage]
|
|
1882
|
+
: []),
|
|
1883
|
+
], requiredCurrent);
|
|
1884
|
+
let generatedMessages = [];
|
|
1885
|
+
const agentResult = await resolvedDeps.runAgent(providerMessages, cb, channel, sig, {
|
|
1886
|
+
...opts,
|
|
1887
|
+
captureGeneratedMessages: (generated) => {
|
|
1888
|
+
opts?.captureGeneratedMessages?.(generated);
|
|
1889
|
+
generatedMessages = structuredClone(generated);
|
|
1890
|
+
},
|
|
1891
|
+
toolContext: {
|
|
1892
|
+
/* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
|
|
1893
|
+
signin: async () => undefined,
|
|
1894
|
+
...safeToolContext,
|
|
1895
|
+
...mcpOwner,
|
|
1896
|
+
summarize,
|
|
1897
|
+
chatActions: (0, tools_chat_1.chatActionsForTurn)({
|
|
1898
|
+
setReplyTarget: (selection) => replyTarget.setSelection(selection),
|
|
1899
|
+
react: (emoji, messageId) => (0, reactions_1.reactInBlueBubbles)(client, event.chat, emoji, messageId),
|
|
1900
|
+
sendFile: (filePath, caption) => (0, send_file_1.sendFileInBlueBubbles)(client, event.chat, filePath, caption),
|
|
1901
|
+
}, event.messageGuid),
|
|
1902
|
+
},
|
|
1903
|
+
});
|
|
1904
|
+
if (generatedMessages.length > 0) {
|
|
1905
|
+
msgs.push(...generatedMessages);
|
|
1906
|
+
}
|
|
1907
|
+
return agentResult;
|
|
1908
|
+
},
|
|
1909
|
+
postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
|
|
1910
|
+
const prepared = resolvedDeps.postTurnTrim(turnMessages, usage, hooks);
|
|
1911
|
+
turnStage.postTurn = {
|
|
1912
|
+
sessionPath: sessionPathArg,
|
|
1913
|
+
prepared,
|
|
1914
|
+
usage,
|
|
1915
|
+
state,
|
|
1916
|
+
};
|
|
1917
|
+
},
|
|
1918
|
+
accumulateFriendTokens: async (tokenStore, tokenFriendId, usage) => {
|
|
1919
|
+
turnStage.tokens = {
|
|
1920
|
+
store: tokenStore,
|
|
1921
|
+
friendId: tokenFriendId,
|
|
1922
|
+
usage,
|
|
1923
|
+
};
|
|
1924
|
+
},
|
|
1925
|
+
signal: controller.signal,
|
|
1926
|
+
runAgentOptions: {
|
|
1927
|
+
mcpManager,
|
|
1928
|
+
orientationFrame,
|
|
1890
1929
|
toolContext: {
|
|
1891
|
-
/* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
|
|
1892
1930
|
signin: async () => undefined,
|
|
1893
|
-
...safeToolContext,
|
|
1894
1931
|
...mcpOwner,
|
|
1895
|
-
|
|
1896
|
-
chatActions: (0, tools_chat_1.chatActionsForTurn)({
|
|
1897
|
-
setReplyTarget: (selection) => replyTarget.setSelection(selection),
|
|
1898
|
-
react: (emoji, messageId) => (0, reactions_1.reactInBlueBubbles)(client, event.chat, emoji, messageId),
|
|
1899
|
-
sendFile: (filePath, caption) => (0, send_file_1.sendFileInBlueBubbles)(client, event.chat, filePath, caption),
|
|
1900
|
-
}, event.messageGuid),
|
|
1932
|
+
currentIngressEvidence: options.currentIngressEvidence,
|
|
1901
1933
|
},
|
|
1902
|
-
|
|
1903
|
-
if (generatedMessages.length > 0) {
|
|
1904
|
-
msgs.push(...generatedMessages);
|
|
1905
|
-
}
|
|
1906
|
-
return agentResult;
|
|
1907
|
-
},
|
|
1908
|
-
postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
|
|
1909
|
-
const prepared = resolvedDeps.postTurnTrim(turnMessages, usage, hooks);
|
|
1910
|
-
turnStage.postTurn = {
|
|
1911
|
-
sessionPath: sessionPathArg,
|
|
1912
|
-
prepared,
|
|
1913
|
-
usage,
|
|
1914
|
-
state,
|
|
1915
|
-
};
|
|
1916
|
-
},
|
|
1917
|
-
accumulateFriendTokens: async (tokenStore, tokenFriendId, usage) => {
|
|
1918
|
-
turnStage.tokens = {
|
|
1919
|
-
store: tokenStore,
|
|
1920
|
-
friendId: tokenFriendId,
|
|
1921
|
-
usage,
|
|
1922
|
-
};
|
|
1923
|
-
},
|
|
1924
|
-
signal: controller.signal,
|
|
1925
|
-
runAgentOptions: {
|
|
1926
|
-
mcpManager,
|
|
1927
|
-
orientationFrame,
|
|
1928
|
-
toolContext: {
|
|
1929
|
-
signin: async () => undefined,
|
|
1930
|
-
...mcpOwner,
|
|
1931
|
-
currentIngressEvidence: options.currentIngressEvidence,
|
|
1932
|
-
},
|
|
1933
|
-
...(options.isReactionSignal ? { isReactionSignal: true } : {}),
|
|
1934
|
-
},
|
|
1935
|
-
callbacks: failoverAwareCallbacks,
|
|
1936
|
-
sessionTurnLease,
|
|
1937
|
-
failoverState: turnStage.failoverState,
|
|
1938
|
-
});
|
|
1939
|
-
/* v8 ignore start -- detached late-rejection telemetry is asserted in timeout tests, but V8 does not reliably attribute Promise.catch callbacks @preserve */
|
|
1940
|
-
void turnPromise
|
|
1941
|
-
.catch((error) => {
|
|
1942
|
-
if (!recoveryTimedOut)
|
|
1943
|
-
return;
|
|
1944
|
-
(0, runtime_1.emitNervesEvent)({
|
|
1945
|
-
level: "warn",
|
|
1946
|
-
component: "senses",
|
|
1947
|
-
event: "senses.bluebubbles_recovery_error",
|
|
1948
|
-
message: "bluebubbles recovery turn rejected after timeout",
|
|
1949
|
-
meta: {
|
|
1950
|
-
messageGuid: event.messageGuid,
|
|
1951
|
-
sessionKey: event.chat.sessionKey,
|
|
1952
|
-
source,
|
|
1953
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
1934
|
+
...(options.isReactionSignal ? { isReactionSignal: true } : {}),
|
|
1954
1935
|
},
|
|
1936
|
+
callbacks: failoverAwareCallbacks,
|
|
1937
|
+
sessionTurnLease,
|
|
1938
|
+
failoverState: turnStage.failoverState,
|
|
1955
1939
|
});
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1940
|
+
/* v8 ignore start -- detached late-rejection telemetry is asserted in timeout tests, but V8 does not reliably attribute Promise.catch callbacks @preserve */
|
|
1941
|
+
void turnPromise
|
|
1942
|
+
.catch((error) => {
|
|
1943
|
+
if (!recoveryTimedOut)
|
|
1944
|
+
return;
|
|
1961
1945
|
(0, runtime_1.emitNervesEvent)({
|
|
1962
1946
|
level: "warn",
|
|
1963
1947
|
component: "senses",
|
|
1964
|
-
event: "senses.
|
|
1965
|
-
message: "
|
|
1948
|
+
event: "senses.bluebubbles_recovery_error",
|
|
1949
|
+
message: "bluebubbles recovery turn rejected after timeout",
|
|
1966
1950
|
meta: {
|
|
1967
1951
|
messageGuid: event.messageGuid,
|
|
1968
1952
|
sessionKey: event.chat.sessionKey,
|
|
1969
1953
|
source,
|
|
1970
|
-
reason:
|
|
1954
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
1971
1955
|
},
|
|
1972
1956
|
});
|
|
1973
|
-
|
|
1974
|
-
handled: true,
|
|
1975
|
-
notifiedAgent: false,
|
|
1976
|
-
kind: event.kind,
|
|
1977
|
-
reason: "turn_timeout",
|
|
1978
|
-
};
|
|
1979
|
-
}
|
|
1980
|
-
/* v8 ignore start -- failover display + error replay @preserve */
|
|
1981
|
-
if (result.failoverMessage) {
|
|
1982
|
-
callbacks.onClearText?.();
|
|
1983
|
-
callbacks.onTextChunk(result.failoverMessage);
|
|
1984
|
-
bufferedTerminalError = null;
|
|
1985
|
-
}
|
|
1986
|
-
else if (bufferedTerminalError) {
|
|
1987
|
-
callbacks.onError(bufferedTerminalError, "terminal");
|
|
1988
|
-
bufferedTerminalError = null;
|
|
1989
|
-
}
|
|
1957
|
+
});
|
|
1990
1958
|
/* v8 ignore stop */
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1959
|
+
const runTurn = (async () => {
|
|
1960
|
+
const result = await turnPromise;
|
|
1961
|
+
if (recoveryTimedOut && !finalTransportInvoked) {
|
|
1962
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1963
|
+
level: "warn",
|
|
1964
|
+
component: "senses",
|
|
1965
|
+
event: "senses.bluebubbles_timed_out_turn_suppressed",
|
|
1966
|
+
message: "suppressed late bluebubbles turn result after timeout",
|
|
1967
|
+
meta: {
|
|
1968
|
+
messageGuid: event.messageGuid,
|
|
1969
|
+
sessionKey: event.chat.sessionKey,
|
|
1970
|
+
source,
|
|
1971
|
+
reason: "turn completed after its final-transport boundary closed",
|
|
1972
|
+
},
|
|
1973
|
+
});
|
|
1974
|
+
return {
|
|
1975
|
+
handled: true,
|
|
1976
|
+
notifiedAgent: false,
|
|
1977
|
+
kind: event.kind,
|
|
1978
|
+
reason: "turn_timeout",
|
|
1979
|
+
};
|
|
1997
1980
|
}
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
1981
|
+
/* v8 ignore start -- failover display + error replay @preserve */
|
|
1982
|
+
if (result.failoverMessage) {
|
|
1983
|
+
callbacks.onClearText?.();
|
|
1984
|
+
callbacks.onTextChunk(result.failoverMessage);
|
|
1985
|
+
bufferedTerminalError = null;
|
|
1986
|
+
}
|
|
1987
|
+
else if (bufferedTerminalError) {
|
|
1988
|
+
callbacks.onError(bufferedTerminalError, "terminal");
|
|
1989
|
+
bufferedTerminalError = null;
|
|
1990
|
+
}
|
|
1991
|
+
/* v8 ignore stop */
|
|
1992
|
+
// ── Handle gate result ────────────────────────────────────────
|
|
1993
|
+
let processedOutcome = "turn-complete";
|
|
1994
|
+
if (!result.gateResult.allowed) {
|
|
1995
|
+
callbacks.onClearText?.();
|
|
1996
|
+
if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
|
|
1997
|
+
callbacks.onTextChunk(result.gateResult.autoReply);
|
|
1998
|
+
}
|
|
1999
|
+
processedOutcome = "trust-gated";
|
|
2000
|
+
}
|
|
2001
|
+
let delivery;
|
|
2002
|
+
try {
|
|
2003
|
+
delivery = await callbacks.flush({ signal: controller.signal });
|
|
2004
|
+
}
|
|
2005
|
+
catch (error) {
|
|
2006
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2007
|
+
level: "warn",
|
|
2008
|
+
component: "senses",
|
|
2009
|
+
event: "senses.bluebubbles_final_transport_failed",
|
|
2010
|
+
message: "bluebubbles final transport failed after invocation",
|
|
2011
|
+
meta: {
|
|
2012
|
+
messageGuid: event.messageGuid,
|
|
2013
|
+
sessionKey: event.chat.sessionKey,
|
|
2014
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
2015
|
+
},
|
|
2016
|
+
});
|
|
2017
|
+
if (spokeBeforeFinalTransport) {
|
|
2018
|
+
// The friend already saw part of this turn; a retry would repeat it.
|
|
2019
|
+
const failed = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash));
|
|
2020
|
+
if (failed) {
|
|
2021
|
+
(0, outbound_state_1.markBlueBubblesOutboundPendingManualVerification)({
|
|
2022
|
+
agentRoot: (0, identity_1.getAgentRoot)(),
|
|
2023
|
+
recordId: failed.recordId,
|
|
2024
|
+
decidedAt: new Date().toISOString(),
|
|
2025
|
+
reason: "mid-turn speech was visible before the final send failed",
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
return {
|
|
2030
|
+
handled: true,
|
|
2031
|
+
notifiedAgent: false,
|
|
2032
|
+
kind: event.kind,
|
|
2033
|
+
reason: "delivery_failed",
|
|
2034
|
+
};
|
|
2035
|
+
}
|
|
2036
|
+
if (delivery.status !== "accepted" || !finalTransportAccepted) {
|
|
2037
|
+
return {
|
|
2038
|
+
handled: true,
|
|
2039
|
+
notifiedAgent: false,
|
|
2040
|
+
kind: event.kind,
|
|
2041
|
+
reason: !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)
|
|
2042
|
+
? "superseded"
|
|
2043
|
+
: "no_visible_reply",
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
// Acceptance is the visibility boundary. Publish the terminal dedupe
|
|
2047
|
+
// receipt first, then project the private generated tail while this
|
|
2048
|
+
// chat's canonical lock remains held. Even if receipt publication
|
|
2049
|
+
// fails, make the best possible canonical projection before surfacing
|
|
2050
|
+
// the retained-claim failure. Ancillary accounting follows both.
|
|
2051
|
+
let receiptFailed = false;
|
|
2052
|
+
let receiptFailure;
|
|
2053
|
+
try {
|
|
2054
|
+
options.publishAcceptedReceipt();
|
|
2055
|
+
}
|
|
2056
|
+
catch (error) {
|
|
2057
|
+
receiptFailed = true;
|
|
2058
|
+
receiptFailure = error;
|
|
2059
|
+
}
|
|
2060
|
+
persistAcceptedBlueBubblesProjection({
|
|
2061
|
+
stage: turnStage,
|
|
2062
|
+
deps: resolvedDeps,
|
|
2063
|
+
event,
|
|
2064
|
+
});
|
|
2065
|
+
if (receiptFailed)
|
|
2066
|
+
throw receiptFailure;
|
|
2067
|
+
promoteAcceptedBlueBubblesAncillaryState({
|
|
2068
|
+
stage: turnStage,
|
|
2069
|
+
deps: resolvedDeps,
|
|
2070
|
+
agentName,
|
|
2071
|
+
event,
|
|
2072
|
+
source,
|
|
2073
|
+
processedOutcome,
|
|
2074
|
+
});
|
|
2005
2075
|
(0, runtime_1.emitNervesEvent)({
|
|
2006
|
-
level: "warn",
|
|
2007
2076
|
component: "senses",
|
|
2008
|
-
event: "senses.
|
|
2009
|
-
message: "bluebubbles
|
|
2077
|
+
event: "senses.bluebubbles_turn_end",
|
|
2078
|
+
message: "bluebubbles event handled",
|
|
2010
2079
|
meta: {
|
|
2011
2080
|
messageGuid: event.messageGuid,
|
|
2081
|
+
kind: event.kind,
|
|
2012
2082
|
sessionKey: event.chat.sessionKey,
|
|
2013
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
2014
2083
|
},
|
|
2015
2084
|
});
|
|
2016
|
-
if (spokeBeforeFinalTransport) {
|
|
2017
|
-
// The friend already saw part of this turn; a retry would repeat it.
|
|
2018
|
-
const failed = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash));
|
|
2019
|
-
if (failed) {
|
|
2020
|
-
(0, outbound_state_1.markBlueBubblesOutboundPendingManualVerification)({
|
|
2021
|
-
agentRoot: (0, identity_1.getAgentRoot)(),
|
|
2022
|
-
recordId: failed.recordId,
|
|
2023
|
-
decidedAt: new Date().toISOString(),
|
|
2024
|
-
reason: "mid-turn speech was visible before the final send failed",
|
|
2025
|
-
});
|
|
2026
|
-
}
|
|
2027
|
-
}
|
|
2028
2085
|
return {
|
|
2029
2086
|
handled: true,
|
|
2030
|
-
notifiedAgent:
|
|
2031
|
-
kind: event.kind,
|
|
2032
|
-
reason: "delivery_failed",
|
|
2033
|
-
};
|
|
2034
|
-
}
|
|
2035
|
-
if (delivery.status !== "accepted" || !finalTransportAccepted) {
|
|
2036
|
-
return {
|
|
2037
|
-
handled: true,
|
|
2038
|
-
notifiedAgent: false,
|
|
2087
|
+
notifiedAgent: true,
|
|
2039
2088
|
kind: event.kind,
|
|
2040
|
-
reason: !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)
|
|
2041
|
-
? "superseded"
|
|
2042
|
-
: "no_visible_reply",
|
|
2043
2089
|
};
|
|
2044
|
-
}
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
event,
|
|
2063
|
-
});
|
|
2064
|
-
if (receiptFailed)
|
|
2065
|
-
throw receiptFailure;
|
|
2066
|
-
promoteAcceptedBlueBubblesAncillaryState({
|
|
2067
|
-
stage: turnStage,
|
|
2068
|
-
deps: resolvedDeps,
|
|
2069
|
-
agentName,
|
|
2070
|
-
event,
|
|
2071
|
-
source,
|
|
2072
|
-
processedOutcome,
|
|
2073
|
-
});
|
|
2074
|
-
(0, runtime_1.emitNervesEvent)({
|
|
2075
|
-
component: "senses",
|
|
2076
|
-
event: "senses.bluebubbles_turn_end",
|
|
2077
|
-
message: "bluebubbles event handled",
|
|
2078
|
-
meta: {
|
|
2079
|
-
messageGuid: event.messageGuid,
|
|
2080
|
-
kind: event.kind,
|
|
2081
|
-
sessionKey: event.chat.sessionKey,
|
|
2082
|
-
},
|
|
2083
|
-
});
|
|
2084
|
-
return {
|
|
2085
|
-
handled: true,
|
|
2086
|
-
notifiedAgent: true,
|
|
2087
|
-
kind: event.kind,
|
|
2088
|
-
};
|
|
2089
|
-
})();
|
|
2090
|
-
activeRunTurn = runTurn;
|
|
2091
|
-
/* v8 ignore start -- detached post-timeout suppression telemetry @preserve */
|
|
2092
|
-
void runTurn.catch((error) => {
|
|
2093
|
-
if (!recoveryTimedOut)
|
|
2094
|
-
return;
|
|
2095
|
-
(0, runtime_1.emitNervesEvent)({
|
|
2096
|
-
level: "warn",
|
|
2097
|
-
component: "senses",
|
|
2098
|
-
event: "senses.bluebubbles_timed_out_turn_suppressed",
|
|
2099
|
-
message: "suppressed late bluebubbles turn result after timeout",
|
|
2100
|
-
meta: {
|
|
2101
|
-
messageGuid: event.messageGuid,
|
|
2102
|
-
sessionKey: event.chat.sessionKey,
|
|
2103
|
-
source,
|
|
2104
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
2105
|
-
},
|
|
2090
|
+
})();
|
|
2091
|
+
activeRunTurn = runTurn;
|
|
2092
|
+
/* v8 ignore start -- detached post-timeout suppression telemetry @preserve */
|
|
2093
|
+
void runTurn.catch((error) => {
|
|
2094
|
+
if (!recoveryTimedOut)
|
|
2095
|
+
return;
|
|
2096
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2097
|
+
level: "warn",
|
|
2098
|
+
component: "senses",
|
|
2099
|
+
event: "senses.bluebubbles_timed_out_turn_suppressed",
|
|
2100
|
+
message: "suppressed late bluebubbles turn result after timeout",
|
|
2101
|
+
meta: {
|
|
2102
|
+
messageGuid: event.messageGuid,
|
|
2103
|
+
sessionKey: event.chat.sessionKey,
|
|
2104
|
+
source,
|
|
2105
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
2106
|
+
},
|
|
2107
|
+
});
|
|
2106
2108
|
});
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2109
|
+
/* v8 ignore stop */
|
|
2110
|
+
return await Promise.race([runTurn, timeoutPromise, supersessionPromise, lifecyclePromise]);
|
|
2111
|
+
}
|
|
2112
|
+
finally {
|
|
2113
|
+
// A timed-out/superseded provider may ignore abort briefly. Never release
|
|
2114
|
+
// the cross-process session lease until that work has actually quiesced.
|
|
2115
|
+
if (activeRunTurn)
|
|
2116
|
+
await activeRunTurn.catch(() => undefined);
|
|
2117
|
+
// If a terminal error was buffered and never replayed (e.g., handleInboundTurn threw),
|
|
2118
|
+
// replay it now so the user still sees the error.
|
|
2119
|
+
/* v8 ignore start -- error replay on throw: tested via BB error test @preserve */
|
|
2120
|
+
if (bufferedTerminalError) {
|
|
2121
|
+
callbacks.onError(bufferedTerminalError, "terminal");
|
|
2122
|
+
bufferedTerminalError = null;
|
|
2123
|
+
}
|
|
2124
|
+
/* v8 ignore stop */
|
|
2125
|
+
clearTimeout(timeoutTimer);
|
|
2126
|
+
options.latestTurnCapability.signal.removeEventListener("abort", cancelForSupersession);
|
|
2127
|
+
lifecycleSignal?.removeEventListener("abort", cancelForShutdown);
|
|
2128
|
+
(0, active_turns_1.finishBlueBubblesActiveTurn)(agentName, liveTurnId);
|
|
2129
|
+
activeTurnId = null;
|
|
2130
|
+
await callbacks.finish({ timeoutMs: BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS });
|
|
2131
|
+
}
|
|
2110
2132
|
}
|
|
2111
2133
|
finally {
|
|
2112
|
-
|
|
2113
|
-
// the cross-process session lease until that work has actually quiesced.
|
|
2114
|
-
if (activeRunTurn)
|
|
2115
|
-
await activeRunTurn.catch(() => undefined);
|
|
2116
|
-
// If a terminal error was buffered and never replayed (e.g., handleInboundTurn threw),
|
|
2117
|
-
// replay it now so the user still sees the error.
|
|
2118
|
-
/* v8 ignore start -- error replay on throw: tested via BB error test @preserve */
|
|
2119
|
-
if (bufferedTerminalError) {
|
|
2120
|
-
callbacks.onError(bufferedTerminalError, "terminal");
|
|
2121
|
-
bufferedTerminalError = null;
|
|
2122
|
-
}
|
|
2123
|
-
/* v8 ignore stop */
|
|
2124
|
-
clearTimeout(timeoutTimer);
|
|
2125
|
-
options.latestTurnCapability.signal.removeEventListener("abort", cancelForSupersession);
|
|
2126
|
-
lifecycleSignal?.removeEventListener("abort", cancelForShutdown);
|
|
2127
|
-
(0, active_turns_1.finishBlueBubblesActiveTurn)(agentName, liveTurnId);
|
|
2128
|
-
activeTurnId = null;
|
|
2129
|
-
await callbacks.finish({ timeoutMs: BLUEBUBBLES_CALLBACK_CLEANUP_TIMEOUT_MS });
|
|
2134
|
+
(0, outbound_record_1.drainOutboundRecords)((0, identity_1.getAgentRoot)(), friendId, "bluebubbles", event.chat.sessionKey, sessionTurnLease);
|
|
2130
2135
|
}
|
|
2131
2136
|
});
|
|
2132
2137
|
});
|