typeclaw 0.43.1 → 0.44.0
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 +1 -1
- package/auth.schema.json +92 -0
- package/package.json +2 -2
- package/secrets.schema.json +92 -0
- package/src/agent/index.ts +14 -2
- package/src/agent/multimodal/look-at.ts +27 -9
- package/src/agent/plugin-tools.ts +9 -4
- package/src/agent/session-origin.ts +1 -0
- package/src/agent/tools/channel-fetch-attachment.ts +45 -3
- package/src/agent/tools/channel-reply.ts +41 -18
- package/src/agent/tools/channel-send.ts +82 -13
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
- package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
- package/src/bundled-plugins/memory/README.md +9 -9
- package/src/bundled-plugins/memory/index.ts +40 -9
- package/src/channels/adapters/github/inbound.ts +20 -14
- package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
- package/src/channels/adapters/teams-classify.ts +144 -0
- package/src/channels/adapters/teams-id-token.ts +112 -0
- package/src/channels/adapters/teams-key.ts +32 -0
- package/src/channels/adapters/teams.ts +519 -0
- package/src/channels/github-review-turn-ledger.ts +43 -0
- package/src/channels/index.ts +1 -1
- package/src/channels/manager.ts +54 -1
- package/src/channels/router.ts +302 -39
- package/src/channels/schema.ts +9 -0
- package/src/cli/channel.ts +92 -4
- package/src/cli/hostd.ts +41 -0
- package/src/cli/init.ts +58 -1
- package/src/config/channels-mutation.ts +9 -1
- package/src/cron/index.ts +16 -4
- package/src/cron/reloadable.ts +25 -7
- package/src/cron/scheduler.ts +4 -0
- package/src/cron/schema.ts +143 -35
- package/src/doctor/channel-checks.ts +27 -0
- package/src/hostd/daemon.ts +23 -3
- package/src/hostd/protocol.ts +2 -0
- package/src/hostd/teams-renewal-manager.ts +212 -0
- package/src/init/checkpoint.ts +1 -1
- package/src/init/index.ts +68 -1
- package/src/init/run-owner-claim.ts +1 -0
- package/src/init/teams-auth.ts +111 -0
- package/src/inspect/label.ts +4 -0
- package/src/permissions/match-rule.ts +11 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/run/index.ts +35 -8
- package/src/run/llm-fetch-observer.ts +27 -5
- package/src/sandbox/build.ts +12 -0
- package/src/sandbox/policy.ts +13 -0
- package/src/sandbox/writable-zones.ts +46 -10
- package/src/secrets/schema.ts +32 -0
- package/src/secrets/teams-renewal.ts +229 -0
- package/src/secrets/teams-store.ts +108 -0
- package/typeclaw.schema.json +163 -3
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
import { TeamsClient, TeamsError, TeamsListener } from 'agent-messenger/teams'
|
|
2
|
+
import type { TeamsListenerEventMap, TeamsMessage, TeamsUser } from 'agent-messenger/teams'
|
|
3
|
+
|
|
4
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
5
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
6
|
+
import type {
|
|
7
|
+
ChannelHistoryMessage,
|
|
8
|
+
ChannelSelfIdentityResolver,
|
|
9
|
+
FetchHistoryArgs,
|
|
10
|
+
FetchHistoryResult,
|
|
11
|
+
HistoryCallback,
|
|
12
|
+
OutboundCallback,
|
|
13
|
+
OutboundMessage,
|
|
14
|
+
SendResult,
|
|
15
|
+
} from '@/channels/types'
|
|
16
|
+
import type { TeamsAccountRecord } from '@/secrets/schema'
|
|
17
|
+
|
|
18
|
+
import { describeError } from './describe-error'
|
|
19
|
+
import {
|
|
20
|
+
classifyChannelInbound,
|
|
21
|
+
classifyChatInbound,
|
|
22
|
+
normalizeTeamsText,
|
|
23
|
+
type InboundDropReason,
|
|
24
|
+
type TeamsInboundEvent,
|
|
25
|
+
} from './teams-classify'
|
|
26
|
+
import { ContainerTeamsClient } from './teams-id-token'
|
|
27
|
+
import { decodeTeamsConversationKey } from './teams-key'
|
|
28
|
+
|
|
29
|
+
// `TeamsChat` is not exported from agent-messenger/teams, so derive its shape
|
|
30
|
+
// from the client method that returns it — this stays in lockstep with the SDK
|
|
31
|
+
// without depending on a named export the package chose to keep internal.
|
|
32
|
+
export type TeamsChatInfo = Awaited<ReturnType<TeamsClient['listChats']>>[number]
|
|
33
|
+
|
|
34
|
+
export type TeamsAdapterLogger = {
|
|
35
|
+
info: (msg: string) => void
|
|
36
|
+
warn: (msg: string) => void
|
|
37
|
+
error: (msg: string) => void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const consoleLogger: TeamsAdapterLogger = {
|
|
41
|
+
info: (m) => console.log(m),
|
|
42
|
+
warn: (m) => console.warn(m),
|
|
43
|
+
error: (m) => console.error(m),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type TeamsClientFactory = () => TeamsClient
|
|
47
|
+
export type TeamsListenerFactory = (client: TeamsClient) => TeamsListener
|
|
48
|
+
|
|
49
|
+
export type TeamsCredentialStore = {
|
|
50
|
+
getAccount(id?: string): Promise<TeamsAccountRecord | null>
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type TeamsAdapterOptions = {
|
|
54
|
+
router: ChannelRouter
|
|
55
|
+
configRef: () => ChannelAdapterConfig
|
|
56
|
+
logger?: TeamsAdapterLogger
|
|
57
|
+
selfAliasesRef?: () => readonly string[]
|
|
58
|
+
credentialsStore?: TeamsCredentialStore
|
|
59
|
+
createClient?: TeamsClientFactory
|
|
60
|
+
createListener?: TeamsListenerFactory
|
|
61
|
+
now?: () => number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type TeamsAdapter = {
|
|
65
|
+
start: () => Promise<void>
|
|
66
|
+
stop: () => Promise<void>
|
|
67
|
+
isConnected: () => boolean
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const TEAMS_LISTENER_START_TIMEOUT_MS = 20_000
|
|
71
|
+
|
|
72
|
+
// The Teams user-account SDK has NO self-identity boundary: `testAuth()` returns
|
|
73
|
+
// the literal id `'ME'`, while realtime/history authors carry the real MRI from
|
|
74
|
+
// `resource.from`. So an id comparison can never recognize the agent's own
|
|
75
|
+
// message echoing back over the trouter socket. Instead every successful send
|
|
76
|
+
// records a (chat, normalized-text) fingerprint; an inbound that matches a
|
|
77
|
+
// recent unconsumed fingerprint in the same chat is treated as the echo of our
|
|
78
|
+
// own send and dropped. The author-name / `'ME'` checks are a fast path; the
|
|
79
|
+
// short content-only window is the fallback for when the platform does not
|
|
80
|
+
// stamp the outbound back with our display name.
|
|
81
|
+
const SELF_ECHO_TTL_MS = 2 * 60_000
|
|
82
|
+
const SELF_ECHO_CONTENT_ONLY_TTL_MS = 5_000
|
|
83
|
+
const MAX_SENT_ECHOES = 200
|
|
84
|
+
|
|
85
|
+
type SentEcho = { chatId: string; textKey: string; sentAt: number; consumed: boolean }
|
|
86
|
+
|
|
87
|
+
export function createOutboundCallback(deps: {
|
|
88
|
+
client: Pick<TeamsClient, 'sendChatMessage' | 'sendMessage'>
|
|
89
|
+
logger: TeamsAdapterLogger
|
|
90
|
+
// Reserve the self-echo fingerprint BEFORE the send is awaited and return a
|
|
91
|
+
// rollback. Teams delivers a send back over the listener socket, and that
|
|
92
|
+
// echo can arrive before the send resolves — reserving after the await would
|
|
93
|
+
// leave a window where the agent's own message routes back in. The key is the
|
|
94
|
+
// conversation id the echo will carry (chatId for chats, channelId for
|
|
95
|
+
// channels). The rollback drops the reservation if the send ultimately fails.
|
|
96
|
+
reserveEcho?: (conversationId: string, text: string) => () => void
|
|
97
|
+
}): OutboundCallback {
|
|
98
|
+
const { client, logger } = deps
|
|
99
|
+
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
100
|
+
if (msg.adapter !== 'teams') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
101
|
+
const text = msg.text ?? ''
|
|
102
|
+
if (text === '') return { ok: false, error: 'message has no text' }
|
|
103
|
+
const decoded = decodeTeamsConversationKey(msg.chat)
|
|
104
|
+
if (decoded === null) return { ok: false, error: `unsupported Teams conversation id: ${msg.chat}` }
|
|
105
|
+
|
|
106
|
+
const conversationId = decoded.kind === 'chat' ? decoded.chatId : decoded.channelId
|
|
107
|
+
logger.info(`[teams] outbound ${decoded.kind}=${conversationId} text_len=${text.length}`)
|
|
108
|
+
const rollbackEcho = deps.reserveEcho?.(conversationId, text)
|
|
109
|
+
try {
|
|
110
|
+
const sent =
|
|
111
|
+
decoded.kind === 'chat'
|
|
112
|
+
? await client.sendChatMessage(decoded.chatId, text)
|
|
113
|
+
: await client.sendMessage(decoded.teamId, decoded.channelId, text, msg.thread ?? undefined)
|
|
114
|
+
logger.info(`[teams] sent id=${sent.id} ${decoded.kind}=${conversationId}`)
|
|
115
|
+
return { ok: true, messageId: sent.id, messageIds: [sent.id] }
|
|
116
|
+
} catch (err) {
|
|
117
|
+
rollbackEcho?.()
|
|
118
|
+
const message = describeError(err)
|
|
119
|
+
logger.error(`[teams] outbound failed: ${message}`)
|
|
120
|
+
return { ok: false, error: message }
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function createTeamsHistoryCallback(deps: {
|
|
126
|
+
client: Pick<TeamsClient, 'getChatMessages' | 'getMessages'>
|
|
127
|
+
logger: TeamsAdapterLogger
|
|
128
|
+
selfIdRef: () => string | null
|
|
129
|
+
}): HistoryCallback {
|
|
130
|
+
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
131
|
+
const decoded = decodeTeamsConversationKey(args.chat)
|
|
132
|
+
if (decoded === null) return { ok: false, error: `unsupported Teams conversation id: ${args.chat}` }
|
|
133
|
+
const limit = clampLimit(args.limit, 100)
|
|
134
|
+
try {
|
|
135
|
+
const messages =
|
|
136
|
+
decoded.kind === 'chat'
|
|
137
|
+
? await deps.client.getChatMessages(decoded.chatId, limit)
|
|
138
|
+
: await deps.client.getMessages(decoded.teamId, decoded.channelId, limit)
|
|
139
|
+
const selfId = deps.selfIdRef()
|
|
140
|
+
return { ok: true, messages: messages.map((m) => mapTeamsHistoryMessage(m, selfId)).reverse() }
|
|
141
|
+
} catch (err) {
|
|
142
|
+
const message = describeError(err)
|
|
143
|
+
deps.logger.warn(`[teams] history fetch failed: ${message}`)
|
|
144
|
+
return { ok: false, error: message }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
|
|
150
|
+
const logger = options.logger ?? consoleLogger
|
|
151
|
+
const now = options.now ?? Date.now
|
|
152
|
+
let loadedAccount: TeamsAccountRecord | null = null
|
|
153
|
+
const createClient = options.createClient ?? (() => new ContainerTeamsClient(() => loadedAccount))
|
|
154
|
+
const createListener = options.createListener ?? ((client) => new TeamsListener(client))
|
|
155
|
+
const client = createClient()
|
|
156
|
+
let listener: TeamsListener | null = null
|
|
157
|
+
let self: TeamsUser | null = null
|
|
158
|
+
let chatsById = new Map<string, TeamsChatInfo>()
|
|
159
|
+
let channelTeamMap = new Map<string, string>()
|
|
160
|
+
let sentEchoes: SentEcho[] = []
|
|
161
|
+
let started = false
|
|
162
|
+
let inflightInbounds = 0
|
|
163
|
+
let stopWaiters: Array<() => void> = []
|
|
164
|
+
|
|
165
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
|
|
166
|
+
self !== null ? { id: self.id, username: self.userPrincipalName ?? self.email ?? self.displayName } : null
|
|
167
|
+
|
|
168
|
+
const reserveEcho = (chatId: string, text: string): (() => void) => {
|
|
169
|
+
const echo: SentEcho = { chatId, textKey: normalizeTeamsText(text), sentAt: now(), consumed: false }
|
|
170
|
+
sentEchoes.push(echo)
|
|
171
|
+
if (sentEchoes.length > MAX_SENT_ECHOES) sentEchoes = sentEchoes.slice(-MAX_SENT_ECHOES)
|
|
172
|
+
return () => {
|
|
173
|
+
const index = sentEchoes.indexOf(echo)
|
|
174
|
+
if (index !== -1) sentEchoes.splice(index, 1)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const isSelfEcho = (event: TeamsInboundEvent): boolean => {
|
|
179
|
+
const conversationId = echoConversationId(event)
|
|
180
|
+
const textKey = normalizeTeamsText(event.content)
|
|
181
|
+
const authorName = event.author.displayName.trim().toLocaleLowerCase()
|
|
182
|
+
const selfName = (self?.displayName ?? '').trim().toLocaleLowerCase()
|
|
183
|
+
const nowMs = now()
|
|
184
|
+
for (const echo of sentEchoes) {
|
|
185
|
+
if (echo.consumed || echo.chatId !== conversationId || echo.textKey !== textKey) continue
|
|
186
|
+
const age = nowMs - echo.sentAt
|
|
187
|
+
if (age > SELF_ECHO_TTL_MS) continue
|
|
188
|
+
const authorLooksSelf =
|
|
189
|
+
event.author.id === 'ME' || (selfName !== '' && authorName === selfName) || authorName === 'me'
|
|
190
|
+
if (authorLooksSelf || age <= SELF_ECHO_CONTENT_ONLY_TTL_MS) {
|
|
191
|
+
echo.consumed = true
|
|
192
|
+
return true
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return false
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const outboundCallback = createOutboundCallback({ client, logger, reserveEcho })
|
|
199
|
+
const historyCallback = createTeamsHistoryCallback({ client, logger, selfIdRef: () => self?.id ?? null })
|
|
200
|
+
|
|
201
|
+
const refreshChats = async (): Promise<void> => {
|
|
202
|
+
const chats = await client.listChats()
|
|
203
|
+
chatsById = new Map(chats.map((chat) => [chat.id, chat]))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const resolveChat = async (chatId: string): Promise<TeamsChatInfo | undefined> => {
|
|
207
|
+
const cached = chatsById.get(chatId)
|
|
208
|
+
if (cached !== undefined) return cached
|
|
209
|
+
try {
|
|
210
|
+
await refreshChats()
|
|
211
|
+
} catch (err) {
|
|
212
|
+
logger.warn(`[teams] chat refresh failed: ${describeError(err)}`)
|
|
213
|
+
}
|
|
214
|
+
return chatsById.get(chatId)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// For a channel event the SDK resolves teamId out-of-band and populates it on
|
|
218
|
+
// the event; `channelTeamMap` is only a defensive fallback for the rare case
|
|
219
|
+
// the SDK emits a channel-typed event with teamId missing. channelId always
|
|
220
|
+
// equals the conversation id (== event.chatId) for channels.
|
|
221
|
+
const resolveChannel = (event: TeamsInboundEvent): { teamId: string; channelId: string } | null => {
|
|
222
|
+
const channelId = event.channelId ?? event.chatId
|
|
223
|
+
const teamId = event.teamId ?? channelTeamMap.get(channelId)
|
|
224
|
+
if (teamId === undefined || channelId === '') return null
|
|
225
|
+
return { teamId, channelId }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const handleMessage = async (event: TeamsInboundEvent): Promise<void> => {
|
|
229
|
+
inflightInbounds++
|
|
230
|
+
try {
|
|
231
|
+
if (isSelfEcho(event)) {
|
|
232
|
+
logger.info(`[teams] dropped id=${event.id} reason=self_echo`)
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
const aliases = options.selfAliasesRef?.() ?? []
|
|
236
|
+
let verdict
|
|
237
|
+
if (event.conversationType === 'channel') {
|
|
238
|
+
const channel = resolveChannel(event)
|
|
239
|
+
verdict =
|
|
240
|
+
channel === null
|
|
241
|
+
? ({ kind: 'drop', reason: 'unknown_channel' } as const)
|
|
242
|
+
: classifyChannelInbound(event, options.configRef(), self, channel, aliases)
|
|
243
|
+
} else {
|
|
244
|
+
const chat = await resolveChat(event.chatId)
|
|
245
|
+
verdict = classifyChatInbound(event, options.configRef(), self, chat, aliases)
|
|
246
|
+
}
|
|
247
|
+
if (verdict.kind === 'drop') {
|
|
248
|
+
logger.info(`[teams] dropped id=${event.id} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
logger.info(
|
|
252
|
+
`[teams] routed id=${event.id} ${event.conversationType}=${event.chatId} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
|
|
253
|
+
)
|
|
254
|
+
await options.router.route(verdict.payload)
|
|
255
|
+
} catch (err) {
|
|
256
|
+
logger.error(`[teams] handleInbound failed: ${describeError(err)}`)
|
|
257
|
+
} finally {
|
|
258
|
+
inflightInbounds--
|
|
259
|
+
if (inflightInbounds === 0 && stopWaiters.length > 0) {
|
|
260
|
+
const waiters = stopWaiters
|
|
261
|
+
stopWaiters = []
|
|
262
|
+
for (const w of waiters) w()
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
async start(): Promise<void> {
|
|
269
|
+
if (started) return
|
|
270
|
+
started = true
|
|
271
|
+
try {
|
|
272
|
+
const account = await (options.credentialsStore ?? null)?.getAccount()
|
|
273
|
+
if (account === null || account === undefined) {
|
|
274
|
+
throw new Error('no Teams account in secrets.json#channels.teams (run typeclaw init to authenticate)')
|
|
275
|
+
}
|
|
276
|
+
warnIfTokenExpiring(account, logger, now())
|
|
277
|
+
await client.login({
|
|
278
|
+
token: account.access_token,
|
|
279
|
+
...(account.token_expires_at !== undefined ? { tokenExpiresAt: account.token_expires_at } : {}),
|
|
280
|
+
accountType: account.account_type,
|
|
281
|
+
...(account.region !== undefined ? { region: account.region } : {}),
|
|
282
|
+
})
|
|
283
|
+
self = await client.testAuth()
|
|
284
|
+
loadedAccount = account
|
|
285
|
+
await refreshChats()
|
|
286
|
+
// Best-effort channelId->teamId map: the SDK already resolves teamId on
|
|
287
|
+
// channel events, so this only backs the defensive fallback in
|
|
288
|
+
// resolveChannel. A failure here must not block startup.
|
|
289
|
+
try {
|
|
290
|
+
channelTeamMap = await client.buildChannelTeamMap()
|
|
291
|
+
} catch (err) {
|
|
292
|
+
logger.warn(`[teams] channel-team map build failed: ${describeError(err)}`)
|
|
293
|
+
}
|
|
294
|
+
logger.info(`[teams] authenticated as ${self.displayName}, ${chatsById.size} chats`)
|
|
295
|
+
} catch (err) {
|
|
296
|
+
started = false
|
|
297
|
+
self = null
|
|
298
|
+
loadedAccount = null
|
|
299
|
+
chatsById = new Map()
|
|
300
|
+
channelTeamMap = new Map()
|
|
301
|
+
logger.error(`[teams] login failed: ${describeError(err)}`)
|
|
302
|
+
throw err
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// REST auth succeeded, so send/history/self-identity work regardless of
|
|
306
|
+
// whether the realtime listener can connect. Register them now and NEVER
|
|
307
|
+
// unregister them on a listener failure — realtime is a best-effort
|
|
308
|
+
// add-on, not a precondition for the adapter being usable.
|
|
309
|
+
options.router.registerOutbound('teams', outboundCallback)
|
|
310
|
+
options.router.registerSelfIdentity('teams', selfIdentityResolver)
|
|
311
|
+
options.router.registerHistory('teams', historyCallback)
|
|
312
|
+
|
|
313
|
+
listener = createListener(client)
|
|
314
|
+
const activeListener = listener
|
|
315
|
+
const isActive = (): boolean => listener === activeListener && started
|
|
316
|
+
|
|
317
|
+
// The realtime trouter listener needs an id_token the container mints from
|
|
318
|
+
// the account's AAD refresh token. When that is unavailable (legacy
|
|
319
|
+
// extracted-token account, expired refresh token, or a genuine trouter
|
|
320
|
+
// outage) the SDK rejects — and, crucially, on a still-running listener it
|
|
321
|
+
// schedules an UNBOUNDED reconnect that re-fails and re-emits `error`
|
|
322
|
+
// forever. Rather than fail the whole adapter (or let it log-loop), tear
|
|
323
|
+
// the listener down and keep running REST-only: send/read still work, we
|
|
324
|
+
// just don't get proactively woken by inbound Teams messages.
|
|
325
|
+
const degradeToRestOnly = (cause: Error): void => {
|
|
326
|
+
if (listener !== activeListener) return
|
|
327
|
+
listener?.stop()
|
|
328
|
+
listener = null
|
|
329
|
+
logger.warn(
|
|
330
|
+
`[teams] realtime listener unavailable, continuing REST-only (send/read work, no proactive inbound): ${describeError(cause)}`,
|
|
331
|
+
)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
listener.on('connected', () => {
|
|
335
|
+
if (!isActive()) return
|
|
336
|
+
logger.info('[teams] connected')
|
|
337
|
+
})
|
|
338
|
+
listener.on('disconnected', () => {
|
|
339
|
+
if (!isActive()) return
|
|
340
|
+
logger.warn('[teams] disconnected')
|
|
341
|
+
})
|
|
342
|
+
// A post-connect `error` for the unrecoverable id_token failure would
|
|
343
|
+
// otherwise loop forever through the SDK's reconnect (each retry re-mints
|
|
344
|
+
// nothing and re-emits `error`). Degrade to REST-only on that specific
|
|
345
|
+
// cause so the loop stops; transient socket errors keep just logging and
|
|
346
|
+
// let the SDK's own reconnect recover them.
|
|
347
|
+
listener.on('error', (err: TeamsListenerEventMap['error'][0]) => {
|
|
348
|
+
if (!isActive()) return
|
|
349
|
+
if (isUnrecoverableRealtimeAuthError(err)) {
|
|
350
|
+
degradeToRestOnly(err)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
logger.error(`[teams] listener error: ${describeError(err)}`)
|
|
354
|
+
})
|
|
355
|
+
listener.on('message', (event: TeamsListenerEventMap['message'][0]) => {
|
|
356
|
+
void handleMessage(event)
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
// The SDK emits `connected` asynchronously, only after the trouter
|
|
360
|
+
// WebSocket registers an endpoint — it is NOT raised synchronously by
|
|
361
|
+
// `listener.start()`. So attach the connected/error race BEFORE start()
|
|
362
|
+
// and await it, rather than sampling a flag right after start() returns.
|
|
363
|
+
const connectedWait = waitForTeamsConnected(listener)
|
|
364
|
+
try {
|
|
365
|
+
await listener.start()
|
|
366
|
+
await connectedWait.promise
|
|
367
|
+
logger.info('[teams] realtime listener connected')
|
|
368
|
+
} catch (err) {
|
|
369
|
+
// Tear down the connected wait first: if `listener.start()` itself
|
|
370
|
+
// rejected, `connectedWait.promise` was never awaited, so its timer and
|
|
371
|
+
// handlers would otherwise linger and reject later unhandled.
|
|
372
|
+
connectedWait.cancel()
|
|
373
|
+
degradeToRestOnly(err instanceof Error ? err : new Error(describeError(err)))
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
|
|
377
|
+
async stop(): Promise<void> {
|
|
378
|
+
if (!started) return
|
|
379
|
+
started = false
|
|
380
|
+
options.router.unregisterOutbound('teams', outboundCallback)
|
|
381
|
+
options.router.unregisterSelfIdentity('teams', selfIdentityResolver)
|
|
382
|
+
options.router.unregisterHistory('teams', historyCallback)
|
|
383
|
+
listener?.stop()
|
|
384
|
+
listener = null
|
|
385
|
+
if (inflightInbounds > 0) {
|
|
386
|
+
await new Promise<void>((resolve) => {
|
|
387
|
+
stopWaiters.push(resolve)
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
self = null
|
|
391
|
+
chatsById = new Map()
|
|
392
|
+
channelTeamMap = new Map()
|
|
393
|
+
sentEchoes = []
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
// REST auth being live is what makes the adapter usable (send/read); the
|
|
397
|
+
// realtime listener is a best-effort add-on. Returning true here even in
|
|
398
|
+
// REST-only mode is deliberate: the channel manager restarts any adapter
|
|
399
|
+
// whose isConnected() is false, which would pointlessly churn a healthy
|
|
400
|
+
// REST-only Teams adapter that can never get a realtime listener.
|
|
401
|
+
isConnected(): boolean {
|
|
402
|
+
return started && self !== null
|
|
403
|
+
},
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Returns the connected/error/timeout race plus a `cancel` that tears down the
|
|
408
|
+
// timer and listener handlers. `cancel` is load-bearing: if `listener.start()`
|
|
409
|
+
// itself rejects, the caller never awaits `promise`, so without cancellation
|
|
410
|
+
// the 20s timer would linger and the promise could later reject with no handler
|
|
411
|
+
// (an unhandled rejection). Cancelling resolves the promise as a no-op so it
|
|
412
|
+
// stays handled.
|
|
413
|
+
function waitForTeamsConnected(
|
|
414
|
+
listener: TeamsListener,
|
|
415
|
+
timeoutMs = TEAMS_LISTENER_START_TIMEOUT_MS,
|
|
416
|
+
): { promise: Promise<void>; cancel: () => void } {
|
|
417
|
+
let settled = false
|
|
418
|
+
let onConnected: () => void = () => {}
|
|
419
|
+
let onError: (err: Error) => void = () => {}
|
|
420
|
+
let resolveNoop: () => void = () => {}
|
|
421
|
+
let timer: ReturnType<typeof setTimeout>
|
|
422
|
+
const cleanup = (): void => {
|
|
423
|
+
clearTimeout(timer)
|
|
424
|
+
listener.off('connected', onConnected)
|
|
425
|
+
listener.off('error', onError)
|
|
426
|
+
}
|
|
427
|
+
const promise = new Promise<void>((resolve, reject) => {
|
|
428
|
+
resolveNoop = resolve
|
|
429
|
+
const settle = (fn: () => void): void => {
|
|
430
|
+
if (settled) return
|
|
431
|
+
settled = true
|
|
432
|
+
cleanup()
|
|
433
|
+
fn()
|
|
434
|
+
}
|
|
435
|
+
onConnected = (): void => settle(resolve)
|
|
436
|
+
onError = (err: Error): void => settle(() => reject(err))
|
|
437
|
+
timer = setTimeout(
|
|
438
|
+
() => settle(() => reject(new Error(`Teams listener did not connect within ${timeoutMs}ms`))),
|
|
439
|
+
timeoutMs,
|
|
440
|
+
)
|
|
441
|
+
listener.on('connected', onConnected)
|
|
442
|
+
listener.on('error', onError)
|
|
443
|
+
})
|
|
444
|
+
const cancel = (): void => {
|
|
445
|
+
if (settled) return
|
|
446
|
+
settled = true
|
|
447
|
+
cleanup()
|
|
448
|
+
resolveNoop()
|
|
449
|
+
}
|
|
450
|
+
return { promise, cancel }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Both `getChatMessages` and `getMessages` already strip HTML and set
|
|
454
|
+
// `author.id` to the real MRI (never `'ME'`), so bot-authored history can only
|
|
455
|
+
// be recognized when the caller knows that MRI — which the SDK does not
|
|
456
|
+
// surface. `selfId` is therefore best-effort: it flags nothing in practice
|
|
457
|
+
// today, but leaving the comparison in place means history attribution starts
|
|
458
|
+
// working for free if a future SDK version exposes the real self id.
|
|
459
|
+
function mapTeamsHistoryMessage(msg: TeamsMessage, selfId: string | null): ChannelHistoryMessage {
|
|
460
|
+
const ts = Date.parse(msg.timestamp)
|
|
461
|
+
return {
|
|
462
|
+
externalMessageId: msg.id,
|
|
463
|
+
authorId: msg.author.id,
|
|
464
|
+
authorName: msg.author.displayName,
|
|
465
|
+
text: msg.content,
|
|
466
|
+
ts: Number.isFinite(ts) ? ts : 0,
|
|
467
|
+
isBot: selfId !== null && msg.author.id === selfId,
|
|
468
|
+
replyToBotMessageId: null,
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function warnIfTokenExpiring(account: TeamsAccountRecord, logger: TeamsAdapterLogger, nowMs: number): void {
|
|
473
|
+
if (account.token_expires_at === undefined) return
|
|
474
|
+
const expiresAt = Date.parse(account.token_expires_at)
|
|
475
|
+
if (!Number.isFinite(expiresAt)) return
|
|
476
|
+
if (expiresAt <= nowMs) {
|
|
477
|
+
logger.warn('[teams] access token is already expired; the adapter will fail until credentials are refreshed')
|
|
478
|
+
} else if (expiresAt - nowMs <= 10 * 60_000) {
|
|
479
|
+
logger.warn('[teams] access token expires soon; long-running sessions will stop until credentials are refreshed')
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// The SDK throws a `TeamsError` with code `no_id_token` when it cannot obtain
|
|
484
|
+
// the trouter id_token. In the container that never self-heals (the token is
|
|
485
|
+
// minted from the AAD refresh token, so if minting fails once it keeps failing
|
|
486
|
+
// every reconnect), so treat it as the signal to stop the doomed reconnect loop
|
|
487
|
+
// and degrade. Transient socket errors carry other codes / plain Errors and are
|
|
488
|
+
// left for the SDK's own reconnect to recover.
|
|
489
|
+
function isUnrecoverableRealtimeAuthError(err: unknown): boolean {
|
|
490
|
+
return err instanceof TeamsError && err.code === 'no_id_token'
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// The echo the socket delivers back for our own send carries the conversation
|
|
494
|
+
// id it was sent to: the channelId for a channel send, the chatId otherwise.
|
|
495
|
+
// (channelId == chatId for channel events today, but prefer channelId so the
|
|
496
|
+
// ledger stays correct if the SDK ever distinguishes them.)
|
|
497
|
+
function echoConversationId(event: TeamsInboundEvent): string {
|
|
498
|
+
if (event.conversationType === 'channel') return event.channelId ?? event.chatId
|
|
499
|
+
return event.chatId
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function clampLimit(requested: number, max: number): number {
|
|
503
|
+
if (!Number.isFinite(requested) || requested <= 0) return max
|
|
504
|
+
return Math.min(Math.floor(requested), max)
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function dropHint(reason: InboundDropReason): string {
|
|
508
|
+
switch (reason) {
|
|
509
|
+
case 'empty_content':
|
|
510
|
+
return ' (message had no text)'
|
|
511
|
+
case 'unknown_chat':
|
|
512
|
+
return ' (chat id not found even after refresh)'
|
|
513
|
+
case 'unknown_channel':
|
|
514
|
+
return ' (channel message missing a resolvable teamId)'
|
|
515
|
+
case 'pre_connect':
|
|
516
|
+
case 'self_author':
|
|
517
|
+
return ''
|
|
518
|
+
}
|
|
519
|
+
}
|
|
@@ -15,6 +15,21 @@ export type ReviewObserver = (args: {
|
|
|
15
15
|
verdict: ReviewVerdict
|
|
16
16
|
}) => void
|
|
17
17
|
|
|
18
|
+
// A formal review LANDED this turn, of ANY state — the two decisive verdicts PLUS
|
|
19
|
+
// a non-decisive COMMENT. This signal ONLY tells the channel router "the agent
|
|
20
|
+
// already delivered output via the GitHub review API this turn" so an empty
|
|
21
|
+
// completion afterward doesn't fire the empty-turn fallback. It is deliberately
|
|
22
|
+
// NOT stored in the false-receipt ledger (`reviewsByPr`): a COMMENT carries no
|
|
23
|
+
// verdict-claim risk and must never satisfy `hasReview()`.
|
|
24
|
+
export type ReviewOutputState = ReviewVerdict | 'COMMENT'
|
|
25
|
+
|
|
26
|
+
export type ReviewOutputObserver = (args: {
|
|
27
|
+
sessionId: string
|
|
28
|
+
workspace: string
|
|
29
|
+
prNumber: number
|
|
30
|
+
state: ReviewOutputState
|
|
31
|
+
}) => void
|
|
32
|
+
|
|
18
33
|
type PrKey = string
|
|
19
34
|
type ThreadKey = string
|
|
20
35
|
|
|
@@ -28,13 +43,19 @@ const resolvedThreads = new Set<ThreadKey>()
|
|
|
28
43
|
// stays the single seam where "a formal verdict happened" is known across the
|
|
29
44
|
// plugin/channels boundary, which is why it owns this hook.
|
|
30
45
|
let reviewObserver: ReviewObserver | null = null
|
|
46
|
+
let reviewOutputObserver: ReviewOutputObserver | null = null
|
|
31
47
|
|
|
32
48
|
export function setReviewObserver(observer: ReviewObserver | null): void {
|
|
33
49
|
reviewObserver = observer
|
|
34
50
|
}
|
|
35
51
|
|
|
52
|
+
export function setReviewOutputObserver(observer: ReviewOutputObserver | null): void {
|
|
53
|
+
reviewOutputObserver = observer
|
|
54
|
+
}
|
|
55
|
+
|
|
36
56
|
export function __resetReviewObserverForTest(): void {
|
|
37
57
|
reviewObserver = null
|
|
58
|
+
reviewOutputObserver = null
|
|
38
59
|
}
|
|
39
60
|
|
|
40
61
|
function prKey(sessionId: string, workspace: string, prNumber: number): PrKey {
|
|
@@ -73,6 +94,28 @@ export function recordReview(args: {
|
|
|
73
94
|
// swallow: a broken broadcast must not break verdict bookkeeping
|
|
74
95
|
}
|
|
75
96
|
}
|
|
97
|
+
// A decisive verdict IS review output too — fan it to the output observer so the
|
|
98
|
+
// router's empty-turn guard sees it without a second detection path.
|
|
99
|
+
recordReviewOutput({
|
|
100
|
+
sessionId: args.sessionId,
|
|
101
|
+
workspace: args.workspace,
|
|
102
|
+
prNumber: args.prNumber,
|
|
103
|
+
state: args.verdict,
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function recordReviewOutput(args: {
|
|
108
|
+
sessionId: string
|
|
109
|
+
workspace: string
|
|
110
|
+
prNumber: number
|
|
111
|
+
state: ReviewOutputState
|
|
112
|
+
}): void {
|
|
113
|
+
if (reviewOutputObserver === null) return
|
|
114
|
+
try {
|
|
115
|
+
reviewOutputObserver(args)
|
|
116
|
+
} catch {
|
|
117
|
+
// swallow: a broken router notification must not break review bookkeeping
|
|
118
|
+
}
|
|
76
119
|
}
|
|
77
120
|
|
|
78
121
|
export function hasReview(args: {
|
package/src/channels/index.ts
CHANGED
|
@@ -20,7 +20,7 @@ export {
|
|
|
20
20
|
type PrVerdictActivityBridge,
|
|
21
21
|
type PrVerdictActivityBridgeOptions,
|
|
22
22
|
} from './pr-verdict-activity-bridge'
|
|
23
|
-
export { setReviewObserver } from './github-review-turn-ledger'
|
|
23
|
+
export { setReviewObserver, setReviewOutputObserver, type ReviewOutputState } from './github-review-turn-ledger'
|
|
24
24
|
export {
|
|
25
25
|
createSubagentCompletionBridge,
|
|
26
26
|
type SubagentCompletionBridge,
|