@open-everywhere/provider-teams 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +46 -2
  4. package/agent/channels/teams-bot-name.ts +162 -0
  5. package/agent/channels/teams-catch-up.ts +244 -0
  6. package/agent/channels/teams-connector.ts +183 -0
  7. package/agent/channels/teams-conversation-ref.ts +398 -0
  8. package/agent/channels/teams-directory.ts +193 -0
  9. package/agent/channels/teams-engagement.ts +391 -0
  10. package/agent/channels/teams-fire-eligibility.ts +152 -0
  11. package/agent/channels/teams-front.ts +1404 -0
  12. package/agent/channels/teams-graph-boundary.ts +178 -0
  13. package/agent/channels/teams-graph-team-id.ts +106 -0
  14. package/agent/channels/teams-id-restore.ts +131 -0
  15. package/agent/channels/teams-identity.ts +395 -0
  16. package/agent/channels/teams-input-response.ts +129 -0
  17. package/agent/channels/teams-message-ops.ts +79 -0
  18. package/agent/channels/teams-origin-codec.ts +104 -0
  19. package/agent/channels/teams-post-arm.ts +323 -0
  20. package/agent/channels/teams-reaction-feedback.ts +127 -0
  21. package/agent/channels/teams-read.ts +510 -0
  22. package/agent/channels/teams-roster.ts +136 -0
  23. package/agent/channels/teams-stop.ts +319 -0
  24. package/agent/channels/teams-supervisor.ts +638 -0
  25. package/agent/channels/teams.ts +270 -0
  26. package/agent/contributions.ts +31 -0
  27. package/agent/docs-generated.ts +15 -0
  28. package/agent/ops.ts +129 -0
  29. package/agent/provider-events.ts +69 -0
  30. package/agent/register.ts +219 -0
  31. package/agent/surface-parity.ts +112 -0
  32. package/dist/agent/channels/teams-bot-name.d.ts +36 -0
  33. package/dist/agent/channels/teams-bot-name.d.ts.map +1 -0
  34. package/dist/agent/channels/teams-bot-name.js +141 -0
  35. package/dist/agent/channels/teams-bot-name.js.map +1 -0
  36. package/dist/agent/channels/teams-catch-up.d.ts +53 -0
  37. package/dist/agent/channels/teams-catch-up.d.ts.map +1 -0
  38. package/dist/agent/channels/teams-catch-up.js +221 -0
  39. package/dist/agent/channels/teams-catch-up.js.map +1 -0
  40. package/dist/agent/channels/teams-connector.d.ts +57 -0
  41. package/dist/agent/channels/teams-connector.d.ts.map +1 -0
  42. package/dist/agent/channels/teams-connector.js +132 -0
  43. package/dist/agent/channels/teams-connector.js.map +1 -0
  44. package/dist/agent/channels/teams-conversation-ref.d.ts +123 -0
  45. package/dist/agent/channels/teams-conversation-ref.d.ts.map +1 -0
  46. package/dist/agent/channels/teams-conversation-ref.js +368 -0
  47. package/dist/agent/channels/teams-conversation-ref.js.map +1 -0
  48. package/dist/agent/channels/teams-directory.d.ts +11 -0
  49. package/dist/agent/channels/teams-directory.d.ts.map +1 -0
  50. package/dist/agent/channels/teams-directory.js +179 -0
  51. package/dist/agent/channels/teams-directory.js.map +1 -0
  52. package/dist/agent/channels/teams-engagement.d.ts +174 -0
  53. package/dist/agent/channels/teams-engagement.d.ts.map +1 -0
  54. package/dist/agent/channels/teams-engagement.js +336 -0
  55. package/dist/agent/channels/teams-engagement.js.map +1 -0
  56. package/dist/agent/channels/teams-fire-eligibility.d.ts +26 -0
  57. package/dist/agent/channels/teams-fire-eligibility.d.ts.map +1 -0
  58. package/dist/agent/channels/teams-fire-eligibility.js +126 -0
  59. package/dist/agent/channels/teams-fire-eligibility.js.map +1 -0
  60. package/dist/agent/channels/teams-front.d.ts +249 -0
  61. package/dist/agent/channels/teams-front.d.ts.map +1 -0
  62. package/dist/agent/channels/teams-front.js +1143 -0
  63. package/dist/agent/channels/teams-front.js.map +1 -0
  64. package/dist/agent/channels/teams-graph-boundary.d.ts +45 -0
  65. package/dist/agent/channels/teams-graph-boundary.d.ts.map +1 -0
  66. package/dist/agent/channels/teams-graph-boundary.js +168 -0
  67. package/dist/agent/channels/teams-graph-boundary.js.map +1 -0
  68. package/dist/agent/channels/teams-graph-team-id.d.ts +30 -0
  69. package/dist/agent/channels/teams-graph-team-id.d.ts.map +1 -0
  70. package/dist/agent/channels/teams-graph-team-id.js +89 -0
  71. package/dist/agent/channels/teams-graph-team-id.js.map +1 -0
  72. package/dist/agent/channels/teams-id-restore.d.ts +34 -0
  73. package/dist/agent/channels/teams-id-restore.d.ts.map +1 -0
  74. package/dist/agent/channels/teams-id-restore.js +123 -0
  75. package/dist/agent/channels/teams-id-restore.js.map +1 -0
  76. package/dist/agent/channels/teams-identity.d.ts +148 -0
  77. package/dist/agent/channels/teams-identity.d.ts.map +1 -0
  78. package/dist/agent/channels/teams-identity.js +336 -0
  79. package/dist/agent/channels/teams-identity.js.map +1 -0
  80. package/dist/agent/channels/teams-input-response.d.ts +23 -0
  81. package/dist/agent/channels/teams-input-response.d.ts.map +1 -0
  82. package/dist/agent/channels/teams-input-response.js +102 -0
  83. package/dist/agent/channels/teams-input-response.js.map +1 -0
  84. package/dist/agent/channels/teams-message-ops.d.ts +3 -0
  85. package/dist/agent/channels/teams-message-ops.d.ts.map +1 -0
  86. package/dist/agent/channels/teams-message-ops.js +72 -0
  87. package/dist/agent/channels/teams-message-ops.js.map +1 -0
  88. package/dist/agent/channels/teams-origin-codec.d.ts +16 -0
  89. package/dist/agent/channels/teams-origin-codec.d.ts.map +1 -0
  90. package/dist/agent/channels/teams-origin-codec.js +99 -0
  91. package/dist/agent/channels/teams-origin-codec.js.map +1 -0
  92. package/dist/agent/channels/teams-post-arm.d.ts +37 -0
  93. package/dist/agent/channels/teams-post-arm.d.ts.map +1 -0
  94. package/dist/agent/channels/teams-post-arm.js +280 -0
  95. package/dist/agent/channels/teams-post-arm.js.map +1 -0
  96. package/dist/agent/channels/teams-reaction-feedback.d.ts +22 -0
  97. package/dist/agent/channels/teams-reaction-feedback.d.ts.map +1 -0
  98. package/dist/agent/channels/teams-reaction-feedback.js +108 -0
  99. package/dist/agent/channels/teams-reaction-feedback.js.map +1 -0
  100. package/dist/agent/channels/teams-read.d.ts +127 -0
  101. package/dist/agent/channels/teams-read.d.ts.map +1 -0
  102. package/dist/agent/channels/teams-read.js +424 -0
  103. package/dist/agent/channels/teams-read.js.map +1 -0
  104. package/dist/agent/channels/teams-roster.d.ts +54 -0
  105. package/dist/agent/channels/teams-roster.d.ts.map +1 -0
  106. package/dist/agent/channels/teams-roster.js +121 -0
  107. package/dist/agent/channels/teams-roster.js.map +1 -0
  108. package/dist/agent/channels/teams-stop.d.ts +74 -0
  109. package/dist/agent/channels/teams-stop.d.ts.map +1 -0
  110. package/dist/agent/channels/teams-stop.js +252 -0
  111. package/dist/agent/channels/teams-stop.js.map +1 -0
  112. package/dist/agent/channels/teams-supervisor.d.ts +351 -0
  113. package/dist/agent/channels/teams-supervisor.d.ts.map +1 -0
  114. package/dist/agent/channels/teams-supervisor.js +366 -0
  115. package/dist/agent/channels/teams-supervisor.js.map +1 -0
  116. package/dist/agent/channels/teams.d.ts +5 -0
  117. package/dist/agent/channels/teams.d.ts.map +1 -0
  118. package/dist/agent/channels/teams.js +246 -0
  119. package/dist/agent/channels/teams.js.map +1 -0
  120. package/dist/agent/contributions.d.ts +12 -0
  121. package/dist/agent/contributions.d.ts.map +1 -0
  122. package/dist/agent/contributions.js +31 -0
  123. package/dist/agent/contributions.js.map +1 -0
  124. package/dist/agent/docs-generated.d.ts +3 -0
  125. package/dist/agent/docs-generated.d.ts.map +1 -0
  126. package/dist/agent/docs-generated.js +13 -0
  127. package/dist/agent/docs-generated.js.map +1 -0
  128. package/dist/agent/ops.d.ts +14 -0
  129. package/dist/agent/ops.d.ts.map +1 -0
  130. package/dist/agent/ops.js +122 -0
  131. package/dist/agent/ops.js.map +1 -0
  132. package/dist/agent/provider-events.d.ts +3 -0
  133. package/dist/agent/provider-events.d.ts.map +1 -0
  134. package/dist/agent/provider-events.js +67 -0
  135. package/dist/agent/provider-events.js.map +1 -0
  136. package/dist/agent/register.d.ts +16 -0
  137. package/dist/agent/register.d.ts.map +1 -0
  138. package/dist/agent/register.js +198 -0
  139. package/dist/agent/register.js.map +1 -0
  140. package/dist/agent/surface-parity.d.ts +3 -0
  141. package/dist/agent/surface-parity.d.ts.map +1 -0
  142. package/dist/agent/surface-parity.js +106 -0
  143. package/dist/agent/surface-parity.js.map +1 -0
  144. package/package.json +183 -4
  145. package/tsconfig.build.json +22 -0
  146. package/tsconfig.json +15 -0
@@ -0,0 +1,638 @@
1
+ // The Microsoft Teams SINGLE-WINDOW core — the eve-FREE tested half of the Teams cross-surface
2
+ // window legs (the FIFTH surface after Slack/GitHub/Linear/Notion; teams-front.ts is the live
3
+ // wiring). Teams is deliberately NARROWER than the other surfaces: it has no per-conversation
4
+ // ambient supervisor of its own, so this core exists ONLY for the single-window mode — every
5
+ // dispatch that reaches it carries a window and is delivered into the synthetic `unified`
6
+ // channel (channels/unified.ts). Flag-off, teams-front forwards every activity to eve's native
7
+ // teamsChannel untouched and nothing in this file runs: byte-identical.
8
+ //
9
+ // WHAT'S REUSED WHOLESALE (zero Teams-specific logic in any of it):
10
+ // • singleWindowMentionPolicy — the ONE shared mention seam — unified-window.ts
11
+ // • renderWake + the channel-watch / direct-mention preambles — normalized-wake.ts
12
+ // • shouldRotate — the pure rotation policy — slack-events.ts (via the live deps)
13
+ // WHAT'S NEW (this file): the Teams PRIVACY FLOOR (the load-bearing decision — see
14
+ // teamsSingleWindowPrivacyOk), the single-window plan, the NormalizedWake builder, and the
15
+ // dispatch core (session get-or-create → build → wake), each mirroring
16
+ // the Notion equivalents (planNotionSingleWindow / buildNotionSupervisorWake /
17
+ // handleNotionSupervisorDispatch) — the closest prior single-leg surface.
18
+ //
19
+ // SINGLE-LEG BY CONSTRUCTION (the Slack build's hard-won lesson): Slack fires TWO webhooks for
20
+ // one @mention (app_mention + its message.channels sibling), and the original two-leg
21
+ // suppress/deliver design could disagree across webhooks and LOSE the mention — the fix was to
22
+ // divert the mention event itself in one leg. Teams never had the hazard: ONE Bot-Framework
23
+ // activity per message, ONE synchronous policy read (the vouch register is a set lookup — no
24
+ // network, no TTL cache to go stale between legs), ONE verdict driving both "suppress the
25
+ // native forward" and "deliver as an addressed wake". There is no second webhook to coordinate
26
+ // with, so neither a lost mention nor a double answer is structurally possible.
27
+
28
+ import {
29
+ spreadVendorTs,
30
+ type VendorEventTime,
31
+ renderWake,
32
+ mkMessageTrigger,
33
+ mintWakeId,
34
+ singleWindowMentionPolicy,
35
+ type NormalizedWake,
36
+ type WakeEngagementTier,
37
+ type WakeTrust,
38
+ type SingleWindowMentionPolicy,
39
+ type UnifiedWindowWake,
40
+ type WakeMessageInput,
41
+ tailAuthorGrain,
42
+ type IngestedChatMessage,
43
+ type SessionTailWakeRow,
44
+ seatCatchUpSinceMs,
45
+ catchUpUnavailableReason,
46
+ type SeatCatchUpRequest,
47
+ type SeatCatchUpResult,
48
+ } from "@open-everywhere/core/agent/adapter-api.js";
49
+ import type { OpenEverywhereTeamsAuth } from "./teams-identity.js";
50
+
51
+ /** The catch-up's REACHBACK FLOOR (hours): how far back a seat that has been quiet for a long time
52
+ * reads. 7 days, the same floor every other surface uses. */
53
+ const TEAMS_CATCH_UP_REACHBACK_HOURS = 168;
54
+
55
+ /**
56
+ * What a seat is told when THIS wake could not resolve the team's Graph address (OPE-1808). TRUSTED,
57
+ * OE-authored and CONSTANT, the same posture as core's `catchUpUnavailableReason`, and deliberately
58
+ * NOT that sentence: this bound is about one wake, not about the surface, and the seat must not be
59
+ * told Teams cannot read its own history when the next wake may read it perfectly well. It states the
60
+ * bound the seat has to act on either way — an empty context here is not evidence of a quiet room.
61
+ */
62
+ const TEAM_ADDRESS_UNRESOLVED_NOTE =
63
+ "teams: this team's Microsoft 365 group id could not be resolved on this wake, so the channel's history since your last wake is NOT shown. That is a failure to READ, not a quiet room — an absence of messages here says nothing about what was said.";
64
+
65
+ // --- supervisor token / sentinel (carry the :oe-sup:g infix — load-bearing) ----------
66
+ //
67
+ // hooks/spend.ts isSupervisorToken keys off the `:oe-sup:g` substring to (a) tag the usage-event
68
+ // `kind="supervisor"` and (b) drive the per-generation cumulative-token rotation counter. Carry
69
+ // the infix and the whole cost/rotation apparatus works for free. In practice Teams only ever
70
+ // dispatches on a unified singleWindow grain (the token is unifiedSupervisorToken's), so this
71
+ // per-container form exists for supervisorTokenForGrain's `perContainer` thunk + shape parity
72
+ // with the other surfaces (notionSupervisorToken et al.), not as a live path.
73
+
74
+ /** The reserved pseudo-thread sentinel for a supervisor generation (mirrors Slack's). */
75
+ function teamsSupervisorSentinel(generation: number): string {
76
+ return `oe-sup:g${generation}`;
77
+ }
78
+
79
+ /** The per-container supervisor token for a Teams channel container (the grain fallback —
80
+ * see the header note; a live Teams dispatch always resolves the unified domain token). */
81
+ export function teamsSupervisorToken(channelKey: string, generation: number): string {
82
+ return `teams:${channelKey}:${teamsSupervisorSentinel(generation)}`;
83
+ }
84
+
85
+ // --- THE PRIVACY FLOOR (fail-closed — the load-bearing security decision) --------------------
86
+
87
+ /** The host-extracted Teams facts the floor decides from — every field comes off the
88
+ * JWT-VERIFIED inbound activity (or the operator's own registers), never model output. */
89
+ export interface TeamsSingleWindowFacts {
90
+ /** Normalized conversation scope ("personal" | "groupChat" | "channel" | "unknown"). */
91
+ readonly scope: string | undefined;
92
+ /** Channel membershipType ("standard" | "private" | "shared") when the activity's channelData
93
+ * positively carried it — inbound activities usually OMIT it (teams-identity.ts). */
94
+ readonly membershipType?: string;
95
+ /** The tenant (org boundary). Absent ⇒ the surface can't be anchored to an org ⇒ refuse. */
96
+ readonly tenantId?: string;
97
+ /** The operator's explicit vouch for THIS surface: isVouchedSurface on the channel key AND the
98
+ * team rung, which WALKS the declaration rungs (OPE-1521/OPE-1538), so a tenant-grain
99
+ * `teams/<tenant>` declaration vouches every room under it and a `public` `team:<id>` carve-out
100
+ * demotes one team out of it — see below. Or the blanket OE_TRUST=internal. Resolved by the
101
+ * live wiring (teams-front.ts). */
102
+ readonly vouched: boolean;
103
+ }
104
+
105
+ /**
106
+ * The Teams privacy floor for the cross-surface window, FAIL-CLOSED. Every surface has one so a
107
+ * public/external surface can never join a private shared window (GitHub: `repository.private
108
+ * === true`; Slack: positively-confirmed-internal channel/group; Linear: team positively
109
+ * private; Notion: operator vouch). Teams' rule:
110
+ *
111
+ * ADMIT ⟺ scope === "channel" AND tenantId present AND membershipType ≠ "shared"
112
+ * AND the OPERATOR VOUCHED the surface (vouch register / OE_TRUST=internal).
113
+ *
114
+ * WHY OPERATOR-VOUCH AND NOT A PLATFORM SIGNAL (the Notion posture, deliberately): Teams has NO
115
+ * reliable in-band fact that means "internal-only, no external eyes".
116
+ * • `membershipType` is usually ABSENT on inbound activities, and even when positively
117
+ * "standard" or "private" it does NOT exclude tenant GUESTS — a guest (an external identity
118
+ * invited into the tenant) sees every standard channel of the teams they're on, and can be a
119
+ * member of private channels too. So the memory-gate verdict (teams-identity.ts teamsTrust,
120
+ * which reads standard/private+tenant as internal) is deliberately NOT sufficient here —
121
+ * the window floor is STRICTER than the memory floor.
122
+ * • A Graph roster sweep (TeamMember.Read.All → userType === "Guest") could positively prove
123
+ * guest-freedom, but OE has no Graph credential plane wired (the bot speaks Bot Connector
124
+ * only), the sweep is racy (membership changes after the check), and Bot-Framework
125
+ * pagedMembers' `userRole` is not a documented-reliable field — inventing a weaker signal
126
+ * is exactly what the floor doctrine forbids. So: the operator vouches, code enforces.
127
+ *
128
+ * ATTACKER ANALYSIS: the leak vector is a message from a surface visible outside the org being
129
+ * admitted to (and answered from) a private cross-surface window. All four conjuncts are
130
+ * host-derived: scope/membershipType/tenantId come off the Bot-Connector-signed activity (a
131
+ * user cannot author channelData — the Teams service stamps it), and the vouch is the
132
+ * operator's own register. Absence of membershipType never ADMITS (only the vouch admits;
133
+ * membershipType only REFUSES). The one positive-external fact we CAN see — membershipType ===
134
+ * "shared", a Teams Connect shared channel spanning tenants — refuses EVEN WHEN VOUCHED (a
135
+ * positive cross-org fact beats a standing assertion). BUT membershipType is usually ABSENT
136
+ * inbound, and an absent signal never demotes, so that guard catches only the rooms Teams labels
137
+ * for us.
138
+ *
139
+ * 🔴 THERE IS NO EXACT-GRAIN BACKSTOP BEHIND IT — the operator's declaration IS the protection.
140
+ * `isVouchedSurface` walks the declaration rungs (OPE-1521), the same most-specific-wins walk every
141
+ * other trust reader uses, and since OPE-1538 the wiring hands it the TEAM rung too, so the walk
142
+ * here has the same reach the binding and memory planes have: a `public` `teams/<tenant>/team:<id>`
143
+ * carve-out now demotes one team out of an internal tenant at this floor, where it used to be
144
+ * skipped and the room admitted. A coarse `teams/<tenant>` declaration still admits EVERY room under
145
+ * that tenant that no narrower entry demotes. `agent/identity/surfaces.ts` ships exactly such a tenant line today. A native
146
+ * internal channel and a cross-tenant Connect/shared channel look alike at that grain, so a
147
+ * shared room whose inbound activities omit membershipType IS admitted on the tenant line. That is
148
+ * the ruling, not a gap: a declaration vouches, and only a POSITIVE external signal demotes. The
149
+ * operator narrows the reach by declaring the channel rung instead. This floor admits or refuses a
150
+ * room that is ALREADY a window member — it enrolls nobody; the domain CONFIG
151
+ * (`agent/memory/config/domains.ts`, read by teams-front.ts) enrolls. Do not read that as a second
152
+ * bound on the reach: a domain's container `reach` entry is legal at TENANT grain, so a tenant claim
153
+ * beside a tenant declaration puts every room in the tenant through this floor, and config load
154
+ * cannot enumerate them. In-tree domains name exact channels today. Residual: the standing
155
+ * "operator vouched something they shouldn't have" residual every vouch surface carries (identical
156
+ * to vouching a web-published Notion page) — now at whatever grain the operator wrote, so a tenant
157
+ * declaration carries it for the whole tenant. Personal and group chats
158
+ * are refused outright: they are per-person surfaces, not org containers, mirroring Slack's
159
+ * channels/groups-only rule. Residual acceptance: a vouched tenant/channel that LATER gains a
160
+ * guest is admitted until the operator retracts the vouch — the documented trade of the vouch
161
+ * posture (identical to Notion's), and strictly safer than any inference we could make.
162
+ */
163
+ export function teamsSingleWindowPrivacyOk(f: TeamsSingleWindowFacts): boolean {
164
+ if (f.scope !== "channel") return false; // personal/groupChat/unknown never join the shared window
165
+ if (!f.tenantId) return false; // no org anchor → fail closed
166
+ if (f.membershipType === "shared") return false; // positively cross-tenant → refuse even when vouched
167
+ return f.vouched === true; // the operator's vouch is the ONLY admitting signal
168
+ }
169
+
170
+ /**
171
+ * The LIVE-shaped single-window mention decision for one Teams activity — the Teams arm of the
172
+ * shared seam (unified-window.ts {@link singleWindowMentionPolicy}), next to the Slack
173
+ * equivalent (slack-events.ts slackSingleWindowMentionPolicy). Pure and SYNCHRONOUS (the floor
174
+ * needs no network — the vouch register is a set lookup), which is what makes the Teams legs
175
+ * single-leg by construction: one verdict, no cache to go stale between a suppress read and a
176
+ * deliver read. Fail-closed throughout: singleWindow off, or any floor conjunct failing, yields
177
+ * today's split (native owns the mention, no addressed wake).
178
+ */
179
+ function teamsSingleWindowMentionPolicy(singleWindow: boolean, isMention: boolean, facts: TeamsSingleWindowFacts): SingleWindowMentionPolicy {
180
+ return singleWindowMentionPolicy(singleWindow, isMention, teamsSingleWindowPrivacyOk(facts));
181
+ }
182
+
183
+ // --- the single-window plan (pure) ----------------------------------------------------
184
+
185
+ /** The host-frozen reply-target facts one Teams activity resolves — everything
186
+ * {@link planTeamsSingleWindow} needs to mint the wake origin (unified-window.ts's teams arm). */
187
+ export interface TeamsSingleWindowTarget {
188
+ /** Bot Connector base URL off the verified activity — the reply's transport host. Empty ⇒ no
189
+ * routable reply target ⇒ NO window (fail closed, never an unanswerable wake). */
190
+ readonly serviceUrl: string;
191
+ /** The Bot Framework conversation id (channel messages carry the reply-chain anchor in it). */
192
+ readonly conversationId: string;
193
+ /** The reply-chain ROOT activity id (eve's teamsThreadRootActivityId: the trigger's replyToId
194
+ * when it was itself a reply, else the trigger activity) — replyToTeamsActivity's target. */
195
+ readonly replyToActivityId?: string;
196
+ readonly tenantId?: string;
197
+ /** The first latency anchor (OPE-1716), recorded on the ingress row. A Bot-Framework activity
198
+ * carries no parsed timestamp on eve's shape, so the caller passes its own FRONT-DOOR RECEIPT —
199
+ * which makes the vendor→ingress segment a lower bound, and the row's `vendorTsSource` says so. */
200
+ readonly vendorTs?: VendorEventTime;
201
+ }
202
+
203
+ /**
204
+ * The ONE single-window decision for a Teams delivery, mirroring planNotionSingleWindow: given
205
+ * the grain's `singleWindow`, whether the activity @mentions the bot, the PRIVACY-FLOOR facts,
206
+ * and the frozen reply target, return the {@link UnifiedWindowWake} the dispatch should carry —
207
+ * or undefined for the byte-identical native path (teams-front then FORWARDS the activity to
208
+ * eve's native teamsChannel exactly as today).
209
+ *
210
+ * Teams' mention signal lives in ONE Bot-Framework activity (no Slack-style dual event), and its
211
+ * "native" handler is the forward this plan suppresses — so suppress-native and divert are the
212
+ * SAME act, both read off this one verdict (never a double turn, never a gap):
213
+ * • @mention on a singleWindow, floor-passing channel → the seam suppresses the native forward
214
+ * and stamps `addressing:"direct-mention"` (the terminal-prose delivery bridge's arm);
215
+ * • ambient (non-mention) channel message on the same surface → Leg A: the window WITHOUT the
216
+ * addressed stamp (judged treatment in the shared window, prose stays hard-dropped);
217
+ * • floor fails, singleWindow off, or no routable reply target → undefined (forward — a
218
+ * mention then keeps today's native conversation-session turn).
219
+ */
220
+ export function planTeamsSingleWindow(
221
+ singleWindow: boolean,
222
+ isMention: boolean,
223
+ facts: TeamsSingleWindowFacts,
224
+ target: TeamsSingleWindowTarget,
225
+ ): UnifiedWindowWake | undefined {
226
+ const policy = teamsSingleWindowMentionPolicy(singleWindow, isMention, facts);
227
+ // A mention diverts iff the seam suppresses the native forward; an ambient message diverts on
228
+ // the same `singleWindow && privacyOk` floor (Leg A). Both derive from the seam's one predicate.
229
+ const divert = isMention ? policy.suppressNative : singleWindow && teamsSingleWindowPrivacyOk(facts);
230
+ if (!divert) return undefined;
231
+ if (!target.serviceUrl || !target.conversationId) return undefined; // no frozen reply target ⇒ no window (fail closed)
232
+ return {
233
+ wakeId: mintWakeId(),
234
+ origin: {
235
+ platform: "teams",
236
+ serviceUrl: target.serviceUrl,
237
+ conversationId: target.conversationId,
238
+ ...(target.replyToActivityId ? { replyToActivityId: target.replyToActivityId } : {}),
239
+ ...(target.tenantId ? { tenantId: target.tenantId } : {}),
240
+ },
241
+ // ADDRESSED @mention ⇒ the seam's stamp marks the wake as OWED a reply, so the envelope tells
242
+ // the seat it owes an answer through the `reply` tool. Ambient wakes omit it. It is not a delivery
243
+ // path: a turn that ends in prose is dropped and re-driven once, on every addressing (OPE-1982).
244
+ ...(policy.addressing !== undefined ? { addressing: policy.addressing } : {}),
245
+ ...spreadVendorTs(target.vendorTs),
246
+ };
247
+ }
248
+
249
+ // --- the wake builder (pure) ---------------------------------------------------------
250
+
251
+ export interface TeamsSupervisorWakeInput {
252
+ /** The Teams CHANNEL id (the container — the envelope's `<channel id>`; the conversation id
253
+ * when the activity carried no channel id). */
254
+ readonly channelId: string;
255
+ /** The trigger activity's facts (host-extracted). */
256
+ readonly trigger: {
257
+ readonly id: string;
258
+ readonly authorId: string;
259
+ readonly authorName?: string;
260
+ readonly sentAt: string;
261
+ readonly text: string;
262
+ /** Per-message trust tier (identity/wake-trust.ts) — resolved by the live dispatch.
263
+ * 🔴 REQUIRED (OPE-596): this builder fail-closed to `relay` while its five siblings defaulted
264
+ * UPWARD, so all six now refuse the omission at compile time instead of each picking a floor.
265
+ * A caller that cannot resolve a tier states the fail-closed one itself: `relay` for a machine
266
+ * author, `unauth` for a human the gate cannot vouch. */
267
+ readonly trust: WakeTrust;
268
+ };
269
+ /** Present ⇔ the trigger sat inside an EXISTING reply chain (its replyToId) — envelope thread
270
+ * meta only; the reply target is the frozen origin, never this. */
271
+ readonly threadRootId?: string;
272
+ /** The seam's addressed verdict (window.addressing === "direct-mention"). */
273
+ readonly directMention: boolean;
274
+ /** Host-minted wake id — always present (Teams only dispatches on the single-window path). */
275
+ readonly wakeId: string;
276
+ /** Engagement calibration for the judged preamble — channel-watch only. */
277
+ readonly engagementTier?: WakeEngagementTier;
278
+ /** The OUTGOING generation's recorded TAIL (OPE-794), rendered as this first wake's backscroll.
279
+ * Only a FRESH generation's first wake carries one. */
280
+ readonly tail?: readonly WakeMessageInput[];
281
+ /** This surface could not read its own channel since the seat's last wake (core
282
+ * channels/seat-catch-up.ts). Rendered as a trusted `<system-note>`; unset ⇒ no note. */
283
+ readonly catchUpUnavailable?: string;
284
+ }
285
+
286
+ /**
287
+ * Build the NormalizedWake for one Teams single-window turn. platform "teams", containerNoun
288
+ * "channel" (a Teams channel is a channel), locus.channel = the Teams channel, locus.thread =
289
+ * the reply chain the trigger sat in (when it did). NO PLATFORM-FETCH BOOTSTRAP: the Bot Connector
290
+ * API this wake arrives over has no message-history read (unlike Slack's conversations.history), so a
291
+ * FRESH generation carries the RECORDED TAIL of the outgoing generation (OPE-794) and nothing else —
292
+ * which is why the recorded ring matters more on Teams than anywhere else. A Teams seat with no
293
+ * recorded tail opens cold, honestly.
294
+ * 🔴 AN ONGOING GENERATION IS A DIFFERENT QUESTION, AND IT IS ANSWERED (OPE-1726): the since-last-wake
295
+ * catch-up reads MICROSOFT GRAPH — a different credential and a different transport from the Bot
296
+ * Connector, the one `read_channel` has always used — so a Teams seat does see what the channel said
297
+ * between its own wakes. See channels/teams-catch-up.ts; the bootstrap gap above is unchanged.
298
+ * Always the unified render (platform address + P5 disclosure): Teams has no non-window
299
+ * supervisor path, so there is no per-container twin to stay byte-identical with.
300
+ */
301
+ export function buildTeamsSupervisorWake(input: TeamsSupervisorWakeInput): NormalizedWake {
302
+ return {
303
+ platform: "teams",
304
+ reason: input.directMention ? "mention" : "channel-activity",
305
+ addressing: input.directMention ? "direct-mention" : "channel-watch",
306
+ // The ambient calibration dial — an addressed mention is owed an answer, so watch-only.
307
+ engagementTier: input.directMention ? undefined : input.engagementTier,
308
+ wakeId: input.wakeId,
309
+ locus: {
310
+ channel: { id: input.channelId },
311
+ ...(input.threadRootId ? { thread: { ts: input.threadRootId } } : {}),
312
+ },
313
+ ...(input.trigger.authorName ? { participants: [{ id: input.trigger.authorId, name: input.trigger.authorName }] } : {}),
314
+ backscroll: input.tail && input.tail.length > 0 ? input.tail : undefined,
315
+ ...(input.catchUpUnavailable !== undefined ? { catchUpUnavailable: input.catchUpUnavailable } : {}),
316
+ trigger: mkMessageTrigger({
317
+ from: "human", // bot/self-authored activities are dropped upstream (teams-front's author gate)
318
+ author: input.trigger.authorName ?? input.trigger.authorId,
319
+ authorId: input.trigger.authorId,
320
+ id: input.trigger.id,
321
+ sentAt: input.trigger.sentAt,
322
+ // The caller's stated per-person tier — no default (OPE-596).
323
+ trust: input.trigger.trust,
324
+ mention: input.directMention,
325
+ body: input.trigger.text,
326
+ }),
327
+ };
328
+ }
329
+
330
+ // --- the dispatch core (session get-or-create → build → wake → terminal rotate) -------
331
+
332
+ /** The live supervisor session pointer, as the deps report it (mirrors the other surfaces). */
333
+ export interface TeamsSupervisorSession {
334
+ readonly token: string;
335
+ readonly generation: number;
336
+ readonly freshGeneration: boolean;
337
+ /** ISO-8601 of the most recent wake this generation delivered (the registry row's `lastWakeAt`),
338
+ * or null on a freshly minted/rotated generation — the lower bound of the since-last-wake catch-up
339
+ * read (OPE-1726); absent ⇒ no catch-up. */
340
+ readonly lastWakeAt?: string | null;
341
+ /** The OUTGOING generation's recorded tail, oldest-first — empty unless this is a fresh
342
+ * generation's first wake (OPE-794). */
343
+ readonly tail: readonly WakeMessageInput[];
344
+ }
345
+
346
+ /** Deps for {@link handleTeamsSingleWindowDispatch} — injected so the core is unit-testable over
347
+ * a mock store + a capture `wake` (scripts/unified-window-test.ts). org is baked into the live
348
+ * impl's closures (a deployment fact — teams-front.ts), so it never crosses this boundary. */
349
+ export interface TeamsSupervisorDeps {
350
+ /** Create-or-fetch the live supervisor session for this surface's grain: generation 1 on first
351
+ * sighting, rotate when shouldRotate says it aged out, else the current generation. */
352
+ readonly getOrCreateSession: (surfaceKey: string, channelId: string, atIso: string) => Promise<TeamsSupervisorSession>;
353
+ /** Record one wake on the current generation (lastWakeAt/turnCount). Best-effort. */
354
+ readonly touchSession?: (surfaceKey: string, atIso: string) => Promise<void>;
355
+ /**
356
+ * THE SINCE-LAST-WAKE CATCH-UP, through the ONE shared path every surface takes
357
+ * (channels/seat-catch-up.ts `seatCatchUp`). Optional so older test doubles keep compiling
358
+ * (absent ⇒ no catch-up, the pre-OPE-1726 behaviour); fail-soft by construction.
359
+ */
360
+ readonly catchUp?: (req: SeatCatchUpRequest) => Promise<SeatCatchUpResult>;
361
+ /**
362
+ * Record this delivered wake onto the LIVE generation's TAIL ring (OPE-794). Injected because the
363
+ * entry has to be filed under an ORG and a registry key, and this core deliberately holds neither
364
+ * — the live wiring does. Absent (a unit test) ⇒ nothing is recorded and the dispatch is
365
+ * unchanged, which is the same posture `touchSession` takes.
366
+ */
367
+ readonly recordWake?: (entry: SessionTailWakeRow, token: string, surfaceKey: string) => Promise<void>;
368
+
369
+ /** Deliver the rendered wake. The live wiring (teams-front.ts) ALWAYS diverts through eve's
370
+ * cross-channel `receive` into the synthetic `unified` channel (divertToUnifiedWindow) — a
371
+ * Teams dispatch has no native send fallback, by construction (window required below). */
372
+ readonly wake: (input: { token: string; auth: OpenEverywhereTeamsAuth; message: string; context: readonly string[]; window: UnifiedWindowWake }) => Promise<void>;
373
+ /** Clock seam (defaults to the real clock). */
374
+ readonly now?: () => string;
375
+ }
376
+
377
+ /** Everything teams-front hands the dispatch: identity/session facts + the wake parts + the
378
+ * REQUIRED window (a Teams dispatch exists only on the single-window path). */
379
+ export interface TeamsSupervisorDispatch {
380
+ /** The DOMAIN-GRAIN surface key (`teams/<tenant>/<channel>` — memory/partition.ts domainKeyOf):
381
+ * the gate/registry/audit key, and what unified.receive re-checks fail-closed. */
382
+ readonly surfaceKey: string;
383
+ /**
384
+ * 🔴 THE ROOM KEY — `partition.surfaceKey`, the CONVERSATION grain (`teams/<tenant>/<conversation
385
+ * id>`), and NOT {@link surfaceKey} above. It is the `container` this wake row carries, and it is
386
+ * a CONTRACT with the post row: `channels/session-tail-record.ts` `tailWindowFor` builds a post's
387
+ * container from `partition.surfaceKey`, and `channels/reply-fold.ts` filters the ring by exact
388
+ * container equality. Two spellings therefore hide every wake row from the fold policy.
389
+ *
390
+ * WHY THE TWO KEYS DIFFER HERE. `bindTeams` (teams-identity.ts) sets `surface` to the conversation
391
+ * id (one reply chain) and `domainSurface` to the channel id, so `surfaceKey` and `domainKeyOf` are
392
+ * different strings on Teams. 🔴 TEAMS IS NOT THE ONLY SURFACE THAT SPLITS THEM. `bindDiscord`
393
+ * (discord-identity.ts) sets `domainSurface` to the parent channel id, so a Discord THREAD splits
394
+ * the same two grains. Those two are the whole set — `memory/partition.ts` names both, and no other
395
+ * binding sets `domainSurface`. Slack sets none, so its two keys are one string and
396
+ * `slack-events.ts` reads `p.surfaceKey` with nothing to get wrong. Discord
397
+ * passes `input.partition.surfaceKey` explicitly and is correct today; a future change to that ring
398
+ * row must keep the surface key, for the reason this field exists. Recording the domain key here
399
+ * made the fold policy refuse a post that a human message had already cleared (OPE-1528, ship #174).
400
+ */
401
+ readonly containerKey: string;
402
+ /** The Teams channel id (envelope container + the per-container token fallback). */
403
+ readonly channelId: string;
404
+ /** The TEAM the channel belongs to, in GRAPH's spelling — the Microsoft 365 GROUP id, NOT the
405
+ * `channelData.team.id` an activity carries (channels/teams-graph-team-id.ts resolves the one
406
+ * into the other; OPE-1808). Graph addresses a channel read as `/teams/{team}/channels/{channel}`,
407
+ * so the catch-up needs both ids and neither is derivable from the other. Absent (a chat activity,
408
+ * or a team id that would not resolve) ⇒ no catch-up, never a guessed team. */
409
+ readonly teamId?: string;
410
+ /** The activity DID name a team and its Graph id would not resolve ON THIS WAKE — the TRANSIENT
411
+ * shape, kept apart from the chat shape because the two owe the seat DIFFERENT sentences (the
412
+ * catch-up arm below). Absent ⇒ the activity named no team at all. */
413
+ readonly teamAddressUnresolved?: boolean;
414
+ readonly auth: OpenEverywhereTeamsAuth;
415
+ /**
416
+ * THE AUTHOR FACTS for every message whose bytes enter this wake's context (OPE-1747), in the same
417
+ * shape and for the same reason the other three seat surfaces carry it. A Teams channel activity is
418
+ * one message per wake, so the front passes exactly one entry — the resolved tier, the Bot Connector
419
+ * roster's `userRole: "guest"` refutation, and the OPERATOR's register query.
420
+ *
421
+ * 🔴 REQUIRED, NOT OPTIONAL, for the reason `stampNonMemberChatAuth` makes its own `room` argument
422
+ * required: an optional field lets a new leg silently lose the author question, and a carriage that is
423
+ * absent looks identical to a carriage that answered "member". The front already computed these facts
424
+ * for its own taint join; what this field adds is that the TAIL ROW records them, so a tail-built
425
+ * envelope is judged by the same two legs a freshly-fetched one is. A leg with genuinely nothing to
426
+ * say passes `[]` and says so on purpose.
427
+ */
428
+ readonly ingested: readonly IngestedChatMessage[];
429
+ readonly trigger: TeamsSupervisorWakeInput["trigger"];
430
+ readonly threadRootId?: string;
431
+ /**
432
+ * 🔴 THE REPLY CHAIN THIS WAKE SITS IN — the second half of the catch-up's read, and NOT {@link
433
+ * threadRootId} (OPE-1817). A Teams CHANNEL activity always sits in one reply chain, named by its
434
+ * conversation id's `;messageid=<root>` suffix, and {@link containerKey} is that same conversation
435
+ * grain. `threadRootId` answers a different question — whether the ENVELOPE renders thread-scoped
436
+ * — and is deliberately absent on a top-level post.
437
+ *
438
+ * Naming the chain matters because Graph's `/channels/{c}/messages` returns TOP-LEVEL messages
439
+ * ONLY: a reply never appears there. So a wake that named no chain read nothing for a chain that
440
+ * had carried the message, with no error to see (ship #206, ship #207). The fetch reads the
441
+ * channel AND the named chain and merges them (channels/teams-catch-up.ts). Absent ⇒ the
442
+ * conversation names no chain, and the read is the container's alone.
443
+ */
444
+ readonly replyChainRootId?: string;
445
+ readonly engagementTier?: WakeEngagementTier;
446
+ /** The minted single-window wake (planTeamsSingleWindow) — REQUIRED: without a window there is
447
+ * nothing for this dispatch to do (the front forwards to the native channel instead). */
448
+ readonly window: UnifiedWindowWake;
449
+ }
450
+
451
+ /**
452
+ * Route one floor-passing Teams activity to the domain's single-window supervisor: get-or-create
453
+ * the (unified-grain) session, build + render the wake for that generation, and deliver it via
454
+ * the wake dep (whose live wiring diverts into the unified channel — registering the durable
455
+ * wakeId→origin map entry BEFORE the send).
456
+ *
457
+ * A DELIVERY failure (the enqueue/divert itself) propagates to the caller's catch. A session that
458
+ * dies at TURN time does not: nothing here observes it, so the trigger is lost SILENTLY, and no
459
+ * reactive arm can exist (OPE-174 removed the inert one; channels/session-resume.ts holds the
460
+ * measurement). The working remedy is PRE-DISPATCH — the live `getOrCreateSession` claims the
461
+ * OPE-599 runtime-change rotation before this call and hands back a session the running eve build
462
+ * can read.
463
+ */
464
+ export async function handleTeamsSingleWindowDispatch(d: TeamsSupervisorDispatch, deps: TeamsSupervisorDeps): Promise<void> {
465
+ const atIso = deps.now ? deps.now() : new Date().toISOString();
466
+ const session = await deps.getOrCreateSession(d.surfaceKey, d.channelId, atIso);
467
+
468
+ const doWake = async (token: string, generation: number, tail: readonly WakeMessageInput[], catchUpUnavailable?: string) => {
469
+ const nw = buildTeamsSupervisorWake({
470
+ channelId: d.channelId,
471
+ trigger: d.trigger,
472
+ threadRootId: d.threadRootId,
473
+ directMention: d.window.addressing === "direct-mention",
474
+ wakeId: d.window.wakeId,
475
+ engagementTier: d.engagementTier,
476
+ tail,
477
+ catchUpUnavailable,
478
+ });
479
+ const { message, context } = renderWake(nw, deps.now);
480
+ await deps.wake({ token, auth: d.auth, message, context: context ?? [], window: d.window });
481
+ };
482
+
483
+ // A wake failure PROPAGATES to the caller's catch. (OPE-174 removed a terminal-session-death
484
+ // force-rotate branch here: it could never fire — a conversation-mode session PARKS at eve's
485
+ // token bound rather than failing, and a turn-time error cannot reject the awaited enqueue
486
+ // anyway. The reachable handler is core's agent/channels/session-park.ts.)
487
+ // 🔴 EVERY WAKE READS THE CHANNEL SINCE THE SEAT LAST LOOKED (OPE-1695 (b), brought to Teams by
488
+ // OPE-1726). A FRESH generation renders its carried tail, as it always did; an ONGOING generation
489
+ // reads what the channel AND this reply chain said since its own `lastWakeAt`, through the ONE
490
+ // shared catch-up path — same bounds, same admission policy, same cap as Slack's. The read runs on
491
+ // MICROSOFT GRAPH, not on the Bot Connector this wake arrived over; see teams-catch-up.ts.
492
+ // FAIL-SOFT: the shared path never throws, and an unregistered fetch comes back as the UNAVAILABLE
493
+ // note rather than as a silent empty context.
494
+ // 🔴 NO TEAM ID STATES ITS BOUND RATHER THAN READING EMPTY, and TWO shapes reach that arm with TWO
495
+ // DIFFERENT SENTENCES. Graph addresses a history read as `/teams/{team}/channels/{channel}`.
496
+ // • A PERSONAL OR GROUP CHAT carries no team at all. That is STRUCTURAL — this surface cannot
497
+ // read its own history, ever — so it takes core's own `catchUpUnavailableReason`.
498
+ // • A CHANNEL whose Connector team id would not resolve to its Graph one
499
+ // (channels/teams-graph-team-id.ts) has no address ON THIS WAKE. That is TRANSIENT, and saying
500
+ // "this surface cannot read its own history" over it would tell the seat something false about
501
+ // Teams — the exact line core's seat-catch-up.ts draws between a structural absence and a
502
+ // failed read. So it gets its own sentence, below.
503
+ // Either way the wake SAYS SO: skipping in silence would render the same empty context a quiet
504
+ // channel renders, which is the one thing this whole mechanism exists to stop.
505
+ // See TeamsSupervisorDispatch.replyChainRootId: the chain this wake sits in is what the read adds
506
+ // to the channel; the envelope's own thread meta is the fallback for a caller that names only that.
507
+ const catchUpRoot = d.replyChainRootId ?? d.threadRootId;
508
+ const catchUp =
509
+ session.freshGeneration || !deps.catchUp
510
+ ? undefined
511
+ : !d.teamId
512
+ ? {
513
+ messages: [] as readonly WakeMessageInput[],
514
+ unavailable: d.teamAddressUnresolved ? TEAM_ADDRESS_UNRESOLVED_NOTE : catchUpUnavailableReason("teams"),
515
+ }
516
+ : await deps.catchUp({
517
+ container: `${d.teamId}/${d.channelId}`,
518
+ ...(catchUpRoot ? { threadRoot: catchUpRoot } : {}),
519
+ sinceMs: seatCatchUpSinceMs(session.lastWakeAt, Date.parse(atIso) || Date.now(), TEAMS_CATCH_UP_REACHBACK_HOURS),
520
+ untilMs: Date.parse(d.trigger.sentAt) || Date.parse(atIso) || Date.now(),
521
+ excludeId: d.trigger.id,
522
+ channelKey: d.surfaceKey,
523
+ });
524
+ await doWake(session.token, session.generation, session.freshGeneration ? session.tail : (catchUp?.messages ?? []), catchUp?.unavailable);
525
+ if (deps.touchSession) await deps.touchSession(d.surfaceKey, atIso);
526
+ if (deps.recordWake) {
527
+ // AFTER the wake landed, and only the TRIGGER — never the backscroll rendered beside it. That is
528
+ // what stops a tail inheriting a tail (channels/session-tail.ts).
529
+ await deps.recordWake(
530
+ {
531
+ kind: "wake",
532
+ at: atIso,
533
+ from: "human",
534
+ trust: d.trigger.trust,
535
+ // THE AUTHOR GRAIN (OPE-1747) — `d.ingested[0]` is the TRIGGER's own facts, the one entry the
536
+ // front's own `stampNonMemberChatAuth` join reads, resolved through the one core road.
537
+ // `refuted: false` on an empty carriage is the answer the live wake acted on, never the UNKNOWN
538
+ // an absent field means — that is reserved for a row persisted before this field existed.
539
+ ...tailAuthorGrain(d.ingested[0] ?? { trust: d.trigger.trust }),
540
+ author: d.trigger.authorName ?? d.trigger.authorId,
541
+ authorId: d.trigger.authorId,
542
+ id: d.trigger.id,
543
+ platform: "teams",
544
+ // The ROOM, not the domain — see TeamsSupervisorDispatch.containerKey. The post that answers
545
+ // this wake files under `partition.surfaceKey`, and the fold policy compares the two strings.
546
+ container: d.containerKey,
547
+ ...(d.threadRootId ? { threadRoot: d.threadRootId } : {}),
548
+ text: d.trigger.text,
549
+ },
550
+ session.token,
551
+ d.surfaceKey,
552
+ );
553
+ }
554
+ }
555
+
556
+ // --- FIRST-CLASS DM WINDOW (OPE-357) — the Teams twin of buildDiscordDmWake / slackDmWake --------
557
+ //
558
+ // A Teams personal/group chat is diverted into its OWN dedicated DM window (channels/dm-seat.ts),
559
+ // exactly as OPE-356 first-classed Discord DMs and OPE-351 stages 2/4 first-classed Slack's. The
560
+ // pure pieces live here (the eve-free core); teams-front.ts owns the live divert wiring. A DM window
561
+ // is STRUCTURALLY SEPARATE from the shared cross-surface window — it never touches
562
+ // teamsSingleWindowPrivacyOk (whose channel-only floor stays exactly as strict); it is its own admit
563
+ // space, keyed on the DM's surface key.
564
+
565
+ /** Everything {@link buildTeamsDmWake} needs — deliberately NARROWER than {@link
566
+ * TeamsSupervisorWakeInput}: a DM has no channel container and no engagement tier, and both
567
+ * absences are a property of the surface rather than a field a caller might or might not fill in
568
+ * (the buildDiscordDmWake discipline). */
569
+ export interface TeamsDmWakeInput {
570
+ /** The DM conversation id — a DM's whole locus (the envelope's `<channel id>`). */
571
+ readonly conversationId: string;
572
+ readonly wakeId: string;
573
+ /** The OUTGOING generation's recorded TAIL (OPE-794), rendered as this first wake's backscroll.
574
+ * Only a FRESH generation's first wake carries one. */
575
+ readonly tail?: readonly WakeMessageInput[];
576
+ readonly trigger: {
577
+ readonly id: string;
578
+ readonly author: string;
579
+ readonly authorId: string;
580
+ readonly sentAt: string;
581
+ readonly text: string;
582
+ /** Resolved per-wake trust tier (identity/wake-trust.ts). 🔴 REQUIRED (OPE-596) — the field
583
+ * used to default to `principal`, the highest tier, on the reasoning that a DM partner IS the
584
+ * seat's principal. That reasoning is about the ROOM, and the tier is about the AUTHOR. See
585
+ * {@link TeamsSupervisorWakeInput}'s trigger tier. */
586
+ readonly trust: WakeTrust;
587
+ };
588
+ }
589
+
590
+ /**
591
+ * THE 1:1 (and group) DM WAKE for a first-classed Teams DM window (OPE-357) — the Teams twin of
592
+ * slack-events.ts's `slackDmWake` and discord-gateway.ts's {@link buildTeamsDmWake} sibling
593
+ * `buildDiscordDmWake`, and it renders through the SAME core renderer with no platform branch, so all
594
+ * three surfaces' DM envelopes are one dialect.
595
+ *
596
+ * ADDRESSING IS `direct-mention`, ALWAYS, doing the same two jobs it does on Slack/Discord. Semantically
597
+ * it is simply TRUE: everything said in a DM is said to the agent, which is why this path bypasses the
598
+ * engagement gate and the name-drop judge entirely — a DM IS ALWAYS ANSWERED. Mechanically it is
599
+ * LOAD-BEARING: `direct-mention` stamps `oe_addressing` through the divert, which marks the wake as
600
+ * OWED a reply and selects the `[direct]` preamble's reply mandate. 🔴 IT IS NOT A DELIVERY PATH
601
+ * (OPE-1982): the addressed-prose bridge it used to arm is deleted, so a DM answer written as prose
602
+ * rather than a `reply` call is DROPPED on that channel like any other, and re-driven once.
603
+ *
604
+ * `reason` is `dm`, not `mention`: the envelope's reason describes the SURFACE SHAPE, and it is the
605
+ * one reason that survives the OPE-744 collapse of `mention` into `channel-activity` — no other
606
+ * attribute states "this is a direct-message room". NO `engagementTier` either — that dial raises
607
+ * the bar for AMBIENT watching, and a DM is always answered.
608
+ *
609
+ * NO PLATFORM-FETCH BACKSCROLL, EVER — and here that is not merely the native path's choice (as on
610
+ * Discord) but a platform fact: the Bot Connector exposes no DM message-history read and the Graph
611
+ * chat-history endpoint is deliberately unwired (teams-read.ts). So a fresh Teams DM generation
612
+ * carries the RECORDED TAIL and nothing else. Pure → unit-testable.
613
+ */
614
+ export function buildTeamsDmWake(input: TeamsDmWakeInput): NormalizedWake {
615
+ return {
616
+ platform: "teams",
617
+ reason: "dm",
618
+ addressing: "direct-mention",
619
+ wakeId: input.wakeId,
620
+ // A DM's container IS the DM conversation: no parent, no thread, and — unlike the channel
621
+ // builder — no `platform` address stamp, because this window sees exactly one surface.
622
+ locus: { channel: { id: input.conversationId } },
623
+ backscroll: input.tail && input.tail.length > 0 ? input.tail : undefined,
624
+ trigger: mkMessageTrigger({
625
+ from: "human", // bot/self-authored activities are dropped at the front's author gate
626
+ author: input.trigger.author,
627
+ authorId: input.trigger.authorId,
628
+ id: input.trigger.id,
629
+ sentAt: input.trigger.sentAt,
630
+ // The caller's stated per-person tier — no default (OPE-596).
631
+ trust: input.trigger.trust,
632
+ // The response-obligation flag, exactly as the Slack/Discord DM wakes carry it.
633
+ mention: true,
634
+ body: input.trigger.text,
635
+ }),
636
+ };
637
+ }
638
+