@ouro.bot/cli 0.1.0-alpha.6 → 0.1.0-alpha.60
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/AdoptionSpecialist.ouro/agent.json +70 -9
- package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
- package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
- package/README.md +147 -205
- package/assets/ouroboros.png +0 -0
- package/changelog.json +325 -0
- package/dist/heart/active-work.js +178 -0
- package/dist/heart/bridges/manager.js +358 -0
- package/dist/heart/bridges/state-machine.js +135 -0
- package/dist/heart/bridges/store.js +123 -0
- package/dist/heart/config.js +57 -23
- package/dist/heart/core.js +236 -90
- package/dist/heart/cross-chat-delivery.js +146 -0
- package/dist/heart/daemon/agent-discovery.js +81 -0
- package/dist/heart/daemon/auth-flow.js +351 -0
- package/dist/heart/daemon/daemon-cli.js +1173 -227
- package/dist/heart/daemon/daemon-entry.js +55 -6
- package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
- package/dist/heart/daemon/daemon.js +189 -10
- package/dist/heart/daemon/hatch-animation.js +10 -3
- package/dist/heart/daemon/hatch-flow.js +4 -82
- package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
- package/dist/heart/daemon/launchd.js +159 -0
- package/dist/heart/daemon/log-tailer.js +4 -3
- package/dist/heart/daemon/message-router.js +17 -8
- package/dist/heart/daemon/ouro-bot-entry.js +0 -0
- package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
- package/dist/heart/daemon/ouro-entry.js +0 -0
- package/dist/heart/daemon/ouro-path-installer.js +178 -0
- package/dist/heart/daemon/ouro-uti.js +11 -2
- package/dist/heart/daemon/process-manager.js +14 -1
- package/dist/heart/daemon/run-hooks.js +37 -0
- package/dist/heart/daemon/runtime-logging.js +58 -15
- package/dist/heart/daemon/runtime-metadata.js +219 -0
- package/dist/heart/daemon/runtime-mode.js +67 -0
- package/dist/heart/daemon/sense-manager.js +307 -0
- package/dist/heart/daemon/socket-client.js +202 -0
- package/dist/heart/daemon/specialist-orchestrator.js +53 -84
- package/dist/heart/daemon/specialist-prompt.js +64 -5
- package/dist/heart/daemon/specialist-tools.js +213 -58
- package/dist/heart/daemon/staged-restart.js +114 -0
- package/dist/heart/daemon/subagent-installer.js +48 -7
- package/dist/heart/daemon/thoughts.js +379 -0
- package/dist/heart/daemon/update-checker.js +111 -0
- package/dist/heart/daemon/update-hooks.js +138 -0
- package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
- package/dist/heart/delegation.js +62 -0
- package/dist/heart/identity.js +122 -19
- package/dist/heart/kicks.js +1 -19
- package/dist/heart/model-capabilities.js +40 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/providers/anthropic.js +74 -9
- package/dist/heart/providers/azure.js +86 -7
- package/dist/heart/providers/minimax.js +4 -0
- package/dist/heart/providers/openai-codex.js +12 -3
- package/dist/heart/safe-workspace.js +228 -0
- package/dist/heart/sense-truth.js +61 -0
- package/dist/heart/session-activity.js +169 -0
- package/dist/heart/session-recall.js +116 -0
- package/dist/heart/streaming.js +100 -22
- package/dist/heart/target-resolution.js +123 -0
- package/dist/heart/turn-coordinator.js +28 -0
- package/dist/mind/associative-recall.js +14 -2
- package/dist/mind/bundle-manifest.js +70 -0
- package/dist/mind/context.js +27 -11
- package/dist/mind/first-impressions.js +16 -2
- package/dist/mind/friends/channel.js +35 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/store-file.js +19 -0
- package/dist/mind/friends/trust-explanation.js +74 -0
- package/dist/mind/friends/types.js +8 -0
- package/dist/mind/memory.js +27 -26
- package/dist/mind/pending.js +72 -9
- package/dist/mind/phrases.js +1 -0
- package/dist/mind/prompt.js +299 -77
- package/dist/mind/token-estimate.js +8 -12
- package/dist/nerves/cli-logging.js +15 -2
- package/dist/nerves/coverage/run-artifacts.js +1 -1
- package/dist/repertoire/ado-client.js +4 -2
- package/dist/repertoire/coding/feedback.js +134 -0
- package/dist/repertoire/coding/index.js +4 -1
- package/dist/repertoire/coding/manager.js +62 -4
- package/dist/repertoire/coding/spawner.js +3 -3
- package/dist/repertoire/coding/tools.js +41 -2
- package/dist/repertoire/data/ado-endpoints.json +188 -0
- package/dist/repertoire/tasks/board.js +12 -0
- package/dist/repertoire/tasks/index.js +23 -9
- package/dist/repertoire/tasks/transitions.js +1 -2
- package/dist/repertoire/tools-base.js +629 -251
- package/dist/repertoire/tools-bluebubbles.js +93 -0
- package/dist/repertoire/tools-teams.js +58 -25
- package/dist/repertoire/tools.js +92 -48
- package/dist/senses/bluebubbles-client.js +210 -5
- package/dist/senses/bluebubbles-entry.js +2 -0
- package/dist/senses/bluebubbles-inbound-log.js +109 -0
- package/dist/senses/bluebubbles-media.js +339 -0
- package/dist/senses/bluebubbles-model.js +12 -4
- package/dist/senses/bluebubbles-mutation-log.js +45 -5
- package/dist/senses/bluebubbles-runtime-state.js +109 -0
- package/dist/senses/bluebubbles-session-cleanup.js +72 -0
- package/dist/senses/bluebubbles.js +890 -45
- package/dist/senses/cli-layout.js +87 -0
- package/dist/senses/cli.js +345 -144
- package/dist/senses/continuity.js +94 -0
- package/dist/senses/debug-activity.js +148 -0
- package/dist/senses/inner-dialog-worker.js +47 -18
- package/dist/senses/inner-dialog.js +330 -84
- package/dist/senses/pipeline.js +278 -0
- package/dist/senses/teams.js +570 -129
- package/dist/senses/trust-gate.js +112 -2
- package/package.json +14 -3
- package/subagents/README.md +46 -33
- package/subagents/work-doer.md +28 -24
- package/subagents/work-merger.md +24 -30
- package/subagents/work-planner.md +44 -27
- package/dist/heart/daemon/specialist-session.js +0 -142
- package/dist/inner-worker-entry.js +0 -4
|
@@ -34,22 +34,38 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.handleBlueBubblesEvent = handleBlueBubblesEvent;
|
|
37
|
+
exports.recoverMissedBlueBubblesMessages = recoverMissedBlueBubblesMessages;
|
|
37
38
|
exports.createBlueBubblesWebhookHandler = createBlueBubblesWebhookHandler;
|
|
39
|
+
exports.sendProactiveBlueBubblesMessageToSession = sendProactiveBlueBubblesMessageToSession;
|
|
40
|
+
exports.drainAndSendPendingBlueBubbles = drainAndSendPendingBlueBubbles;
|
|
38
41
|
exports.startBlueBubblesApp = startBlueBubblesApp;
|
|
42
|
+
const fs = __importStar(require("node:fs"));
|
|
39
43
|
const http = __importStar(require("node:http"));
|
|
40
44
|
const path = __importStar(require("node:path"));
|
|
41
45
|
const core_1 = require("../heart/core");
|
|
42
46
|
const config_1 = require("../heart/config");
|
|
43
47
|
const identity_1 = require("../heart/identity");
|
|
48
|
+
const turn_coordinator_1 = require("../heart/turn-coordinator");
|
|
44
49
|
const context_1 = require("../mind/context");
|
|
45
50
|
const tokens_1 = require("../mind/friends/tokens");
|
|
51
|
+
const group_context_1 = require("../mind/friends/group-context");
|
|
46
52
|
const resolver_1 = require("../mind/friends/resolver");
|
|
47
53
|
const store_file_1 = require("../mind/friends/store-file");
|
|
54
|
+
const types_1 = require("../mind/friends/types");
|
|
55
|
+
const channel_1 = require("../mind/friends/channel");
|
|
56
|
+
const pending_1 = require("../mind/pending");
|
|
48
57
|
const prompt_1 = require("../mind/prompt");
|
|
58
|
+
const phrases_1 = require("../mind/phrases");
|
|
49
59
|
const runtime_1 = require("../nerves/runtime");
|
|
50
60
|
const bluebubbles_model_1 = require("./bluebubbles-model");
|
|
51
61
|
const bluebubbles_client_1 = require("./bluebubbles-client");
|
|
62
|
+
const bluebubbles_inbound_log_1 = require("./bluebubbles-inbound-log");
|
|
52
63
|
const bluebubbles_mutation_log_1 = require("./bluebubbles-mutation-log");
|
|
64
|
+
const bluebubbles_runtime_state_1 = require("./bluebubbles-runtime-state");
|
|
65
|
+
const bluebubbles_session_cleanup_1 = require("./bluebubbles-session-cleanup");
|
|
66
|
+
const debug_activity_1 = require("./debug-activity");
|
|
67
|
+
const trust_gate_1 = require("./trust-gate");
|
|
68
|
+
const pipeline_1 = require("./pipeline");
|
|
53
69
|
const defaultDeps = {
|
|
54
70
|
getAgentName: identity_1.getAgentName,
|
|
55
71
|
buildSystem: prompt_1.buildSystem,
|
|
@@ -64,6 +80,7 @@ const defaultDeps = {
|
|
|
64
80
|
createFriendResolver: (store, params) => new resolver_1.FriendResolver(store, params),
|
|
65
81
|
createServer: http.createServer,
|
|
66
82
|
};
|
|
83
|
+
const BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS = 30_000;
|
|
67
84
|
function resolveFriendParams(event) {
|
|
68
85
|
if (event.chat.isGroup) {
|
|
69
86
|
const groupKey = event.chat.chatGuid ?? event.chat.chatIdentifier ?? event.sender.externalId;
|
|
@@ -81,21 +98,308 @@ function resolveFriendParams(event) {
|
|
|
81
98
|
channel: "bluebubbles",
|
|
82
99
|
};
|
|
83
100
|
}
|
|
84
|
-
function
|
|
101
|
+
function resolveGroupExternalId(event) {
|
|
102
|
+
const groupKey = event.chat.chatGuid ?? event.chat.chatIdentifier ?? event.sender.externalId;
|
|
103
|
+
return `group:${groupKey}`;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Check if any participant in a group chat is a known family member.
|
|
107
|
+
* Looks up each participant handle in the friend store.
|
|
108
|
+
*/
|
|
109
|
+
async function checkGroupHasFamilyMember(store, event) {
|
|
110
|
+
if (!event.chat.isGroup)
|
|
111
|
+
return false;
|
|
112
|
+
for (const handle of event.chat.participantHandles ?? []) {
|
|
113
|
+
const friend = await store.findByExternalId("imessage-handle", handle);
|
|
114
|
+
if (friend?.trustLevel === "family")
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Check if an acquaintance shares any group chat with a family member.
|
|
121
|
+
* Compares group-prefixed externalIds between the acquaintance and all family members.
|
|
122
|
+
*/
|
|
123
|
+
async function checkHasExistingGroupWithFamily(store, senderFriend) {
|
|
124
|
+
const trustLevel = senderFriend.trustLevel ?? "friend";
|
|
125
|
+
if (trustLevel !== "acquaintance")
|
|
126
|
+
return false;
|
|
127
|
+
const acquaintanceGroups = new Set((senderFriend.externalIds ?? [])
|
|
128
|
+
.filter((eid) => eid.externalId.startsWith("group:"))
|
|
129
|
+
.map((eid) => eid.externalId));
|
|
130
|
+
if (acquaintanceGroups.size === 0)
|
|
131
|
+
return false;
|
|
132
|
+
const allFriends = await (store.listAll?.() ?? Promise.resolve([]));
|
|
133
|
+
for (const friend of allFriends) {
|
|
134
|
+
if (friend.trustLevel !== "family")
|
|
135
|
+
continue;
|
|
136
|
+
const friendGroups = (friend.externalIds ?? [])
|
|
137
|
+
.filter((eid) => eid.externalId.startsWith("group:"))
|
|
138
|
+
.map((eid) => eid.externalId);
|
|
139
|
+
for (const group of friendGroups) {
|
|
140
|
+
if (acquaintanceGroups.has(group))
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
function extractMessageText(content) {
|
|
147
|
+
if (typeof content === "string")
|
|
148
|
+
return content;
|
|
149
|
+
if (!Array.isArray(content))
|
|
150
|
+
return "";
|
|
151
|
+
return content
|
|
152
|
+
.map((part) => {
|
|
153
|
+
if (part && typeof part === "object" && "type" in part && part.type === "text" && typeof part.text === "string") {
|
|
154
|
+
return part.text;
|
|
155
|
+
}
|
|
156
|
+
return "";
|
|
157
|
+
})
|
|
158
|
+
.filter(Boolean)
|
|
159
|
+
.join("\n");
|
|
160
|
+
}
|
|
161
|
+
function isHistoricalLaneMetadataLine(line) {
|
|
162
|
+
return /^\[(conversation scope|recent active lanes|routing control):?/i.test(line)
|
|
163
|
+
|| /^- (top_level|thread:[^:]+):/i.test(line);
|
|
164
|
+
}
|
|
165
|
+
function extractHistoricalLaneSummary(messages) {
|
|
166
|
+
const seen = new Set();
|
|
167
|
+
const summaries = [];
|
|
168
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
169
|
+
const message = messages[index];
|
|
170
|
+
if (message.role !== "user")
|
|
171
|
+
continue;
|
|
172
|
+
const text = extractMessageText(message.content);
|
|
173
|
+
if (!text)
|
|
174
|
+
continue;
|
|
175
|
+
const firstLine = text.split("\n")[0].trim();
|
|
176
|
+
const threadMatch = firstLine.match(/thread id: ([^\]|]+)/i);
|
|
177
|
+
const laneKey = threadMatch
|
|
178
|
+
? `thread:${threadMatch[1].trim()}`
|
|
179
|
+
: /top[-_]level/i.test(firstLine)
|
|
180
|
+
? "top_level"
|
|
181
|
+
: null;
|
|
182
|
+
if (!laneKey || seen.has(laneKey))
|
|
183
|
+
continue;
|
|
184
|
+
seen.add(laneKey);
|
|
185
|
+
const snippet = text
|
|
186
|
+
.split("\n")
|
|
187
|
+
.slice(1)
|
|
188
|
+
.map((line) => line.trim())
|
|
189
|
+
.find((line) => line.length > 0 && !isHistoricalLaneMetadataLine(line))
|
|
190
|
+
?.slice(0, 80) ?? "(no recent text)";
|
|
191
|
+
summaries.push({
|
|
192
|
+
key: laneKey,
|
|
193
|
+
label: laneKey === "top_level" ? "top_level" : laneKey,
|
|
194
|
+
snippet,
|
|
195
|
+
});
|
|
196
|
+
if (summaries.length >= 5)
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
return summaries;
|
|
200
|
+
}
|
|
201
|
+
function buildConversationScopePrefix(event, existingMessages) {
|
|
202
|
+
if (event.kind !== "message") {
|
|
203
|
+
return "";
|
|
204
|
+
}
|
|
205
|
+
const summaries = extractHistoricalLaneSummary(existingMessages);
|
|
206
|
+
const lines = [];
|
|
207
|
+
if (event.threadOriginatorGuid?.trim()) {
|
|
208
|
+
lines.push(`[conversation scope: existing chat trunk | current inbound lane: thread | current thread id: ${event.threadOriginatorGuid.trim()} | default outbound target for this turn: current_lane]`);
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
lines.push("[conversation scope: existing chat trunk | current inbound lane: top_level | default outbound target for this turn: top_level]");
|
|
212
|
+
}
|
|
213
|
+
if (summaries.length > 0) {
|
|
214
|
+
lines.push("[recent active lanes]");
|
|
215
|
+
for (const summary of summaries) {
|
|
216
|
+
lines.push(`- ${summary.label}: ${summary.snippet}`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (event.threadOriginatorGuid?.trim() || summaries.some((summary) => summary.key.startsWith("thread:"))) {
|
|
220
|
+
lines.push("[routing control: use bluebubbles_set_reply_target with target=top_level to widen back out, or target=thread plus a listed thread id to route into a specific active thread]");
|
|
221
|
+
}
|
|
222
|
+
return lines.join("\n");
|
|
223
|
+
}
|
|
224
|
+
function buildInboundText(event, existingMessages) {
|
|
225
|
+
const metadataPrefix = buildConversationScopePrefix(event, existingMessages);
|
|
85
226
|
const baseText = event.repairNotice?.trim()
|
|
86
227
|
? `${event.textForAgent}\n[${event.repairNotice.trim()}]`
|
|
87
228
|
: event.textForAgent;
|
|
88
|
-
if (!event.chat.isGroup)
|
|
89
|
-
return baseText;
|
|
229
|
+
if (!event.chat.isGroup) {
|
|
230
|
+
return metadataPrefix ? `${metadataPrefix}\n${baseText}` : baseText;
|
|
231
|
+
}
|
|
232
|
+
const scopedText = metadataPrefix ? `${metadataPrefix}\n${baseText}` : baseText;
|
|
90
233
|
if (event.kind === "mutation") {
|
|
91
|
-
return `${event.sender.displayName} ${
|
|
234
|
+
return `${event.sender.displayName} ${scopedText}`;
|
|
235
|
+
}
|
|
236
|
+
return `${event.sender.displayName}: ${scopedText}`;
|
|
237
|
+
}
|
|
238
|
+
function buildInboundContent(event, existingMessages) {
|
|
239
|
+
const text = buildInboundText(event, existingMessages);
|
|
240
|
+
if (event.kind !== "message" || !event.inputPartsForAgent || event.inputPartsForAgent.length === 0) {
|
|
241
|
+
return text;
|
|
92
242
|
}
|
|
93
|
-
return
|
|
243
|
+
return [
|
|
244
|
+
{ type: "text", text },
|
|
245
|
+
...event.inputPartsForAgent,
|
|
246
|
+
];
|
|
94
247
|
}
|
|
95
|
-
function
|
|
248
|
+
function sessionLikelyContainsMessage(event, existingMessages) {
|
|
249
|
+
const fragment = event.textForAgent.trim();
|
|
250
|
+
if (!fragment)
|
|
251
|
+
return false;
|
|
252
|
+
return existingMessages.some((message) => {
|
|
253
|
+
if (message.role !== "user")
|
|
254
|
+
return false;
|
|
255
|
+
return extractMessageText(message.content).includes(fragment);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
function mutationEntryToEvent(entry) {
|
|
259
|
+
return {
|
|
260
|
+
kind: "mutation",
|
|
261
|
+
eventType: entry.eventType,
|
|
262
|
+
mutationType: entry.mutationType,
|
|
263
|
+
messageGuid: entry.messageGuid,
|
|
264
|
+
targetMessageGuid: entry.targetMessageGuid ?? undefined,
|
|
265
|
+
timestamp: Date.parse(entry.recordedAt) || Date.now(),
|
|
266
|
+
fromMe: entry.fromMe,
|
|
267
|
+
sender: {
|
|
268
|
+
provider: "imessage-handle",
|
|
269
|
+
externalId: entry.chatIdentifier ?? entry.chatGuid ?? "unknown",
|
|
270
|
+
rawId: entry.chatIdentifier ?? entry.chatGuid ?? "unknown",
|
|
271
|
+
displayName: entry.chatIdentifier ?? entry.chatGuid ?? "Unknown",
|
|
272
|
+
},
|
|
273
|
+
chat: {
|
|
274
|
+
chatGuid: entry.chatGuid ?? undefined,
|
|
275
|
+
chatIdentifier: entry.chatIdentifier ?? undefined,
|
|
276
|
+
displayName: undefined,
|
|
277
|
+
isGroup: Boolean(entry.chatGuid?.includes(";+;")),
|
|
278
|
+
sessionKey: entry.sessionKey,
|
|
279
|
+
sendTarget: entry.chatGuid
|
|
280
|
+
? { kind: "chat_guid", value: entry.chatGuid }
|
|
281
|
+
: { kind: "chat_identifier", value: entry.chatIdentifier ?? "unknown" },
|
|
282
|
+
participantHandles: [],
|
|
283
|
+
},
|
|
284
|
+
shouldNotifyAgent: entry.shouldNotifyAgent,
|
|
285
|
+
textForAgent: entry.textForAgent,
|
|
286
|
+
requiresRepair: true,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function getBlueBubblesContinuityIngressTexts(event) {
|
|
290
|
+
if (event.kind !== "message")
|
|
291
|
+
return [];
|
|
292
|
+
const text = event.textForAgent.trim();
|
|
293
|
+
if (text.length > 0)
|
|
294
|
+
return [text];
|
|
295
|
+
const fallbackText = (event.inputPartsForAgent ?? [])
|
|
296
|
+
.map((part) => {
|
|
297
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
298
|
+
return part.text.trim();
|
|
299
|
+
}
|
|
300
|
+
return "";
|
|
301
|
+
})
|
|
302
|
+
.filter(Boolean)
|
|
303
|
+
.join("\n");
|
|
304
|
+
return fallbackText ? [fallbackText] : [];
|
|
305
|
+
}
|
|
306
|
+
function createReplyTargetController(event) {
|
|
307
|
+
const defaultTargetLabel = event.kind === "message" && event.threadOriginatorGuid?.trim() ? "current_lane" : "top_level";
|
|
308
|
+
let selection = event.kind === "message" && event.threadOriginatorGuid?.trim()
|
|
309
|
+
? { target: "current_lane" }
|
|
310
|
+
: { target: "top_level" };
|
|
311
|
+
return {
|
|
312
|
+
getReplyToMessageGuid() {
|
|
313
|
+
if (event.kind !== "message")
|
|
314
|
+
return undefined;
|
|
315
|
+
if (selection.target === "top_level")
|
|
316
|
+
return undefined;
|
|
317
|
+
if (selection.target === "thread")
|
|
318
|
+
return selection.threadOriginatorGuid.trim();
|
|
319
|
+
return event.threadOriginatorGuid?.trim() ? event.messageGuid : undefined;
|
|
320
|
+
},
|
|
321
|
+
setSelection(next) {
|
|
322
|
+
selection = next;
|
|
323
|
+
if (next.target === "top_level") {
|
|
324
|
+
return "bluebubbles reply target override: top_level";
|
|
325
|
+
}
|
|
326
|
+
if (next.target === "thread") {
|
|
327
|
+
return `bluebubbles reply target override: thread:${next.threadOriginatorGuid}`;
|
|
328
|
+
}
|
|
329
|
+
return `bluebubbles reply target: using default for this turn (${defaultTargetLabel})`;
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function emitBlueBubblesMarkReadWarning(chat, error) {
|
|
334
|
+
(0, runtime_1.emitNervesEvent)({
|
|
335
|
+
level: "warn",
|
|
336
|
+
component: "senses",
|
|
337
|
+
event: "senses.bluebubbles_mark_read_error",
|
|
338
|
+
message: "failed to mark bluebubbles chat as read",
|
|
339
|
+
meta: {
|
|
340
|
+
chatGuid: chat.chatGuid ?? null,
|
|
341
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function createBlueBubblesCallbacks(client, chat, replyTarget) {
|
|
96
346
|
let textBuffer = "";
|
|
347
|
+
const phrases = (0, phrases_1.getPhrases)();
|
|
348
|
+
const activity = (0, debug_activity_1.createDebugActivityController)({
|
|
349
|
+
thinkingPhrases: phrases.thinking,
|
|
350
|
+
followupPhrases: phrases.followup,
|
|
351
|
+
startTypingOnModelStart: true,
|
|
352
|
+
suppressInitialModelStatus: true,
|
|
353
|
+
suppressFollowupPhraseStatus: true,
|
|
354
|
+
transport: {
|
|
355
|
+
sendStatus: async (text) => {
|
|
356
|
+
const sent = await client.sendText({
|
|
357
|
+
chat,
|
|
358
|
+
text,
|
|
359
|
+
replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
|
|
360
|
+
});
|
|
361
|
+
return sent.messageGuid;
|
|
362
|
+
},
|
|
363
|
+
editStatus: async (_messageGuid, text) => {
|
|
364
|
+
await client.sendText({
|
|
365
|
+
chat,
|
|
366
|
+
text,
|
|
367
|
+
replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
|
|
368
|
+
});
|
|
369
|
+
},
|
|
370
|
+
setTyping: async (active) => {
|
|
371
|
+
if (!active) {
|
|
372
|
+
await client.setTyping(chat, false);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const [markReadResult, typingResult] = await Promise.allSettled([
|
|
376
|
+
client.markChatRead(chat),
|
|
377
|
+
client.setTyping(chat, true),
|
|
378
|
+
]);
|
|
379
|
+
if (markReadResult.status === "rejected") {
|
|
380
|
+
emitBlueBubblesMarkReadWarning(chat, markReadResult.reason);
|
|
381
|
+
}
|
|
382
|
+
if (typingResult.status === "rejected") {
|
|
383
|
+
throw typingResult.reason;
|
|
384
|
+
}
|
|
385
|
+
},
|
|
386
|
+
},
|
|
387
|
+
onTransportError: (operation, error) => {
|
|
388
|
+
(0, runtime_1.emitNervesEvent)({
|
|
389
|
+
level: "warn",
|
|
390
|
+
component: "senses",
|
|
391
|
+
event: "senses.bluebubbles_activity_error",
|
|
392
|
+
message: "bluebubbles activity transport failed",
|
|
393
|
+
meta: {
|
|
394
|
+
operation,
|
|
395
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
},
|
|
399
|
+
});
|
|
97
400
|
return {
|
|
98
401
|
onModelStart() {
|
|
402
|
+
activity.onModelStart();
|
|
99
403
|
(0, runtime_1.emitNervesEvent)({
|
|
100
404
|
component: "senses",
|
|
101
405
|
event: "senses.bluebubbles_turn_start",
|
|
@@ -112,10 +416,12 @@ function createBlueBubblesCallbacks(client, chat, replyToMessageGuid) {
|
|
|
112
416
|
});
|
|
113
417
|
},
|
|
114
418
|
onTextChunk(text) {
|
|
419
|
+
activity.onTextChunk(text);
|
|
115
420
|
textBuffer += text;
|
|
116
421
|
},
|
|
117
422
|
onReasoningChunk(_text) { },
|
|
118
423
|
onToolStart(name, _args) {
|
|
424
|
+
activity.onToolStart(name, _args);
|
|
119
425
|
(0, runtime_1.emitNervesEvent)({
|
|
120
426
|
component: "senses",
|
|
121
427
|
event: "senses.bluebubbles_tool_start",
|
|
@@ -124,6 +430,7 @@ function createBlueBubblesCallbacks(client, chat, replyToMessageGuid) {
|
|
|
124
430
|
});
|
|
125
431
|
},
|
|
126
432
|
onToolEnd(name, summary, success) {
|
|
433
|
+
activity.onToolEnd(name, summary, success);
|
|
127
434
|
(0, runtime_1.emitNervesEvent)({
|
|
128
435
|
component: "senses",
|
|
129
436
|
event: "senses.bluebubbles_tool_end",
|
|
@@ -132,6 +439,7 @@ function createBlueBubblesCallbacks(client, chat, replyToMessageGuid) {
|
|
|
132
439
|
});
|
|
133
440
|
},
|
|
134
441
|
onError(error, severity) {
|
|
442
|
+
activity.onError(error);
|
|
135
443
|
(0, runtime_1.emitNervesEvent)({
|
|
136
444
|
level: severity === "terminal" ? "error" : "warn",
|
|
137
445
|
component: "senses",
|
|
@@ -144,17 +452,23 @@ function createBlueBubblesCallbacks(client, chat, replyToMessageGuid) {
|
|
|
144
452
|
textBuffer = "";
|
|
145
453
|
},
|
|
146
454
|
async flush() {
|
|
455
|
+
await activity.drain();
|
|
147
456
|
const trimmed = textBuffer.trim();
|
|
148
457
|
if (!trimmed) {
|
|
458
|
+
await activity.finish();
|
|
149
459
|
return;
|
|
150
460
|
}
|
|
151
461
|
textBuffer = "";
|
|
462
|
+
await activity.finish();
|
|
152
463
|
await client.sendText({
|
|
153
464
|
chat,
|
|
154
465
|
text: trimmed,
|
|
155
|
-
replyToMessageGuid,
|
|
466
|
+
replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
|
|
156
467
|
});
|
|
157
468
|
},
|
|
469
|
+
async finish() {
|
|
470
|
+
await activity.finish();
|
|
471
|
+
},
|
|
158
472
|
};
|
|
159
473
|
}
|
|
160
474
|
async function readRequestBody(req) {
|
|
@@ -173,10 +487,8 @@ function isWebhookPasswordValid(url, expectedPassword) {
|
|
|
173
487
|
const provided = url.searchParams.get("password");
|
|
174
488
|
return !provided || provided === expectedPassword;
|
|
175
489
|
}
|
|
176
|
-
async function
|
|
177
|
-
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
490
|
+
async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source) {
|
|
178
491
|
const client = resolvedDeps.createClient();
|
|
179
|
-
const event = await client.repairEvent((0, bluebubbles_model_1.normalizeBlueBubblesEvent)(payload));
|
|
180
492
|
if (event.fromMe) {
|
|
181
493
|
(0, runtime_1.emitNervesEvent)({
|
|
182
494
|
component: "senses",
|
|
@@ -219,46 +531,268 @@ async function handleBlueBubblesEvent(payload, deps = {}) {
|
|
|
219
531
|
});
|
|
220
532
|
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "mutation_state_only" };
|
|
221
533
|
}
|
|
534
|
+
// ── Adapter setup: friend, session, content, callbacks ──────────
|
|
222
535
|
const store = resolvedDeps.createFriendStore();
|
|
223
536
|
const resolver = resolvedDeps.createFriendResolver(store, resolveFriendParams(event));
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
friendStore: store,
|
|
228
|
-
summarize: (0, core_1.createSummarize)(),
|
|
229
|
-
context,
|
|
230
|
-
};
|
|
537
|
+
const baseContext = await resolver.resolve();
|
|
538
|
+
const context = { ...baseContext, isGroupChat: event.chat.isGroup };
|
|
539
|
+
const replyTarget = createReplyTargetController(event);
|
|
231
540
|
const friendId = context.friend.id;
|
|
232
541
|
const sessPath = resolvedDeps.sessionPath(friendId, "bluebubbles", event.chat.sessionKey);
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
542
|
+
try {
|
|
543
|
+
(0, bluebubbles_session_cleanup_1.findObsoleteBlueBubblesThreadSessions)(sessPath);
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
(0, runtime_1.emitNervesEvent)({
|
|
547
|
+
level: "warn",
|
|
548
|
+
component: "senses",
|
|
549
|
+
event: "senses.bluebubbles_thread_lane_cleanup_error",
|
|
550
|
+
message: "failed to inspect obsolete bluebubbles thread-lane sessions",
|
|
551
|
+
meta: {
|
|
552
|
+
sessionPath: sessPath,
|
|
553
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
554
|
+
},
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
return (0, turn_coordinator_1.withSharedTurnLock)("bluebubbles", sessPath, async () => {
|
|
558
|
+
// Pre-load session inside the turn lock so same-chat deliveries cannot race on stale trunk state.
|
|
559
|
+
const existing = resolvedDeps.loadSession(sessPath);
|
|
560
|
+
const sessionMessages = existing?.messages && existing.messages.length > 0
|
|
561
|
+
? existing.messages
|
|
562
|
+
: [{ role: "system", content: await resolvedDeps.buildSystem("bluebubbles", undefined, context) }];
|
|
563
|
+
if (event.kind === "message") {
|
|
564
|
+
const agentName = resolvedDeps.getAgentName();
|
|
565
|
+
if ((0, bluebubbles_inbound_log_1.hasRecordedBlueBubblesInbound)(agentName, event.chat.sessionKey, event.messageGuid)) {
|
|
566
|
+
(0, runtime_1.emitNervesEvent)({
|
|
567
|
+
component: "senses",
|
|
568
|
+
event: "senses.bluebubbles_recovery_skip",
|
|
569
|
+
message: "skipped bluebubbles message already recorded as handled",
|
|
570
|
+
meta: {
|
|
571
|
+
messageGuid: event.messageGuid,
|
|
572
|
+
sessionKey: event.chat.sessionKey,
|
|
573
|
+
source,
|
|
574
|
+
},
|
|
575
|
+
});
|
|
576
|
+
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "already_processed" };
|
|
577
|
+
}
|
|
578
|
+
if (source !== "webhook" && sessionLikelyContainsMessage(event, existing?.messages ?? sessionMessages)) {
|
|
579
|
+
(0, bluebubbles_inbound_log_1.recordBlueBubblesInbound)(agentName, event, "recovery-bootstrap");
|
|
580
|
+
(0, runtime_1.emitNervesEvent)({
|
|
581
|
+
component: "senses",
|
|
582
|
+
event: "senses.bluebubbles_recovery_skip",
|
|
583
|
+
message: "skipped bluebubbles recovery because the session already contains the message text",
|
|
584
|
+
meta: {
|
|
585
|
+
messageGuid: event.messageGuid,
|
|
586
|
+
sessionKey: event.chat.sessionKey,
|
|
587
|
+
source,
|
|
588
|
+
},
|
|
589
|
+
});
|
|
590
|
+
return { handled: true, notifiedAgent: false, kind: event.kind, reason: "already_processed" };
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (event.kind === "message" && event.chat.isGroup) {
|
|
594
|
+
await (0, group_context_1.upsertGroupContextParticipants)({
|
|
595
|
+
store,
|
|
596
|
+
participants: (event.chat.participantHandles ?? []).map((externalId) => ({
|
|
597
|
+
provider: "imessage-handle",
|
|
598
|
+
externalId,
|
|
599
|
+
})),
|
|
600
|
+
groupExternalId: resolveGroupExternalId(event),
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
// Build inbound user message (adapter concern: BB-specific content formatting)
|
|
604
|
+
const userMessage = {
|
|
605
|
+
role: "user",
|
|
606
|
+
content: buildInboundContent(event, existing?.messages ?? sessionMessages),
|
|
607
|
+
};
|
|
608
|
+
const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget);
|
|
609
|
+
const controller = new AbortController();
|
|
610
|
+
// BB-specific tool context wrappers
|
|
611
|
+
const summarize = (0, core_1.createSummarize)();
|
|
612
|
+
const bbCapabilities = (0, channel_1.getChannelCapabilities)("bluebubbles");
|
|
613
|
+
const pendingDir = (0, pending_1.getPendingDir)(resolvedDeps.getAgentName(), friendId, "bluebubbles", event.chat.sessionKey);
|
|
614
|
+
// ── Compute trust gate context for group/acquaintance rules ─────
|
|
615
|
+
const groupHasFamilyMember = await checkGroupHasFamilyMember(store, event);
|
|
616
|
+
const hasExistingGroupWithFamily = event.chat.isGroup
|
|
617
|
+
? false
|
|
618
|
+
: await checkHasExistingGroupWithFamily(store, context.friend);
|
|
619
|
+
// ── Call shared pipeline ──────────────────────────────────────────
|
|
620
|
+
try {
|
|
621
|
+
const result = await (0, pipeline_1.handleInboundTurn)({
|
|
622
|
+
channel: "bluebubbles",
|
|
623
|
+
sessionKey: event.chat.sessionKey,
|
|
624
|
+
capabilities: bbCapabilities,
|
|
625
|
+
messages: [userMessage],
|
|
626
|
+
continuityIngressTexts: getBlueBubblesContinuityIngressTexts(event),
|
|
627
|
+
callbacks,
|
|
628
|
+
friendResolver: { resolve: () => Promise.resolve(context) },
|
|
629
|
+
sessionLoader: { loadOrCreate: () => Promise.resolve({ messages: sessionMessages, sessionPath: sessPath, state: existing?.state }) },
|
|
630
|
+
pendingDir,
|
|
631
|
+
friendStore: store,
|
|
632
|
+
provider: "imessage-handle",
|
|
633
|
+
externalId: event.sender.externalId || event.sender.rawId,
|
|
634
|
+
isGroupChat: event.chat.isGroup,
|
|
635
|
+
groupHasFamilyMember,
|
|
636
|
+
hasExistingGroupWithFamily,
|
|
637
|
+
enforceTrustGate: trust_gate_1.enforceTrustGate,
|
|
638
|
+
drainPending: pending_1.drainPending,
|
|
639
|
+
drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(resolvedDeps.getAgentName(), deferredFriendId),
|
|
640
|
+
runAgent: (msgs, cb, channel, sig, opts) => resolvedDeps.runAgent(msgs, cb, channel, sig, {
|
|
641
|
+
...opts,
|
|
642
|
+
toolContext: {
|
|
643
|
+
/* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
|
|
644
|
+
signin: async () => undefined,
|
|
645
|
+
...opts?.toolContext,
|
|
646
|
+
summarize,
|
|
647
|
+
bluebubblesReplyTarget: {
|
|
648
|
+
setSelection: (selection) => replyTarget.setSelection(selection),
|
|
649
|
+
},
|
|
650
|
+
codingFeedback: {
|
|
651
|
+
send: async (message) => {
|
|
652
|
+
await client.sendText({
|
|
653
|
+
chat: event.chat,
|
|
654
|
+
text: message,
|
|
655
|
+
replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
|
|
656
|
+
});
|
|
657
|
+
},
|
|
658
|
+
},
|
|
659
|
+
},
|
|
660
|
+
}),
|
|
661
|
+
postTurn: resolvedDeps.postTurn,
|
|
662
|
+
accumulateFriendTokens: resolvedDeps.accumulateFriendTokens,
|
|
663
|
+
signal: controller.signal,
|
|
664
|
+
});
|
|
665
|
+
// ── Handle gate result ────────────────────────────────────────
|
|
666
|
+
if (!result.gateResult.allowed) {
|
|
667
|
+
// Send auto-reply via BB API if the gate provides one
|
|
668
|
+
if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
|
|
669
|
+
await client.sendText({
|
|
670
|
+
chat: event.chat,
|
|
671
|
+
text: result.gateResult.autoReply,
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
if (event.kind === "message") {
|
|
675
|
+
(0, bluebubbles_inbound_log_1.recordBlueBubblesInbound)(resolvedDeps.getAgentName(), event, source);
|
|
676
|
+
}
|
|
677
|
+
return {
|
|
678
|
+
handled: true,
|
|
679
|
+
notifiedAgent: false,
|
|
680
|
+
kind: event.kind,
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
// Gate allowed — flush the agent's reply
|
|
684
|
+
await callbacks.flush();
|
|
685
|
+
if (event.kind === "message") {
|
|
686
|
+
(0, bluebubbles_inbound_log_1.recordBlueBubblesInbound)(resolvedDeps.getAgentName(), event, source);
|
|
687
|
+
}
|
|
688
|
+
(0, runtime_1.emitNervesEvent)({
|
|
689
|
+
component: "senses",
|
|
690
|
+
event: "senses.bluebubbles_turn_end",
|
|
691
|
+
message: "bluebubbles event handled",
|
|
692
|
+
meta: {
|
|
693
|
+
messageGuid: event.messageGuid,
|
|
694
|
+
kind: event.kind,
|
|
695
|
+
sessionKey: event.chat.sessionKey,
|
|
696
|
+
},
|
|
697
|
+
});
|
|
698
|
+
return {
|
|
699
|
+
handled: true,
|
|
700
|
+
notifiedAgent: true,
|
|
701
|
+
kind: event.kind,
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
finally {
|
|
705
|
+
await callbacks.finish();
|
|
706
|
+
}
|
|
256
707
|
});
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
708
|
+
}
|
|
709
|
+
async function handleBlueBubblesEvent(payload, deps = {}) {
|
|
710
|
+
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
711
|
+
const client = resolvedDeps.createClient();
|
|
712
|
+
const event = await client.repairEvent((0, bluebubbles_model_1.normalizeBlueBubblesEvent)(payload));
|
|
713
|
+
return handleBlueBubblesNormalizedEvent(event, resolvedDeps, "webhook");
|
|
714
|
+
}
|
|
715
|
+
function countPendingRecoveryCandidates(agentName) {
|
|
716
|
+
return (0, bluebubbles_mutation_log_1.listBlueBubblesRecoveryCandidates)(agentName)
|
|
717
|
+
.filter((entry) => !(0, bluebubbles_inbound_log_1.hasRecordedBlueBubblesInbound)(agentName, entry.sessionKey, entry.messageGuid))
|
|
718
|
+
.length;
|
|
719
|
+
}
|
|
720
|
+
async function syncBlueBubblesRuntime(deps = {}) {
|
|
721
|
+
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
722
|
+
const agentName = resolvedDeps.getAgentName();
|
|
723
|
+
const client = resolvedDeps.createClient();
|
|
724
|
+
const checkedAt = new Date().toISOString();
|
|
725
|
+
try {
|
|
726
|
+
await client.checkHealth();
|
|
727
|
+
const recovery = await recoverMissedBlueBubblesMessages(resolvedDeps);
|
|
728
|
+
(0, bluebubbles_runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
|
|
729
|
+
upstreamStatus: recovery.pending > 0 || recovery.failed > 0 ? "error" : "ok",
|
|
730
|
+
detail: recovery.failed > 0
|
|
731
|
+
? `recovery failures: ${recovery.failed}`
|
|
732
|
+
: recovery.pending > 0
|
|
733
|
+
? `pending recovery: ${recovery.pending}`
|
|
734
|
+
: "upstream reachable",
|
|
735
|
+
lastCheckedAt: checkedAt,
|
|
736
|
+
pendingRecoveryCount: recovery.pending,
|
|
737
|
+
lastRecoveredAt: recovery.recovered > 0 ? checkedAt : undefined,
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
catch (error) {
|
|
741
|
+
(0, bluebubbles_runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
|
|
742
|
+
upstreamStatus: "error",
|
|
743
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
744
|
+
lastCheckedAt: checkedAt,
|
|
745
|
+
pendingRecoveryCount: countPendingRecoveryCandidates(agentName),
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
async function recoverMissedBlueBubblesMessages(deps = {}) {
|
|
750
|
+
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
751
|
+
const agentName = resolvedDeps.getAgentName();
|
|
752
|
+
const client = resolvedDeps.createClient();
|
|
753
|
+
const result = { recovered: 0, skipped: 0, pending: 0, failed: 0 };
|
|
754
|
+
for (const candidate of (0, bluebubbles_mutation_log_1.listBlueBubblesRecoveryCandidates)(agentName)) {
|
|
755
|
+
if ((0, bluebubbles_inbound_log_1.hasRecordedBlueBubblesInbound)(agentName, candidate.sessionKey, candidate.messageGuid)) {
|
|
756
|
+
result.skipped++;
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
try {
|
|
760
|
+
const repaired = await client.repairEvent(mutationEntryToEvent(candidate));
|
|
761
|
+
if (repaired.kind !== "message") {
|
|
762
|
+
result.pending++;
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
const handled = await handleBlueBubblesNormalizedEvent(repaired, resolvedDeps, "mutation-recovery");
|
|
766
|
+
if (handled.reason === "already_processed") {
|
|
767
|
+
result.skipped++;
|
|
768
|
+
}
|
|
769
|
+
else {
|
|
770
|
+
result.recovered++;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
catch (error) {
|
|
774
|
+
result.failed++;
|
|
775
|
+
(0, runtime_1.emitNervesEvent)({
|
|
776
|
+
level: "warn",
|
|
777
|
+
component: "senses",
|
|
778
|
+
event: "senses.bluebubbles_recovery_error",
|
|
779
|
+
message: "bluebubbles backlog recovery failed",
|
|
780
|
+
meta: {
|
|
781
|
+
messageGuid: candidate.messageGuid,
|
|
782
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
783
|
+
},
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
if (result.recovered > 0 || result.skipped > 0 || result.pending > 0 || result.failed > 0) {
|
|
788
|
+
(0, runtime_1.emitNervesEvent)({
|
|
789
|
+
component: "senses",
|
|
790
|
+
event: "senses.bluebubbles_recovery_complete",
|
|
791
|
+
message: "bluebubbles backlog recovery pass completed",
|
|
792
|
+
meta: { ...result },
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
return result;
|
|
262
796
|
}
|
|
263
797
|
function createBlueBubblesWebhookHandler(deps = {}) {
|
|
264
798
|
return async (req, res) => {
|
|
@@ -315,11 +849,321 @@ function createBlueBubblesWebhookHandler(deps = {}) {
|
|
|
315
849
|
}
|
|
316
850
|
};
|
|
317
851
|
}
|
|
852
|
+
function findImessageHandle(friend) {
|
|
853
|
+
for (const ext of friend.externalIds) {
|
|
854
|
+
if (ext.provider === "imessage-handle" && !ext.externalId.startsWith("group:")) {
|
|
855
|
+
return ext.externalId;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return undefined;
|
|
859
|
+
}
|
|
860
|
+
function normalizeBlueBubblesSessionKey(sessionKey) {
|
|
861
|
+
const trimmed = sessionKey.trim();
|
|
862
|
+
if (trimmed.startsWith("chat_identifier_")) {
|
|
863
|
+
return `chat_identifier:${trimmed.slice("chat_identifier_".length)}`;
|
|
864
|
+
}
|
|
865
|
+
if (trimmed.startsWith("chat_")) {
|
|
866
|
+
return `chat:${trimmed.slice("chat_".length)}`;
|
|
867
|
+
}
|
|
868
|
+
return trimmed;
|
|
869
|
+
}
|
|
870
|
+
function extractChatIdentifierFromSessionKey(sessionKey) {
|
|
871
|
+
const normalizedKey = normalizeBlueBubblesSessionKey(sessionKey);
|
|
872
|
+
if (normalizedKey.startsWith("chat:")) {
|
|
873
|
+
const chatGuid = normalizedKey.slice("chat:".length).trim();
|
|
874
|
+
const parts = chatGuid.split(";");
|
|
875
|
+
return parts.length >= 3 ? parts[2]?.trim() || undefined : undefined;
|
|
876
|
+
}
|
|
877
|
+
if (normalizedKey.startsWith("chat_identifier:")) {
|
|
878
|
+
const identifier = normalizedKey.slice("chat_identifier:".length).trim();
|
|
879
|
+
return identifier || undefined;
|
|
880
|
+
}
|
|
881
|
+
return undefined;
|
|
882
|
+
}
|
|
883
|
+
function buildChatRefForSessionKey(friend, sessionKey) {
|
|
884
|
+
const normalizedKey = normalizeBlueBubblesSessionKey(sessionKey);
|
|
885
|
+
if (normalizedKey.startsWith("chat:")) {
|
|
886
|
+
const chatGuid = normalizedKey.slice("chat:".length).trim();
|
|
887
|
+
if (!chatGuid)
|
|
888
|
+
return null;
|
|
889
|
+
return {
|
|
890
|
+
chatGuid,
|
|
891
|
+
chatIdentifier: extractChatIdentifierFromSessionKey(sessionKey) ?? findImessageHandle(friend),
|
|
892
|
+
isGroup: chatGuid.includes(";+;"),
|
|
893
|
+
sessionKey,
|
|
894
|
+
sendTarget: { kind: "chat_guid", value: chatGuid },
|
|
895
|
+
participantHandles: [],
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
const chatIdentifier = extractChatIdentifierFromSessionKey(sessionKey) ?? findImessageHandle(friend);
|
|
899
|
+
if (!chatIdentifier)
|
|
900
|
+
return null;
|
|
901
|
+
return {
|
|
902
|
+
chatIdentifier,
|
|
903
|
+
isGroup: false,
|
|
904
|
+
sessionKey,
|
|
905
|
+
sendTarget: { kind: "chat_identifier", value: chatIdentifier },
|
|
906
|
+
participantHandles: [],
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
async function sendProactiveBlueBubblesMessageToSession(params, deps = {}) {
|
|
910
|
+
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
911
|
+
const client = resolvedDeps.createClient();
|
|
912
|
+
const store = resolvedDeps.createFriendStore();
|
|
913
|
+
let friend;
|
|
914
|
+
try {
|
|
915
|
+
friend = await store.get(params.friendId);
|
|
916
|
+
}
|
|
917
|
+
catch {
|
|
918
|
+
friend = null;
|
|
919
|
+
}
|
|
920
|
+
if (!friend) {
|
|
921
|
+
(0, runtime_1.emitNervesEvent)({
|
|
922
|
+
level: "warn",
|
|
923
|
+
component: "senses",
|
|
924
|
+
event: "senses.bluebubbles_proactive_no_friend",
|
|
925
|
+
message: "proactive send skipped: friend not found",
|
|
926
|
+
meta: { friendId: params.friendId, sessionKey: params.sessionKey },
|
|
927
|
+
});
|
|
928
|
+
return { delivered: false, reason: "friend_not_found" };
|
|
929
|
+
}
|
|
930
|
+
const explicitCrossChatAuthorized = params.intent === "explicit_cross_chat"
|
|
931
|
+
&& types_1.TRUSTED_LEVELS.has(params.authorizingSession?.trustLevel ?? "stranger");
|
|
932
|
+
if (!explicitCrossChatAuthorized && !types_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
|
|
933
|
+
(0, runtime_1.emitNervesEvent)({
|
|
934
|
+
component: "senses",
|
|
935
|
+
event: "senses.bluebubbles_proactive_trust_skip",
|
|
936
|
+
message: "proactive send skipped: trust level not allowed",
|
|
937
|
+
meta: {
|
|
938
|
+
friendId: params.friendId,
|
|
939
|
+
sessionKey: params.sessionKey,
|
|
940
|
+
trustLevel: friend.trustLevel ?? "unknown",
|
|
941
|
+
intent: params.intent ?? "generic_outreach",
|
|
942
|
+
authorizingTrustLevel: params.authorizingSession?.trustLevel ?? null,
|
|
943
|
+
},
|
|
944
|
+
});
|
|
945
|
+
return { delivered: false, reason: "trust_skip" };
|
|
946
|
+
}
|
|
947
|
+
const chat = buildChatRefForSessionKey(friend, params.sessionKey);
|
|
948
|
+
if (!chat) {
|
|
949
|
+
(0, runtime_1.emitNervesEvent)({
|
|
950
|
+
level: "warn",
|
|
951
|
+
component: "senses",
|
|
952
|
+
event: "senses.bluebubbles_proactive_no_handle",
|
|
953
|
+
message: "proactive send skipped: no iMessage handle found",
|
|
954
|
+
meta: { friendId: params.friendId, sessionKey: params.sessionKey },
|
|
955
|
+
});
|
|
956
|
+
return { delivered: false, reason: "missing_target" };
|
|
957
|
+
}
|
|
958
|
+
try {
|
|
959
|
+
await client.sendText({ chat, text: params.text });
|
|
960
|
+
(0, runtime_1.emitNervesEvent)({
|
|
961
|
+
component: "senses",
|
|
962
|
+
event: "senses.bluebubbles_proactive_sent",
|
|
963
|
+
message: "proactive bluebubbles message sent",
|
|
964
|
+
meta: {
|
|
965
|
+
friendId: params.friendId,
|
|
966
|
+
sessionKey: params.sessionKey,
|
|
967
|
+
chatGuid: chat.chatGuid ?? null,
|
|
968
|
+
chatIdentifier: chat.chatIdentifier ?? null,
|
|
969
|
+
},
|
|
970
|
+
});
|
|
971
|
+
return { delivered: true };
|
|
972
|
+
}
|
|
973
|
+
catch (error) {
|
|
974
|
+
(0, runtime_1.emitNervesEvent)({
|
|
975
|
+
level: "error",
|
|
976
|
+
component: "senses",
|
|
977
|
+
event: "senses.bluebubbles_proactive_send_error",
|
|
978
|
+
message: "proactive bluebubbles send failed",
|
|
979
|
+
meta: {
|
|
980
|
+
friendId: params.friendId,
|
|
981
|
+
sessionKey: params.sessionKey,
|
|
982
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
983
|
+
},
|
|
984
|
+
});
|
|
985
|
+
return { delivered: false, reason: "send_error" };
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
function scanPendingBlueBubblesFiles(pendingRoot) {
|
|
989
|
+
const results = [];
|
|
990
|
+
let friendIds;
|
|
991
|
+
try {
|
|
992
|
+
friendIds = fs.readdirSync(pendingRoot);
|
|
993
|
+
}
|
|
994
|
+
catch {
|
|
995
|
+
return results;
|
|
996
|
+
}
|
|
997
|
+
for (const friendId of friendIds) {
|
|
998
|
+
const bbDir = path.join(pendingRoot, friendId, "bluebubbles");
|
|
999
|
+
let keys;
|
|
1000
|
+
try {
|
|
1001
|
+
keys = fs.readdirSync(bbDir);
|
|
1002
|
+
}
|
|
1003
|
+
catch {
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
for (const key of keys) {
|
|
1007
|
+
const keyDir = path.join(bbDir, key);
|
|
1008
|
+
let files;
|
|
1009
|
+
try {
|
|
1010
|
+
files = fs.readdirSync(keyDir);
|
|
1011
|
+
}
|
|
1012
|
+
catch {
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
|
|
1016
|
+
const filePath = path.join(keyDir, file);
|
|
1017
|
+
try {
|
|
1018
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
1019
|
+
results.push({ friendId, key, filePath, content });
|
|
1020
|
+
}
|
|
1021
|
+
catch {
|
|
1022
|
+
// skip unreadable files
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return results;
|
|
1028
|
+
}
|
|
1029
|
+
async function drainAndSendPendingBlueBubbles(deps = {}, pendingRoot) {
|
|
1030
|
+
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
1031
|
+
const root = pendingRoot ?? path.join((0, identity_1.getAgentRoot)(), "state", "pending");
|
|
1032
|
+
const client = resolvedDeps.createClient();
|
|
1033
|
+
const store = resolvedDeps.createFriendStore();
|
|
1034
|
+
const pendingFiles = scanPendingBlueBubblesFiles(root);
|
|
1035
|
+
const result = { sent: 0, skipped: 0, failed: 0 };
|
|
1036
|
+
for (const { friendId, filePath, content } of pendingFiles) {
|
|
1037
|
+
let parsed;
|
|
1038
|
+
try {
|
|
1039
|
+
parsed = JSON.parse(content);
|
|
1040
|
+
}
|
|
1041
|
+
catch {
|
|
1042
|
+
result.failed++;
|
|
1043
|
+
try {
|
|
1044
|
+
fs.unlinkSync(filePath);
|
|
1045
|
+
}
|
|
1046
|
+
catch { /* ignore */ }
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
const messageText = typeof parsed.content === "string" ? parsed.content : "";
|
|
1050
|
+
if (!messageText.trim()) {
|
|
1051
|
+
result.skipped++;
|
|
1052
|
+
try {
|
|
1053
|
+
fs.unlinkSync(filePath);
|
|
1054
|
+
}
|
|
1055
|
+
catch { /* ignore */ }
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
let friend;
|
|
1059
|
+
try {
|
|
1060
|
+
friend = await store.get(friendId);
|
|
1061
|
+
}
|
|
1062
|
+
catch {
|
|
1063
|
+
friend = null;
|
|
1064
|
+
}
|
|
1065
|
+
if (!friend) {
|
|
1066
|
+
result.skipped++;
|
|
1067
|
+
try {
|
|
1068
|
+
fs.unlinkSync(filePath);
|
|
1069
|
+
}
|
|
1070
|
+
catch { /* ignore */ }
|
|
1071
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1072
|
+
level: "warn",
|
|
1073
|
+
component: "senses",
|
|
1074
|
+
event: "senses.bluebubbles_proactive_no_friend",
|
|
1075
|
+
message: "proactive send skipped: friend not found",
|
|
1076
|
+
meta: { friendId },
|
|
1077
|
+
});
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (!types_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
|
|
1081
|
+
result.skipped++;
|
|
1082
|
+
try {
|
|
1083
|
+
fs.unlinkSync(filePath);
|
|
1084
|
+
}
|
|
1085
|
+
catch { /* ignore */ }
|
|
1086
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1087
|
+
component: "senses",
|
|
1088
|
+
event: "senses.bluebubbles_proactive_trust_skip",
|
|
1089
|
+
message: "proactive send skipped: trust level not allowed",
|
|
1090
|
+
meta: { friendId, trustLevel: friend.trustLevel ?? "unknown" },
|
|
1091
|
+
});
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
1094
|
+
const handle = findImessageHandle(friend);
|
|
1095
|
+
if (!handle) {
|
|
1096
|
+
result.skipped++;
|
|
1097
|
+
try {
|
|
1098
|
+
fs.unlinkSync(filePath);
|
|
1099
|
+
}
|
|
1100
|
+
catch { /* ignore */ }
|
|
1101
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1102
|
+
level: "warn",
|
|
1103
|
+
component: "senses",
|
|
1104
|
+
event: "senses.bluebubbles_proactive_no_handle",
|
|
1105
|
+
message: "proactive send skipped: no iMessage handle found",
|
|
1106
|
+
meta: { friendId },
|
|
1107
|
+
});
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
const chat = {
|
|
1111
|
+
chatIdentifier: handle,
|
|
1112
|
+
isGroup: false,
|
|
1113
|
+
sessionKey: friendId,
|
|
1114
|
+
sendTarget: { kind: "chat_identifier", value: handle },
|
|
1115
|
+
participantHandles: [],
|
|
1116
|
+
};
|
|
1117
|
+
try {
|
|
1118
|
+
await client.sendText({ chat, text: messageText });
|
|
1119
|
+
result.sent++;
|
|
1120
|
+
try {
|
|
1121
|
+
fs.unlinkSync(filePath);
|
|
1122
|
+
}
|
|
1123
|
+
catch { /* ignore */ }
|
|
1124
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1125
|
+
component: "senses",
|
|
1126
|
+
event: "senses.bluebubbles_proactive_sent",
|
|
1127
|
+
message: "proactive bluebubbles message sent",
|
|
1128
|
+
meta: { friendId, handle },
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
catch (error) {
|
|
1132
|
+
result.failed++;
|
|
1133
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1134
|
+
level: "error",
|
|
1135
|
+
component: "senses",
|
|
1136
|
+
event: "senses.bluebubbles_proactive_send_error",
|
|
1137
|
+
message: "proactive bluebubbles send failed",
|
|
1138
|
+
meta: {
|
|
1139
|
+
friendId,
|
|
1140
|
+
handle,
|
|
1141
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
1142
|
+
},
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (result.sent > 0 || result.skipped > 0 || result.failed > 0) {
|
|
1147
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1148
|
+
component: "senses",
|
|
1149
|
+
event: "senses.bluebubbles_proactive_drain_complete",
|
|
1150
|
+
message: "bluebubbles proactive drain complete",
|
|
1151
|
+
meta: { sent: result.sent, skipped: result.skipped, failed: result.failed },
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
return result;
|
|
1155
|
+
}
|
|
318
1156
|
function startBlueBubblesApp(deps = {}) {
|
|
319
1157
|
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
320
1158
|
resolvedDeps.createClient();
|
|
321
1159
|
const channelConfig = (0, config_1.getBlueBubblesChannelConfig)();
|
|
322
1160
|
const server = resolvedDeps.createServer(createBlueBubblesWebhookHandler(deps));
|
|
1161
|
+
const runtimeTimer = setInterval(() => {
|
|
1162
|
+
void syncBlueBubblesRuntime(resolvedDeps);
|
|
1163
|
+
}, BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS);
|
|
1164
|
+
server.on?.("close", () => {
|
|
1165
|
+
clearInterval(runtimeTimer);
|
|
1166
|
+
});
|
|
323
1167
|
server.listen(channelConfig.port, () => {
|
|
324
1168
|
(0, runtime_1.emitNervesEvent)({
|
|
325
1169
|
component: "channels",
|
|
@@ -328,5 +1172,6 @@ function startBlueBubblesApp(deps = {}) {
|
|
|
328
1172
|
meta: { port: channelConfig.port, webhookPath: channelConfig.webhookPath },
|
|
329
1173
|
});
|
|
330
1174
|
});
|
|
1175
|
+
void syncBlueBubblesRuntime(resolvedDeps);
|
|
331
1176
|
return server;
|
|
332
1177
|
}
|