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