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