@ouro.bot/cli 0.1.0-alpha.5 → 0.1.0-alpha.50

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 (102) 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 +242 -0
  7. package/dist/heart/active-work.js +157 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/config.js +81 -8
  12. package/dist/heart/core.js +145 -50
  13. package/dist/heart/daemon/agent-discovery.js +81 -0
  14. package/dist/heart/daemon/daemon-cli.js +1099 -164
  15. package/dist/heart/daemon/daemon-entry.js +14 -5
  16. package/dist/heart/daemon/daemon-runtime-sync.js +90 -0
  17. package/dist/heart/daemon/daemon.js +184 -9
  18. package/dist/heart/daemon/hatch-animation.js +10 -3
  19. package/dist/heart/daemon/hatch-flow.js +3 -20
  20. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  21. package/dist/heart/daemon/launchd.js +151 -0
  22. package/dist/heart/daemon/message-router.js +15 -6
  23. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  24. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  25. package/dist/heart/daemon/ouro-entry.js +0 -0
  26. package/dist/heart/daemon/ouro-path-installer.js +178 -0
  27. package/dist/heart/daemon/ouro-uti.js +11 -2
  28. package/dist/heart/daemon/process-manager.js +1 -1
  29. package/dist/heart/daemon/run-hooks.js +37 -0
  30. package/dist/heart/daemon/runtime-metadata.js +118 -0
  31. package/dist/heart/daemon/sense-manager.js +290 -0
  32. package/dist/heart/daemon/socket-client.js +202 -0
  33. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  34. package/dist/heart/daemon/specialist-prompt.js +64 -5
  35. package/dist/heart/daemon/specialist-tools.js +213 -58
  36. package/dist/heart/daemon/staged-restart.js +114 -0
  37. package/dist/heart/daemon/subagent-installer.js +48 -7
  38. package/dist/heart/daemon/thoughts.js +379 -0
  39. package/dist/heart/daemon/update-checker.js +111 -0
  40. package/dist/heart/daemon/update-hooks.js +138 -0
  41. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  42. package/dist/heart/delegation.js +62 -0
  43. package/dist/heart/identity.js +82 -4
  44. package/dist/heart/kicks.js +1 -19
  45. package/dist/heart/progress-story.js +42 -0
  46. package/dist/heart/providers/anthropic.js +16 -2
  47. package/dist/heart/sense-truth.js +61 -0
  48. package/dist/heart/session-activity.js +169 -0
  49. package/dist/heart/session-recall.js +116 -0
  50. package/dist/heart/streaming.js +96 -21
  51. package/dist/heart/turn-coordinator.js +28 -0
  52. package/dist/mind/associative-recall.js +14 -2
  53. package/dist/mind/bundle-manifest.js +70 -0
  54. package/dist/mind/context.js +27 -11
  55. package/dist/mind/first-impressions.js +16 -2
  56. package/dist/mind/friends/channel.js +43 -0
  57. package/dist/mind/friends/store-file.js +19 -0
  58. package/dist/mind/friends/types.js +9 -1
  59. package/dist/mind/memory.js +10 -3
  60. package/dist/mind/pending.js +72 -9
  61. package/dist/mind/phrases.js +1 -0
  62. package/dist/mind/prompt.js +266 -77
  63. package/dist/mind/token-estimate.js +8 -12
  64. package/dist/nerves/cli-logging.js +15 -2
  65. package/dist/repertoire/ado-client.js +4 -2
  66. package/dist/repertoire/coding/feedback.js +134 -0
  67. package/dist/repertoire/coding/index.js +4 -1
  68. package/dist/repertoire/coding/manager.js +62 -4
  69. package/dist/repertoire/coding/spawner.js +3 -3
  70. package/dist/repertoire/coding/tools.js +41 -2
  71. package/dist/repertoire/data/ado-endpoints.json +188 -0
  72. package/dist/repertoire/tasks/board.js +12 -0
  73. package/dist/repertoire/tasks/index.js +23 -9
  74. package/dist/repertoire/tasks/transitions.js +1 -2
  75. package/dist/repertoire/tools-base.js +462 -245
  76. package/dist/repertoire/tools-bluebubbles.js +93 -0
  77. package/dist/repertoire/tools-teams.js +58 -25
  78. package/dist/repertoire/tools.js +57 -35
  79. package/dist/senses/bluebubbles-client.js +484 -0
  80. package/dist/senses/bluebubbles-entry.js +13 -0
  81. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  82. package/dist/senses/bluebubbles-media.js +338 -0
  83. package/dist/senses/bluebubbles-model.js +261 -0
  84. package/dist/senses/bluebubbles-mutation-log.js +116 -0
  85. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  86. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  87. package/dist/senses/bluebubbles.js +1142 -0
  88. package/dist/senses/cli.js +340 -138
  89. package/dist/senses/continuity.js +94 -0
  90. package/dist/senses/debug-activity.js +148 -0
  91. package/dist/senses/inner-dialog-worker.js +47 -18
  92. package/dist/senses/inner-dialog.js +330 -84
  93. package/dist/senses/pipeline.js +256 -0
  94. package/dist/senses/teams.js +541 -129
  95. package/dist/senses/trust-gate.js +112 -2
  96. package/package.json +14 -3
  97. package/subagents/README.md +46 -33
  98. package/subagents/work-doer.md +28 -24
  99. package/subagents/work-merger.md +24 -30
  100. package/subagents/work-planner.md +44 -27
  101. package/dist/heart/daemon/specialist-session.js +0 -142
  102. package/dist/inner-worker-entry.js +0 -4
@@ -40,10 +40,14 @@ exports.createTeamsCallbacks = createTeamsCallbacks;
40
40
  exports.resolvePendingConfirmation = resolvePendingConfirmation;
41
41
  exports.withConversationLock = withConversationLock;
42
42
  exports.handleTeamsMessage = handleTeamsMessage;
43
+ exports.drainAndSendPendingTeams = drainAndSendPendingTeams;
43
44
  exports.startTeamsApp = startTeamsApp;
45
+ const fs = __importStar(require("fs"));
44
46
  const teams_apps_1 = require("@microsoft/teams.apps");
45
47
  const teams_dev_1 = require("@microsoft/teams.dev");
46
48
  const core_1 = require("../heart/core");
49
+ const tools_1 = require("../repertoire/tools");
50
+ const channel_1 = require("../mind/friends/channel");
47
51
  const config_1 = require("../heart/config");
48
52
  const prompt_1 = require("../mind/prompt");
49
53
  const phrases_1 = require("../mind/phrases");
@@ -54,12 +58,18 @@ const commands_1 = require("./commands");
54
58
  const nerves_1 = require("../nerves");
55
59
  const runtime_1 = require("../nerves/runtime");
56
60
  const store_file_1 = require("../mind/friends/store-file");
61
+ const types_1 = require("../mind/friends/types");
57
62
  const resolver_1 = require("../mind/friends/resolver");
58
63
  const tokens_1 = require("../mind/friends/tokens");
59
64
  const turn_coordinator_1 = require("../heart/turn-coordinator");
60
65
  const identity_1 = require("../heart/identity");
66
+ const progress_story_1 = require("../heart/progress-story");
67
+ const http = __importStar(require("http"));
61
68
  const path = __importStar(require("path"));
62
69
  const trust_gate_1 = require("./trust-gate");
70
+ const pipeline_1 = require("./pipeline");
71
+ const pending_1 = require("../mind/pending");
72
+ const continuity_1 = require("./continuity");
63
73
  // Strip @mention markup from incoming messages.
64
74
  // Removes <at>...</at> tags and trims extra whitespace.
65
75
  // Fallback safety net -- the SDK's activity.mentions.stripText should handle
@@ -317,14 +327,29 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
317
327
  onToolStart: (name, args) => {
318
328
  stopPhraseRotation();
319
329
  flushTextBuffer();
320
- const argSummary = Object.values(args).join(", ");
321
- safeUpdate(`running ${name} (${argSummary})...`);
330
+ // Emit a placeholder to satisfy the 15s Copilot timeout for initial
331
+ // stream.emit(). Without this, long tool chains (e.g. ADO batch ops)
332
+ // never emit before the timeout and the user sees "this response was
333
+ // stopped". The placeholder is replaced by actual content on next emit.
334
+ // https://learn.microsoft.com/en-us/answers/questions/2288017/m365-custom-engine-agents-timeout-message-after-15
335
+ if (!streamHasContent)
336
+ safeEmit("⏳");
337
+ const argSummary = (0, tools_1.summarizeArgs)(name, args) || Object.keys(args).join(", ");
338
+ safeUpdate((0, progress_story_1.renderProgressStory)((0, progress_story_1.buildProgressStory)({
339
+ scope: "shared-work",
340
+ phase: "processing",
341
+ objective: `running ${name} (${argSummary})...`,
342
+ })));
322
343
  hadToolRun = true;
323
344
  },
324
345
  onToolEnd: (name, summary, success) => {
325
346
  stopPhraseRotation();
326
347
  const msg = (0, format_1.formatToolResult)(name, summary, success);
327
- safeUpdate(msg);
348
+ safeUpdate((0, progress_story_1.renderProgressStory)((0, progress_story_1.buildProgressStory)({
349
+ scope: "shared-work",
350
+ phase: "processing",
351
+ objective: msg,
352
+ })));
328
353
  },
329
354
  onKick: () => {
330
355
  stopPhraseRotation();
@@ -335,7 +360,11 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
335
360
  stopPhraseRotation();
336
361
  if (stopped)
337
362
  return;
338
- const msg = (0, format_1.formatError)(error);
363
+ const msg = (0, progress_story_1.renderProgressStory)((0, progress_story_1.buildProgressStory)({
364
+ scope: "shared-work",
365
+ phase: "errored",
366
+ outcomeText: (0, format_1.formatError)(error),
367
+ }));
339
368
  if (severity === "transient") {
340
369
  safeUpdate(msg);
341
370
  }
@@ -424,6 +453,34 @@ function getFriendStore() {
424
453
  const friendsPath = path.join((0, identity_1.getAgentRoot)(), "friends");
425
454
  return new store_file_1.FileFriendStore(friendsPath);
426
455
  }
456
+ function createTeamsCommandRegistry() {
457
+ const registry = (0, commands_1.createCommandRegistry)();
458
+ (0, commands_1.registerDefaultCommands)(registry);
459
+ return registry;
460
+ }
461
+ function handleTeamsSlashCommand(text, registry, friendId, conversationId, stream, emitResponse = true) {
462
+ const parsed = (0, commands_1.parseSlashCommand)(text);
463
+ if (!parsed)
464
+ return null;
465
+ const dispatchResult = registry.dispatch(parsed.command, { channel: "teams" });
466
+ if (!dispatchResult.handled || !dispatchResult.result) {
467
+ return null;
468
+ }
469
+ if (dispatchResult.result.action === "new") {
470
+ (0, context_1.deleteSession)((0, config_2.sessionPath)(friendId, "teams", conversationId));
471
+ if (emitResponse) {
472
+ stream.emit("session cleared");
473
+ }
474
+ return "new";
475
+ }
476
+ if (dispatchResult.result.action === "response") {
477
+ if (emitResponse) {
478
+ stream.emit(dispatchResult.result.message || "");
479
+ }
480
+ return "response";
481
+ }
482
+ return null;
483
+ }
427
484
  // Handle an incoming Teams message
428
485
  async function handleTeamsMessage(text, stream, conversationId, teamsContext, sendMessage) {
429
486
  const turnKey = teamsTurnKey(conversationId);
@@ -434,148 +491,227 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
434
491
  // before sync I/O (session load, trim) blocks the event loop.
435
492
  stream.update((0, phrases_1.pickPhrase)((0, phrases_1.getPhrases)().thinking) + "...");
436
493
  await new Promise(r => setImmediate(r));
437
- // Resolve context kernel (identity + channel) early so we can use the friend UUID for session path
494
+ // Resolve identity provider early for friend resolution + slash command session path
438
495
  const store = getFriendStore();
439
496
  const provider = teamsContext?.aadObjectId ? "aad" : "teams-conversation";
440
497
  const externalId = teamsContext?.aadObjectId || conversationId;
441
- const toolContext = teamsContext ? {
498
+ // Build FriendResolver for the pipeline
499
+ const resolver = new resolver_1.FriendResolver(store, {
500
+ provider,
501
+ externalId,
502
+ tenantId: teamsContext?.tenantId,
503
+ displayName: teamsContext?.displayName || "Unknown",
504
+ channel: "teams",
505
+ });
506
+ // Pre-resolve friend for session path + slash commands (pipeline will re-use the cached result)
507
+ const resolvedContext = await resolver.resolve();
508
+ const friendId = resolvedContext.friend.id;
509
+ const registry = createTeamsCommandRegistry();
510
+ // Check for slash commands (before pipeline -- these are transport-level concerns)
511
+ if (handleTeamsSlashCommand(text, registry, friendId, conversationId, stream)) {
512
+ return;
513
+ }
514
+ // ── Teams adapter concerns: controller, callbacks, session path ──────────
515
+ const controller = new AbortController();
516
+ const channelConfig = (0, config_2.getTeamsChannelConfig)();
517
+ const callbacks = createTeamsCallbacks(stream, controller, sendMessage, { conversationId, flushIntervalMs: channelConfig.flushIntervalMs });
518
+ const traceId = (0, nerves_1.createTraceId)();
519
+ const sessPath = (0, config_2.sessionPath)(friendId, "teams", conversationId);
520
+ const teamsCapabilities = (0, channel_1.getChannelCapabilities)("teams");
521
+ const pendingDir = (0, pending_1.getPendingDir)((0, identity_1.getAgentName)(), friendId, "teams", conversationId);
522
+ // Build Teams-specific toolContext fields for injection into the pipeline
523
+ const teamsToolContext = teamsContext ? {
442
524
  graphToken: teamsContext.graphToken,
443
525
  adoToken: teamsContext.adoToken,
444
526
  githubToken: teamsContext.githubToken,
445
527
  signin: teamsContext.signin,
446
- friendStore: store,
447
528
  summarize: (0, core_1.createSummarize)(),
448
- } : undefined;
449
- if (toolContext) {
450
- const resolver = new resolver_1.FriendResolver(store, {
451
- provider,
452
- externalId,
453
- tenantId: teamsContext?.tenantId,
454
- displayName: teamsContext?.displayName || "Unknown",
529
+ tenantId: teamsContext.tenantId,
530
+ botApi: teamsContext.botApi,
531
+ } : {};
532
+ let currentText = text;
533
+ while (true) {
534
+ let drainedSteeringFollowUps = [];
535
+ // Build runAgentOptions with Teams-specific fields
536
+ const agentOptions = {
537
+ traceId,
538
+ toolContext: teamsToolContext,
539
+ drainSteeringFollowUps: () => {
540
+ drainedSteeringFollowUps = _turnCoordinator.drainFollowUps(turnKey)
541
+ .map(({ text: followUpText, effect }) => ({ text: followUpText, effect }));
542
+ return drainedSteeringFollowUps;
543
+ },
544
+ };
545
+ if (channelConfig.skipConfirmation)
546
+ agentOptions.skipConfirmation = true;
547
+ // ── Call shared pipeline ──────────────────────────────────────────
548
+ const result = await (0, pipeline_1.handleInboundTurn)({
455
549
  channel: "teams",
456
- });
457
- toolContext.context = await resolver.resolve();
458
- }
459
- const friendId = toolContext?.context?.friend?.id || "default";
460
- if (toolContext?.context?.friend) {
461
- const trustGate = (0, trust_gate_1.enforceTrustGate)({
462
- friend: toolContext.context.friend,
550
+ sessionKey: conversationId,
551
+ capabilities: teamsCapabilities,
552
+ messages: [{ role: "user", content: currentText }],
553
+ continuityIngressTexts: [currentText],
554
+ callbacks,
555
+ friendResolver: { resolve: () => Promise.resolve(resolvedContext) },
556
+ sessionLoader: {
557
+ loadOrCreate: async () => {
558
+ const existing = (0, context_1.loadSession)(sessPath);
559
+ const messages = existing?.messages && existing.messages.length > 0
560
+ ? existing.messages
561
+ : [{ role: "system", content: await (0, prompt_1.buildSystem)("teams", undefined, resolvedContext) }];
562
+ (0, core_1.repairOrphanedToolCalls)(messages);
563
+ return { messages, sessionPath: sessPath, state: existing?.state };
564
+ },
565
+ },
566
+ pendingDir,
567
+ friendStore: store,
463
568
  provider,
464
569
  externalId,
465
570
  tenantId: teamsContext?.tenantId,
466
- channel: "teams",
571
+ isGroupChat: false,
572
+ groupHasFamilyMember: false,
573
+ hasExistingGroupWithFamily: false,
574
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
575
+ drainPending: pending_1.drainPending,
576
+ drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)((0, identity_1.getAgentName)(), deferredFriendId),
577
+ runAgent: (msgs, cb, channel, sig, opts) => (0, core_1.runAgent)(msgs, cb, channel, sig, {
578
+ ...opts,
579
+ toolContext: {
580
+ /* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
581
+ signin: async () => undefined,
582
+ ...opts?.toolContext,
583
+ summarize: teamsToolContext.summarize,
584
+ },
585
+ }),
586
+ postTurn: context_1.postTurn,
587
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
588
+ signal: controller.signal,
589
+ runAgentOptions: agentOptions,
467
590
  });
468
- if (!trustGate.allowed) {
469
- if (trustGate.reason === "stranger_first_reply") {
470
- stream.emit(trustGate.autoReply);
591
+ // ── Handle gate result ────────────────────────────────────────
592
+ if (!result.gateResult.allowed) {
593
+ if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
594
+ stream.emit(result.gateResult.autoReply);
471
595
  }
472
596
  return;
473
597
  }
598
+ // Flush any remaining accumulated text at end of turn
599
+ await callbacks.flush();
600
+ // After the agent loop, check if any tool returned AUTH_REQUIRED and trigger signin.
601
+ // This must happen after the stream is done so the OAuth card renders properly.
602
+ if (teamsContext && result.messages) {
603
+ const allContent = result.messages.map(m => typeof m.content === "string" ? m.content : "").join("\n");
604
+ if (allContent.includes("AUTH_REQUIRED:graph") && teamsContext.graphConnectionName)
605
+ await teamsContext.signin(teamsContext.graphConnectionName);
606
+ if (allContent.includes("AUTH_REQUIRED:ado") && teamsContext.adoConnectionName)
607
+ await teamsContext.signin(teamsContext.adoConnectionName);
608
+ if (allContent.includes("AUTH_REQUIRED:github") && teamsContext.githubConnectionName)
609
+ await teamsContext.signin(teamsContext.githubConnectionName);
610
+ }
611
+ if (result.turnOutcome !== "superseded") {
612
+ return;
613
+ }
614
+ const supersedingIndex = drainedSteeringFollowUps
615
+ .map((followUp) => followUp.effect)
616
+ .lastIndexOf("clear_and_supersede");
617
+ if (supersedingIndex < 0) {
618
+ return;
619
+ }
620
+ const supersedingFollowUp = drainedSteeringFollowUps[supersedingIndex];
621
+ const replayTail = drainedSteeringFollowUps
622
+ .slice(supersedingIndex + 1)
623
+ .map((followUp) => followUp.text.trim())
624
+ .filter((followUpText) => followUpText.length > 0)
625
+ .join("\n");
626
+ if (replayTail) {
627
+ currentText = replayTail;
628
+ continue;
629
+ }
630
+ if (handleTeamsSlashCommand(supersedingFollowUp.text, registry, friendId, conversationId, stream, false)) {
631
+ return;
632
+ }
633
+ currentText = supersedingFollowUp.text;
474
634
  }
475
- const registry = (0, commands_1.createCommandRegistry)();
476
- (0, commands_1.registerDefaultCommands)(registry);
477
- // Check for slash commands
478
- const parsed = (0, commands_1.parseSlashCommand)(text);
479
- if (parsed) {
480
- const dispatchResult = registry.dispatch(parsed.command, { channel: "teams" });
481
- if (dispatchResult.handled && dispatchResult.result) {
482
- if (dispatchResult.result.action === "new") {
483
- const sessPath = (0, config_2.sessionPath)(friendId, "teams", conversationId);
484
- (0, context_1.deleteSession)(sessPath);
485
- stream.emit("session cleared");
486
- return;
487
- }
488
- else if (dispatchResult.result.action === "response") {
489
- stream.emit(dispatchResult.result.message || "");
490
- return;
491
- }
635
+ }
636
+ // Internal port for the secondary bot App (not exposed externally).
637
+ // The primary app proxies /api/messages-secondary → localhost:SECONDARY_PORT/api/messages.
638
+ const SECONDARY_INTERNAL_PORT = 3979;
639
+ // Collect all unique OAuth connection names across top-level config and tenant overrides.
640
+ /* v8 ignore start -- runtime Teams SDK config; no unit-testable surface @preserve */
641
+ function allOAuthConnectionNames() {
642
+ const oauthConfig = (0, config_1.getOAuthConfig)();
643
+ const names = new Set();
644
+ if (oauthConfig.graphConnectionName)
645
+ names.add(oauthConfig.graphConnectionName);
646
+ if (oauthConfig.adoConnectionName)
647
+ names.add(oauthConfig.adoConnectionName);
648
+ if (oauthConfig.githubConnectionName)
649
+ names.add(oauthConfig.githubConnectionName);
650
+ if (oauthConfig.tenantOverrides) {
651
+ for (const ov of Object.values(oauthConfig.tenantOverrides)) {
652
+ if (ov.graphConnectionName)
653
+ names.add(ov.graphConnectionName);
654
+ if (ov.adoConnectionName)
655
+ names.add(ov.adoConnectionName);
656
+ if (ov.githubConnectionName)
657
+ names.add(ov.githubConnectionName);
492
658
  }
493
659
  }
494
- // Load or create session
495
- const sessPath = (0, config_2.sessionPath)(friendId, "teams", conversationId);
496
- const existing = (0, context_1.loadSession)(sessPath);
497
- const messages = existing?.messages && existing.messages.length > 0
498
- ? existing.messages
499
- : [{ role: "system", content: await (0, prompt_1.buildSystem)("teams", undefined, toolContext?.context) }];
500
- // Push user message
501
- messages.push({ role: "user", content: text });
502
- // Run agent
503
- const controller = new AbortController();
504
- const channelConfig = (0, config_2.getTeamsChannelConfig)();
505
- const callbacks = createTeamsCallbacks(stream, controller, sendMessage, { conversationId, flushIntervalMs: channelConfig.flushIntervalMs });
506
- const traceId = (0, nerves_1.createTraceId)();
507
- const agentOptions = {};
508
- agentOptions.traceId = traceId;
509
- if (toolContext)
510
- agentOptions.toolContext = toolContext;
511
- if (channelConfig.skipConfirmation)
512
- agentOptions.skipConfirmation = true;
513
- agentOptions.drainSteeringFollowUps = () => _turnCoordinator.drainFollowUps(turnKey).map((m) => ({ text: m.text }));
514
- const result = await (0, core_1.runAgent)(messages, callbacks, "teams", controller.signal, agentOptions);
515
- // Flush any remaining accumulated text at end of turn
516
- await callbacks.flush();
517
- // After the agent loop, check if any tool returned AUTH_REQUIRED and trigger signin.
518
- // This must happen after the stream is done so the OAuth card renders properly.
519
- if (teamsContext) {
520
- const allContent = messages.map(m => typeof m.content === "string" ? m.content : "").join("\n");
521
- if (allContent.includes("AUTH_REQUIRED:graph"))
522
- await teamsContext.signin("graph");
523
- if (allContent.includes("AUTH_REQUIRED:ado"))
524
- await teamsContext.signin("ado");
525
- if (allContent.includes("AUTH_REQUIRED:github"))
526
- await teamsContext.signin("github");
527
- }
528
- // Trim context and save session
529
- (0, context_1.postTurn)(messages, sessPath, result.usage);
530
- // Accumulate token usage on friend record
531
- if (toolContext?.context?.friend?.id) {
532
- await (0, tokens_1.accumulateFriendTokens)(store, toolContext.context.friend.id, result.usage);
533
- }
534
- // SDK auto-closes the stream after our handler returns (app.process.js)
660
+ return [...names];
535
661
  }
536
- // Start the Teams app in DevtoolsPlugin mode (local dev) or Bot Service mode (real Teams).
537
- // Mode is determined by getTeamsConfig().clientId.
538
- // Text is always accumulated in textBuffer and flushed periodically (chunked streaming).
539
- function startTeamsApp() {
662
+ // Create an App instance from a TeamsConfig. Returns { app, mode }.
663
+ function createBotApp(teamsConfig) {
540
664
  const mentionStripping = { activity: { mentions: { stripText: true } } };
541
- const teamsConfig = (0, config_2.getTeamsConfig)();
542
- let app;
543
- let mode;
544
665
  const oauthConfig = (0, config_1.getOAuthConfig)();
545
- if (teamsConfig.clientId) {
546
- // Bot Service mode -- real Teams connection with SingleTenant credentials
547
- app = new teams_apps_1.App({
548
- clientId: teamsConfig.clientId,
549
- clientSecret: teamsConfig.clientSecret,
550
- tenantId: teamsConfig.tenantId,
551
- oauth: { defaultConnectionName: oauthConfig.graphConnectionName },
552
- ...mentionStripping,
553
- });
554
- mode = "Bot Service";
666
+ if (teamsConfig.clientId && teamsConfig.clientSecret) {
667
+ return {
668
+ app: new teams_apps_1.App({
669
+ clientId: teamsConfig.clientId,
670
+ clientSecret: teamsConfig.clientSecret,
671
+ tenantId: teamsConfig.tenantId,
672
+ oauth: { defaultConnectionName: oauthConfig.graphConnectionName },
673
+ ...mentionStripping,
674
+ }),
675
+ mode: "Bot Service (client secret)",
676
+ };
677
+ }
678
+ else if (teamsConfig.clientId) {
679
+ return {
680
+ app: new teams_apps_1.App({
681
+ clientId: teamsConfig.clientId,
682
+ tenantId: teamsConfig.tenantId,
683
+ ...(teamsConfig.managedIdentityClientId ? { managedIdentityClientId: teamsConfig.managedIdentityClientId } : {}),
684
+ oauth: { defaultConnectionName: oauthConfig.graphConnectionName },
685
+ ...mentionStripping,
686
+ }),
687
+ mode: "Bot Service (managed identity)",
688
+ };
555
689
  }
556
690
  else {
557
- // DevtoolsPlugin mode -- local development with Teams DevtoolsPlugin UI
558
- app = new teams_apps_1.App({
559
- plugins: [new teams_dev_1.DevtoolsPlugin()],
560
- ...mentionStripping,
561
- });
562
- mode = "DevtoolsPlugin";
691
+ return {
692
+ app: new teams_apps_1.App({
693
+ plugins: [new teams_dev_1.DevtoolsPlugin()],
694
+ ...mentionStripping,
695
+ }),
696
+ mode: "DevtoolsPlugin",
697
+ };
563
698
  }
699
+ }
700
+ /* v8 ignore stop */
701
+ // Register message, verify-state, and error handlers on an App instance.
702
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
703
+ function registerBotHandlers(app, label) {
704
+ const connectionNames = allOAuthConnectionNames();
564
705
  // Override default OAuth verify-state handler. The SDK's built-in handler
565
706
  // uses a single defaultConnectionName, which breaks multi-connection setups
566
707
  // (graph + ado + github). The verifyState activity only carries a `state`
567
708
  // code with no connectionName, so we try each configured connection until
568
709
  // one succeeds.
569
- const allConnectionNames = [
570
- oauthConfig.graphConnectionName,
571
- oauthConfig.adoConnectionName,
572
- oauthConfig.githubConnectionName,
573
- ].filter(Boolean);
574
710
  app.on("signin.verify-state", async (ctx) => {
575
711
  const { api, activity } = ctx;
576
712
  if (!activity.value?.state)
577
713
  return { status: 404 };
578
- for (const cn of allConnectionNames) {
714
+ for (const cn of connectionNames) {
579
715
  try {
580
716
  await api.users.token.get({
581
717
  channelId: activity.channelId,
@@ -583,12 +719,12 @@ function startTeamsApp() {
583
719
  connectionName: cn,
584
720
  code: activity.value.state,
585
721
  });
586
- (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.verify_state", component: "channels", message: `verify-state succeeded for connection "${cn}"`, meta: { connectionName: cn } });
722
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.verify_state", component: "channels", message: `[${label}] verify-state succeeded for connection "${cn}"`, meta: { connectionName: cn } });
587
723
  return { status: 200 };
588
724
  }
589
725
  catch { /* try next */ }
590
726
  }
591
- (0, runtime_1.emitNervesEvent)({ level: "warn", event: "channel.verify_state", component: "channels", message: "verify-state failed for all connections", meta: {} });
727
+ (0, runtime_1.emitNervesEvent)({ level: "warn", event: "channel.verify_state", component: "channels", message: `[${label}] verify-state failed for all connections`, meta: {} });
592
728
  return { status: 412 };
593
729
  });
594
730
  app.on("message", async (ctx) => {
@@ -598,18 +734,49 @@ function startTeamsApp() {
598
734
  const turnKey = teamsTurnKey(convId);
599
735
  const userId = activity.from?.id || "";
600
736
  const channelId = activity.channelId || "msteams";
601
- (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.message_received", component: "channels", message: "incoming teams message", meta: { userId: userId.slice(0, 12), conversationId: convId.slice(0, 20) } });
737
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.message_received", component: "channels", message: `[${label}] incoming teams message`, meta: { userId: userId.slice(0, 12), conversationId: convId.slice(0, 20) } });
602
738
  // Resolve pending confirmations IMMEDIATELY — before token fetches or
603
739
  // the conversation lock. The original message holds the lock while
604
740
  // awaiting confirmation, so acquiring it here would deadlock. Token
605
741
  // fetches are also unnecessary (and slow) for a simple yes/no reply.
606
742
  if (resolvePendingConfirmation(convId, text)) {
607
- // Don't emit on this stream — the original message's stream is still
608
- // active. Opening a second streaming response in the same conversation
609
- // can corrupt the first. The original stream will show tool progress
610
- // once the confirmation Promise resolves.
611
743
  return;
612
744
  }
745
+ const commandRegistry = createTeamsCommandRegistry();
746
+ const parsedSlashCommand = (0, commands_1.parseSlashCommand)(text);
747
+ if (parsedSlashCommand) {
748
+ const dispatchResult = commandRegistry.dispatch(parsedSlashCommand.command, { channel: "teams" });
749
+ if (dispatchResult.handled && dispatchResult.result) {
750
+ if (dispatchResult.result.action === "response") {
751
+ stream.emit(dispatchResult.result.message || "");
752
+ return;
753
+ }
754
+ if (dispatchResult.result.action === "new") {
755
+ const commandStore = getFriendStore();
756
+ const commandProvider = activity.from?.aadObjectId ? "aad" : "teams-conversation";
757
+ const commandExternalId = activity.from?.aadObjectId || convId;
758
+ const commandResolver = new resolver_1.FriendResolver(commandStore, {
759
+ provider: commandProvider,
760
+ externalId: commandExternalId,
761
+ tenantId: activity.conversation?.tenantId,
762
+ displayName: activity.from?.name || "Unknown",
763
+ channel: "teams",
764
+ });
765
+ const commandContext = await commandResolver.resolve();
766
+ (0, context_1.deleteSession)((0, config_2.sessionPath)(commandContext.friend.id, "teams", convId));
767
+ stream.emit("session cleared");
768
+ if (_turnCoordinator.isTurnActive(turnKey)) {
769
+ _turnCoordinator.enqueueFollowUp(turnKey, {
770
+ conversationId: convId,
771
+ text,
772
+ receivedAt: Date.now(),
773
+ effect: "clear_and_supersede",
774
+ });
775
+ }
776
+ return;
777
+ }
778
+ }
779
+ }
613
780
  // If this conversation already has an active turn, steer follow-up input
614
781
  // into that turn and avoid starting a second concurrent turn.
615
782
  if (!_turnCoordinator.tryBeginTurn(turnKey)) {
@@ -617,31 +784,35 @@ function startTeamsApp() {
617
784
  conversationId: convId,
618
785
  text,
619
786
  receivedAt: Date.now(),
787
+ effect: (0, continuity_1.classifySteeringFollowUpEffect)(text),
620
788
  });
621
789
  return;
622
790
  }
623
791
  try {
792
+ // Resolve OAuth connection names for this user's tenant (supports per-tenant overrides).
793
+ const tenantId = activity.conversation?.tenantId;
794
+ const tenantOAuth = (0, config_1.resolveOAuthForTenant)(tenantId);
624
795
  // Fetch tokens for both OAuth connections independently.
625
796
  // Failures are silently caught -- the tool handler will request signin if needed.
626
797
  let graphToken;
627
798
  let adoToken;
628
799
  let githubToken;
629
800
  try {
630
- const graphRes = await api.users.token.get({ userId, connectionName: oauthConfig.graphConnectionName, channelId });
801
+ const graphRes = await api.users.token.get({ userId, connectionName: tenantOAuth.graphConnectionName, channelId });
631
802
  graphToken = graphRes?.token;
632
803
  }
633
804
  catch { /* no token yet — tool handler will trigger signin */ }
634
805
  try {
635
- const adoRes = await api.users.token.get({ userId, connectionName: oauthConfig.adoConnectionName, channelId });
806
+ const adoRes = await api.users.token.get({ userId, connectionName: tenantOAuth.adoConnectionName, channelId });
636
807
  adoToken = adoRes?.token;
637
808
  }
638
809
  catch { /* no token yet — tool handler will trigger signin */ }
639
810
  try {
640
- const githubRes = await api.users.token.get({ userId, connectionName: oauthConfig.githubConnectionName, channelId });
811
+ const githubRes = await api.users.token.get({ userId, connectionName: tenantOAuth.githubConnectionName, channelId });
641
812
  githubToken = githubRes?.token;
642
813
  }
643
814
  catch { /* no token yet — tool handler will trigger signin */ }
644
- (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.token_status", component: "channels", message: "oauth token availability", meta: { graph: !!graphToken, ado: !!adoToken, github: !!githubToken } });
815
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.token_status", component: "channels", message: "oauth token availability", meta: { graph: !!graphToken, ado: !!adoToken, github: !!githubToken, tenantId } });
645
816
  const teamsContext = {
646
817
  graphToken,
647
818
  adoToken,
@@ -661,6 +832,11 @@ function startTeamsApp() {
661
832
  aadObjectId: activity.from?.aadObjectId,
662
833
  tenantId: activity.conversation?.tenantId,
663
834
  displayName: activity.from?.name,
835
+ graphConnectionName: tenantOAuth.graphConnectionName,
836
+ adoConnectionName: tenantOAuth.adoConnectionName,
837
+ githubConnectionName: tenantOAuth.githubConnectionName,
838
+ /* v8 ignore next -- bot API availability branch; requires live SDK context @preserve */
839
+ botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
664
840
  };
665
841
  /* v8 ignore next 5 -- bot-framework integration callback; tested via handleTeamsMessage sendMessage path @preserve */
666
842
  const ctxSend = async (t) => {
@@ -678,6 +854,199 @@ function startTeamsApp() {
678
854
  _turnCoordinator.endTurn(turnKey);
679
855
  }
680
856
  });
857
+ app.event("error", ({ error }) => {
858
+ const msg = error instanceof Error ? error.message : String(error);
859
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.app_error", component: "channels", message: `[${label}] ${msg}`, meta: {} });
860
+ });
861
+ }
862
+ function findAadObjectId(friend) {
863
+ for (const ext of friend.externalIds) {
864
+ if (ext.provider === "aad" && !ext.externalId.startsWith("group:")) {
865
+ return { aadObjectId: ext.externalId, tenantId: ext.tenantId };
866
+ }
867
+ }
868
+ return undefined;
869
+ }
870
+ function scanPendingTeamsFiles(pendingRoot) {
871
+ const results = [];
872
+ let friendIds;
873
+ try {
874
+ friendIds = fs.readdirSync(pendingRoot);
875
+ }
876
+ catch {
877
+ return results;
878
+ }
879
+ for (const friendId of friendIds) {
880
+ const teamsDir = path.join(pendingRoot, friendId, "teams");
881
+ let keys;
882
+ try {
883
+ keys = fs.readdirSync(teamsDir);
884
+ }
885
+ catch {
886
+ continue;
887
+ }
888
+ for (const key of keys) {
889
+ const keyDir = path.join(teamsDir, key);
890
+ let files;
891
+ try {
892
+ files = fs.readdirSync(keyDir);
893
+ }
894
+ catch {
895
+ continue;
896
+ }
897
+ for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
898
+ const filePath = path.join(keyDir, file);
899
+ try {
900
+ const content = fs.readFileSync(filePath, "utf-8");
901
+ results.push({ friendId, key, filePath, content });
902
+ }
903
+ catch {
904
+ // skip unreadable files
905
+ }
906
+ }
907
+ }
908
+ }
909
+ return results;
910
+ }
911
+ async function drainAndSendPendingTeams(store, botApi, pendingRoot) {
912
+ const root = pendingRoot ?? path.join((0, identity_1.getAgentRoot)(), "state", "pending");
913
+ const pendingFiles = scanPendingTeamsFiles(root);
914
+ const result = { sent: 0, skipped: 0, failed: 0 };
915
+ const conversations = botApi.conversations;
916
+ for (const { friendId, filePath, content } of pendingFiles) {
917
+ let parsed;
918
+ try {
919
+ parsed = JSON.parse(content);
920
+ }
921
+ catch {
922
+ result.failed++;
923
+ try {
924
+ fs.unlinkSync(filePath);
925
+ }
926
+ catch { /* ignore */ }
927
+ continue;
928
+ }
929
+ const messageText = typeof parsed.content === "string" ? parsed.content : "";
930
+ if (!messageText.trim()) {
931
+ result.skipped++;
932
+ try {
933
+ fs.unlinkSync(filePath);
934
+ }
935
+ catch { /* ignore */ }
936
+ continue;
937
+ }
938
+ let friend;
939
+ try {
940
+ friend = await store.get(friendId);
941
+ }
942
+ catch {
943
+ friend = null;
944
+ }
945
+ if (!friend) {
946
+ result.skipped++;
947
+ try {
948
+ fs.unlinkSync(filePath);
949
+ }
950
+ catch { /* ignore */ }
951
+ (0, runtime_1.emitNervesEvent)({
952
+ level: "warn",
953
+ component: "senses",
954
+ event: "senses.teams_proactive_no_friend",
955
+ message: "proactive send skipped: friend not found",
956
+ meta: { friendId },
957
+ });
958
+ continue;
959
+ }
960
+ if (!types_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
961
+ result.skipped++;
962
+ try {
963
+ fs.unlinkSync(filePath);
964
+ }
965
+ catch { /* ignore */ }
966
+ (0, runtime_1.emitNervesEvent)({
967
+ component: "senses",
968
+ event: "senses.teams_proactive_trust_skip",
969
+ message: "proactive send skipped: trust level not allowed",
970
+ meta: { friendId, trustLevel: friend.trustLevel ?? "unknown" },
971
+ });
972
+ continue;
973
+ }
974
+ const aadInfo = findAadObjectId(friend);
975
+ if (!aadInfo) {
976
+ result.skipped++;
977
+ try {
978
+ fs.unlinkSync(filePath);
979
+ }
980
+ catch { /* ignore */ }
981
+ (0, runtime_1.emitNervesEvent)({
982
+ level: "warn",
983
+ component: "senses",
984
+ event: "senses.teams_proactive_no_aad_id",
985
+ message: "proactive send skipped: no AAD object ID found",
986
+ meta: { friendId },
987
+ });
988
+ continue;
989
+ }
990
+ try {
991
+ const conversation = await conversations.create({
992
+ bot: { id: botApi.id },
993
+ members: [{ id: aadInfo.aadObjectId, role: "user", name: friend.name || aadInfo.aadObjectId }],
994
+ tenantId: aadInfo.tenantId,
995
+ isGroup: false,
996
+ });
997
+ await conversations.activities(conversation.id).create({
998
+ type: "message",
999
+ text: messageText,
1000
+ });
1001
+ result.sent++;
1002
+ try {
1003
+ fs.unlinkSync(filePath);
1004
+ }
1005
+ catch { /* ignore */ }
1006
+ (0, runtime_1.emitNervesEvent)({
1007
+ component: "senses",
1008
+ event: "senses.teams_proactive_sent",
1009
+ message: "proactive teams message sent",
1010
+ meta: { friendId, aadObjectId: aadInfo.aadObjectId },
1011
+ });
1012
+ }
1013
+ catch (error) {
1014
+ result.failed++;
1015
+ (0, runtime_1.emitNervesEvent)({
1016
+ level: "error",
1017
+ component: "senses",
1018
+ event: "senses.teams_proactive_send_error",
1019
+ message: "proactive teams send failed",
1020
+ meta: {
1021
+ friendId,
1022
+ aadObjectId: aadInfo.aadObjectId,
1023
+ reason: error instanceof Error ? error.message : String(error),
1024
+ },
1025
+ });
1026
+ }
1027
+ }
1028
+ if (result.sent > 0 || result.skipped > 0 || result.failed > 0) {
1029
+ (0, runtime_1.emitNervesEvent)({
1030
+ component: "senses",
1031
+ event: "senses.teams_proactive_drain_complete",
1032
+ message: "teams proactive drain complete",
1033
+ meta: { sent: result.sent, skipped: result.skipped, failed: result.failed },
1034
+ });
1035
+ }
1036
+ return result;
1037
+ }
1038
+ // Start the Teams app in DevtoolsPlugin mode (local dev) or Bot Service mode (real Teams).
1039
+ // Mode is determined by getTeamsConfig().clientId.
1040
+ // Text is always accumulated in textBuffer and flushed periodically (chunked streaming).
1041
+ //
1042
+ // Dual-bot support: if teamsSecondary is configured with a clientId, a second App
1043
+ // instance starts on an internal port and the primary app proxies requests from
1044
+ // /api/messages-secondary to it. This lets a single App Service serve two bot
1045
+ // registrations (e.g. one per tenant) without SDK modifications.
1046
+ function startTeamsApp() {
1047
+ const teamsConfig = (0, config_2.getTeamsConfig)();
1048
+ const { app, mode } = createBotApp(teamsConfig);
1049
+ registerBotHandlers(app, "primary");
681
1050
  if (!process.listeners("unhandledRejection").some((l) => l.__agentHandler)) {
682
1051
  const handler = (err) => {
683
1052
  const msg = err instanceof Error ? err.message : String(err);
@@ -686,11 +1055,54 @@ function startTeamsApp() {
686
1055
  handler.__agentHandler = true;
687
1056
  process.on("unhandledRejection", handler);
688
1057
  }
689
- app.event("error", ({ error }) => {
690
- const msg = error instanceof Error ? error.message : String(error);
691
- (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.app_error", component: "channels", message: msg, meta: {} });
692
- });
693
- const port = (0, config_2.getTeamsChannelConfig)().port;
1058
+ /* v8 ignore next -- PORT env branch; runtime-only @preserve */
1059
+ const port = process.env.PORT ? Number(process.env.PORT) : (0, config_2.getTeamsChannelConfig)().port;
694
1060
  app.start(port);
695
- (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 } });
1061
+ // Diagnostic: log tool count at startup to verify deploy
1062
+ const startupTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)("teams"));
1063
+ const toolNames = startupTools.map((t) => t.function.name);
1064
+ (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") } });
1065
+ // --- Secondary bot (dual-bot support) ---
1066
+ // If teamsSecondary has a clientId, start a second App on an internal port
1067
+ // and proxy /api/messages-secondary on the primary app to it.
1068
+ /* v8 ignore start -- dual-bot proxy wiring; requires live Teams SDK + HTTP @preserve */
1069
+ const secondaryConfig = (0, config_1.getTeamsSecondaryConfig)();
1070
+ if (secondaryConfig.clientId) {
1071
+ const { app: secondaryApp, mode: secondaryMode } = createBotApp(secondaryConfig);
1072
+ registerBotHandlers(secondaryApp, "secondary");
1073
+ secondaryApp.start(SECONDARY_INTERNAL_PORT);
1074
+ (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 } });
1075
+ // Proxy: forward /api/messages-secondary on the primary app's Express
1076
+ // to localhost:SECONDARY_INTERNAL_PORT/api/messages.
1077
+ // The SDK's HttpPlugin exposes .post() bound to its Express instance.
1078
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1079
+ const httpPlugin = app.http;
1080
+ httpPlugin.post("/api/messages-secondary", (req, res) => {
1081
+ const body = JSON.stringify(req.body);
1082
+ const proxyReq = http.request({
1083
+ hostname: "127.0.0.1",
1084
+ port: SECONDARY_INTERNAL_PORT,
1085
+ path: "/api/messages",
1086
+ method: "POST",
1087
+ headers: {
1088
+ ...req.headers,
1089
+ "content-length": Buffer.byteLength(body).toString(),
1090
+ },
1091
+ }, (proxyRes) => {
1092
+ res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
1093
+ proxyRes.pipe(res);
1094
+ });
1095
+ proxyReq.on("error", (err) => {
1096
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.proxy_error", component: "channels", message: `secondary proxy error: ${err.message}`, meta: {} });
1097
+ if (!res.headersSent) {
1098
+ res.writeHead(502);
1099
+ res.end("Bad Gateway");
1100
+ }
1101
+ });
1102
+ proxyReq.write(body);
1103
+ proxyReq.end();
1104
+ });
1105
+ (0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.proxy_ready", component: "channels", message: "proxy /api/messages-secondary → secondary bot ready", meta: {} });
1106
+ }
1107
+ /* v8 ignore stop */
696
1108
  }