@ouro.bot/cli 0.1.0-alpha.2 → 0.1.0-alpha.200
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/README.md +187 -191
- package/SerpentGuide.ouro/agent.json +82 -0
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +6 -3
- package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
- package/assets/ouroboros.png +0 -0
- package/changelog.json +1248 -0
- package/dist/heart/active-work.js +832 -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/cares.js +179 -0
- package/dist/heart/commitments.js +111 -0
- package/dist/heart/config.js +114 -28
- package/dist/heart/core.js +689 -120
- package/dist/heart/cross-chat-delivery.js +146 -0
- package/dist/heart/daemon/agent-config-check.js +149 -0
- package/dist/heart/daemon/agent-discovery.js +81 -0
- package/dist/heart/daemon/agent-service.js +360 -0
- package/dist/heart/daemon/auth-flow.js +477 -0
- package/dist/heart/daemon/cadence.js +70 -0
- package/dist/heart/daemon/daemon-cli.js +2897 -193
- package/dist/heart/daemon/daemon-entry.js +194 -8
- package/dist/heart/daemon/daemon-health.js +136 -0
- package/dist/heart/daemon/daemon-runtime-sync.js +231 -0
- package/dist/heart/daemon/daemon-tombstone.js +123 -0
- package/dist/heart/daemon/daemon.js +488 -13
- package/dist/heart/daemon/habit-migration.js +181 -0
- package/dist/heart/daemon/habit-parser.js +119 -0
- package/dist/heart/daemon/habit-scheduler.js +369 -0
- package/dist/heart/daemon/hatch-animation.js +35 -0
- package/dist/heart/daemon/hatch-flow.js +32 -122
- package/dist/heart/daemon/hatch-specialist.js +7 -2
- package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
- package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
- package/dist/heart/daemon/inner-status.js +89 -0
- package/dist/heart/daemon/launchd.js +165 -0
- package/dist/heart/daemon/log-tailer.js +4 -3
- package/dist/heart/daemon/mcp-server.js +591 -0
- package/dist/heart/daemon/message-router.js +17 -8
- package/dist/heart/daemon/os-cron-deps.js +134 -0
- package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
- package/dist/heart/daemon/ouro-bot-wrapper.js +4 -3
- package/dist/heart/daemon/ouro-path-installer.js +221 -0
- package/dist/heart/daemon/ouro-uti.js +11 -2
- package/dist/heart/daemon/ouro-version-manager.js +171 -0
- package/dist/heart/daemon/outlook-http.js +439 -0
- package/dist/heart/daemon/outlook-read.js +1618 -0
- package/dist/heart/daemon/outlook-render.js +1032 -0
- package/dist/heart/daemon/outlook-types.js +7 -0
- package/dist/heart/daemon/outlook-view.js +194 -0
- package/dist/heart/daemon/process-manager.js +94 -1
- package/dist/heart/daemon/run-hooks.js +39 -0
- package/dist/heart/daemon/runtime-logging.js +61 -14
- package/dist/heart/daemon/runtime-metadata.js +219 -0
- package/dist/heart/daemon/runtime-mode.js +67 -0
- package/dist/heart/daemon/safe-mode.js +161 -0
- package/dist/heart/daemon/sense-manager.js +314 -0
- package/dist/heart/daemon/session-id-resolver.js +131 -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 +129 -0
- package/dist/heart/daemon/specialist-prompt.js +101 -0
- package/dist/heart/daemon/specialist-tools.js +283 -0
- package/dist/heart/daemon/staged-restart.js +138 -0
- package/dist/heart/daemon/task-scheduler.js +3 -25
- 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 +220 -52
- package/dist/heart/intentions.js +173 -0
- package/dist/heart/kicks.js +2 -20
- package/dist/heart/migrate-config.js +127 -0
- package/dist/heart/model-capabilities.js +48 -0
- package/dist/heart/obligations.js +225 -0
- package/dist/heart/presence.js +185 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/provider-failover.js +88 -0
- package/dist/heart/provider-ping.js +178 -0
- package/dist/heart/providers/anthropic-token.js +163 -0
- package/dist/heart/providers/anthropic.js +199 -36
- package/dist/heart/providers/azure.js +116 -10
- package/dist/heart/providers/github-copilot.js +157 -0
- package/dist/heart/providers/minimax.js +33 -3
- package/dist/heart/providers/openai-codex.js +51 -16
- package/dist/heart/sense-truth.js +61 -0
- package/dist/heart/session-activity.js +172 -0
- package/dist/heart/session-recall.js +216 -0
- package/dist/heart/start-of-turn-packet.js +232 -0
- package/dist/heart/streaming.js +120 -33
- package/dist/heart/sync.js +217 -0
- package/dist/heart/target-resolution.js +127 -0
- package/dist/heart/tempo.js +93 -0
- package/dist/heart/temporal-view.js +41 -0
- package/dist/heart/tool-activity-callbacks.js +36 -0
- package/dist/heart/tool-description.js +135 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-coordinator.js +28 -0
- package/dist/mind/associative-recall.js +122 -32
- package/dist/mind/bundle-manifest.js +77 -1
- package/dist/mind/context.js +125 -14
- package/dist/mind/{memory.js → diary.js} +69 -56
- package/dist/mind/episodes.js +119 -0
- package/dist/mind/file-state.js +179 -0
- package/dist/mind/first-impressions.js +16 -2
- package/dist/mind/friends/channel.js +64 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/store-file.js +36 -0
- package/dist/mind/friends/trust-explanation.js +74 -0
- package/dist/mind/friends/types.js +9 -1
- package/dist/mind/journal-index.js +161 -0
- package/dist/mind/obligation-steering.js +221 -0
- package/dist/mind/obligations.js +138 -0
- package/dist/mind/pending.js +76 -9
- package/dist/mind/phrases.js +1 -0
- package/dist/mind/prompt.js +861 -105
- package/dist/mind/scrutiny.js +173 -0
- package/dist/mind/token-estimate.js +8 -12
- package/dist/nerves/cli-logging.js +15 -2
- package/dist/nerves/coverage/audit.js +1 -1
- package/dist/nerves/coverage/run-artifacts.js +1 -1
- package/dist/nerves/event-buffer.js +111 -0
- package/dist/nerves/index.js +63 -3
- package/dist/nerves/observation.js +20 -0
- package/dist/nerves/runtime.js +5 -1
- package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
- package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
- package/dist/outlook-ui/index.html +15 -0
- package/dist/repertoire/ado-client.js +4 -2
- package/dist/repertoire/ado-semantic.js +11 -5
- package/dist/repertoire/coding/codex-jsonl.js +64 -0
- package/dist/repertoire/coding/context-pack.js +330 -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 +58 -12
- package/dist/repertoire/coding/tools.js +209 -7
- package/dist/repertoire/data/ado-endpoints.json +188 -0
- package/dist/repertoire/guardrails.js +291 -0
- package/dist/repertoire/mcp-client.js +254 -0
- package/dist/repertoire/mcp-manager.js +251 -0
- package/dist/repertoire/shell-sessions.js +133 -0
- package/dist/repertoire/skills.js +14 -23
- package/dist/repertoire/tasks/board.js +43 -5
- package/dist/repertoire/tasks/fix.js +182 -0
- package/dist/repertoire/tasks/index.js +28 -10
- package/dist/repertoire/tasks/lifecycle.js +2 -2
- package/dist/repertoire/tasks/parser.js +3 -2
- package/dist/repertoire/tasks/scanner.js +194 -37
- package/dist/repertoire/tasks/transitions.js +11 -28
- package/dist/repertoire/tools-base.js +1360 -271
- package/dist/repertoire/tools-bluebubbles.js +94 -0
- package/dist/repertoire/tools-github.js +1 -6
- package/dist/repertoire/tools-teams.js +65 -59
- package/dist/repertoire/tools.js +318 -91
- package/dist/scripts/claude-code-hook.js +41 -0
- package/dist/scripts/claude-code-stop-hook.js +47 -0
- package/dist/senses/attention-queue.js +97 -0
- package/dist/senses/bluebubbles-client.js +532 -0
- package/dist/senses/bluebubbles-entry.js +13 -0
- package/dist/senses/bluebubbles-inbound-log.js +109 -0
- package/dist/senses/bluebubbles-media.js +339 -0
- package/dist/senses/bluebubbles-model.js +261 -0
- package/dist/senses/bluebubbles-mutation-log.js +116 -0
- package/dist/senses/bluebubbles-runtime-state.js +109 -0
- package/dist/senses/bluebubbles-session-cleanup.js +72 -0
- package/dist/senses/bluebubbles.js +1327 -0
- package/dist/senses/cli/adapter.js +274 -0
- package/dist/senses/cli/ink-app.js +156 -0
- package/dist/senses/cli/inline-diff.js +64 -0
- package/dist/senses/cli/message-list.js +51 -0
- package/dist/senses/cli/ouro-tui.js +349 -0
- package/dist/senses/cli/spinner-imperative.js +135 -0
- package/dist/senses/cli/spinner.js +101 -0
- package/dist/senses/cli/status-line.js +60 -0
- package/dist/senses/cli/streaming-markdown.js +526 -0
- package/dist/senses/cli/tool-display.js +83 -0
- package/dist/senses/cli/tool-render.js +85 -0
- package/dist/senses/cli/tui-store.js +198 -0
- package/dist/senses/cli/virtual-list.js +35 -0
- package/dist/senses/cli-entry.js +1 -1
- package/dist/senses/cli-layout.js +187 -0
- package/dist/senses/cli.js +687 -262
- package/dist/senses/commands.js +65 -1
- package/dist/senses/continuity.js +94 -0
- package/dist/senses/habit-turn-message.js +108 -0
- package/dist/senses/inner-dialog-worker.js +112 -19
- package/dist/senses/inner-dialog.js +592 -84
- package/dist/senses/pipeline.js +693 -0
- package/dist/senses/shared-turn.js +196 -0
- package/dist/senses/surface-tool.js +95 -0
- package/dist/senses/teams.js +817 -151
- package/dist/senses/trust-gate.js +112 -2
- package/package.json +24 -7
- package/skills/configure-dev-tools.md +81 -0
- package/subagents/README.md +4 -70
- package/AdoptionSpecialist.ouro/agent.json +0 -20
- 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/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
- /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
package/dist/senses/teams.js
CHANGED
|
@@ -34,16 +34,25 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.DEFAULT_FLUSH_INTERVAL_MS = void 0;
|
|
37
|
+
exports.aiLabelEntities = aiLabelEntities;
|
|
37
38
|
exports.stripMentions = stripMentions;
|
|
38
39
|
exports.splitMessage = splitMessage;
|
|
40
|
+
exports.sanitizeFeedbackComment = sanitizeFeedbackComment;
|
|
41
|
+
exports.buildFeedbackSyntheticText = buildFeedbackSyntheticText;
|
|
42
|
+
exports.buildWelcomeCard = buildWelcomeCard;
|
|
39
43
|
exports.createTeamsCallbacks = createTeamsCallbacks;
|
|
40
44
|
exports.resolvePendingConfirmation = resolvePendingConfirmation;
|
|
41
45
|
exports.withConversationLock = withConversationLock;
|
|
42
46
|
exports.handleTeamsMessage = handleTeamsMessage;
|
|
47
|
+
exports.sendProactiveTeamsMessageToSession = sendProactiveTeamsMessageToSession;
|
|
48
|
+
exports.drainAndSendPendingTeams = drainAndSendPendingTeams;
|
|
43
49
|
exports.startTeamsApp = startTeamsApp;
|
|
50
|
+
const fs = __importStar(require("fs"));
|
|
44
51
|
const teams_apps_1 = require("@microsoft/teams.apps");
|
|
45
52
|
const teams_dev_1 = require("@microsoft/teams.dev");
|
|
46
53
|
const core_1 = require("../heart/core");
|
|
54
|
+
const tools_1 = require("../repertoire/tools");
|
|
55
|
+
const channel_1 = require("../mind/friends/channel");
|
|
47
56
|
const config_1 = require("../heart/config");
|
|
48
57
|
const prompt_1 = require("../mind/prompt");
|
|
49
58
|
const phrases_1 = require("../mind/phrases");
|
|
@@ -54,12 +63,32 @@ const commands_1 = require("./commands");
|
|
|
54
63
|
const nerves_1 = require("../nerves");
|
|
55
64
|
const runtime_1 = require("../nerves/runtime");
|
|
56
65
|
const store_file_1 = require("../mind/friends/store-file");
|
|
66
|
+
const types_1 = require("../mind/friends/types");
|
|
57
67
|
const resolver_1 = require("../mind/friends/resolver");
|
|
58
68
|
const tokens_1 = require("../mind/friends/tokens");
|
|
59
69
|
const turn_coordinator_1 = require("../heart/turn-coordinator");
|
|
60
70
|
const identity_1 = require("../heart/identity");
|
|
71
|
+
const mcp_manager_1 = require("../repertoire/mcp-manager");
|
|
72
|
+
const progress_story_1 = require("../heart/progress-story");
|
|
73
|
+
const tool_activity_callbacks_1 = require("../heart/tool-activity-callbacks");
|
|
74
|
+
const commands_2 = require("./commands");
|
|
75
|
+
const http = __importStar(require("http"));
|
|
61
76
|
const path = __importStar(require("path"));
|
|
62
77
|
const trust_gate_1 = require("./trust-gate");
|
|
78
|
+
const pipeline_1 = require("./pipeline");
|
|
79
|
+
const teamsFailoverStates = new Map();
|
|
80
|
+
const pending_1 = require("../mind/pending");
|
|
81
|
+
const continuity_1 = require("./continuity");
|
|
82
|
+
// AIGeneratedContent entity and feedbackLoopEnabled channelData for all outbound
|
|
83
|
+
// Teams messages. Required by Teams AI UX best practices.
|
|
84
|
+
function aiLabelEntities() {
|
|
85
|
+
return [{
|
|
86
|
+
type: "https://schema.org/Message",
|
|
87
|
+
"@type": "Message",
|
|
88
|
+
"@context": "https://schema.org",
|
|
89
|
+
additionalType: ["AIGeneratedContent"],
|
|
90
|
+
}];
|
|
91
|
+
}
|
|
63
92
|
// Strip @mention markup from incoming messages.
|
|
64
93
|
// Removes <at>...</at> tags and trims extra whitespace.
|
|
65
94
|
// Fallback safety net -- the SDK's activity.mentions.stripText should handle
|
|
@@ -114,6 +143,46 @@ function splitMessage(text, maxLen) {
|
|
|
114
143
|
}
|
|
115
144
|
return chunks;
|
|
116
145
|
}
|
|
146
|
+
// Sanitize user-provided feedback comments: truncate, strip control chars and newlines.
|
|
147
|
+
function sanitizeFeedbackComment(comment) {
|
|
148
|
+
const cleaned = comment.replace(/[\x00-\x1f\n\r]/g, "");
|
|
149
|
+
return cleaned.length > 200 ? cleaned.slice(0, 200) : cleaned;
|
|
150
|
+
}
|
|
151
|
+
// Build synthetic message text from a Teams feedback reaction.
|
|
152
|
+
function buildFeedbackSyntheticText(reaction, comment) {
|
|
153
|
+
const emoji = reaction === "like" ? "thumbs-up" : "thumbs-down";
|
|
154
|
+
if (comment) {
|
|
155
|
+
const sanitized = sanitizeFeedbackComment(comment);
|
|
156
|
+
return `[reacted with ${emoji} to your message: "${sanitized}"]`;
|
|
157
|
+
}
|
|
158
|
+
return `[reacted with ${emoji} to your message]`;
|
|
159
|
+
}
|
|
160
|
+
// Build a welcome Adaptive Card with prompt starters for new bot installs.
|
|
161
|
+
function buildWelcomeCard() {
|
|
162
|
+
const promptStarters = [
|
|
163
|
+
"What can you help me with?",
|
|
164
|
+
"Tell me about yourself",
|
|
165
|
+
"What's on my calendar today?",
|
|
166
|
+
"Summarize my recent emails",
|
|
167
|
+
];
|
|
168
|
+
return {
|
|
169
|
+
type: "AdaptiveCard",
|
|
170
|
+
version: "1.5",
|
|
171
|
+
body: [
|
|
172
|
+
{
|
|
173
|
+
type: "TextBlock",
|
|
174
|
+
text: "Hey! I'm here and ready to help. Try one of these to get started, or just ask me anything.",
|
|
175
|
+
wrap: true,
|
|
176
|
+
size: "Medium",
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
|
+
actions: promptStarters.map((prompt) => ({
|
|
180
|
+
type: "Action.Submit",
|
|
181
|
+
title: prompt,
|
|
182
|
+
data: { msteams: { type: "messageBack", text: prompt, displayText: prompt } },
|
|
183
|
+
})),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
117
186
|
// Create Teams-specific callbacks for the agent loop.
|
|
118
187
|
// The SDK handles cumulative text, debouncing (500ms), and the streaming
|
|
119
188
|
// protocol (streamSequence, streamId, informative/streaming/final types).
|
|
@@ -126,12 +195,16 @@ function splitMessage(text, maxLen) {
|
|
|
126
195
|
// (transient status) or safeSend (terminal errors). Reasoning is accumulated
|
|
127
196
|
// and periodically pushed via safeUpdate on the same flush timer tick.
|
|
128
197
|
function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
198
|
+
const MIN_INITIAL_CHARS = 20;
|
|
129
199
|
let stopped = false; // set when stream signals cancellation (403)
|
|
130
200
|
let hadToolRun = false;
|
|
131
201
|
let hadRealOutput = false; // true once reasoning/tool output shown; suppresses phrases
|
|
132
202
|
let reasoningBuf = ""; // accumulated reasoning text for status display
|
|
203
|
+
let totalEmitted = 0; // cumulative chars emitted via safeEmit (for >4000 finalization)
|
|
204
|
+
let streamFinalized = false; // true after stream.close() — subsequent flushes go to safeSend
|
|
133
205
|
let textBuffer = ""; // accumulated text output for chunked streaming
|
|
134
206
|
let streamHasContent = false; // tracks whether primary output has received content
|
|
207
|
+
let firstContentEmitted = false; // true after first content push — disables MIN_INITIAL_CHARS threshold
|
|
135
208
|
let phraseTimer = null;
|
|
136
209
|
let lastPhrase = "";
|
|
137
210
|
let flushTimer = null;
|
|
@@ -181,15 +254,16 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
181
254
|
result.catch(() => markStopped());
|
|
182
255
|
}
|
|
183
256
|
}
|
|
184
|
-
// Safely emit a text delta to the stream.
|
|
257
|
+
// Safely emit a text delta to the stream with AI labels.
|
|
185
258
|
// On error (e.g. 403 from Teams stop button), abort the controller.
|
|
186
259
|
function safeEmit(text) {
|
|
187
260
|
/* v8 ignore next -- defensive guard: stopped set by prior 403; tested via flush abort path @preserve */
|
|
188
261
|
if (stopped)
|
|
189
262
|
return;
|
|
190
263
|
try {
|
|
191
|
-
catchAsync(stream.emit(text));
|
|
264
|
+
catchAsync(stream.emit({ text, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } }));
|
|
192
265
|
streamHasContent = true;
|
|
266
|
+
totalEmitted += text.length;
|
|
193
267
|
}
|
|
194
268
|
catch {
|
|
195
269
|
markStopped();
|
|
@@ -204,7 +278,7 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
204
278
|
try {
|
|
205
279
|
// stream.emit() is typed as void but the Teams SDK returns a Promise
|
|
206
280
|
// internally (async HTTP). Cast to capture the result for awaiting.
|
|
207
|
-
const result = stream.emit(text);
|
|
281
|
+
const result = stream.emit({ text, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
|
|
208
282
|
streamHasContent = true;
|
|
209
283
|
if (result && typeof result.then === "function") {
|
|
210
284
|
await result;
|
|
@@ -260,11 +334,49 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
260
334
|
// emitted text into a single streaming message (cumulative), so every
|
|
261
335
|
// periodic flush appends to the same response — not separate messages.
|
|
262
336
|
// No preemptive splitting — sends full text. Error recovery happens in flush().
|
|
337
|
+
// Hybrid MIN_INITIAL_CHARS: hold back until >= MIN_INITIAL_CHARS accumulated
|
|
338
|
+
// before the first content emit, so phrase rotation shows while real content
|
|
339
|
+
// buffers. After first emit, flush normally (no threshold).
|
|
263
340
|
function flushTextBuffer() {
|
|
264
341
|
if (!textBuffer)
|
|
265
342
|
return;
|
|
343
|
+
if (!firstContentEmitted && textBuffer.length < MIN_INITIAL_CHARS)
|
|
344
|
+
return;
|
|
345
|
+
// Proactive >4000 finalization: if cumulative emitted + buffer >= RECOVERY_CHUNK_SIZE,
|
|
346
|
+
// finalize the stream and send overflow via safeSend (follow-up message).
|
|
347
|
+
if (!streamFinalized && totalEmitted + textBuffer.length >= RECOVERY_CHUNK_SIZE) {
|
|
348
|
+
const remaining = RECOVERY_CHUNK_SIZE - totalEmitted;
|
|
349
|
+
/* v8 ignore next 2 -- defensive: remaining always > 0 because finalization runs once @preserve */
|
|
350
|
+
if (remaining > 0)
|
|
351
|
+
safeEmit(textBuffer.slice(0, remaining));
|
|
352
|
+
try {
|
|
353
|
+
stream.close();
|
|
354
|
+
}
|
|
355
|
+
catch { /* stream may already be dead */ }
|
|
356
|
+
streamFinalized = true;
|
|
357
|
+
/* v8 ignore next -- defensive ternary: remaining always > 0 at first finalization @preserve */
|
|
358
|
+
const overflow = textBuffer.slice(remaining > 0 ? remaining : 0);
|
|
359
|
+
textBuffer = "";
|
|
360
|
+
if (overflow)
|
|
361
|
+
safeSend(overflow);
|
|
362
|
+
if (!firstContentEmitted) {
|
|
363
|
+
firstContentEmitted = true;
|
|
364
|
+
stopPhraseRotation();
|
|
365
|
+
}
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (streamFinalized) {
|
|
369
|
+
// After finalization, all content goes to safeSend (follow-up messages)
|
|
370
|
+
safeSend(textBuffer);
|
|
371
|
+
textBuffer = "";
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
266
374
|
safeEmit(textBuffer);
|
|
267
375
|
textBuffer = "";
|
|
376
|
+
if (!firstContentEmitted) {
|
|
377
|
+
firstContentEmitted = true;
|
|
378
|
+
stopPhraseRotation();
|
|
379
|
+
}
|
|
268
380
|
}
|
|
269
381
|
function startPhraseRotation(pool) {
|
|
270
382
|
stopPhraseRotation();
|
|
@@ -307,25 +419,45 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
307
419
|
onTextChunk: (text) => {
|
|
308
420
|
if (stopped)
|
|
309
421
|
return;
|
|
310
|
-
|
|
422
|
+
// Don't stop phrase rotation here — let it continue until first content
|
|
423
|
+
// emit (handled in flushTextBuffer when MIN_INITIAL_CHARS threshold met).
|
|
311
424
|
textBuffer += text;
|
|
312
425
|
startFlushTimer();
|
|
313
426
|
},
|
|
314
427
|
onClearText: () => {
|
|
315
428
|
textBuffer = "";
|
|
316
429
|
},
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
430
|
+
...(() => {
|
|
431
|
+
const toolCbs = (0, tool_activity_callbacks_1.createToolActivityCallbacks)({
|
|
432
|
+
onDescription: (text) => safeUpdate(text),
|
|
433
|
+
/* v8 ignore next -- onResult only called in debug mode; tested via tool-activity-callbacks.test.ts @preserve */
|
|
434
|
+
onResult: (text) => safeUpdate(text),
|
|
435
|
+
/* v8 ignore next -- onFailure tested via onToolEnd failure test @preserve */
|
|
436
|
+
onFailure: (text) => safeUpdate(text),
|
|
437
|
+
isDebug: commands_2.getDebugMode,
|
|
438
|
+
});
|
|
439
|
+
return {
|
|
440
|
+
onToolStart: (name, args) => {
|
|
441
|
+
stopPhraseRotation();
|
|
442
|
+
// Force-flush any accumulated text, bypassing MIN_INITIAL_CHARS threshold
|
|
443
|
+
firstContentEmitted = true;
|
|
444
|
+
flushTextBuffer();
|
|
445
|
+
// Emit a placeholder to satisfy the 15s Copilot timeout for initial
|
|
446
|
+
// stream.emit(). Without this, long tool chains (e.g. ADO batch ops)
|
|
447
|
+
// never emit before the timeout and the user sees "this response was
|
|
448
|
+
// stopped". The placeholder is replaced by actual content on next emit.
|
|
449
|
+
// https://learn.microsoft.com/en-us/answers/questions/2288017/m365-custom-engine-agents-timeout-message-after-15
|
|
450
|
+
if (!streamHasContent)
|
|
451
|
+
safeEmit("\u23f3");
|
|
452
|
+
toolCbs.onToolStart(name, args);
|
|
453
|
+
hadToolRun = true;
|
|
454
|
+
},
|
|
455
|
+
onToolEnd: (name, summary, success) => {
|
|
456
|
+
stopPhraseRotation();
|
|
457
|
+
toolCbs.onToolEnd(name, summary, success);
|
|
458
|
+
},
|
|
459
|
+
};
|
|
460
|
+
})(),
|
|
329
461
|
onKick: () => {
|
|
330
462
|
stopPhraseRotation();
|
|
331
463
|
const msg = (0, format_1.formatKick)();
|
|
@@ -335,7 +467,11 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
335
467
|
stopPhraseRotation();
|
|
336
468
|
if (stopped)
|
|
337
469
|
return;
|
|
338
|
-
const msg = (0,
|
|
470
|
+
const msg = (0, progress_story_1.renderProgressStory)((0, progress_story_1.buildProgressStory)({
|
|
471
|
+
scope: "shared-work",
|
|
472
|
+
phase: "errored",
|
|
473
|
+
outcomeText: (0, format_1.formatError)(error),
|
|
474
|
+
}));
|
|
339
475
|
if (severity === "transient") {
|
|
340
476
|
safeUpdate(msg);
|
|
341
477
|
}
|
|
@@ -363,18 +499,25 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
363
499
|
: undefined,
|
|
364
500
|
flush: async () => {
|
|
365
501
|
stopFlushTimer();
|
|
502
|
+
stopPhraseRotation();
|
|
366
503
|
if (textBuffer) {
|
|
504
|
+
// Bypass MIN_INITIAL_CHARS threshold — flush delivers all remaining content
|
|
505
|
+
firstContentEmitted = true;
|
|
367
506
|
const text = textBuffer;
|
|
368
507
|
textBuffer = "";
|
|
369
|
-
if (
|
|
508
|
+
if (streamFinalized && sendMessage) {
|
|
509
|
+
// Stream already finalized (>4000 path) — send remaining content as follow-up
|
|
510
|
+
safeSend(text);
|
|
511
|
+
}
|
|
512
|
+
else if (!stopped) {
|
|
370
513
|
// Stream is alive — await the emit so we can catch async 413/failure
|
|
371
514
|
// and fall through to sendMessage recovery.
|
|
372
515
|
const ok = await tryEmit(text);
|
|
373
516
|
if (!ok)
|
|
374
517
|
markStopped();
|
|
375
518
|
}
|
|
376
|
-
if (stopped && sendMessage) {
|
|
377
|
-
// Stream is dead — fall back to sendMessage; split on failure as recovery.
|
|
519
|
+
if (stopped && !streamFinalized && sendMessage) {
|
|
520
|
+
// Stream is dead (not from finalization) — fall back to sendMessage; split on failure as recovery.
|
|
378
521
|
try {
|
|
379
522
|
await sendMessage(text);
|
|
380
523
|
}
|
|
@@ -385,8 +528,8 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
|
|
|
385
528
|
}
|
|
386
529
|
}
|
|
387
530
|
}
|
|
388
|
-
else if (!streamHasContent) {
|
|
389
|
-
safeEmit("(completed with tool calls only
|
|
531
|
+
else if (!streamHasContent && !options?.suppressEmptyStreamMessage) {
|
|
532
|
+
safeEmit("(completed with tool calls only — no text response)");
|
|
390
533
|
}
|
|
391
534
|
},
|
|
392
535
|
};
|
|
@@ -424,158 +567,311 @@ function getFriendStore() {
|
|
|
424
567
|
const friendsPath = path.join((0, identity_1.getAgentRoot)(), "friends");
|
|
425
568
|
return new store_file_1.FileFriendStore(friendsPath);
|
|
426
569
|
}
|
|
570
|
+
function createTeamsCommandRegistry() {
|
|
571
|
+
const registry = (0, commands_1.createCommandRegistry)();
|
|
572
|
+
(0, commands_1.registerDefaultCommands)(registry);
|
|
573
|
+
return registry;
|
|
574
|
+
}
|
|
575
|
+
/* v8 ignore start -- superseding follow-up slash command handler; tested via startTeamsApp integration tests @preserve */
|
|
576
|
+
function handleTeamsSlashCommand(text, registry, friendId, conversationId, stream, emitResponse = true) {
|
|
577
|
+
const parsed = (0, commands_1.parseSlashCommand)(text);
|
|
578
|
+
if (!parsed)
|
|
579
|
+
return null;
|
|
580
|
+
const dispatchResult = registry.dispatch(parsed.command, { channel: "teams" });
|
|
581
|
+
if (!dispatchResult.handled || !dispatchResult.result) {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
if (dispatchResult.result.action === "new") {
|
|
585
|
+
(0, context_1.deleteSession)((0, config_2.sessionPath)(friendId, "teams", conversationId));
|
|
586
|
+
if (emitResponse) {
|
|
587
|
+
stream.emit("session cleared");
|
|
588
|
+
}
|
|
589
|
+
return "new";
|
|
590
|
+
}
|
|
591
|
+
if (dispatchResult.result.action === "response") {
|
|
592
|
+
if (emitResponse) {
|
|
593
|
+
stream.emit(dispatchResult.result.message || "");
|
|
594
|
+
}
|
|
595
|
+
return "response";
|
|
596
|
+
}
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
/* v8 ignore stop */
|
|
427
600
|
// Handle an incoming Teams message
|
|
428
|
-
async function handleTeamsMessage(text, stream, conversationId, teamsContext, sendMessage) {
|
|
601
|
+
async function handleTeamsMessage(text, stream, conversationId, teamsContext, sendMessage, reactionOverrides) {
|
|
429
602
|
const turnKey = teamsTurnKey(conversationId);
|
|
430
603
|
// NOTE: Confirmation resolution is handled in the app.on("message") handler
|
|
431
604
|
// BEFORE the conversation lock. By the time we get here, any pending
|
|
432
605
|
// confirmation has already been resolved and the reply consumed.
|
|
433
606
|
// Send first thinking phrase immediately so the user sees feedback
|
|
434
607
|
// before sync I/O (session load, trim) blocks the event loop.
|
|
435
|
-
|
|
608
|
+
// Skip for reaction signals — they should be processed quietly.
|
|
609
|
+
if (!reactionOverrides) {
|
|
610
|
+
stream.update((0, phrases_1.pickPhrase)((0, phrases_1.getPhrases)().thinking) + "...");
|
|
611
|
+
}
|
|
436
612
|
await new Promise(r => setImmediate(r));
|
|
437
|
-
// Resolve
|
|
613
|
+
// Resolve identity provider early for friend resolution + slash command session path
|
|
438
614
|
const store = getFriendStore();
|
|
439
615
|
const provider = teamsContext?.aadObjectId ? "aad" : "teams-conversation";
|
|
440
616
|
const externalId = teamsContext?.aadObjectId || conversationId;
|
|
441
|
-
|
|
617
|
+
// Build FriendResolver for the pipeline
|
|
618
|
+
const resolver = new resolver_1.FriendResolver(store, {
|
|
619
|
+
provider,
|
|
620
|
+
externalId,
|
|
621
|
+
tenantId: teamsContext?.tenantId,
|
|
622
|
+
displayName: teamsContext?.displayName || "Unknown",
|
|
623
|
+
channel: "teams",
|
|
624
|
+
});
|
|
625
|
+
// Pre-resolve friend for session path + slash commands (pipeline will re-use the cached result)
|
|
626
|
+
const resolvedContext = await resolver.resolve();
|
|
627
|
+
const friendId = resolvedContext.friend.id;
|
|
628
|
+
// ── Teams adapter concerns: controller, callbacks, session path ──────────
|
|
629
|
+
const controller = new AbortController();
|
|
630
|
+
const channelConfig = (0, config_2.getTeamsChannelConfig)();
|
|
631
|
+
const callbacks = createTeamsCallbacks(stream, controller, sendMessage, { conversationId, flushIntervalMs: channelConfig.flushIntervalMs, ...(reactionOverrides?.suppressEmptyStreamMessage ? { suppressEmptyStreamMessage: true } : {}) });
|
|
632
|
+
const traceId = (0, nerves_1.createTraceId)();
|
|
633
|
+
const sessPath = (0, config_2.sessionPath)(friendId, "teams", conversationId);
|
|
634
|
+
const teamsCapabilities = (0, channel_1.getChannelCapabilities)("teams");
|
|
635
|
+
const pendingDir = (0, pending_1.getPendingDir)((0, identity_1.getAgentName)(), friendId, "teams", conversationId);
|
|
636
|
+
// Build Teams-specific toolContext fields for injection into the pipeline
|
|
637
|
+
const teamsToolContext = teamsContext ? {
|
|
442
638
|
graphToken: teamsContext.graphToken,
|
|
443
639
|
adoToken: teamsContext.adoToken,
|
|
444
640
|
githubToken: teamsContext.githubToken,
|
|
445
641
|
signin: teamsContext.signin,
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
642
|
+
summarize: (0, core_1.createSummarize)("human"),
|
|
643
|
+
tenantId: teamsContext.tenantId,
|
|
644
|
+
botApi: teamsContext.botApi,
|
|
645
|
+
} : {};
|
|
646
|
+
let currentText = text;
|
|
647
|
+
const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)() ?? undefined;
|
|
648
|
+
while (true) {
|
|
649
|
+
let drainedSteeringFollowUps = [];
|
|
650
|
+
// Build runAgentOptions with Teams-specific fields
|
|
651
|
+
const agentOptions = {
|
|
652
|
+
traceId,
|
|
653
|
+
toolContext: teamsToolContext,
|
|
654
|
+
mcpManager,
|
|
655
|
+
drainSteeringFollowUps: () => {
|
|
656
|
+
drainedSteeringFollowUps = _turnCoordinator.drainFollowUps(turnKey)
|
|
657
|
+
.map(({ text: followUpText, effect }) => ({ text: followUpText, effect }));
|
|
658
|
+
return drainedSteeringFollowUps;
|
|
659
|
+
},
|
|
660
|
+
...(reactionOverrides?.isReactionSignal ? { isReactionSignal: true } : {}),
|
|
661
|
+
};
|
|
662
|
+
if (channelConfig.skipConfirmation)
|
|
663
|
+
agentOptions.skipConfirmation = true;
|
|
664
|
+
// ── Call shared pipeline ──────────────────────────────────────────
|
|
665
|
+
// Capture terminal errors — failover message replaces the error card if it triggers
|
|
666
|
+
let capturedTerminalError = null;
|
|
667
|
+
const teamsFailoverState = (() => {
|
|
668
|
+
if (!teamsFailoverStates.has(conversationId)) {
|
|
669
|
+
teamsFailoverStates.set(conversationId, { pending: null });
|
|
670
|
+
}
|
|
671
|
+
return teamsFailoverStates.get(conversationId);
|
|
672
|
+
})();
|
|
673
|
+
/* v8 ignore start -- failover-aware callback wrapper: tested via pipeline integration @preserve */
|
|
674
|
+
const failoverAwareCallbacks = {
|
|
675
|
+
...callbacks,
|
|
676
|
+
onError: (error, severity) => {
|
|
677
|
+
if (severity === "terminal" && teamsFailoverState) {
|
|
678
|
+
capturedTerminalError = error;
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
callbacks.onError(error, severity);
|
|
682
|
+
},
|
|
683
|
+
};
|
|
684
|
+
/* v8 ignore stop */
|
|
685
|
+
const result = await (0, pipeline_1.handleInboundTurn)({
|
|
455
686
|
channel: "teams",
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
687
|
+
sessionKey: conversationId,
|
|
688
|
+
capabilities: teamsCapabilities,
|
|
689
|
+
messages: [{ role: "user", content: currentText }],
|
|
690
|
+
continuityIngressTexts: [currentText],
|
|
691
|
+
callbacks: failoverAwareCallbacks,
|
|
692
|
+
friendResolver: { resolve: () => Promise.resolve(resolvedContext) },
|
|
693
|
+
sessionLoader: {
|
|
694
|
+
loadOrCreate: async () => {
|
|
695
|
+
const existing = (0, context_1.loadSession)(sessPath);
|
|
696
|
+
const messages = existing?.messages && existing.messages.length > 0
|
|
697
|
+
? existing.messages
|
|
698
|
+
: [{ role: "system", content: await (0, prompt_1.buildSystem)("teams", { mcpManager }, resolvedContext) }];
|
|
699
|
+
(0, core_1.repairOrphanedToolCalls)(messages);
|
|
700
|
+
return {
|
|
701
|
+
messages,
|
|
702
|
+
sessionPath: sessPath,
|
|
703
|
+
state: existing?.state,
|
|
704
|
+
};
|
|
705
|
+
},
|
|
706
|
+
},
|
|
707
|
+
pendingDir,
|
|
708
|
+
friendStore: store,
|
|
463
709
|
provider,
|
|
464
710
|
externalId,
|
|
465
711
|
tenantId: teamsContext?.tenantId,
|
|
466
|
-
|
|
712
|
+
isGroupChat: false,
|
|
713
|
+
groupHasFamilyMember: false,
|
|
714
|
+
hasExistingGroupWithFamily: false,
|
|
715
|
+
enforceTrustGate: trust_gate_1.enforceTrustGate,
|
|
716
|
+
drainPending: pending_1.drainPending,
|
|
717
|
+
drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)((0, identity_1.getAgentName)(), deferredFriendId),
|
|
718
|
+
runAgent: (msgs, cb, channel, sig, opts) => (0, core_1.runAgent)(msgs, cb, channel, sig, {
|
|
719
|
+
...opts,
|
|
720
|
+
toolContext: {
|
|
721
|
+
/* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
|
|
722
|
+
signin: async () => undefined,
|
|
723
|
+
...opts?.toolContext,
|
|
724
|
+
summarize: teamsToolContext.summarize,
|
|
725
|
+
},
|
|
726
|
+
}),
|
|
727
|
+
postTurn: context_1.postTurn,
|
|
728
|
+
accumulateFriendTokens: tokens_1.accumulateFriendTokens,
|
|
729
|
+
signal: controller.signal,
|
|
730
|
+
runAgentOptions: agentOptions,
|
|
731
|
+
failoverState: teamsFailoverState,
|
|
467
732
|
});
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
}
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
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);
|
|
733
|
+
// ── Handle pipeline-intercepted commands ────────────────────────
|
|
734
|
+
if (result.turnOutcome === "command") {
|
|
735
|
+
if (result.commandAction === "new") {
|
|
484
736
|
(0, context_1.deleteSession)(sessPath);
|
|
485
737
|
stream.emit("session cleared");
|
|
486
|
-
return;
|
|
487
738
|
}
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
739
|
+
// For "response" commands: pipeline already emitted the response via onTextChunk
|
|
740
|
+
await callbacks.flush();
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
/* v8 ignore start -- failover display: tested via pipeline integration tests @preserve */
|
|
744
|
+
if (result.failoverMessage) {
|
|
745
|
+
stream.emit(result.failoverMessage);
|
|
746
|
+
}
|
|
747
|
+
else if (capturedTerminalError) {
|
|
748
|
+
callbacks.onError(capturedTerminalError, "terminal");
|
|
749
|
+
}
|
|
750
|
+
/* v8 ignore stop */
|
|
751
|
+
// ── Handle gate result ────────────────────────────────────────
|
|
752
|
+
if (!result.gateResult.allowed) {
|
|
753
|
+
if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
|
|
754
|
+
stream.emit(result.gateResult.autoReply);
|
|
491
755
|
}
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
// Flush any remaining accumulated text at end of turn
|
|
759
|
+
await callbacks.flush();
|
|
760
|
+
// After the agent loop, check if any tool returned AUTH_REQUIRED and trigger signin.
|
|
761
|
+
// This must happen after the stream is done so the OAuth card renders properly.
|
|
762
|
+
if (teamsContext && result.messages) {
|
|
763
|
+
const allContent = result.messages.map(m => typeof m.content === "string" ? m.content : "").join("\n");
|
|
764
|
+
if (allContent.includes("AUTH_REQUIRED:graph") && teamsContext.graphConnectionName)
|
|
765
|
+
await teamsContext.signin(teamsContext.graphConnectionName);
|
|
766
|
+
if (allContent.includes("AUTH_REQUIRED:ado") && teamsContext.adoConnectionName)
|
|
767
|
+
await teamsContext.signin(teamsContext.adoConnectionName);
|
|
768
|
+
if (allContent.includes("AUTH_REQUIRED:github") && teamsContext.githubConnectionName)
|
|
769
|
+
await teamsContext.signin(teamsContext.githubConnectionName);
|
|
770
|
+
}
|
|
771
|
+
if (result.turnOutcome !== "superseded") {
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
const supersedingIndex = drainedSteeringFollowUps
|
|
775
|
+
.map((followUp) => followUp.effect)
|
|
776
|
+
.lastIndexOf("clear_and_supersede");
|
|
777
|
+
if (supersedingIndex < 0) {
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
const supersedingFollowUp = drainedSteeringFollowUps[supersedingIndex];
|
|
781
|
+
const replayTail = drainedSteeringFollowUps
|
|
782
|
+
.slice(supersedingIndex + 1)
|
|
783
|
+
.map((followUp) => followUp.text.trim())
|
|
784
|
+
.filter((followUpText) => followUpText.length > 0)
|
|
785
|
+
.join("\n");
|
|
786
|
+
if (replayTail) {
|
|
787
|
+
currentText = replayTail;
|
|
788
|
+
continue;
|
|
492
789
|
}
|
|
790
|
+
if (handleTeamsSlashCommand(supersedingFollowUp.text, createTeamsCommandRegistry(), friendId, conversationId, stream, false)) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
currentText = supersedingFollowUp.text;
|
|
493
794
|
}
|
|
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)
|
|
535
795
|
}
|
|
536
|
-
//
|
|
537
|
-
//
|
|
538
|
-
|
|
539
|
-
|
|
796
|
+
// Internal port for the secondary bot App (not exposed externally).
|
|
797
|
+
// The primary app proxies /api/messages-secondary → localhost:SECONDARY_PORT/api/messages.
|
|
798
|
+
const SECONDARY_INTERNAL_PORT = 3979;
|
|
799
|
+
// Collect all unique OAuth connection names across top-level config and tenant overrides.
|
|
800
|
+
/* v8 ignore start -- runtime Teams SDK config; no unit-testable surface @preserve */
|
|
801
|
+
function allOAuthConnectionNames() {
|
|
802
|
+
const oauthConfig = (0, config_1.getOAuthConfig)();
|
|
803
|
+
const names = new Set();
|
|
804
|
+
if (oauthConfig.graphConnectionName)
|
|
805
|
+
names.add(oauthConfig.graphConnectionName);
|
|
806
|
+
if (oauthConfig.adoConnectionName)
|
|
807
|
+
names.add(oauthConfig.adoConnectionName);
|
|
808
|
+
if (oauthConfig.githubConnectionName)
|
|
809
|
+
names.add(oauthConfig.githubConnectionName);
|
|
810
|
+
if (oauthConfig.tenantOverrides) {
|
|
811
|
+
for (const ov of Object.values(oauthConfig.tenantOverrides)) {
|
|
812
|
+
if (ov.graphConnectionName)
|
|
813
|
+
names.add(ov.graphConnectionName);
|
|
814
|
+
if (ov.adoConnectionName)
|
|
815
|
+
names.add(ov.adoConnectionName);
|
|
816
|
+
if (ov.githubConnectionName)
|
|
817
|
+
names.add(ov.githubConnectionName);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return [...names];
|
|
821
|
+
}
|
|
822
|
+
// Create an App instance from a TeamsConfig. Returns { app, mode }.
|
|
823
|
+
function createBotApp(teamsConfig) {
|
|
540
824
|
const mentionStripping = { activity: { mentions: { stripText: true } } };
|
|
541
|
-
const teamsConfig = (0, config_2.getTeamsConfig)();
|
|
542
|
-
let app;
|
|
543
|
-
let mode;
|
|
544
825
|
const oauthConfig = (0, config_1.getOAuthConfig)();
|
|
545
|
-
if (teamsConfig.clientId) {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
826
|
+
if (teamsConfig.clientId && teamsConfig.clientSecret) {
|
|
827
|
+
return {
|
|
828
|
+
app: new teams_apps_1.App({
|
|
829
|
+
clientId: teamsConfig.clientId,
|
|
830
|
+
clientSecret: teamsConfig.clientSecret,
|
|
831
|
+
tenantId: teamsConfig.tenantId,
|
|
832
|
+
oauth: { defaultConnectionName: oauthConfig.graphConnectionName },
|
|
833
|
+
...mentionStripping,
|
|
834
|
+
}),
|
|
835
|
+
mode: "Bot Service (client secret)",
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
else if (teamsConfig.clientId) {
|
|
839
|
+
return {
|
|
840
|
+
app: new teams_apps_1.App({
|
|
841
|
+
clientId: teamsConfig.clientId,
|
|
842
|
+
tenantId: teamsConfig.tenantId,
|
|
843
|
+
...(teamsConfig.managedIdentityClientId ? { managedIdentityClientId: teamsConfig.managedIdentityClientId } : {}),
|
|
844
|
+
oauth: { defaultConnectionName: oauthConfig.graphConnectionName },
|
|
845
|
+
...mentionStripping,
|
|
846
|
+
}),
|
|
847
|
+
mode: "Bot Service (managed identity)",
|
|
848
|
+
};
|
|
555
849
|
}
|
|
556
850
|
else {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
851
|
+
return {
|
|
852
|
+
app: new teams_apps_1.App({
|
|
853
|
+
plugins: [new teams_dev_1.DevtoolsPlugin()],
|
|
854
|
+
...mentionStripping,
|
|
855
|
+
}),
|
|
856
|
+
mode: "DevtoolsPlugin",
|
|
857
|
+
};
|
|
563
858
|
}
|
|
859
|
+
}
|
|
860
|
+
/* v8 ignore stop */
|
|
861
|
+
// Register message, verify-state, and error handlers on an App instance.
|
|
862
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
863
|
+
function registerBotHandlers(app, label) {
|
|
864
|
+
const connectionNames = allOAuthConnectionNames();
|
|
564
865
|
// Override default OAuth verify-state handler. The SDK's built-in handler
|
|
565
866
|
// uses a single defaultConnectionName, which breaks multi-connection setups
|
|
566
867
|
// (graph + ado + github). The verifyState activity only carries a `state`
|
|
567
868
|
// code with no connectionName, so we try each configured connection until
|
|
568
869
|
// one succeeds.
|
|
569
|
-
const allConnectionNames = [
|
|
570
|
-
oauthConfig.graphConnectionName,
|
|
571
|
-
oauthConfig.adoConnectionName,
|
|
572
|
-
oauthConfig.githubConnectionName,
|
|
573
|
-
].filter(Boolean);
|
|
574
870
|
app.on("signin.verify-state", async (ctx) => {
|
|
575
871
|
const { api, activity } = ctx;
|
|
576
872
|
if (!activity.value?.state)
|
|
577
873
|
return { status: 404 };
|
|
578
|
-
for (const cn of
|
|
874
|
+
for (const cn of connectionNames) {
|
|
579
875
|
try {
|
|
580
876
|
await api.users.token.get({
|
|
581
877
|
channelId: activity.channelId,
|
|
@@ -583,14 +879,80 @@ function startTeamsApp() {
|
|
|
583
879
|
connectionName: cn,
|
|
584
880
|
code: activity.value.state,
|
|
585
881
|
});
|
|
586
|
-
(0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.verify_state", component: "channels", message: `verify-state succeeded for connection "${cn}"`, meta: { connectionName: cn } });
|
|
882
|
+
(0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.verify_state", component: "channels", message: `[${label}] verify-state succeeded for connection "${cn}"`, meta: { connectionName: cn } });
|
|
587
883
|
return { status: 200 };
|
|
588
884
|
}
|
|
589
885
|
catch { /* try next */ }
|
|
590
886
|
}
|
|
591
|
-
(0, runtime_1.emitNervesEvent)({ level: "warn", event: "channel.verify_state", component: "channels", message:
|
|
887
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", event: "channel.verify_state", component: "channels", message: `[${label}] verify-state failed for all connections`, meta: {} });
|
|
592
888
|
return { status: 412 };
|
|
593
889
|
});
|
|
890
|
+
// Handle Teams feedback reactions (thumbs up/down on AI-generated messages).
|
|
891
|
+
// SDK routes message/submitAction with actionName "feedback" to this event.
|
|
892
|
+
/* v8 ignore start -- Teams SDK invoke handler; requires live SDK context @preserve */
|
|
893
|
+
app.on("message.submit.feedback", async (ctx) => {
|
|
894
|
+
const { stream, activity } = ctx;
|
|
895
|
+
const reaction = activity.value?.actionValue?.reaction;
|
|
896
|
+
const comment = activity.value?.actionValue?.feedback;
|
|
897
|
+
const convId = activity.conversation?.id || "unknown";
|
|
898
|
+
const turnKey = teamsTurnKey(convId);
|
|
899
|
+
// Validate payload — graceful no-op for malformed invocations
|
|
900
|
+
if (activity.value?.actionName !== "feedback" || !reaction) {
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
const syntheticText = buildFeedbackSyntheticText(reaction, comment);
|
|
904
|
+
// Turn coordination: if a turn is active, enqueue as steering follow-up
|
|
905
|
+
if (!_turnCoordinator.tryBeginTurn(turnKey)) {
|
|
906
|
+
_turnCoordinator.enqueueFollowUp(turnKey, {
|
|
907
|
+
conversationId: convId,
|
|
908
|
+
text: syntheticText,
|
|
909
|
+
receivedAt: Date.now(),
|
|
910
|
+
effect: (0, continuity_1.classifySteeringFollowUpEffect)(syntheticText),
|
|
911
|
+
});
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
try {
|
|
915
|
+
const teamsContext = {
|
|
916
|
+
signin: async () => undefined,
|
|
917
|
+
aadObjectId: activity.from?.aadObjectId,
|
|
918
|
+
tenantId: activity.conversation?.tenantId,
|
|
919
|
+
displayName: activity.from?.name,
|
|
920
|
+
};
|
|
921
|
+
const ctxSend = async (t) => {
|
|
922
|
+
await ctx.send({ type: "message", text: t, replyToId: activity.replyToId, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
|
|
923
|
+
};
|
|
924
|
+
await handleTeamsMessage(syntheticText, stream, convId, teamsContext, ctxSend, { isReactionSignal: true, suppressEmptyStreamMessage: true });
|
|
925
|
+
}
|
|
926
|
+
catch (err) {
|
|
927
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
928
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.feedback_handler_error", component: "channels", message: msg.slice(0, 200), meta: {} });
|
|
929
|
+
}
|
|
930
|
+
finally {
|
|
931
|
+
_turnCoordinator.endTurn(turnKey);
|
|
932
|
+
}
|
|
933
|
+
});
|
|
934
|
+
/* v8 ignore stop */
|
|
935
|
+
// Handle bot install — send welcome Adaptive Card with prompt starters.
|
|
936
|
+
/* v8 ignore start -- Teams SDK install handler; requires live SDK context @preserve */
|
|
937
|
+
app.on("install.add", async (ctx) => {
|
|
938
|
+
try {
|
|
939
|
+
const card = buildWelcomeCard();
|
|
940
|
+
await ctx.send({
|
|
941
|
+
type: "message",
|
|
942
|
+
attachments: [{
|
|
943
|
+
contentType: "application/vnd.microsoft.card.adaptive",
|
|
944
|
+
content: card,
|
|
945
|
+
}],
|
|
946
|
+
entities: aiLabelEntities(),
|
|
947
|
+
channelData: { feedbackLoopEnabled: true },
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
catch (err) {
|
|
951
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
952
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.welcome_handler_error", component: "channels", message: msg.slice(0, 200), meta: {} });
|
|
953
|
+
}
|
|
954
|
+
});
|
|
955
|
+
/* v8 ignore stop */
|
|
594
956
|
app.on("message", async (ctx) => {
|
|
595
957
|
const { stream, activity, api, signin } = ctx;
|
|
596
958
|
const text = activity.text || "";
|
|
@@ -598,18 +960,49 @@ function startTeamsApp() {
|
|
|
598
960
|
const turnKey = teamsTurnKey(convId);
|
|
599
961
|
const userId = activity.from?.id || "";
|
|
600
962
|
const channelId = activity.channelId || "msteams";
|
|
601
|
-
(0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.message_received", component: "channels", message:
|
|
963
|
+
(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
964
|
// Resolve pending confirmations IMMEDIATELY — before token fetches or
|
|
603
965
|
// the conversation lock. The original message holds the lock while
|
|
604
966
|
// awaiting confirmation, so acquiring it here would deadlock. Token
|
|
605
967
|
// fetches are also unnecessary (and slow) for a simple yes/no reply.
|
|
606
968
|
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
969
|
return;
|
|
612
970
|
}
|
|
971
|
+
const commandRegistry = createTeamsCommandRegistry();
|
|
972
|
+
const parsedSlashCommand = (0, commands_1.parseSlashCommand)(text);
|
|
973
|
+
if (parsedSlashCommand) {
|
|
974
|
+
const dispatchResult = commandRegistry.dispatch(parsedSlashCommand.command, { channel: "teams" });
|
|
975
|
+
if (dispatchResult.handled && dispatchResult.result) {
|
|
976
|
+
if (dispatchResult.result.action === "response") {
|
|
977
|
+
stream.emit(dispatchResult.result.message || "");
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (dispatchResult.result.action === "new") {
|
|
981
|
+
const commandStore = getFriendStore();
|
|
982
|
+
const commandProvider = activity.from?.aadObjectId ? "aad" : "teams-conversation";
|
|
983
|
+
const commandExternalId = activity.from?.aadObjectId || convId;
|
|
984
|
+
const commandResolver = new resolver_1.FriendResolver(commandStore, {
|
|
985
|
+
provider: commandProvider,
|
|
986
|
+
externalId: commandExternalId,
|
|
987
|
+
tenantId: activity.conversation?.tenantId,
|
|
988
|
+
displayName: activity.from?.name || "Unknown",
|
|
989
|
+
channel: "teams",
|
|
990
|
+
});
|
|
991
|
+
const commandContext = await commandResolver.resolve();
|
|
992
|
+
(0, context_1.deleteSession)((0, config_2.sessionPath)(commandContext.friend.id, "teams", convId));
|
|
993
|
+
stream.emit("session cleared");
|
|
994
|
+
if (_turnCoordinator.isTurnActive(turnKey)) {
|
|
995
|
+
_turnCoordinator.enqueueFollowUp(turnKey, {
|
|
996
|
+
conversationId: convId,
|
|
997
|
+
text,
|
|
998
|
+
receivedAt: Date.now(),
|
|
999
|
+
effect: "clear_and_supersede",
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
613
1006
|
// If this conversation already has an active turn, steer follow-up input
|
|
614
1007
|
// into that turn and avoid starting a second concurrent turn.
|
|
615
1008
|
if (!_turnCoordinator.tryBeginTurn(turnKey)) {
|
|
@@ -617,31 +1010,35 @@ function startTeamsApp() {
|
|
|
617
1010
|
conversationId: convId,
|
|
618
1011
|
text,
|
|
619
1012
|
receivedAt: Date.now(),
|
|
1013
|
+
effect: (0, continuity_1.classifySteeringFollowUpEffect)(text),
|
|
620
1014
|
});
|
|
621
1015
|
return;
|
|
622
1016
|
}
|
|
623
1017
|
try {
|
|
1018
|
+
// Resolve OAuth connection names for this user's tenant (supports per-tenant overrides).
|
|
1019
|
+
const tenantId = activity.conversation?.tenantId;
|
|
1020
|
+
const tenantOAuth = (0, config_1.resolveOAuthForTenant)(tenantId);
|
|
624
1021
|
// Fetch tokens for both OAuth connections independently.
|
|
625
1022
|
// Failures are silently caught -- the tool handler will request signin if needed.
|
|
626
1023
|
let graphToken;
|
|
627
1024
|
let adoToken;
|
|
628
1025
|
let githubToken;
|
|
629
1026
|
try {
|
|
630
|
-
const graphRes = await api.users.token.get({ userId, connectionName:
|
|
1027
|
+
const graphRes = await api.users.token.get({ userId, connectionName: tenantOAuth.graphConnectionName, channelId });
|
|
631
1028
|
graphToken = graphRes?.token;
|
|
632
1029
|
}
|
|
633
1030
|
catch { /* no token yet — tool handler will trigger signin */ }
|
|
634
1031
|
try {
|
|
635
|
-
const adoRes = await api.users.token.get({ userId, connectionName:
|
|
1032
|
+
const adoRes = await api.users.token.get({ userId, connectionName: tenantOAuth.adoConnectionName, channelId });
|
|
636
1033
|
adoToken = adoRes?.token;
|
|
637
1034
|
}
|
|
638
1035
|
catch { /* no token yet — tool handler will trigger signin */ }
|
|
639
1036
|
try {
|
|
640
|
-
const githubRes = await api.users.token.get({ userId, connectionName:
|
|
1037
|
+
const githubRes = await api.users.token.get({ userId, connectionName: tenantOAuth.githubConnectionName, channelId });
|
|
641
1038
|
githubToken = githubRes?.token;
|
|
642
1039
|
}
|
|
643
1040
|
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 } });
|
|
1041
|
+
(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
1042
|
const teamsContext = {
|
|
646
1043
|
graphToken,
|
|
647
1044
|
adoToken,
|
|
@@ -661,12 +1058,17 @@ function startTeamsApp() {
|
|
|
661
1058
|
aadObjectId: activity.from?.aadObjectId,
|
|
662
1059
|
tenantId: activity.conversation?.tenantId,
|
|
663
1060
|
displayName: activity.from?.name,
|
|
1061
|
+
graphConnectionName: tenantOAuth.graphConnectionName,
|
|
1062
|
+
adoConnectionName: tenantOAuth.adoConnectionName,
|
|
1063
|
+
githubConnectionName: tenantOAuth.githubConnectionName,
|
|
1064
|
+
/* v8 ignore next -- bot API availability branch; requires live SDK context @preserve */
|
|
1065
|
+
botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
|
|
664
1066
|
};
|
|
665
1067
|
/* v8 ignore next 5 -- bot-framework integration callback; tested via handleTeamsMessage sendMessage path @preserve */
|
|
666
1068
|
const ctxSend = async (t) => {
|
|
667
1069
|
// Use send with replyToId (not reply, which adds a blockquote).
|
|
668
1070
|
// replyToId anchors the message after the user's message in Copilot Chat.
|
|
669
|
-
await ctx.send({ type: "message", text: t, replyToId: activity.id });
|
|
1071
|
+
await ctx.send({ type: "message", text: t, replyToId: activity.id, entities: aiLabelEntities(), channelData: { feedbackLoopEnabled: true } });
|
|
670
1072
|
};
|
|
671
1073
|
await handleTeamsMessage(text, stream, convId, teamsContext, ctxSend);
|
|
672
1074
|
}
|
|
@@ -678,6 +1080,227 @@ function startTeamsApp() {
|
|
|
678
1080
|
_turnCoordinator.endTurn(turnKey);
|
|
679
1081
|
}
|
|
680
1082
|
});
|
|
1083
|
+
app.event("error", ({ error }) => {
|
|
1084
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1085
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.app_error", component: "channels", message: `[${label}] ${msg}`, meta: {} });
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
function findAadObjectId(friend) {
|
|
1089
|
+
for (const ext of friend.externalIds) {
|
|
1090
|
+
if (ext.provider === "aad" && !ext.externalId.startsWith("group:")) {
|
|
1091
|
+
return { aadObjectId: ext.externalId, tenantId: ext.tenantId };
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return undefined;
|
|
1095
|
+
}
|
|
1096
|
+
function resolveTeamsFriendStore(deps) {
|
|
1097
|
+
return deps.store
|
|
1098
|
+
?? deps.createFriendStore?.()
|
|
1099
|
+
?? new store_file_1.FileFriendStore(path.join((0, identity_1.getAgentRoot)(), "friends"));
|
|
1100
|
+
}
|
|
1101
|
+
function getTeamsConversations(botApi) {
|
|
1102
|
+
return botApi.conversations;
|
|
1103
|
+
}
|
|
1104
|
+
function hasExplicitCrossChatAuthorization(params) {
|
|
1105
|
+
return params.intent === "explicit_cross_chat"
|
|
1106
|
+
&& types_1.TRUSTED_LEVELS.has(params.authorizingSession?.trustLevel ?? "stranger");
|
|
1107
|
+
}
|
|
1108
|
+
async function sendProactiveTeamsMessageToSession(params, deps) {
|
|
1109
|
+
const store = resolveTeamsFriendStore(deps);
|
|
1110
|
+
const conversations = getTeamsConversations(deps.botApi);
|
|
1111
|
+
let friend;
|
|
1112
|
+
try {
|
|
1113
|
+
friend = await store.get(params.friendId);
|
|
1114
|
+
}
|
|
1115
|
+
catch {
|
|
1116
|
+
friend = null;
|
|
1117
|
+
}
|
|
1118
|
+
if (!friend) {
|
|
1119
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1120
|
+
level: "warn",
|
|
1121
|
+
component: "senses",
|
|
1122
|
+
event: "senses.teams_proactive_no_friend",
|
|
1123
|
+
message: "proactive send skipped: friend not found",
|
|
1124
|
+
meta: { friendId: params.friendId, sessionKey: params.sessionKey },
|
|
1125
|
+
});
|
|
1126
|
+
return { delivered: false, reason: "friend_not_found" };
|
|
1127
|
+
}
|
|
1128
|
+
if (!hasExplicitCrossChatAuthorization(params) && !types_1.TRUSTED_LEVELS.has(friend.trustLevel ?? "stranger")) {
|
|
1129
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1130
|
+
component: "senses",
|
|
1131
|
+
event: "senses.teams_proactive_trust_skip",
|
|
1132
|
+
message: "proactive send skipped: trust level not allowed",
|
|
1133
|
+
meta: {
|
|
1134
|
+
friendId: params.friendId,
|
|
1135
|
+
trustLevel: friend.trustLevel ?? "unknown",
|
|
1136
|
+
intent: params.intent ?? "generic_outreach",
|
|
1137
|
+
authorizingTrustLevel: params.authorizingSession?.trustLevel ?? null,
|
|
1138
|
+
},
|
|
1139
|
+
});
|
|
1140
|
+
return { delivered: false, reason: "trust_skip" };
|
|
1141
|
+
}
|
|
1142
|
+
const aadInfo = findAadObjectId(friend);
|
|
1143
|
+
if (!aadInfo) {
|
|
1144
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1145
|
+
level: "warn",
|
|
1146
|
+
component: "senses",
|
|
1147
|
+
event: "senses.teams_proactive_no_aad_id",
|
|
1148
|
+
message: "proactive send skipped: no AAD object ID found",
|
|
1149
|
+
meta: { friendId: params.friendId, sessionKey: params.sessionKey },
|
|
1150
|
+
});
|
|
1151
|
+
return { delivered: false, reason: "missing_target" };
|
|
1152
|
+
}
|
|
1153
|
+
try {
|
|
1154
|
+
const conversation = await conversations.create({
|
|
1155
|
+
bot: { id: deps.botApi.id },
|
|
1156
|
+
members: [{ id: aadInfo.aadObjectId, role: "user", name: friend.name || aadInfo.aadObjectId }],
|
|
1157
|
+
tenantId: aadInfo.tenantId,
|
|
1158
|
+
isGroup: false,
|
|
1159
|
+
});
|
|
1160
|
+
await conversations.activities(conversation.id).create({
|
|
1161
|
+
type: "message",
|
|
1162
|
+
text: params.text,
|
|
1163
|
+
});
|
|
1164
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1165
|
+
component: "senses",
|
|
1166
|
+
event: "senses.teams_proactive_sent",
|
|
1167
|
+
message: "proactive teams message sent",
|
|
1168
|
+
meta: { friendId: params.friendId, aadObjectId: aadInfo.aadObjectId, sessionKey: params.sessionKey },
|
|
1169
|
+
});
|
|
1170
|
+
return { delivered: true };
|
|
1171
|
+
}
|
|
1172
|
+
catch (error) {
|
|
1173
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1174
|
+
level: "error",
|
|
1175
|
+
component: "senses",
|
|
1176
|
+
event: "senses.teams_proactive_send_error",
|
|
1177
|
+
message: "proactive teams send failed",
|
|
1178
|
+
meta: {
|
|
1179
|
+
friendId: params.friendId,
|
|
1180
|
+
aadObjectId: aadInfo.aadObjectId,
|
|
1181
|
+
sessionKey: params.sessionKey,
|
|
1182
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
1183
|
+
},
|
|
1184
|
+
});
|
|
1185
|
+
return { delivered: false, reason: "send_error" };
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
function scanPendingTeamsFiles(pendingRoot) {
|
|
1189
|
+
const results = [];
|
|
1190
|
+
let friendIds;
|
|
1191
|
+
try {
|
|
1192
|
+
friendIds = fs.readdirSync(pendingRoot);
|
|
1193
|
+
}
|
|
1194
|
+
catch {
|
|
1195
|
+
return results;
|
|
1196
|
+
}
|
|
1197
|
+
for (const friendId of friendIds) {
|
|
1198
|
+
const teamsDir = path.join(pendingRoot, friendId, "teams");
|
|
1199
|
+
let keys;
|
|
1200
|
+
try {
|
|
1201
|
+
keys = fs.readdirSync(teamsDir);
|
|
1202
|
+
}
|
|
1203
|
+
catch {
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
for (const key of keys) {
|
|
1207
|
+
const keyDir = path.join(teamsDir, key);
|
|
1208
|
+
let files;
|
|
1209
|
+
try {
|
|
1210
|
+
files = fs.readdirSync(keyDir);
|
|
1211
|
+
}
|
|
1212
|
+
catch {
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
|
|
1216
|
+
const filePath = path.join(keyDir, file);
|
|
1217
|
+
try {
|
|
1218
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
1219
|
+
results.push({ friendId, key, filePath, content });
|
|
1220
|
+
}
|
|
1221
|
+
catch {
|
|
1222
|
+
// skip unreadable files
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
return results;
|
|
1228
|
+
}
|
|
1229
|
+
async function drainAndSendPendingTeams(store, botApi, pendingRoot) {
|
|
1230
|
+
const root = pendingRoot ?? path.join((0, identity_1.getAgentRoot)(), "state", "pending");
|
|
1231
|
+
const pendingFiles = scanPendingTeamsFiles(root);
|
|
1232
|
+
const result = { sent: 0, skipped: 0, failed: 0 };
|
|
1233
|
+
for (const { friendId, key, filePath, content } of pendingFiles) {
|
|
1234
|
+
let parsed;
|
|
1235
|
+
try {
|
|
1236
|
+
parsed = JSON.parse(content);
|
|
1237
|
+
}
|
|
1238
|
+
catch {
|
|
1239
|
+
result.failed++;
|
|
1240
|
+
try {
|
|
1241
|
+
fs.unlinkSync(filePath);
|
|
1242
|
+
}
|
|
1243
|
+
catch { /* ignore */ }
|
|
1244
|
+
continue;
|
|
1245
|
+
}
|
|
1246
|
+
const messageText = typeof parsed.content === "string" ? parsed.content : "";
|
|
1247
|
+
if (!messageText.trim()) {
|
|
1248
|
+
result.skipped++;
|
|
1249
|
+
try {
|
|
1250
|
+
fs.unlinkSync(filePath);
|
|
1251
|
+
}
|
|
1252
|
+
catch { /* ignore */ }
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const sendResult = await sendProactiveTeamsMessageToSession({
|
|
1256
|
+
friendId,
|
|
1257
|
+
sessionKey: key,
|
|
1258
|
+
text: messageText,
|
|
1259
|
+
intent: "generic_outreach",
|
|
1260
|
+
}, {
|
|
1261
|
+
botApi,
|
|
1262
|
+
store,
|
|
1263
|
+
});
|
|
1264
|
+
if (sendResult.delivered) {
|
|
1265
|
+
result.sent++;
|
|
1266
|
+
try {
|
|
1267
|
+
fs.unlinkSync(filePath);
|
|
1268
|
+
}
|
|
1269
|
+
catch { /* ignore */ }
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
if (sendResult.reason === "friend_not_found" || sendResult.reason === "trust_skip" || sendResult.reason === "missing_target") {
|
|
1273
|
+
result.skipped++;
|
|
1274
|
+
try {
|
|
1275
|
+
fs.unlinkSync(filePath);
|
|
1276
|
+
}
|
|
1277
|
+
catch { /* ignore */ }
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
result.failed++;
|
|
1281
|
+
}
|
|
1282
|
+
if (result.sent > 0 || result.skipped > 0 || result.failed > 0) {
|
|
1283
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1284
|
+
component: "senses",
|
|
1285
|
+
event: "senses.teams_proactive_drain_complete",
|
|
1286
|
+
message: "teams proactive drain complete",
|
|
1287
|
+
meta: { sent: result.sent, skipped: result.skipped, failed: result.failed },
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
return result;
|
|
1291
|
+
}
|
|
1292
|
+
// Start the Teams app in DevtoolsPlugin mode (local dev) or Bot Service mode (real Teams).
|
|
1293
|
+
// Mode is determined by getTeamsConfig().clientId.
|
|
1294
|
+
// Text is always accumulated in textBuffer and flushed periodically (chunked streaming).
|
|
1295
|
+
//
|
|
1296
|
+
// Dual-bot support: if teamsSecondary is configured with a clientId, a second App
|
|
1297
|
+
// instance starts on an internal port and the primary app proxies requests from
|
|
1298
|
+
// /api/messages-secondary to it. This lets a single App Service serve two bot
|
|
1299
|
+
// registrations (e.g. one per tenant) without SDK modifications.
|
|
1300
|
+
function startTeamsApp() {
|
|
1301
|
+
const teamsConfig = (0, config_2.getTeamsConfig)();
|
|
1302
|
+
const { app, mode } = createBotApp(teamsConfig);
|
|
1303
|
+
registerBotHandlers(app, "primary");
|
|
681
1304
|
if (!process.listeners("unhandledRejection").some((l) => l.__agentHandler)) {
|
|
682
1305
|
const handler = (err) => {
|
|
683
1306
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -686,11 +1309,54 @@ function startTeamsApp() {
|
|
|
686
1309
|
handler.__agentHandler = true;
|
|
687
1310
|
process.on("unhandledRejection", handler);
|
|
688
1311
|
}
|
|
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;
|
|
1312
|
+
/* v8 ignore next -- PORT env branch; runtime-only @preserve */
|
|
1313
|
+
const port = process.env.PORT ? Number(process.env.PORT) : (0, config_2.getTeamsChannelConfig)().port;
|
|
694
1314
|
app.start(port);
|
|
695
|
-
|
|
1315
|
+
// Diagnostic: log tool count at startup to verify deploy
|
|
1316
|
+
const startupTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)("teams"));
|
|
1317
|
+
const toolNames = startupTools.map((t) => t.function.name);
|
|
1318
|
+
(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") } });
|
|
1319
|
+
// --- Secondary bot (dual-bot support) ---
|
|
1320
|
+
// If teamsSecondary has a clientId, start a second App on an internal port
|
|
1321
|
+
// and proxy /api/messages-secondary on the primary app to it.
|
|
1322
|
+
/* v8 ignore start -- dual-bot proxy wiring; requires live Teams SDK + HTTP @preserve */
|
|
1323
|
+
const secondaryConfig = (0, config_1.getTeamsSecondaryConfig)();
|
|
1324
|
+
if (secondaryConfig.clientId) {
|
|
1325
|
+
const { app: secondaryApp, mode: secondaryMode } = createBotApp(secondaryConfig);
|
|
1326
|
+
registerBotHandlers(secondaryApp, "secondary");
|
|
1327
|
+
secondaryApp.start(SECONDARY_INTERNAL_PORT);
|
|
1328
|
+
(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 } });
|
|
1329
|
+
// Proxy: forward /api/messages-secondary on the primary app's Express
|
|
1330
|
+
// to localhost:SECONDARY_INTERNAL_PORT/api/messages.
|
|
1331
|
+
// The SDK's HttpPlugin exposes .post() bound to its Express instance.
|
|
1332
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1333
|
+
const httpPlugin = app.http;
|
|
1334
|
+
httpPlugin.post("/api/messages-secondary", (req, res) => {
|
|
1335
|
+
const body = JSON.stringify(req.body);
|
|
1336
|
+
const proxyReq = http.request({
|
|
1337
|
+
hostname: "127.0.0.1",
|
|
1338
|
+
port: SECONDARY_INTERNAL_PORT,
|
|
1339
|
+
path: "/api/messages",
|
|
1340
|
+
method: "POST",
|
|
1341
|
+
headers: {
|
|
1342
|
+
...req.headers,
|
|
1343
|
+
"content-length": Buffer.byteLength(body).toString(),
|
|
1344
|
+
},
|
|
1345
|
+
}, (proxyRes) => {
|
|
1346
|
+
res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
|
|
1347
|
+
proxyRes.pipe(res);
|
|
1348
|
+
});
|
|
1349
|
+
proxyReq.on("error", (err) => {
|
|
1350
|
+
(0, runtime_1.emitNervesEvent)({ level: "error", event: "channel.proxy_error", component: "channels", message: `secondary proxy error: ${err.message}`, meta: {} });
|
|
1351
|
+
if (!res.headersSent) {
|
|
1352
|
+
res.writeHead(502);
|
|
1353
|
+
res.end("Bad Gateway");
|
|
1354
|
+
}
|
|
1355
|
+
});
|
|
1356
|
+
proxyReq.write(body);
|
|
1357
|
+
proxyReq.end();
|
|
1358
|
+
});
|
|
1359
|
+
(0, runtime_1.emitNervesEvent)({ level: "info", event: "channel.proxy_ready", component: "channels", message: "proxy /api/messages-secondary → secondary bot ready", meta: {} });
|
|
1360
|
+
}
|
|
1361
|
+
/* v8 ignore stop */
|
|
696
1362
|
}
|