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