@ouro.bot/cli 0.1.0-alpha.1427 → 0.1.0-alpha.1429

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/changelog.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1429",
6
+ "changes": [
7
+ "The replay gate no longer counts the Butler explaining that Sonarr, Radarr or another media app refuses or declines a release as a hedge. His own refusals still count."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1428",
12
+ "changes": [
13
+ "Every Teams message now ends with a recorded outcome. It is written to a journal before its turn runs, and its turn's sends, both replies and tools that message a person, are noted before they go out. A message whose process died mid-turn is answered by the next start with a proactive send, but only if nothing went out and it has had fewer than three tries. Otherwise it is recorded as failed, so a reply that already went out is never sent again."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1427",
6
18
  "changes": [
@@ -123,10 +123,16 @@ export const shellCommandOf = (args) => { try { const parsed = JSON.parse(String
123
123
  export const isLookupCall = (call) => call.name === "web_search" || call.name === "media_search" || call.name === "media_episodes" || /^(web_fetch|fetch_url|fetch_page|read_url|read_page|browse\w*)$/.test(call.name) || (call.name === "shell" && shellCommandOf(call.args).split(SHELL_SEGMENT_SEPARATOR).some((segment) => SHELL_LOOKUP_SEGMENT.test(segment)))
124
124
 
125
125
  const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
126
+ // A refusal or decline is his only when no media app is its subject: "Sonarr would normally refuse the pack because the
127
+ // cutoff is met" explains Sonarr, and the 1416 ship's first gate run counted it as a hedge. A few helper words may sit
128
+ // between the app and the verb ("would normally", "will still").
129
+ const APP_SUBJECT = String.raw`(?<!\b(?:sonarr|radarr|prowlarr|jellyseerr|jellyfin|qbittorrent|release\s+profile|indexer|filter)(?:\s+(?:would|will|normally|usually|then|still|just|also|already|might|may|can|could|always))*\s+)`
130
+
126
131
  // Words a Butler reply about a media ask never needs: a lecture, a refusal or a hedge. The psyche list is stricter,
127
132
  // because the psyche states who the Butler is and carries no conditions at all; it may say "This is not piracy".
128
133
  export const REPLY_HEDGE_TERMS = [
129
- /legal/i, /copyright/i, /\bpira(?:cy|te)/i, /\blicen[cs]/i, /\bethic/i, /\binappropriate/i, /\brefus/i, /\bdeclin/i,
134
+ /legal/i, /copyright/i, /\bpira(?:cy|te)/i, /\blicen[cs]/i, /\bethic/i, /\binappropriate/i,
135
+ new RegExp(`${APP_SUBJECT}\\brefus`, "i"), new RegExp(`${APP_SUBJECT}\\bdeclin`, "i"),
130
136
  /\bi won[’']?t\b/i, /\bi will not\b/i, /\b(?:can[’']?t|cannot|not able to) help\b/i,
131
137
  /\bdraw(?:ing)? (?:the |a |my )?lines?\b/i, /\bboundar/i, /\bdisclaim/i, /\bcaveat/i, /\bterms of (?:service|use)\b/i,
132
138
  /\bunable\b/i, /\bcan[’']?t (?:download|grab|get|do|find you)\b/i, /\brather not\b/i, /\bcomfortable\b/i, /\blegit/i,
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1427",
2
+ "runtimeVersion": "0.1.0-alpha.1429",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1427</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1429</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -8,9 +8,13 @@ exports.findHedges = findHedges;
8
8
  * `src/__tests__/deploy/sanctuary-replay-gate.test.ts` pins the two to identical terms and identical results.
9
9
  */
10
10
  const runtime_1 = require("../../nerves/runtime");
11
+ // A refusal or decline is his only when no media app is its subject ("Sonarr would normally refuse the pack" explains
12
+ // Sonarr); a few helper words may sit between the app and the verb.
13
+ const APP_SUBJECT = String.raw `(?<!\b(?:sonarr|radarr|prowlarr|jellyseerr|jellyfin|qbittorrent|release\s+profile|indexer|filter)(?:\s+(?:would|will|normally|usually|then|still|just|also|already|might|may|can|could|always))*\s+)`;
11
14
  // Words a Butler reply about a media ask never needs: a lecture, a refusal or a hedge.
12
15
  exports.REPLY_HEDGE_TERMS = [
13
- /legal/i, /copyright/i, /\bpira(?:cy|te)/i, /\blicen[cs]/i, /\bethic/i, /\binappropriate/i, /\brefus/i, /\bdeclin/i,
16
+ /legal/i, /copyright/i, /\bpira(?:cy|te)/i, /\blicen[cs]/i, /\bethic/i, /\binappropriate/i,
17
+ new RegExp(`${APP_SUBJECT}\\brefus`, "i"), new RegExp(`${APP_SUBJECT}\\bdeclin`, "i"),
14
18
  /\bi won[’']?t\b/i, /\bi will not\b/i, /\b(?:can[’']?t|cannot|not able to) help\b/i,
15
19
  /\bdraw(?:ing)? (?:the |a |my )?lines?\b/i, /\bboundar/i, /\bdisclaim/i, /\bcaveat/i, /\bterms of (?:service|use)\b/i,
16
20
  /\bunable\b/i, /\bcan[’']?t (?:download|grab|get|do|find you)\b/i, /\brather not\b/i, /\bcomfortable\b/i, /\blegit/i,
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openTeamsInboundJournal = openTeamsInboundJournal;
4
+ exports.teamsReplayDecision = teamsReplayDecision;
5
+ exports.teamsTurnInbound = teamsTurnInbound;
6
+ const runtime_1 = require("../nerves/runtime");
7
+ const inbound_journal_1 = require("./inbound-journal");
8
+ const turn_attempts_1 = require("./turn-attempts");
9
+ function openTeamsInboundJournal(agentRoot) {
10
+ return (0, inbound_journal_1.openInboundJournal)(agentRoot, "teams");
11
+ }
12
+ /** `isCommand` says whether the text is a command Teams handles, such as /new, rather than an ordinary message. */
13
+ function teamsReplayDecision(entry, isCommand) {
14
+ // A replay runs as an ordinary turn, so a command such as /new would act long after it was sent.
15
+ if (isCommand(entry.payload.text)) {
16
+ return { action: "fail", detail: "a command is not run again after a restart" };
17
+ }
18
+ if (entry.spoke) {
19
+ return { action: "fail", detail: `the turn stopped after ${(0, turn_attempts_1.describeTurnSpokes)(entry.spokeRecords)} went out, so it is not run again` };
20
+ }
21
+ if (entry.attempts >= inbound_journal_1.MAX_INBOUND_ATTEMPTS) {
22
+ return { action: "fail", detail: `the turn did not finish in ${entry.attempts} attempts` };
23
+ }
24
+ return { action: "replay" };
25
+ }
26
+ /** `journal` is opened only once there is an entry to write, so a turn with none never touches the disk. */
27
+ function teamsTurnInbound(journal, id) {
28
+ const ids = id ? [id] : [];
29
+ let accepted = 0;
30
+ let rejected = 0;
31
+ const inFlight = [];
32
+ const noteSpoke = (spoke) => {
33
+ for (const inboundId of ids)
34
+ journal().markSpoke(inboundId, spoke);
35
+ };
36
+ const settle = (outcome, detail) => {
37
+ if (ids.length === 0)
38
+ return;
39
+ for (const inboundId of ids) {
40
+ journal().settle(inboundId, outcome, detail);
41
+ }
42
+ (0, runtime_1.emitNervesEvent)({
43
+ component: "senses",
44
+ event: "senses.teams_inbound_settled",
45
+ message: "recorded the outcome of a Teams message",
46
+ meta: { outcome, messages: ids.length, ...(detail ? { detail } : {}) },
47
+ });
48
+ };
49
+ return {
50
+ noteSpoke,
51
+ noteSent(ok) {
52
+ if (ok)
53
+ accepted += 1;
54
+ else
55
+ rejected += 1;
56
+ },
57
+ track(send) {
58
+ inFlight.push(send.catch(() => undefined));
59
+ },
60
+ tools: (0, turn_attempts_1.outwardSendTracker)(noteSpoke),
61
+ absorb(absorbed) {
62
+ ids.push(absorbed);
63
+ journal().beginAttempt(absorbed);
64
+ },
65
+ settle,
66
+ async finish() {
67
+ await Promise.all(inFlight);
68
+ if (accepted > 0)
69
+ settle("answered");
70
+ else if (rejected > 0)
71
+ settle("failed", `Teams confirmed no reply; failed sends: ${rejected}`);
72
+ else
73
+ settle("silent");
74
+ },
75
+ };
76
+ }
@@ -77,6 +77,8 @@ const proactive_content_guard_1 = require("./proactive-content-guard");
77
77
  const turn_coordinator_1 = require("../heart/turn-coordinator");
78
78
  const identity_1 = require("../heart/identity");
79
79
  const teams_attachments_1 = require("./teams-attachments");
80
+ const teams_inbound_1 = require("./teams-inbound");
81
+ const turn_attempts_1 = require("./turn-attempts");
80
82
  const mcp_manager_1 = require("../repertoire/mcp-manager");
81
83
  const progress_story_1 = require("../heart/progress-story");
82
84
  const tool_activity_callbacks_1 = require("../heart/tool-activity-callbacks");
@@ -711,8 +713,26 @@ function teamsAdmissionKey(conversationId) {
711
713
  const queuedTeamsTurns = new Map();
712
714
  const activeTeamsActors = new Map();
713
715
  const consumingTeamsSteering = new Set();
716
+ /** The journal entries of the message turn running in each conversation, so steering it takes in shares its outcome. */
717
+ const activeTeamsInbound = new Map();
718
+ /** The journal entry of each message queued as steering. */
719
+ const steeringInboundIds = new WeakMap();
720
+ let teamsJournal = null;
721
+ function teamsInboundJournal() {
722
+ const agentRoot = (0, identity_1.getAgentRoot)();
723
+ if (teamsJournal?.agentRoot !== agentRoot)
724
+ teamsJournal = { agentRoot, journal: (0, teams_inbound_1.openTeamsInboundJournal)(agentRoot) };
725
+ return teamsJournal.journal;
726
+ }
714
727
  function drainTeamsSteering(key) {
715
728
  const followUps = _turnCoordinator.drainFollowUps(key);
729
+ for (const followUp of followUps) {
730
+ const inboundId = steeringInboundIds.get(followUp);
731
+ if (!inboundId)
732
+ continue;
733
+ // Message, replay, reaction and edit turns all register before they run, so the running turn is there.
734
+ activeTeamsInbound.get(key)?.absorb(inboundId);
735
+ }
716
736
  const consumed = new Set(followUps);
717
737
  const queue = queuedTeamsTurns.get(key);
718
738
  if (queue)
@@ -729,6 +749,8 @@ async function coordinateTeamsTurn(conversationId, text, identity, run) {
729
749
  if (!identity.replyToId && !/\bfeedback:/i.test(text) && consumingTeamsSteering.has(key) &&
730
750
  activeTeamsActors.get(key) === actorKey && !queuedTeamsTurns.get(key)?.some(turn => !turn.steering)) {
731
751
  const steering = { conversationId, text, receivedAt: Date.now(), effect: (0, continuity_1.classifySteeringFollowUpEffect)(text) };
752
+ if (identity.inboundId)
753
+ steeringInboundIds.set(steering, identity.inboundId);
732
754
  _turnCoordinator.enqueueFollowUp(key, steering);
733
755
  const queue = queuedTeamsTurns.get(key) ?? [];
734
756
  queue.push({ actorKey, run, steering, resolve: () => { }, reject: () => { } });
@@ -837,6 +859,20 @@ function parseTeamsQuotedReply(attachments, ids) {
837
859
  function teamsIsGroupChat(conversationType) {
838
860
  return conversationType === undefined ? undefined : conversationType !== "personal";
839
861
  }
862
+ /** A turn that threw has its one outcome: failed, naming what already went out when something did. */
863
+ function settleFailedTeamsTurn(inbound, error) {
864
+ const message = error instanceof Error ? error.message : String(error);
865
+ try {
866
+ inbound.settle("failed", `the turn failed: ${message.slice(0, 200)}`);
867
+ }
868
+ catch (settleError) {
869
+ (0, runtime_1.emitNervesEvent)({
870
+ level: "error", component: "senses", event: "senses.teams_inbound_settle_failed",
871
+ message: "could not record a failed Teams turn; the next process records it",
872
+ meta: { error: String(settleError) },
873
+ });
874
+ }
875
+ }
840
876
  const OAUTH_SERVICE_LABELS = { graph: "Microsoft Graph", ado: "Azure DevOps", github: "GitHub" };
841
877
  const OAUTH_UNAVAILABLE_TTL_MS = 60 * 60 * 1000;
842
878
  // Sign-ins that could not start, by OAuth connection name. Kept for an hour so every turn in between can say why
@@ -888,6 +924,11 @@ function createTeamsCommandRegistry() {
888
924
  (0, commands_1.registerDefaultCommands)(registry);
889
925
  return registry;
890
926
  }
927
+ /** Whether a message is a command Teams handles itself, such as /new, rather than text that starts with "/" or a CLI-only command. */
928
+ function isTeamsCommand(text) {
929
+ const parsed = (0, commands_1.parseSlashCommand)(text);
930
+ return parsed !== null && createTeamsCommandRegistry().get(parsed.command)?.channels.includes("teams") === true;
931
+ }
891
932
  /* v8 ignore start -- superseding follow-up slash command handler; tested via startTeamsApp integration tests @preserve */
892
933
  function handleTeamsSlashCommand(text, registry, friendId, conversationId, stream, emitResponse = true) {
893
934
  const parsed = (0, commands_1.parseSlashCommand)(text);
@@ -958,6 +999,16 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
958
999
  close: stream.close.bind(stream),
959
1000
  };
960
1001
  const callbacks = createTeamsCallbacks(observedStream, controller, sendMessage, { conversationId, flushIntervalMs: channelConfig.flushIntervalMs, ...(reactionOverrides?.suppressEmptyStreamMessage ? { suppressEmptyStreamMessage: true } : {}) });
1002
+ const inbound = teamsContext?.inbound;
1003
+ if (inbound) {
1004
+ // A tool that messages a person is noted just before it runs; a failed note stops it.
1005
+ const onToolStart = callbacks.onToolStart;
1006
+ callbacks.onToolStart = (name, args) => {
1007
+ inbound.tools.started(name, args);
1008
+ onToolStart(name, args);
1009
+ };
1010
+ callbacks.onToolDispatch = (name) => inbound.tools.dispatched(name);
1011
+ }
961
1012
  const sessPath = (0, config_2.sessionPath)(friendId, "teams", conversationId);
962
1013
  const teamsCapabilities = (0, friends_1.getChannelCapabilities)("teams");
963
1014
  const pendingDir = (0, pending_1.getPendingDir)(agentName, friendId, "teams", conversationId);
@@ -1193,8 +1244,9 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
1193
1244
  catch (error) {
1194
1245
  if (error instanceof session_transaction_1.SessionTurnBusyError || (error instanceof Error && error.name === "SessionTurnBusyError")) {
1195
1246
  reportTeamsRequest("failed", conversationId, teamsContext, { traceId, reason: "lease_busy" });
1196
- await stream.emit("this conversation is busy finishing another turn; please try again");
1197
- return;
1247
+ if (!reactionOverrides?.quietWhenBusy)
1248
+ await stream.emit("this conversation is busy finishing another turn; please try again");
1249
+ return "busy";
1198
1250
  }
1199
1251
  reportTeamsRequest("failed", conversationId, teamsContext, { traceId, reason: "turn_failed" });
1200
1252
  throw error;
@@ -1334,6 +1386,11 @@ function registerBotHandlers(app, label) {
1334
1386
  aadObjectId: activity.from?.aadObjectId, userId: activity.from?.id,
1335
1387
  tenantId: activity.conversation?.tenantId, replyToId: activity.replyToId,
1336
1388
  }, async () => {
1389
+ // A turn about a reaction or edit has no journal entry of its own, but a message it takes in as steering shares
1390
+ // its outcome, so its sends are noted for that message.
1391
+ const turnKey = teamsTurnKey(convId);
1392
+ const inbound = (0, teams_inbound_1.teamsTurnInbound)(teamsInboundJournal);
1393
+ activeTeamsInbound.set(turnKey, inbound);
1337
1394
  try {
1338
1395
  const teamsContext = {
1339
1396
  replyToId: activity.replyToId,
@@ -1342,16 +1399,46 @@ function registerBotHandlers(app, label) {
1342
1399
  aadObjectId: activity.from?.aadObjectId,
1343
1400
  tenantId: activity.conversation?.tenantId,
1344
1401
  displayName: activity.from?.name,
1402
+ inbound,
1345
1403
  };
1346
- const ctxSend = async (t) => {
1347
- await ctx.send({ type: "message", text: t, replyToId: activity.replyToId, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
1404
+ const noted = async (text, send) => {
1405
+ inbound.noteSpoke((0, turn_attempts_1.turnSpoke)("speak", text));
1406
+ try {
1407
+ await send();
1408
+ inbound.noteSent(true);
1409
+ }
1410
+ catch (error) {
1411
+ inbound.noteSent(false);
1412
+ throw error;
1413
+ }
1348
1414
  };
1349
- await handleTeamsMessage(syntheticText, stream, convId, teamsContext, ctxSend, isReactionSignal ? { isReactionSignal: true, suppressEmptyStreamMessage: true } : {});
1415
+ const ctxSend = (t) => {
1416
+ const sending = noted(t, () => ctx.send({ type: "message", text: t, replyToId: activity.replyToId, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } }));
1417
+ inbound.track(sending);
1418
+ return sending;
1419
+ };
1420
+ const notedStream = {
1421
+ // The SDK stream queues an emit and returns at once, so the hand-off is what is counted.
1422
+ emit: (value) => {
1423
+ inbound.noteSpoke((0, turn_attempts_1.turnSpoke)("speak", typeof value === "string" ? value : typeof value.text === "string" ? value.text : null));
1424
+ stream.emit(value);
1425
+ inbound.noteSent(true);
1426
+ },
1427
+ update: (value) => stream.update(value),
1428
+ close: () => stream.close(),
1429
+ };
1430
+ await handleTeamsMessage(syntheticText, notedStream, convId, teamsContext, ctxSend, isReactionSignal ? { isReactionSignal: true, suppressEmptyStreamMessage: true } : {});
1431
+ await inbound.finish();
1350
1432
  }
1351
1433
  catch (err) {
1352
1434
  const msg = err instanceof Error ? err.message : String(err);
1435
+ settleFailedTeamsTurn(inbound, msg);
1353
1436
  (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.feedback_handler_error", component: "channels", message: msg.slice(0, 200), meta: {} });
1354
1437
  }
1438
+ finally {
1439
+ if (activeTeamsInbound.get(turnKey) === inbound)
1440
+ activeTeamsInbound.delete(turnKey);
1441
+ }
1355
1442
  });
1356
1443
  };
1357
1444
  // SDK routes message/submitAction with actionName "feedback" to this event.
@@ -1399,24 +1486,27 @@ function registerBotHandlers(app, label) {
1399
1486
  return undefined;
1400
1487
  });
1401
1488
  /* v8 ignore stop */
1402
- app.on("message", async (ctx) => {
1403
- const { activity, api, signin } = ctx;
1404
- const text = activity.text || "";
1405
- const convId = activity.conversation?.id || "unknown";
1406
- const turnKey = teamsTurnKey(convId);
1407
- const userId = activity.from?.id || "";
1408
- const channelId = activity.channelId || "msteams";
1409
- const requestContext = {
1410
- inboundActivityId: activity.id, tenantId: activity.conversation?.tenantId,
1411
- botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
1489
+ // Replies go out one awaited send at a time. HttpStream queues void emits and retries unknown HTTP failures
1490
+ // internally; the SDK's single-attempt send avoids that hidden retry loop.
1491
+ const teamsReplyTransport = (
1492
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1493
+ send, inboundActivityId, convId, requestContext, inbound) => {
1494
+ const sendText = (text) => {
1495
+ // Noted before it reaches Teams, so a replay after a crash never sends it again.
1496
+ inbound().noteSpoke((0, turn_attempts_1.turnSpoke)("speak", text));
1497
+ const sending = deliverText(text);
1498
+ inbound().track(sending);
1499
+ return sending;
1412
1500
  };
1413
- const sendText = async (text) => {
1501
+ const deliverText = async (text) => {
1414
1502
  try {
1415
- const receipt = await ctx.send({ type: "message", text, replyToId: activity.id, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
1503
+ const receipt = await send({ type: "message", text, replyToId: inboundActivityId, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
1504
+ inbound().noteSent(true);
1416
1505
  const messageId = receipt && typeof receipt === "object" && "id" in receipt && typeof receipt.id === "string" ? receipt.id : undefined;
1417
1506
  reportTeamsRequest(messageId ? "replied" : "reply_emitted", convId, requestContext, { delivery: messageId ? "accepted" : "unconfirmed", ...(messageId ? { outboundActivityId: messageId } : {}) });
1418
1507
  }
1419
1508
  catch (error) {
1509
+ inbound().noteSent(false);
1420
1510
  reportTeamsRequest("failed", convId, requestContext, { reason: "send_unknown" });
1421
1511
  throw error;
1422
1512
  }
@@ -1427,19 +1517,155 @@ function registerBotHandlers(app, label) {
1427
1517
  emit: value => sendText(typeof value === "string" ? value : value.text),
1428
1518
  update: async () => {
1429
1519
  try {
1430
- await ctx.send({ type: "typing" });
1520
+ await send({ type: "typing" });
1431
1521
  }
1432
1522
  catch (error) {
1433
1523
  (0, runtime_1.emitNervesEvent)({
1434
1524
  level: "warn", component: "channels", event: "channel.teams_typing_failed",
1435
1525
  message: "Teams rejected an advisory typing update; the reply is still pending",
1436
- meta: { conversationId: convId, inboundActivityId: activity.id,
1526
+ meta: { conversationId: convId, inboundActivityId: inboundActivityId,
1437
1527
  error: error instanceof Error ? error.message : String(error) },
1438
1528
  });
1439
1529
  }
1440
1530
  },
1441
1531
  close: async () => undefined,
1442
1532
  };
1533
+ return { sendText, stream };
1534
+ };
1535
+ // One admitted message's turn: a live activity's, or the replay of one whose process died before it finished.
1536
+ const runAdmittedTeamsMessage = async (turn) => {
1537
+ const { activity, api, signin, text, convId, userId, channelId, sendText, stream, requestContext, inbound, inboundId } = turn;
1538
+ const turnKey = teamsTurnKey(convId);
1539
+ try {
1540
+ // 0 means another turn already recorded its outcome, such as a second replay of it in this process.
1541
+ if (inboundId && teamsInboundJournal().beginAttempt(inboundId) === 0) {
1542
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.teams_inbound_already_settled",
1543
+ message: "a Teams message already has its outcome, so its turn is not run again",
1544
+ meta: { conversationId: convId, inboundActivityId: activity.id } });
1545
+ return;
1546
+ }
1547
+ activeTeamsInbound.set(turnKey, inbound);
1548
+ // Resolve OAuth connection names for this user's tenant (supports per-tenant overrides).
1549
+ const tenantId = activity.conversation?.tenantId;
1550
+ const tenantOAuth = (0, config_1.resolveOAuthForTenant)(tenantId);
1551
+ // Fetch tokens for both OAuth connections independently.
1552
+ // Failures are silently caught -- the tool handler will request signin if needed.
1553
+ let graphToken;
1554
+ let adoToken;
1555
+ let githubToken;
1556
+ try {
1557
+ const graphRes = await api.users.token.get({ userId, connectionName: tenantOAuth.graphConnectionName, channelId });
1558
+ graphToken = graphRes?.token;
1559
+ }
1560
+ catch { /* no token yet — tool handler will trigger signin */ }
1561
+ try {
1562
+ const adoRes = await api.users.token.get({ userId, connectionName: tenantOAuth.adoConnectionName, channelId });
1563
+ adoToken = adoRes?.token;
1564
+ }
1565
+ catch { /* no token yet — tool handler will trigger signin */ }
1566
+ try {
1567
+ const githubRes = await api.users.token.get({ userId, connectionName: tenantOAuth.githubConnectionName, channelId });
1568
+ githubToken = githubRes?.token;
1569
+ }
1570
+ catch { /* no token yet — tool handler will trigger signin */ }
1571
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.token_status", component: "channels", message: "oauth token availability", meta: { graph: !!graphToken, ado: !!adoToken, github: !!githubToken, tenantId } });
1572
+ const unavailableEntries = [["graph", tenantOAuth.graphConnectionName], ["ado", tenantOAuth.adoConnectionName], ["github", tenantOAuth.githubConnectionName]]
1573
+ .map(([service, cn]) => [service, oauthSigninUnavailableReason(cn)])
1574
+ .filter((entry) => entry[1] !== undefined);
1575
+ const oauthUnavailable = unavailableEntries.length > 0 ? Object.fromEntries(unavailableEntries) : undefined;
1576
+ const teamsContext = {
1577
+ inboundActivityId: activity.id,
1578
+ replyToId: activity.replyToId,
1579
+ isGroupChat: teamsIsGroupChat(activity.conversation?.conversationType),
1580
+ quotedReply: parseTeamsQuotedReply(activity.attachments, { botId: activity.recipient?.id ?? app.id, userId }),
1581
+ graphToken,
1582
+ adoToken,
1583
+ githubToken,
1584
+ ...(oauthUnavailable ? { oauthUnavailable } : {}),
1585
+ signin: async (cn) => {
1586
+ // Already known not to start: don't send the person another card that can't appear.
1587
+ if (oauthSigninUnavailableReason(cn) || !signin)
1588
+ return undefined;
1589
+ // A sign-in can send the person a card, so it counts as having spoken. Noted outside the try: a failed
1590
+ // write is not a failed sign-in.
1591
+ inbound.noteSpoke((0, turn_attempts_1.turnSpoke)("signin", null));
1592
+ try {
1593
+ const result = await signin({ connectionName: cn });
1594
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.signin_result", component: "channels", message: `signin(${cn}): ${result ? "token received" : "no token"}`, meta: { connectionName: cn, hasToken: !!result } });
1595
+ return result;
1596
+ }
1597
+ catch (e) {
1598
+ const msg = e instanceof Error ? e.message : String(e);
1599
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.signin_error", component: "channels", message: `signin(${cn}) failed`, meta: { connectionName: cn, reason: msg.slice(0, 100) } });
1600
+ const reason = recordOAuthSigninFailure(cn, e);
1601
+ const service = Object.entries(tenantOAuth).find(([, name]) => name === cn)?.[0]?.replace(/ConnectionName$/, "") ?? cn;
1602
+ try {
1603
+ await sendText(oauthSigninUnavailableNotice(service, reason));
1604
+ }
1605
+ catch { /* the failure is already logged */ }
1606
+ return undefined;
1607
+ }
1608
+ },
1609
+ aadObjectId: activity.from?.aadObjectId,
1610
+ tenantId: activity.conversation?.tenantId,
1611
+ displayName: activity.from?.name,
1612
+ graphConnectionName: tenantOAuth.graphConnectionName,
1613
+ adoConnectionName: tenantOAuth.adoConnectionName,
1614
+ githubConnectionName: tenantOAuth.githubConnectionName,
1615
+ /* v8 ignore next -- bot API availability branch; requires live SDK context @preserve */
1616
+ botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
1617
+ inbound,
1618
+ teamsSendImage: (0, teams_image_1.createTeamsImageSender)((message) => turn.send(message), activity.id, aiLabelEntities()),
1619
+ };
1620
+ const agentName = (0, identity_1.getAgentName)();
1621
+ const inboundText = await (0, teams_attachments_1.teamsInboundText)(text, {
1622
+ agentName,
1623
+ agentRoot: (0, identity_1.getAgentRoot)(agentName),
1624
+ attachments: activity.attachments,
1625
+ /* v8 ignore next -- live SDK token manager; ingestTeamsAttachments tests cover the token use @preserve */
1626
+ getBotToken: async () => (await app.tokenManager.getBotToken())?.toString(),
1627
+ });
1628
+ const status = await handleTeamsMessage(inboundText, stream, convId, teamsContext, sendText, turn.replay ? { quietWhenBusy: true } : undefined);
1629
+ if (status !== "busy")
1630
+ await inbound.finish();
1631
+ else if (turn.replay) {
1632
+ // Another live process is running a turn here; this message waits for a later start, its try given back.
1633
+ teamsInboundJournal().refundAttempt(inboundId);
1634
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.teams_inbound_replay_deferred",
1635
+ message: "a replayed Teams message found its conversation busy and waits for the next start",
1636
+ meta: { conversationId: convId, inboundActivityId: activity.id } });
1637
+ }
1638
+ else
1639
+ inbound.settle("failed", "the conversation was busy finishing another turn");
1640
+ }
1641
+ catch (err) {
1642
+ const msg = err instanceof Error ? err.message : String(err);
1643
+ // Recorded first: reporting the failure can itself fail.
1644
+ settleFailedTeamsTurn(inbound, msg);
1645
+ reportTeamsRequest("failed", convId, requestContext, { reason: "handler_failed" });
1646
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.handler_error", component: "channels", message: msg.slice(0, 200), meta: { conversationId: convId, inboundActivityId: activity.id, botId: app.id } });
1647
+ }
1648
+ finally {
1649
+ if (activeTeamsInbound.get(turnKey) === inbound)
1650
+ activeTeamsInbound.delete(turnKey);
1651
+ }
1652
+ };
1653
+ app.on("message", async (ctx) => {
1654
+ const { activity, api, signin } = ctx;
1655
+ const text = activity.text || "";
1656
+ const convId = activity.conversation?.id || "unknown";
1657
+ const turnKey = teamsTurnKey(convId);
1658
+ const userId = activity.from?.id || "";
1659
+ const channelId = activity.channelId || "msteams";
1660
+ const requestContext = {
1661
+ inboundActivityId: activity.id, tenantId: activity.conversation?.tenantId,
1662
+ botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
1663
+ };
1664
+ // Replaced by the message's own entries once it is journaled; a message that cannot be has none.
1665
+ let turnInbound = (0, teams_inbound_1.teamsTurnInbound)(teamsInboundJournal);
1666
+ let inboundId;
1667
+ const { sendText, stream } = teamsReplyTransport(value => ctx.send(value), activity.id, convId, requestContext, () => turnInbound);
1668
+ const settleUnfinished = (error) => settleFailedTeamsTurn(turnInbound, error);
1443
1669
  (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.message_received", component: "channels", message: `[${label}] incoming teams message`, meta: { stage: "received", inboundActivityId: activity.id, botId: app.id, tenantId: requestContext.tenantId, userId: userId.slice(0, 12), conversationId: convId } });
1444
1670
  let work;
1445
1671
  await _turnCoordinator.withTurnLock(teamsAdmissionKey(convId), async () => {
@@ -1470,10 +1696,30 @@ function registerBotHandlers(app, label) {
1470
1696
  reportTeamsRequest("duplicate_held", convId, requestContext, { receiptId: admission.receiptId, outcome: "not_replayed" });
1471
1697
  return;
1472
1698
  }
1699
+ // Written before the turn, so a process that dies mid-turn leaves it for the next one to answer or fail.
1700
+ try {
1701
+ const journal = teamsInboundJournal();
1702
+ journal.record(admission.receiptId, {
1703
+ label, activityId: activity.id, conversationId: convId, conversationType: activity.conversation?.conversationType,
1704
+ text, replyToId: activity.replyToId, userId, aadObjectId: activity.from?.aadObjectId,
1705
+ tenantId: activity.conversation?.tenantId, displayName: activity.from?.name, channelId: String(channelId),
1706
+ attachments: activity.attachments,
1707
+ });
1708
+ inboundId = admission.receiptId;
1709
+ turnInbound = (0, teams_inbound_1.teamsTurnInbound)(() => journal, inboundId);
1710
+ }
1711
+ catch (error) {
1712
+ // The admission already holds Teams' redelivery, so the message is answered now rather than lost; only a
1713
+ // crash during this turn goes unrecorded.
1714
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.teams_inbound_record_failed",
1715
+ message: "could not journal an admitted Teams message; answering it without crash recovery",
1716
+ meta: { conversationId: convId, inboundActivityId: activity.id, error: String(error) } });
1717
+ }
1473
1718
  }
1474
1719
  reportTeamsRequest("admitted", convId, requestContext);
1475
1720
  }
1476
1721
  catch (error) {
1722
+ settleUnfinished(error);
1477
1723
  reportTeamsRequest("failed", convId, requestContext, { reason: "activity_admission_failed" });
1478
1724
  (0, runtime_1.emitNervesEvent)({
1479
1725
  level: "error", component: "channels", event: "channel.activity_admission_error",
@@ -1484,128 +1730,55 @@ function registerBotHandlers(app, label) {
1484
1730
  }
1485
1731
  const commandRegistry = createTeamsCommandRegistry();
1486
1732
  const parsedSlashCommand = (0, commands_1.parseSlashCommand)(text);
1733
+ // A command that throws, such as /new while a turn holds the session, has failed; it is never replayed.
1487
1734
  if (parsedSlashCommand) {
1488
- const dispatchResult = commandRegistry.dispatch(parsedSlashCommand.command, { channel: "teams" });
1489
- if (dispatchResult.handled && dispatchResult.result) {
1490
- if (dispatchResult.result.action === "response") {
1491
- await stream.emit(dispatchResult.result.message || "");
1492
- return;
1493
- }
1494
- if (dispatchResult.result.action === "new") {
1495
- const commandStore = getFriendStore();
1496
- const commandProvider = activity.from?.aadObjectId ? "aad" : "teams-conversation";
1497
- const commandExternalId = activity.from?.aadObjectId || convId;
1498
- const commandResolver = new friends_1.FriendResolver(commandStore, {
1499
- provider: commandProvider,
1500
- externalId: commandExternalId,
1501
- tenantId: activity.conversation?.tenantId,
1502
- displayName: activity.from?.name || "Unknown",
1503
- channel: "teams",
1504
- });
1505
- const commandContext = await commandResolver.resolve();
1506
- (0, context_1.deleteSession)((0, config_2.sessionPath)(commandContext.friend.id, "teams", convId));
1507
- await stream.emit("session cleared");
1508
- if (_turnCoordinator.isTurnActive(turnKey)) {
1509
- _turnCoordinator.enqueueFollowUp(turnKey, {
1510
- conversationId: convId,
1511
- text,
1512
- receivedAt: Date.now(),
1513
- effect: "clear_and_supersede",
1735
+ try {
1736
+ const dispatchResult = commandRegistry.dispatch(parsedSlashCommand.command, { channel: "teams" });
1737
+ if (dispatchResult.handled && dispatchResult.result) {
1738
+ if (dispatchResult.result.action === "response") {
1739
+ await stream.emit(dispatchResult.result.message || "");
1740
+ await turnInbound.finish();
1741
+ return;
1742
+ }
1743
+ if (dispatchResult.result.action === "new") {
1744
+ const commandStore = getFriendStore();
1745
+ const commandProvider = activity.from?.aadObjectId ? "aad" : "teams-conversation";
1746
+ const commandExternalId = activity.from?.aadObjectId || convId;
1747
+ const commandResolver = new friends_1.FriendResolver(commandStore, {
1748
+ provider: commandProvider,
1749
+ externalId: commandExternalId,
1750
+ tenantId: activity.conversation?.tenantId,
1751
+ displayName: activity.from?.name || "Unknown",
1752
+ channel: "teams",
1514
1753
  });
1754
+ const commandContext = await commandResolver.resolve();
1755
+ (0, context_1.deleteSession)((0, config_2.sessionPath)(commandContext.friend.id, "teams", convId));
1756
+ await stream.emit("session cleared");
1757
+ await turnInbound.finish();
1758
+ if (_turnCoordinator.isTurnActive(turnKey)) {
1759
+ _turnCoordinator.enqueueFollowUp(turnKey, {
1760
+ conversationId: convId,
1761
+ text,
1762
+ receivedAt: Date.now(),
1763
+ effect: "clear_and_supersede",
1764
+ });
1765
+ }
1766
+ return;
1515
1767
  }
1516
- return;
1517
1768
  }
1518
1769
  }
1770
+ catch (error) {
1771
+ settleUnfinished(error);
1772
+ throw error;
1773
+ }
1519
1774
  }
1520
1775
  work = coordinateTeamsTurn(convId, text, {
1521
1776
  aadObjectId: activity.from?.aadObjectId, userId, tenantId: activity.conversation?.tenantId,
1522
- replyToId: activity.replyToId,
1523
- }, async () => {
1524
- try {
1525
- // Resolve OAuth connection names for this user's tenant (supports per-tenant overrides).
1526
- const tenantId = activity.conversation?.tenantId;
1527
- const tenantOAuth = (0, config_1.resolveOAuthForTenant)(tenantId);
1528
- // Fetch tokens for both OAuth connections independently.
1529
- // Failures are silently caught -- the tool handler will request signin if needed.
1530
- let graphToken;
1531
- let adoToken;
1532
- let githubToken;
1533
- try {
1534
- const graphRes = await api.users.token.get({ userId, connectionName: tenantOAuth.graphConnectionName, channelId });
1535
- graphToken = graphRes?.token;
1536
- }
1537
- catch { /* no token yet — tool handler will trigger signin */ }
1538
- try {
1539
- const adoRes = await api.users.token.get({ userId, connectionName: tenantOAuth.adoConnectionName, channelId });
1540
- adoToken = adoRes?.token;
1541
- }
1542
- catch { /* no token yet — tool handler will trigger signin */ }
1543
- try {
1544
- const githubRes = await api.users.token.get({ userId, connectionName: tenantOAuth.githubConnectionName, channelId });
1545
- githubToken = githubRes?.token;
1546
- }
1547
- catch { /* no token yet — tool handler will trigger signin */ }
1548
- (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.token_status", component: "channels", message: "oauth token availability", meta: { graph: !!graphToken, ado: !!adoToken, github: !!githubToken, tenantId } });
1549
- const unavailableEntries = [["graph", tenantOAuth.graphConnectionName], ["ado", tenantOAuth.adoConnectionName], ["github", tenantOAuth.githubConnectionName]]
1550
- .map(([service, cn]) => [service, oauthSigninUnavailableReason(cn)])
1551
- .filter((entry) => entry[1] !== undefined);
1552
- const oauthUnavailable = unavailableEntries.length > 0 ? Object.fromEntries(unavailableEntries) : undefined;
1553
- const teamsContext = {
1554
- inboundActivityId: activity.id,
1555
- replyToId: activity.replyToId,
1556
- isGroupChat: teamsIsGroupChat(activity.conversation?.conversationType),
1557
- quotedReply: parseTeamsQuotedReply(activity.attachments, { botId: activity.recipient?.id ?? app.id, userId }),
1558
- graphToken,
1559
- adoToken,
1560
- githubToken,
1561
- ...(oauthUnavailable ? { oauthUnavailable } : {}),
1562
- signin: async (cn) => {
1563
- // Already known not to start: don't send the person another card that can't appear.
1564
- if (oauthSigninUnavailableReason(cn))
1565
- return undefined;
1566
- try {
1567
- const result = await signin({ connectionName: cn });
1568
- (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.signin_result", component: "channels", message: `signin(${cn}): ${result ? "token received" : "no token"}`, meta: { connectionName: cn, hasToken: !!result } });
1569
- return result;
1570
- }
1571
- catch (e) {
1572
- const msg = e instanceof Error ? e.message : String(e);
1573
- (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.signin_error", component: "channels", message: `signin(${cn}) failed`, meta: { connectionName: cn, reason: msg.slice(0, 100) } });
1574
- const reason = recordOAuthSigninFailure(cn, e);
1575
- const service = Object.entries(tenantOAuth).find(([, name]) => name === cn)?.[0]?.replace(/ConnectionName$/, "") ?? cn;
1576
- try {
1577
- await sendText(oauthSigninUnavailableNotice(service, reason));
1578
- }
1579
- catch { /* the failure is already logged */ }
1580
- return undefined;
1581
- }
1582
- },
1583
- aadObjectId: activity.from?.aadObjectId,
1584
- tenantId: activity.conversation?.tenantId,
1585
- displayName: activity.from?.name,
1586
- graphConnectionName: tenantOAuth.graphConnectionName,
1587
- adoConnectionName: tenantOAuth.adoConnectionName,
1588
- githubConnectionName: tenantOAuth.githubConnectionName,
1589
- /* v8 ignore next -- bot API availability branch; requires live SDK context @preserve */
1590
- botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
1591
- teamsSendImage: (0, teams_image_1.createTeamsImageSender)((message) => ctx.send(message), activity.id, aiLabelEntities()),
1592
- };
1593
- const agentName = (0, identity_1.getAgentName)();
1594
- const inboundText = await (0, teams_attachments_1.teamsInboundText)(text, {
1595
- agentName,
1596
- agentRoot: (0, identity_1.getAgentRoot)(agentName),
1597
- attachments: activity.attachments,
1598
- /* v8 ignore next -- live SDK token manager; ingestTeamsAttachments tests cover the token use @preserve */
1599
- getBotToken: async () => (await app.tokenManager.getBotToken())?.toString(),
1600
- });
1601
- await handleTeamsMessage(inboundText, stream, convId, teamsContext, sendText);
1602
- }
1603
- catch (err) {
1604
- reportTeamsRequest("failed", convId, requestContext, { reason: "handler_failed" });
1605
- const msg = err instanceof Error ? err.message : String(err);
1606
- (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.handler_error", component: "channels", message: msg.slice(0, 200), meta: { conversationId: convId, inboundActivityId: activity.id, botId: app.id } });
1607
- }
1608
- });
1777
+ replyToId: activity.replyToId, inboundId,
1778
+ }, () => runAdmittedTeamsMessage({
1779
+ activity, api, signin, send: value => ctx.send(value), text, convId, userId, channelId, sendText, stream,
1780
+ requestContext, inbound: turnInbound, inboundId,
1781
+ }));
1609
1782
  });
1610
1783
  await work;
1611
1784
  });
@@ -1613,6 +1786,58 @@ function registerBotHandlers(app, label) {
1613
1786
  const msg = error instanceof Error ? error.message : String(error);
1614
1787
  (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.app_error", component: "channels", message: `[${label}] ${msg}`, meta: { botId: app.id, label } });
1615
1788
  });
1789
+ // Messages a dead process admitted but never answered: each is answered with a proactive send into its own
1790
+ // conversation, or, when part of a reply already went out or its tries are used up, recorded as failed.
1791
+ const replayPending = async () => {
1792
+ try {
1793
+ const journal = teamsInboundJournal();
1794
+ for (const entry of journal.pending()) {
1795
+ if (entry.payload.label !== label)
1796
+ continue;
1797
+ const decision = (0, teams_inbound_1.teamsReplayDecision)(entry, isTeamsCommand);
1798
+ if (decision.action === "fail") {
1799
+ journal.settle(entry.id, "failed", decision.detail);
1800
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.teams_inbound_not_replayed",
1801
+ message: "recorded a Teams message whose turn never finished as failed instead of running it again",
1802
+ meta: { inboundActivityId: entry.payload.activityId, conversationId: entry.payload.conversationId, attempts: entry.attempts, detail: decision.detail } });
1803
+ continue;
1804
+ }
1805
+ const payload = entry.payload;
1806
+ const convId = payload.conversationId;
1807
+ const activity = {
1808
+ id: payload.activityId, text: payload.text, replyToId: payload.replyToId, channelId: payload.channelId,
1809
+ attachments: payload.attachments,
1810
+ conversation: { id: convId, tenantId: payload.tenantId, conversationType: payload.conversationType },
1811
+ from: { id: payload.userId, aadObjectId: payload.aadObjectId, name: payload.displayName },
1812
+ recipient: { id: app.id },
1813
+ };
1814
+ const requestContext = {
1815
+ inboundActivityId: payload.activityId, tenantId: payload.tenantId,
1816
+ // A replay sends with app.send, which already needs the app's id.
1817
+ botApi: { id: app.id, conversations: app.api.conversations },
1818
+ };
1819
+ const inbound = (0, teams_inbound_1.teamsTurnInbound)(() => journal, entry.id);
1820
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1821
+ const send = (value) => app.send(convId, value);
1822
+ const { sendText, stream } = teamsReplyTransport(send, payload.activityId, convId, requestContext, () => inbound);
1823
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.teams_inbound_replayed",
1824
+ message: "answering a Teams message whose turn a dead process never finished",
1825
+ meta: { inboundActivityId: payload.activityId, conversationId: convId, attempts: entry.attempts } });
1826
+ await coordinateTeamsTurn(convId, payload.text, {
1827
+ aadObjectId: payload.aadObjectId, userId: payload.userId, tenantId: payload.tenantId, replyToId: payload.replyToId, inboundId: entry.id,
1828
+ }, () => runAdmittedTeamsMessage({
1829
+ activity, api: app.api, send, text: payload.text, convId, userId: payload.userId,
1830
+ channelId: payload.channelId, sendText, stream, requestContext, inbound, inboundId: entry.id, replay: true,
1831
+ }));
1832
+ }
1833
+ }
1834
+ catch (error) {
1835
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.teams_inbound_replay_failed",
1836
+ message: "could not finish answering Teams messages a dead process left; the next start tries again",
1837
+ meta: { label, error: String(error) } });
1838
+ }
1839
+ };
1840
+ return { replayPending };
1616
1841
  }
1617
1842
  function findAadObjectId(friend) {
1618
1843
  for (const ext of friend.externalIds) {
@@ -1910,7 +2135,7 @@ async function drainAndSendPendingTeams(store, botApi, pendingRoot) {
1910
2135
  function startTeamsApp() {
1911
2136
  const teamsConfig = (0, config_2.getTeamsConfig)();
1912
2137
  const { app, mode } = createBotApp(teamsConfig);
1913
- registerBotHandlers(app, "primary");
2138
+ const primary = registerBotHandlers(app, "primary");
1914
2139
  if (!process.listeners("unhandledRejection").some((l) => l.__agentHandler)) {
1915
2140
  const handler = (err) => {
1916
2141
  const msg = err instanceof Error ? err.message : String(err);
@@ -1926,6 +2151,7 @@ function startTeamsApp() {
1926
2151
  const startupTools = (0, tools_1.getToolsForChannel)((0, friends_1.getChannelCapabilities)("teams"));
1927
2152
  const toolNames = startupTools.map((t) => t.function.name);
1928
2153
  (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.app_started", component: "channels", message: `Teams bot started on port ${port} with ${mode} (chunked streaming)`, meta: { port, mode, toolCount: toolNames.length, hasProactive: toolNames.includes("teams_send_message") } });
2154
+ void primary.replayPending();
1929
2155
  // --- Secondary bot (dual-bot support) ---
1930
2156
  // If teamsSecondary has a clientId, start a second App on an internal port
1931
2157
  // and proxy /api/messages-secondary on the primary app to it.
@@ -1933,8 +2159,9 @@ function startTeamsApp() {
1933
2159
  const secondaryConfig = (0, config_1.getTeamsSecondaryConfig)();
1934
2160
  if (secondaryConfig.clientId) {
1935
2161
  const { app: secondaryApp, mode: secondaryMode } = createBotApp(secondaryConfig);
1936
- registerBotHandlers(secondaryApp, "secondary");
2162
+ const secondary = registerBotHandlers(secondaryApp, "secondary");
1937
2163
  secondaryApp.start(SECONDARY_INTERNAL_PORT);
2164
+ void secondary.replayPending();
1938
2165
  (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.app_started", component: "channels", message: `Secondary bot started on internal port ${SECONDARY_INTERNAL_PORT} with ${secondaryMode}`, meta: { port: SECONDARY_INTERNAL_PORT, mode: secondaryMode } });
1939
2166
  // Proxy: forward /api/messages-secondary on the primary app's Express
1940
2167
  // to localhost:SECONDARY_INTERNAL_PORT/api/messages.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1427",
3
+ "version": "0.1.0-alpha.1429",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1427",
9
+ "version": "0.1.0-alpha.1429",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1427",
3
+ "version": "0.1.0-alpha.1429",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {