@ouro.bot/cli 0.1.0-alpha.4 → 0.1.0-alpha.41

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.
Files changed (84) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +70 -9
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +117 -188
  5. package/assets/ouroboros.png +0 -0
  6. package/changelog.json +170 -0
  7. package/dist/heart/config.js +81 -8
  8. package/dist/heart/core.js +78 -45
  9. package/dist/heart/daemon/agent-discovery.js +81 -0
  10. package/dist/heart/daemon/daemon-cli.js +987 -77
  11. package/dist/heart/daemon/daemon-entry.js +14 -5
  12. package/dist/heart/daemon/daemon-runtime-sync.js +90 -0
  13. package/dist/heart/daemon/daemon.js +177 -9
  14. package/dist/heart/daemon/hatch-animation.js +35 -0
  15. package/dist/heart/daemon/hatch-flow.js +4 -20
  16. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  17. package/dist/heart/daemon/launchd.js +134 -0
  18. package/dist/heart/daemon/message-router.js +15 -6
  19. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  20. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  21. package/dist/heart/daemon/ouro-entry.js +0 -0
  22. package/dist/heart/daemon/ouro-path-installer.js +178 -0
  23. package/dist/heart/daemon/ouro-uti.js +11 -2
  24. package/dist/heart/daemon/process-manager.js +1 -1
  25. package/dist/heart/daemon/run-hooks.js +37 -0
  26. package/dist/heart/daemon/runtime-metadata.js +118 -0
  27. package/dist/heart/daemon/sense-manager.js +266 -0
  28. package/dist/heart/daemon/specialist-orchestrator.js +129 -0
  29. package/dist/heart/daemon/specialist-prompt.js +99 -0
  30. package/dist/heart/daemon/specialist-tools.js +283 -0
  31. package/dist/heart/daemon/staged-restart.js +114 -0
  32. package/dist/heart/daemon/subagent-installer.js +10 -1
  33. package/dist/heart/daemon/update-checker.js +111 -0
  34. package/dist/heart/daemon/update-hooks.js +138 -0
  35. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  36. package/dist/heart/identity.js +96 -4
  37. package/dist/heart/kicks.js +1 -19
  38. package/dist/heart/providers/anthropic.js +16 -2
  39. package/dist/heart/sense-truth.js +61 -0
  40. package/dist/heart/streaming.js +96 -21
  41. package/dist/mind/bundle-manifest.js +70 -0
  42. package/dist/mind/context.js +7 -7
  43. package/dist/mind/first-impressions.js +2 -1
  44. package/dist/mind/friends/channel.js +43 -0
  45. package/dist/mind/friends/store-file.js +19 -0
  46. package/dist/mind/friends/types.js +9 -1
  47. package/dist/mind/memory.js +10 -3
  48. package/dist/mind/pending.js +10 -2
  49. package/dist/mind/phrases.js +1 -0
  50. package/dist/mind/prompt.js +222 -7
  51. package/dist/mind/token-estimate.js +8 -12
  52. package/dist/nerves/cli-logging.js +15 -2
  53. package/dist/repertoire/ado-client.js +4 -2
  54. package/dist/repertoire/coding/feedback.js +134 -0
  55. package/dist/repertoire/coding/index.js +4 -1
  56. package/dist/repertoire/coding/manager.js +62 -4
  57. package/dist/repertoire/coding/spawner.js +3 -3
  58. package/dist/repertoire/coding/tools.js +41 -2
  59. package/dist/repertoire/data/ado-endpoints.json +188 -0
  60. package/dist/repertoire/tasks/index.js +2 -9
  61. package/dist/repertoire/tasks/transitions.js +1 -2
  62. package/dist/repertoire/tools-base.js +202 -219
  63. package/dist/repertoire/tools-bluebubbles.js +93 -0
  64. package/dist/repertoire/tools-teams.js +58 -25
  65. package/dist/repertoire/tools.js +55 -35
  66. package/dist/senses/bluebubbles-client.js +434 -0
  67. package/dist/senses/bluebubbles-entry.js +11 -0
  68. package/dist/senses/bluebubbles-media.js +338 -0
  69. package/dist/senses/bluebubbles-model.js +261 -0
  70. package/dist/senses/bluebubbles-mutation-log.js +74 -0
  71. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  72. package/dist/senses/bluebubbles.js +832 -0
  73. package/dist/senses/cli.js +327 -138
  74. package/dist/senses/debug-activity.js +127 -0
  75. package/dist/senses/inner-dialog.js +103 -55
  76. package/dist/senses/pipeline.js +124 -0
  77. package/dist/senses/teams.js +427 -112
  78. package/dist/senses/trust-gate.js +112 -2
  79. package/package.json +14 -3
  80. package/subagents/README.md +40 -53
  81. package/subagents/work-doer.md +26 -24
  82. package/subagents/work-merger.md +24 -30
  83. package/subagents/work-planner.md +34 -25
  84. package/dist/inner-worker-entry.js +0 -4
@@ -0,0 +1,832 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.handleBlueBubblesEvent = handleBlueBubblesEvent;
37
+ exports.createBlueBubblesWebhookHandler = createBlueBubblesWebhookHandler;
38
+ exports.drainAndSendPendingBlueBubbles = drainAndSendPendingBlueBubbles;
39
+ exports.startBlueBubblesApp = startBlueBubblesApp;
40
+ const fs = __importStar(require("node:fs"));
41
+ const http = __importStar(require("node:http"));
42
+ const path = __importStar(require("node:path"));
43
+ const core_1 = require("../heart/core");
44
+ const config_1 = require("../heart/config");
45
+ const identity_1 = require("../heart/identity");
46
+ const context_1 = require("../mind/context");
47
+ const tokens_1 = require("../mind/friends/tokens");
48
+ const resolver_1 = require("../mind/friends/resolver");
49
+ const store_file_1 = require("../mind/friends/store-file");
50
+ const types_1 = require("../mind/friends/types");
51
+ const channel_1 = require("../mind/friends/channel");
52
+ const pending_1 = require("../mind/pending");
53
+ const prompt_1 = require("../mind/prompt");
54
+ const phrases_1 = require("../mind/phrases");
55
+ const runtime_1 = require("../nerves/runtime");
56
+ const bluebubbles_model_1 = require("./bluebubbles-model");
57
+ const bluebubbles_client_1 = require("./bluebubbles-client");
58
+ const bluebubbles_mutation_log_1 = require("./bluebubbles-mutation-log");
59
+ const bluebubbles_session_cleanup_1 = require("./bluebubbles-session-cleanup");
60
+ const debug_activity_1 = require("./debug-activity");
61
+ const trust_gate_1 = require("./trust-gate");
62
+ const pipeline_1 = require("./pipeline");
63
+ const defaultDeps = {
64
+ getAgentName: identity_1.getAgentName,
65
+ buildSystem: prompt_1.buildSystem,
66
+ runAgent: core_1.runAgent,
67
+ loadSession: context_1.loadSession,
68
+ postTurn: context_1.postTurn,
69
+ sessionPath: config_1.sessionPath,
70
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
71
+ createClient: () => (0, bluebubbles_client_1.createBlueBubblesClient)(),
72
+ recordMutation: bluebubbles_mutation_log_1.recordBlueBubblesMutation,
73
+ createFriendStore: () => new store_file_1.FileFriendStore(path.join((0, identity_1.getAgentRoot)(), "friends")),
74
+ createFriendResolver: (store, params) => new resolver_1.FriendResolver(store, params),
75
+ createServer: http.createServer,
76
+ };
77
+ function resolveFriendParams(event) {
78
+ if (event.chat.isGroup) {
79
+ const groupKey = event.chat.chatGuid ?? event.chat.chatIdentifier ?? event.sender.externalId;
80
+ return {
81
+ provider: "imessage-handle",
82
+ externalId: `group:${groupKey}`,
83
+ displayName: event.chat.displayName ?? "Unknown Group",
84
+ channel: "bluebubbles",
85
+ };
86
+ }
87
+ return {
88
+ provider: "imessage-handle",
89
+ externalId: event.sender.externalId || event.sender.rawId,
90
+ displayName: event.sender.displayName || "Unknown",
91
+ channel: "bluebubbles",
92
+ };
93
+ }
94
+ /**
95
+ * Check if any participant in a group chat is a known family member.
96
+ * Looks up each participant handle in the friend store.
97
+ */
98
+ async function checkGroupHasFamilyMember(store, event) {
99
+ if (!event.chat.isGroup)
100
+ return false;
101
+ for (const handle of event.chat.participantHandles ?? []) {
102
+ const friend = await store.findByExternalId("imessage-handle", handle);
103
+ if (friend?.trustLevel === "family")
104
+ return true;
105
+ }
106
+ return false;
107
+ }
108
+ /**
109
+ * Check if an acquaintance shares any group chat with a family member.
110
+ * Compares group-prefixed externalIds between the acquaintance and all family members.
111
+ */
112
+ async function checkHasExistingGroupWithFamily(store, senderFriend) {
113
+ const trustLevel = senderFriend.trustLevel ?? "friend";
114
+ if (trustLevel !== "acquaintance")
115
+ return false;
116
+ const acquaintanceGroups = new Set((senderFriend.externalIds ?? [])
117
+ .filter((eid) => eid.externalId.startsWith("group:"))
118
+ .map((eid) => eid.externalId));
119
+ if (acquaintanceGroups.size === 0)
120
+ return false;
121
+ const allFriends = await (store.listAll?.() ?? Promise.resolve([]));
122
+ for (const friend of allFriends) {
123
+ if (friend.trustLevel !== "family")
124
+ continue;
125
+ const friendGroups = (friend.externalIds ?? [])
126
+ .filter((eid) => eid.externalId.startsWith("group:"))
127
+ .map((eid) => eid.externalId);
128
+ for (const group of friendGroups) {
129
+ if (acquaintanceGroups.has(group))
130
+ return true;
131
+ }
132
+ }
133
+ return false;
134
+ }
135
+ function extractMessageText(content) {
136
+ if (typeof content === "string")
137
+ return content;
138
+ if (!Array.isArray(content))
139
+ return "";
140
+ return content
141
+ .map((part) => {
142
+ if (part && typeof part === "object" && "type" in part && part.type === "text" && typeof part.text === "string") {
143
+ return part.text;
144
+ }
145
+ return "";
146
+ })
147
+ .filter(Boolean)
148
+ .join("\n");
149
+ }
150
+ function extractHistoricalLaneSummary(messages) {
151
+ const seen = new Set();
152
+ const summaries = [];
153
+ for (let index = messages.length - 1; index >= 0; index--) {
154
+ const message = messages[index];
155
+ if (message.role !== "user")
156
+ continue;
157
+ const text = extractMessageText(message.content);
158
+ if (!text)
159
+ continue;
160
+ const firstLine = text.split("\n")[0].trim();
161
+ const threadMatch = firstLine.match(/thread id: ([^\]|]+)/i);
162
+ const laneKey = threadMatch
163
+ ? `thread:${threadMatch[1].trim()}`
164
+ : /top[-_]level/i.test(firstLine)
165
+ ? "top_level"
166
+ : null;
167
+ if (!laneKey || seen.has(laneKey))
168
+ continue;
169
+ seen.add(laneKey);
170
+ const snippet = text
171
+ .split("\n")
172
+ .slice(1)
173
+ .map((line) => line.trim())
174
+ .find(Boolean)
175
+ ?.slice(0, 80) ?? "(no recent text)";
176
+ summaries.push({
177
+ key: laneKey,
178
+ label: laneKey === "top_level" ? "top_level" : laneKey,
179
+ snippet,
180
+ });
181
+ if (summaries.length >= 5)
182
+ break;
183
+ }
184
+ return summaries;
185
+ }
186
+ function buildConversationScopePrefix(event, existingMessages) {
187
+ if (event.kind !== "message") {
188
+ return "";
189
+ }
190
+ const summaries = extractHistoricalLaneSummary(existingMessages);
191
+ const lines = [];
192
+ if (event.threadOriginatorGuid?.trim()) {
193
+ 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]`);
194
+ }
195
+ else {
196
+ lines.push("[conversation scope: existing chat trunk | current inbound lane: top_level | default outbound target for this turn: top_level]");
197
+ }
198
+ if (summaries.length > 0) {
199
+ lines.push("[recent active lanes]");
200
+ for (const summary of summaries) {
201
+ lines.push(`- ${summary.label}: ${summary.snippet}`);
202
+ }
203
+ }
204
+ if (event.threadOriginatorGuid?.trim() || summaries.some((summary) => summary.key.startsWith("thread:"))) {
205
+ 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]");
206
+ }
207
+ return lines.join("\n");
208
+ }
209
+ function buildInboundText(event, existingMessages) {
210
+ const metadataPrefix = buildConversationScopePrefix(event, existingMessages);
211
+ const baseText = event.repairNotice?.trim()
212
+ ? `${event.textForAgent}\n[${event.repairNotice.trim()}]`
213
+ : event.textForAgent;
214
+ if (!event.chat.isGroup) {
215
+ return metadataPrefix ? `${metadataPrefix}\n${baseText}` : baseText;
216
+ }
217
+ const scopedText = metadataPrefix ? `${metadataPrefix}\n${baseText}` : baseText;
218
+ if (event.kind === "mutation") {
219
+ return `${event.sender.displayName} ${scopedText}`;
220
+ }
221
+ return `${event.sender.displayName}: ${scopedText}`;
222
+ }
223
+ function buildInboundContent(event, existingMessages) {
224
+ const text = buildInboundText(event, existingMessages);
225
+ if (event.kind !== "message" || !event.inputPartsForAgent || event.inputPartsForAgent.length === 0) {
226
+ return text;
227
+ }
228
+ return [
229
+ { type: "text", text },
230
+ ...event.inputPartsForAgent,
231
+ ];
232
+ }
233
+ function createReplyTargetController(event) {
234
+ const defaultTargetLabel = event.kind === "message" && event.threadOriginatorGuid?.trim() ? "current_lane" : "top_level";
235
+ let selection = event.kind === "message" && event.threadOriginatorGuid?.trim()
236
+ ? { target: "current_lane" }
237
+ : { target: "top_level" };
238
+ return {
239
+ getReplyToMessageGuid() {
240
+ if (event.kind !== "message")
241
+ return undefined;
242
+ if (selection.target === "top_level")
243
+ return undefined;
244
+ if (selection.target === "thread")
245
+ return selection.threadOriginatorGuid.trim();
246
+ return event.threadOriginatorGuid?.trim() ? event.messageGuid : undefined;
247
+ },
248
+ setSelection(next) {
249
+ selection = next;
250
+ if (next.target === "top_level") {
251
+ return "bluebubbles reply target override: top_level";
252
+ }
253
+ if (next.target === "thread") {
254
+ return `bluebubbles reply target override: thread:${next.threadOriginatorGuid}`;
255
+ }
256
+ return `bluebubbles reply target: using default for this turn (${defaultTargetLabel})`;
257
+ },
258
+ };
259
+ }
260
+ function emitBlueBubblesMarkReadWarning(chat, error) {
261
+ (0, runtime_1.emitNervesEvent)({
262
+ level: "warn",
263
+ component: "senses",
264
+ event: "senses.bluebubbles_mark_read_error",
265
+ message: "failed to mark bluebubbles chat as read",
266
+ meta: {
267
+ chatGuid: chat.chatGuid ?? null,
268
+ reason: error instanceof Error ? error.message : String(error),
269
+ },
270
+ });
271
+ }
272
+ function createBlueBubblesCallbacks(client, chat, replyTarget) {
273
+ let textBuffer = "";
274
+ const phrases = (0, phrases_1.getPhrases)();
275
+ const activity = (0, debug_activity_1.createDebugActivityController)({
276
+ thinkingPhrases: phrases.thinking,
277
+ followupPhrases: phrases.followup,
278
+ startTypingOnModelStart: true,
279
+ suppressInitialModelStatus: true,
280
+ suppressFollowupPhraseStatus: true,
281
+ transport: {
282
+ sendStatus: async (text) => {
283
+ const sent = await client.sendText({
284
+ chat,
285
+ text,
286
+ replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
287
+ });
288
+ return sent.messageGuid;
289
+ },
290
+ editStatus: async (_messageGuid, text) => {
291
+ await client.sendText({
292
+ chat,
293
+ text,
294
+ replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
295
+ });
296
+ },
297
+ setTyping: async (active) => {
298
+ if (!active) {
299
+ await client.setTyping(chat, false);
300
+ return;
301
+ }
302
+ const [markReadResult, typingResult] = await Promise.allSettled([
303
+ client.markChatRead(chat),
304
+ client.setTyping(chat, true),
305
+ ]);
306
+ if (markReadResult.status === "rejected") {
307
+ emitBlueBubblesMarkReadWarning(chat, markReadResult.reason);
308
+ }
309
+ if (typingResult.status === "rejected") {
310
+ throw typingResult.reason;
311
+ }
312
+ },
313
+ },
314
+ onTransportError: (operation, error) => {
315
+ (0, runtime_1.emitNervesEvent)({
316
+ level: "warn",
317
+ component: "senses",
318
+ event: "senses.bluebubbles_activity_error",
319
+ message: "bluebubbles activity transport failed",
320
+ meta: {
321
+ operation,
322
+ reason: error instanceof Error ? error.message : String(error),
323
+ },
324
+ });
325
+ },
326
+ });
327
+ return {
328
+ onModelStart() {
329
+ activity.onModelStart();
330
+ (0, runtime_1.emitNervesEvent)({
331
+ component: "senses",
332
+ event: "senses.bluebubbles_turn_start",
333
+ message: "bluebubbles turn started",
334
+ meta: { chatGuid: chat.chatGuid ?? null },
335
+ });
336
+ },
337
+ onModelStreamStart() {
338
+ (0, runtime_1.emitNervesEvent)({
339
+ component: "senses",
340
+ event: "senses.bluebubbles_stream_start",
341
+ message: "bluebubbles non-streaming response started",
342
+ meta: {},
343
+ });
344
+ },
345
+ onTextChunk(text) {
346
+ activity.onTextChunk(text);
347
+ textBuffer += text;
348
+ },
349
+ onReasoningChunk(_text) { },
350
+ onToolStart(name, _args) {
351
+ activity.onToolStart(name, _args);
352
+ (0, runtime_1.emitNervesEvent)({
353
+ component: "senses",
354
+ event: "senses.bluebubbles_tool_start",
355
+ message: "bluebubbles tool execution started",
356
+ meta: { name },
357
+ });
358
+ },
359
+ onToolEnd(name, summary, success) {
360
+ activity.onToolEnd(name, summary, success);
361
+ (0, runtime_1.emitNervesEvent)({
362
+ component: "senses",
363
+ event: "senses.bluebubbles_tool_end",
364
+ message: "bluebubbles tool execution completed",
365
+ meta: { name, success, summary },
366
+ });
367
+ },
368
+ onError(error, severity) {
369
+ activity.onError(error);
370
+ (0, runtime_1.emitNervesEvent)({
371
+ level: severity === "terminal" ? "error" : "warn",
372
+ component: "senses",
373
+ event: "senses.bluebubbles_turn_error",
374
+ message: "bluebubbles turn callback error",
375
+ meta: { severity, reason: error.message },
376
+ });
377
+ },
378
+ onClearText() {
379
+ textBuffer = "";
380
+ },
381
+ async flush() {
382
+ await activity.drain();
383
+ const trimmed = textBuffer.trim();
384
+ if (!trimmed) {
385
+ await activity.finish();
386
+ return;
387
+ }
388
+ textBuffer = "";
389
+ await activity.finish();
390
+ await client.sendText({
391
+ chat,
392
+ text: trimmed,
393
+ replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
394
+ });
395
+ },
396
+ async finish() {
397
+ await activity.finish();
398
+ },
399
+ };
400
+ }
401
+ async function readRequestBody(req) {
402
+ let body = "";
403
+ for await (const chunk of req) {
404
+ body += chunk.toString();
405
+ }
406
+ return body;
407
+ }
408
+ function writeJson(res, statusCode, payload) {
409
+ res.statusCode = statusCode;
410
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
411
+ res.end(JSON.stringify(payload));
412
+ }
413
+ function isWebhookPasswordValid(url, expectedPassword) {
414
+ const provided = url.searchParams.get("password");
415
+ return !provided || provided === expectedPassword;
416
+ }
417
+ async function handleBlueBubblesEvent(payload, deps = {}) {
418
+ const resolvedDeps = { ...defaultDeps, ...deps };
419
+ const client = resolvedDeps.createClient();
420
+ const event = await client.repairEvent((0, bluebubbles_model_1.normalizeBlueBubblesEvent)(payload));
421
+ if (event.fromMe) {
422
+ (0, runtime_1.emitNervesEvent)({
423
+ component: "senses",
424
+ event: "senses.bluebubbles_from_me_ignored",
425
+ message: "ignored from-me bluebubbles event",
426
+ meta: {
427
+ messageGuid: event.messageGuid,
428
+ kind: event.kind,
429
+ },
430
+ });
431
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "from_me" };
432
+ }
433
+ if (event.kind === "mutation") {
434
+ try {
435
+ resolvedDeps.recordMutation(resolvedDeps.getAgentName(), event);
436
+ }
437
+ catch (error) {
438
+ (0, runtime_1.emitNervesEvent)({
439
+ level: "error",
440
+ component: "senses",
441
+ event: "senses.bluebubbles_mutation_log_error",
442
+ message: "failed recording bluebubbles mutation sidecar",
443
+ meta: {
444
+ messageGuid: event.messageGuid,
445
+ mutationType: event.mutationType,
446
+ reason: error instanceof Error ? error.message : String(error),
447
+ },
448
+ });
449
+ }
450
+ }
451
+ if (event.kind === "mutation" && !event.shouldNotifyAgent) {
452
+ (0, runtime_1.emitNervesEvent)({
453
+ component: "senses",
454
+ event: "senses.bluebubbles_state_mutation_recorded",
455
+ message: "recorded non-notify bluebubbles mutation",
456
+ meta: {
457
+ messageGuid: event.messageGuid,
458
+ mutationType: event.mutationType,
459
+ },
460
+ });
461
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "mutation_state_only" };
462
+ }
463
+ // ── Adapter setup: friend, session, content, callbacks ──────────
464
+ const store = resolvedDeps.createFriendStore();
465
+ const resolver = resolvedDeps.createFriendResolver(store, resolveFriendParams(event));
466
+ const baseContext = await resolver.resolve();
467
+ const context = { ...baseContext, isGroupChat: event.chat.isGroup };
468
+ const replyTarget = createReplyTargetController(event);
469
+ const friendId = context.friend.id;
470
+ const sessPath = resolvedDeps.sessionPath(friendId, "bluebubbles", event.chat.sessionKey);
471
+ try {
472
+ (0, bluebubbles_session_cleanup_1.findObsoleteBlueBubblesThreadSessions)(sessPath);
473
+ }
474
+ catch (error) {
475
+ (0, runtime_1.emitNervesEvent)({
476
+ level: "warn",
477
+ component: "senses",
478
+ event: "senses.bluebubbles_thread_lane_cleanup_error",
479
+ message: "failed to inspect obsolete bluebubbles thread-lane sessions",
480
+ meta: {
481
+ sessionPath: sessPath,
482
+ reason: error instanceof Error ? error.message : String(error),
483
+ },
484
+ });
485
+ }
486
+ // Pre-load session (adapter needs existing messages for lane history in content building)
487
+ const existing = resolvedDeps.loadSession(sessPath);
488
+ const sessionMessages = existing?.messages && existing.messages.length > 0
489
+ ? existing.messages
490
+ : [{ role: "system", content: await resolvedDeps.buildSystem("bluebubbles", undefined, context) }];
491
+ // Build inbound user message (adapter concern: BB-specific content formatting)
492
+ const userMessage = {
493
+ role: "user",
494
+ content: buildInboundContent(event, existing?.messages ?? sessionMessages),
495
+ };
496
+ const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget);
497
+ const controller = new AbortController();
498
+ // BB-specific tool context wrappers
499
+ const summarize = (0, core_1.createSummarize)();
500
+ const bbCapabilities = (0, channel_1.getChannelCapabilities)("bluebubbles");
501
+ const pendingDir = (0, pending_1.getPendingDir)(resolvedDeps.getAgentName(), friendId, "bluebubbles", event.chat.sessionKey);
502
+ // ── Compute trust gate context for group/acquaintance rules ─────
503
+ const groupHasFamilyMember = await checkGroupHasFamilyMember(store, event);
504
+ const hasExistingGroupWithFamily = event.chat.isGroup
505
+ ? false
506
+ : await checkHasExistingGroupWithFamily(store, context.friend);
507
+ // ── Call shared pipeline ──────────────────────────────────────────
508
+ try {
509
+ const result = await (0, pipeline_1.handleInboundTurn)({
510
+ channel: "bluebubbles",
511
+ capabilities: bbCapabilities,
512
+ messages: [userMessage],
513
+ callbacks,
514
+ friendResolver: { resolve: () => Promise.resolve(context) },
515
+ sessionLoader: { loadOrCreate: () => Promise.resolve({ messages: sessionMessages, sessionPath: sessPath }) },
516
+ pendingDir,
517
+ friendStore: store,
518
+ provider: "imessage-handle",
519
+ externalId: event.sender.externalId || event.sender.rawId,
520
+ isGroupChat: event.chat.isGroup,
521
+ groupHasFamilyMember,
522
+ hasExistingGroupWithFamily,
523
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
524
+ drainPending: pending_1.drainPending,
525
+ runAgent: (msgs, cb, channel, sig, opts) => resolvedDeps.runAgent(msgs, cb, channel, sig, {
526
+ ...opts,
527
+ toolContext: {
528
+ /* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
529
+ signin: async () => undefined,
530
+ ...opts?.toolContext,
531
+ summarize,
532
+ bluebubblesReplyTarget: {
533
+ setSelection: (selection) => replyTarget.setSelection(selection),
534
+ },
535
+ codingFeedback: {
536
+ send: async (message) => {
537
+ await client.sendText({
538
+ chat: event.chat,
539
+ text: message,
540
+ replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
541
+ });
542
+ },
543
+ },
544
+ },
545
+ }),
546
+ postTurn: resolvedDeps.postTurn,
547
+ accumulateFriendTokens: resolvedDeps.accumulateFriendTokens,
548
+ signal: controller.signal,
549
+ });
550
+ // ── Handle gate result ────────────────────────────────────────
551
+ if (!result.gateResult.allowed) {
552
+ // Send auto-reply via BB API if the gate provides one
553
+ if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
554
+ await client.sendText({
555
+ chat: event.chat,
556
+ text: result.gateResult.autoReply,
557
+ });
558
+ }
559
+ return {
560
+ handled: true,
561
+ notifiedAgent: false,
562
+ kind: event.kind,
563
+ };
564
+ }
565
+ // Gate allowed — flush the agent's reply
566
+ await callbacks.flush();
567
+ (0, runtime_1.emitNervesEvent)({
568
+ component: "senses",
569
+ event: "senses.bluebubbles_turn_end",
570
+ message: "bluebubbles event handled",
571
+ meta: {
572
+ messageGuid: event.messageGuid,
573
+ kind: event.kind,
574
+ sessionKey: event.chat.sessionKey,
575
+ },
576
+ });
577
+ return {
578
+ handled: true,
579
+ notifiedAgent: true,
580
+ kind: event.kind,
581
+ };
582
+ }
583
+ finally {
584
+ await callbacks.finish();
585
+ }
586
+ }
587
+ function createBlueBubblesWebhookHandler(deps = {}) {
588
+ return async (req, res) => {
589
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
590
+ const channelConfig = (0, config_1.getBlueBubblesChannelConfig)();
591
+ const runtimeConfig = (0, config_1.getBlueBubblesConfig)();
592
+ if (url.pathname !== channelConfig.webhookPath) {
593
+ writeJson(res, 404, { error: "Not found" });
594
+ return;
595
+ }
596
+ if (req.method !== "POST") {
597
+ writeJson(res, 405, { error: "Method not allowed" });
598
+ return;
599
+ }
600
+ if (!isWebhookPasswordValid(url, runtimeConfig.password)) {
601
+ writeJson(res, 401, { error: "Unauthorized" });
602
+ return;
603
+ }
604
+ let payload;
605
+ try {
606
+ const rawBody = await readRequestBody(req);
607
+ payload = JSON.parse(rawBody);
608
+ }
609
+ catch (error) {
610
+ (0, runtime_1.emitNervesEvent)({
611
+ level: "warn",
612
+ component: "senses",
613
+ event: "senses.bluebubbles_webhook_bad_json",
614
+ message: "failed to parse bluebubbles webhook body",
615
+ meta: {
616
+ reason: error instanceof Error ? error.message : String(error),
617
+ },
618
+ });
619
+ writeJson(res, 400, { error: "Invalid JSON body" });
620
+ return;
621
+ }
622
+ try {
623
+ const result = await handleBlueBubblesEvent(payload, deps);
624
+ writeJson(res, 200, result);
625
+ }
626
+ catch (error) {
627
+ (0, runtime_1.emitNervesEvent)({
628
+ level: "error",
629
+ component: "senses",
630
+ event: "senses.bluebubbles_webhook_error",
631
+ message: "bluebubbles webhook handling failed",
632
+ meta: {
633
+ reason: error instanceof Error ? error.message : String(error),
634
+ },
635
+ });
636
+ writeJson(res, 500, {
637
+ error: error instanceof Error ? error.message : String(error),
638
+ });
639
+ }
640
+ };
641
+ }
642
+ function findImessageHandle(friend) {
643
+ for (const ext of friend.externalIds) {
644
+ if (ext.provider === "imessage-handle" && !ext.externalId.startsWith("group:")) {
645
+ return ext.externalId;
646
+ }
647
+ }
648
+ return undefined;
649
+ }
650
+ function scanPendingBlueBubblesFiles(pendingRoot) {
651
+ const results = [];
652
+ let friendIds;
653
+ try {
654
+ friendIds = fs.readdirSync(pendingRoot);
655
+ }
656
+ catch {
657
+ return results;
658
+ }
659
+ for (const friendId of friendIds) {
660
+ const bbDir = path.join(pendingRoot, friendId, "bluebubbles");
661
+ let keys;
662
+ try {
663
+ keys = fs.readdirSync(bbDir);
664
+ }
665
+ catch {
666
+ continue;
667
+ }
668
+ for (const key of keys) {
669
+ const keyDir = path.join(bbDir, key);
670
+ let files;
671
+ try {
672
+ files = fs.readdirSync(keyDir);
673
+ }
674
+ catch {
675
+ continue;
676
+ }
677
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
678
+ const filePath = path.join(keyDir, file);
679
+ try {
680
+ const content = fs.readFileSync(filePath, "utf-8");
681
+ results.push({ friendId, key, filePath, content });
682
+ }
683
+ catch {
684
+ // skip unreadable files
685
+ }
686
+ }
687
+ }
688
+ }
689
+ return results;
690
+ }
691
+ async function drainAndSendPendingBlueBubbles(deps = {}, pendingRoot) {
692
+ const resolvedDeps = { ...defaultDeps, ...deps };
693
+ const root = pendingRoot ?? path.join((0, identity_1.getAgentRoot)(), "state", "pending");
694
+ const client = resolvedDeps.createClient();
695
+ const store = resolvedDeps.createFriendStore();
696
+ const pendingFiles = scanPendingBlueBubblesFiles(root);
697
+ const result = { sent: 0, skipped: 0, failed: 0 };
698
+ for (const { friendId, filePath, content } of pendingFiles) {
699
+ let parsed;
700
+ try {
701
+ parsed = JSON.parse(content);
702
+ }
703
+ catch {
704
+ result.failed++;
705
+ try {
706
+ fs.unlinkSync(filePath);
707
+ }
708
+ catch { /* ignore */ }
709
+ continue;
710
+ }
711
+ const messageText = typeof parsed.content === "string" ? parsed.content : "";
712
+ if (!messageText.trim()) {
713
+ result.skipped++;
714
+ try {
715
+ fs.unlinkSync(filePath);
716
+ }
717
+ catch { /* ignore */ }
718
+ continue;
719
+ }
720
+ let friend;
721
+ try {
722
+ friend = await store.get(friendId);
723
+ }
724
+ catch {
725
+ friend = null;
726
+ }
727
+ if (!friend) {
728
+ result.skipped++;
729
+ try {
730
+ fs.unlinkSync(filePath);
731
+ }
732
+ catch { /* ignore */ }
733
+ (0, runtime_1.emitNervesEvent)({
734
+ level: "warn",
735
+ component: "senses",
736
+ event: "senses.bluebubbles_proactive_no_friend",
737
+ message: "proactive send skipped: friend not found",
738
+ meta: { friendId },
739
+ });
740
+ continue;
741
+ }
742
+ if (!types_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
743
+ result.skipped++;
744
+ try {
745
+ fs.unlinkSync(filePath);
746
+ }
747
+ catch { /* ignore */ }
748
+ (0, runtime_1.emitNervesEvent)({
749
+ component: "senses",
750
+ event: "senses.bluebubbles_proactive_trust_skip",
751
+ message: "proactive send skipped: trust level not allowed",
752
+ meta: { friendId, trustLevel: friend.trustLevel ?? "unknown" },
753
+ });
754
+ continue;
755
+ }
756
+ const handle = findImessageHandle(friend);
757
+ if (!handle) {
758
+ result.skipped++;
759
+ try {
760
+ fs.unlinkSync(filePath);
761
+ }
762
+ catch { /* ignore */ }
763
+ (0, runtime_1.emitNervesEvent)({
764
+ level: "warn",
765
+ component: "senses",
766
+ event: "senses.bluebubbles_proactive_no_handle",
767
+ message: "proactive send skipped: no iMessage handle found",
768
+ meta: { friendId },
769
+ });
770
+ continue;
771
+ }
772
+ const chat = {
773
+ chatIdentifier: handle,
774
+ isGroup: false,
775
+ sessionKey: friendId,
776
+ sendTarget: { kind: "chat_identifier", value: handle },
777
+ participantHandles: [],
778
+ };
779
+ try {
780
+ await client.sendText({ chat, text: messageText });
781
+ result.sent++;
782
+ try {
783
+ fs.unlinkSync(filePath);
784
+ }
785
+ catch { /* ignore */ }
786
+ (0, runtime_1.emitNervesEvent)({
787
+ component: "senses",
788
+ event: "senses.bluebubbles_proactive_sent",
789
+ message: "proactive bluebubbles message sent",
790
+ meta: { friendId, handle },
791
+ });
792
+ }
793
+ catch (error) {
794
+ result.failed++;
795
+ (0, runtime_1.emitNervesEvent)({
796
+ level: "error",
797
+ component: "senses",
798
+ event: "senses.bluebubbles_proactive_send_error",
799
+ message: "proactive bluebubbles send failed",
800
+ meta: {
801
+ friendId,
802
+ handle,
803
+ reason: error instanceof Error ? error.message : String(error),
804
+ },
805
+ });
806
+ }
807
+ }
808
+ if (result.sent > 0 || result.skipped > 0 || result.failed > 0) {
809
+ (0, runtime_1.emitNervesEvent)({
810
+ component: "senses",
811
+ event: "senses.bluebubbles_proactive_drain_complete",
812
+ message: "bluebubbles proactive drain complete",
813
+ meta: { sent: result.sent, skipped: result.skipped, failed: result.failed },
814
+ });
815
+ }
816
+ return result;
817
+ }
818
+ function startBlueBubblesApp(deps = {}) {
819
+ const resolvedDeps = { ...defaultDeps, ...deps };
820
+ resolvedDeps.createClient();
821
+ const channelConfig = (0, config_1.getBlueBubblesChannelConfig)();
822
+ const server = resolvedDeps.createServer(createBlueBubblesWebhookHandler(deps));
823
+ server.listen(channelConfig.port, () => {
824
+ (0, runtime_1.emitNervesEvent)({
825
+ component: "channels",
826
+ event: "channel.app_started",
827
+ message: "BlueBubbles sense started",
828
+ meta: { port: channelConfig.port, webhookPath: channelConfig.webhookPath },
829
+ });
830
+ });
831
+ return server;
832
+ }