typeclaw 0.37.7 → 0.38.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 (44) hide show
  1. package/README.md +2 -2
  2. package/auth.schema.json +109 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +109 -0
  5. package/src/agent/session-origin.ts +16 -2
  6. package/src/bundled-plugins/memory/README.md +12 -1
  7. package/src/bundled-plugins/memory/index.ts +39 -2
  8. package/src/channels/adapters/kakaotalk.ts +1 -1
  9. package/src/channels/adapters/webex-bot-channel-resolver.ts +29 -0
  10. package/src/channels/adapters/webex-bot-classify.ts +98 -0
  11. package/src/channels/adapters/webex-bot-reference.ts +49 -0
  12. package/src/channels/adapters/webex-bot.ts +462 -0
  13. package/src/channels/adapters/webex-channel-resolver.ts +29 -0
  14. package/src/channels/adapters/webex-classify.ts +104 -0
  15. package/src/channels/adapters/webex-format.ts +53 -0
  16. package/src/channels/adapters/webex-id-ref.ts +32 -0
  17. package/src/channels/adapters/webex-reference.ts +49 -0
  18. package/src/channels/adapters/webex.ts +493 -0
  19. package/src/channels/manager.ts +75 -4
  20. package/src/channels/persistence.ts +67 -5
  21. package/src/channels/router.ts +9 -0
  22. package/src/channels/schema.ts +17 -1
  23. package/src/cli/channel.ts +155 -8
  24. package/src/cli/init.ts +129 -6
  25. package/src/config/channels-mutation.ts +11 -2
  26. package/src/doctor/channel-checks.ts +56 -1
  27. package/src/hostd/daemon.ts +7 -5
  28. package/src/hostd/protocol.ts +2 -2
  29. package/src/init/checkpoint.ts +1 -1
  30. package/src/init/index.ts +97 -17
  31. package/src/init/run-owner-claim.ts +2 -0
  32. package/src/init/webex-auth.ts +68 -0
  33. package/src/inspect/label.ts +13 -2
  34. package/src/inspect/render.ts +5 -3
  35. package/src/permissions/match-rule.ts +7 -3
  36. package/src/permissions/resolve.ts +44 -5
  37. package/src/role-claim/match-rule.ts +7 -2
  38. package/src/secrets/codex-auth-json.ts +52 -17
  39. package/src/secrets/defaults.ts +1 -0
  40. package/src/secrets/encryption.ts +5 -1
  41. package/src/secrets/export-codex-auth-file.ts +26 -3
  42. package/src/secrets/schema.ts +35 -0
  43. package/src/secrets/webex-store.ts +113 -0
  44. package/typeclaw.schema.json +321 -1
@@ -0,0 +1,49 @@
1
+ import type { WebexClient } from 'agent-messenger/webex'
2
+
3
+ import type { InboundMessage, QuoteAnchorSource } from '@/channels/types'
4
+
5
+ import { resolveWebexBodyText } from './webex-format'
6
+
7
+ // Webex Mercury delivers only the parent message id inline, not its author,
8
+ // so the classifier cannot tell whether a reply targets the bot. We fetch the
9
+ // parent here (already needed for the quote anchor) and use its author to set
10
+ // the reply-target fields the engagement layer reads: a non-mention reply to a
11
+ // bot-authored parent must engage via the `reply` trigger, and a reply to a
12
+ // different author must suppress the solo-human fallback. Both are no-ops if
13
+ // the classifier already attributed the reply (it sets replyToBotMessageId
14
+ // when the reply also @-mentions the bot).
15
+ export async function enrichWebexMessageReference(args: {
16
+ client: Pick<WebexClient, 'getMessage'>
17
+ inbound: InboundMessage
18
+ parentRef?: string
19
+ botPersonId: string | null
20
+ }): Promise<InboundMessage> {
21
+ if (args.parentRef === undefined || args.parentRef === '') return args.inbound
22
+ try {
23
+ const parent = await args.client.getMessage(args.parentRef)
24
+ const attributed = attributeReply(args.inbound, parent.ref, parent.personRef, args.botPersonId)
25
+ const source: QuoteAnchorSource = {
26
+ adapter: 'webex',
27
+ authorId: parent.personRef,
28
+ authorName: parent.personEmail,
29
+ text: resolveWebexBodyText(parent),
30
+ }
31
+ if (source.text.trim() === '') return attributed
32
+ return { ...attributed, referenceContext: { kind: 'reply', sources: [source] } }
33
+ } catch {
34
+ return args.inbound
35
+ }
36
+ }
37
+
38
+ function attributeReply(
39
+ inbound: InboundMessage,
40
+ parentId: string,
41
+ parentPersonId: string,
42
+ botPersonId: string | null,
43
+ ): InboundMessage {
44
+ if (inbound.replyToBotMessageId !== null || inbound.replyToOtherMessageId !== null) return inbound
45
+ if (botPersonId !== null && parentPersonId === botPersonId) {
46
+ return { ...inbound, replyToBotMessageId: parentId }
47
+ }
48
+ return { ...inbound, replyToOtherMessageId: parentId }
49
+ }
@@ -0,0 +1,493 @@
1
+ // WebexListener + WebexListenerEventMap/Options require agent-messenger/webex (PR #239);
2
+ // loginWithPassword path requires PR #238. Both land via the linked upstream.
3
+ import { WebexClient, WebexListener } from 'agent-messenger/webex'
4
+ import type {
5
+ WebexListenerEventMap,
6
+ WebexListenerOptions,
7
+ WebexMembership,
8
+ WebexMessage,
9
+ WebexPerson,
10
+ } from 'agent-messenger/webex'
11
+
12
+ import {
13
+ MEMBERSHIP_ENUMERATION_CAP,
14
+ type MembershipResolver,
15
+ type MembershipResolverFailure,
16
+ type MembershipResolverResult,
17
+ } from '@/channels/membership'
18
+ import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
19
+ import type { ChannelRouter } from '@/channels/router'
20
+ import type { ChannelAdapterConfig } from '@/channels/schema'
21
+ import type {
22
+ ChannelHistoryMessage,
23
+ ChannelSelfIdentityResolver,
24
+ FetchAttachmentCallback,
25
+ FetchHistoryArgs,
26
+ FetchHistoryResult,
27
+ HistoryCallback,
28
+ OutboundCallback,
29
+ OutboundMessage,
30
+ ResolvedChannelNames,
31
+ SendResult,
32
+ } from '@/channels/types'
33
+ import type { WebexAccountRecord } from '@/secrets/schema'
34
+
35
+ import { createWebexChannelNameResolver } from './webex-channel-resolver'
36
+ import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-classify'
37
+ import { resolveWebexBodyText } from './webex-format'
38
+ import { enrichWebexMessageReference } from './webex-reference'
39
+
40
+ export type WebexAdapterLogger = {
41
+ info: (msg: string) => void
42
+ warn: (msg: string) => void
43
+ error: (msg: string) => void
44
+ }
45
+
46
+ const consoleLogger: WebexAdapterLogger = {
47
+ info: (m) => console.log(m),
48
+ warn: (m) => console.warn(m),
49
+ error: (m) => console.error(m),
50
+ }
51
+
52
+ export type WebexListenerTokenClient = { getToken: () => string }
53
+ export type WebexClientFactory = () => WebexClient
54
+ export type WebexListenerFactory = (client: WebexListenerTokenClient, options: WebexListenerOptions) => WebexListener
55
+
56
+ export type WebexCredentialStore = {
57
+ getAccount(id?: string): Promise<WebexAccountRecord | null>
58
+ }
59
+
60
+ export type WebexAdapterOptions = {
61
+ router: ChannelRouter
62
+ configRef: () => ChannelAdapterConfig
63
+ logger?: WebexAdapterLogger
64
+ selfAliasesRef?: () => readonly string[]
65
+ credentialsStore?: WebexCredentialStore
66
+ createClient?: WebexClientFactory
67
+ createListener?: WebexListenerFactory
68
+ listenerOptions?: Omit<WebexListenerOptions, 'ignoreSelfMessages'>
69
+ fetchImpl?: typeof fetch
70
+ }
71
+
72
+ export type WebexAdapter = {
73
+ start: () => Promise<void>
74
+ stop: () => Promise<void>
75
+ isConnected: () => boolean
76
+ }
77
+
78
+ export type WebexOutboundFile = { content: Blob; filename: string }
79
+ export type WebexFileReader = (path: string) => Promise<WebexOutboundFile>
80
+
81
+ // Webex resolves any `parentId` to the thread root, so threading a reply and
82
+ // replying to a specific message land in the same thread. `replyTo` (the native
83
+ // quote anchor the router sets in native mode) is the more precise target, so it
84
+ // wins over `msg.thread` when present — both `sendMessage` and `uploadFile`
85
+ // accept `parentId`, so attachment replies thread natively too (unlike
86
+ // Discord/Telegram, where uploads land bare).
87
+ //
88
+ // `uploadFile` carries `text` + `parentId` in one multipart POST, so a
89
+ // text+single-file message is one call (Slack's `initial_comment` shape). With
90
+ // multiple files the first upload carries the text and every upload carries the
91
+ // parentId; remaining uploads are bare so the text is not duplicated.
92
+ export function createOutboundCallback(deps: {
93
+ client: Pick<WebexClient, 'sendMessage' | 'uploadFile'>
94
+ logger: WebexAdapterLogger
95
+ formatChannelTag: (chat: string) => Promise<string>
96
+ readFile?: WebexFileReader
97
+ resolvePath?: (path: string) => string
98
+ }): OutboundCallback {
99
+ const { client, logger, formatChannelTag, resolvePath } = deps
100
+ const readFile = deps.readFile ?? defaultReadFile
101
+ return async (msg: OutboundMessage): Promise<SendResult> => {
102
+ if (msg.adapter !== 'webex') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
103
+ const text = msg.text ?? ''
104
+ const attachments = msg.attachments ?? []
105
+ if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
106
+
107
+ const tag = await formatChannelTag(msg.chat)
108
+ const parentId = msg.replyTo?.externalMessageId ?? msg.thread ?? undefined
109
+ logger.info(
110
+ `[webex] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${parentId !== undefined ? ` parent=${parentId}` : ''}`,
111
+ )
112
+
113
+ try {
114
+ if (attachments.length > 0) {
115
+ for (const [index, attachment] of attachments.entries()) {
116
+ const path = resolvePath ? resolvePath(attachment.path) : attachment.path
117
+ const file = await readFile(path)
118
+ if (attachment.filename !== undefined) file.filename = attachment.filename
119
+ const carriesText = index === 0 && text !== ''
120
+ const sent = await client.uploadFile(msg.chat, file, {
121
+ ...(carriesText ? { text } : {}),
122
+ ...(parentId !== undefined ? { parentId } : {}),
123
+ })
124
+ logger.info(`[webex] uploaded id=${sent.ref} filename=${file.filename} ${tag}`)
125
+ }
126
+ return { ok: true }
127
+ }
128
+
129
+ const sent = await client.sendMessage(msg.chat, text, parentId !== undefined ? { parentId } : undefined)
130
+ logger.info(`[webex] sent id=${sent.ref} ${tag}`)
131
+ return { ok: true }
132
+ } catch (err) {
133
+ const message = describe(err)
134
+ logger.error(`[webex] outbound failed: ${message}`)
135
+ return { ok: false, error: message }
136
+ }
137
+ }
138
+ }
139
+
140
+ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
141
+ return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
142
+ }
143
+
144
+ export function createWebexHistoryCallback(deps: {
145
+ client: Pick<WebexClient, 'listMessages'>
146
+ logger: WebexAdapterLogger
147
+ botPersonIdRef: () => string | null
148
+ }): HistoryCallback {
149
+ return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
150
+ try {
151
+ const messages = await deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
152
+ const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
153
+ const botPersonId = deps.botPersonIdRef()
154
+ return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
155
+ } catch (err) {
156
+ const message = describe(err)
157
+ deps.logger.warn(`[webex] history fetch failed: ${message}`)
158
+ return { ok: false, error: message }
159
+ }
160
+ }
161
+ }
162
+
163
+ export function createWebexMembershipResolver(deps: {
164
+ client: Pick<WebexClient, 'listMemberships'>
165
+ logger: WebexAdapterLogger
166
+ historyCallback: HistoryCallback
167
+ botPersonIdRef: () => string | null
168
+ now?: () => number
169
+ }): MembershipResolver {
170
+ const now = deps.now ?? Date.now
171
+ return async (key): Promise<MembershipResolverResult> => {
172
+ if (key.adapter !== 'webex') return { kind: 'permanent' } satisfies MembershipResolverFailure
173
+ if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
174
+ try {
175
+ const memberships: WebexMembership[] = await deps.client.listMemberships(key.chat, {
176
+ max: MEMBERSHIP_ENUMERATION_CAP,
177
+ })
178
+ // Below the cap the enumeration is complete and authoritative, so it must
179
+ // NOT be marked truncated: `resolveEffectiveHumans` only trusts a fresh
180
+ // untruncated read over persisted speakers, and the `Math.max()` truncated
181
+ // path lets a stale/legacy email-keyed participant double-count the same
182
+ // human and silence the solo-human fallback.
183
+ const truncated = memberships.length >= MEMBERSHIP_ENUMERATION_CAP
184
+ // WebexMembership has no bot/person type field, so only the self bot can be
185
+ // classified; peer bots count as humans here (they still reach the agent
186
+ // via mention/reply/sticky triggers regardless of this count).
187
+ const botPersonId = deps.botPersonIdRef()
188
+ const humanMemberIds: string[] = []
189
+ let bots = 0
190
+ for (const member of memberships) {
191
+ if (botPersonId !== null && member.personRef === botPersonId) bots++
192
+ else humanMemberIds.push(member.personRef)
193
+ }
194
+ if (truncated) {
195
+ return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated }
196
+ }
197
+ return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated, humanMemberIds }
198
+ } catch (err) {
199
+ deps.logger.warn(`[webex] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
200
+ return await deriveMembershipFromHistory({
201
+ fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
202
+ now,
203
+ })
204
+ }
205
+ }
206
+ }
207
+
208
+ const WEBEX_ATTACHMENT_HOSTS = new Set(['webexapis.com', 'api.ciscospark.com'])
209
+
210
+ export function createFetchAttachmentCallback(deps: {
211
+ tokenRef: () => string | null
212
+ logger: WebexAdapterLogger
213
+ fetchImpl?: typeof fetch
214
+ }): FetchAttachmentCallback {
215
+ const fetchImpl = deps.fetchImpl ?? fetch
216
+ return async ({ ref, filename }) => {
217
+ const token = deps.tokenRef()
218
+ if (token === null) return { ok: false, error: 'webex account token is not available' }
219
+ let url: URL
220
+ try {
221
+ url = new URL(ref)
222
+ } catch {
223
+ return { ok: false, error: `invalid Webex file URL: ${ref}` }
224
+ }
225
+ // The bearer token must never leave over plaintext: an allowlisted host
226
+ // on http:// would still leak the credential, so gate on https before the
227
+ // host check.
228
+ if (url.protocol !== 'https:') {
229
+ return { ok: false, error: `Webex file URL must use https: ${url.protocol}//${url.hostname}` }
230
+ }
231
+ if (!isAllowedWebexFileHost(url.hostname)) {
232
+ return { ok: false, error: `not a Webex file URL: ${url.hostname}` }
233
+ }
234
+ try {
235
+ const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${token}` } })
236
+ if (!res.ok) {
237
+ const body = await res.text().catch(() => '')
238
+ const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
239
+ deps.logger.error(`[webex] fetchAttachment failed for ${url.toString()}: ${message}`)
240
+ return { ok: false, error: message }
241
+ }
242
+ const buffer = Buffer.from(await res.arrayBuffer())
243
+ const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
244
+ const contentType = res.headers.get('content-type') ?? undefined
245
+ return {
246
+ ok: true,
247
+ buffer,
248
+ filename: inferredFilename,
249
+ ...(contentType !== undefined ? { mimetype: contentType } : {}),
250
+ size: buffer.length,
251
+ }
252
+ } catch (err) {
253
+ const message = describe(err)
254
+ deps.logger.error(`[webex] fetchAttachment failed for ${url.toString()}: ${message}`)
255
+ return { ok: false, error: message }
256
+ }
257
+ }
258
+ }
259
+
260
+ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
261
+ const logger = options.logger ?? consoleLogger
262
+ const createClient = options.createClient ?? (() => new WebexClient())
263
+ const createListener =
264
+ options.createListener ?? ((client, listenerOptions) => new WebexListener(client, listenerOptions))
265
+ const client = createClient()
266
+ const fetchImpl = options.fetchImpl ?? fetch
267
+ let listener: WebexListener | null = null
268
+ let botPerson: WebexPerson | null = null
269
+ let currentToken: string | null = null
270
+ let connected = false
271
+ let started = false
272
+ let inflightInbounds = 0
273
+ let stopWaiters: Array<() => void> = []
274
+
275
+ const channelResolver = createWebexChannelNameResolver({ client })
276
+ const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
277
+ botPerson !== null ? { id: botPerson.ref, username: botPerson.emails[0] ?? botPerson.displayName } : null
278
+
279
+ const formatChannelTag = async (chat: string): Promise<string> => {
280
+ const names = await channelResolver({ adapter: 'webex', workspace: chat, chat, thread: null }).catch(
281
+ (): ResolvedChannelNames => ({}),
282
+ )
283
+ const label = names.chatName ?? null
284
+ return label === null || label === chat ? `room=${chat}` : `room=${label}(${chat})`
285
+ }
286
+
287
+ const historyCallback = createWebexHistoryCallback({ client, logger, botPersonIdRef: () => botPerson?.ref ?? null })
288
+ const membershipResolver = createWebexMembershipResolver({
289
+ client,
290
+ logger,
291
+ historyCallback,
292
+ botPersonIdRef: () => botPerson?.ref ?? null,
293
+ })
294
+ const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
295
+ const fetchAttachmentCallback = createFetchAttachmentCallback({ tokenRef: () => currentToken, logger, fetchImpl })
296
+
297
+ const handleMessage = async (event: WebexInboundMessage): Promise<void> => {
298
+ inflightInbounds++
299
+ const botSnapshot = botPerson
300
+ try {
301
+ const tag = await formatChannelTag(event.roomRef)
302
+ logger.info(`[webex] inbound id=${event.ref} author=${event.personEmail} ${tag} text_len=${event.text.length}`)
303
+ const verdict = classifyInbound(
304
+ event,
305
+ options.configRef(),
306
+ botSnapshot?.ref ?? null,
307
+ options.selfAliasesRef?.() ?? [],
308
+ )
309
+ if (verdict.kind === 'drop') {
310
+ logger.info(`[webex] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
311
+ return
312
+ }
313
+ const payload = await enrichWebexMessageReference({
314
+ client,
315
+ inbound: verdict.payload,
316
+ parentRef: event.parentRef,
317
+ botPersonId: botSnapshot?.ref ?? null,
318
+ })
319
+ logger.info(
320
+ `[webex] routed id=${event.ref} ${tag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
321
+ )
322
+ await options.router.route(payload)
323
+ } catch (err) {
324
+ logger.error(`[webex] handleInbound failed: ${describe(err)}`)
325
+ } finally {
326
+ inflightInbounds--
327
+ if (inflightInbounds === 0 && stopWaiters.length > 0) {
328
+ const waiters = stopWaiters
329
+ stopWaiters = []
330
+ for (const w of waiters) w()
331
+ }
332
+ }
333
+ }
334
+
335
+ return {
336
+ async start(): Promise<void> {
337
+ if (started) return
338
+ started = true
339
+ try {
340
+ const account = await (options.credentialsStore ?? null)?.getAccount()
341
+ if (account === null || account === undefined) {
342
+ throw new Error('no Webex account in secrets.json#channels.webex (run typeclaw init to authenticate)')
343
+ }
344
+ currentToken = account.access_token
345
+ await client.login({ token: account.access_token, deviceUrl: account.device_url, tokenType: 'password' })
346
+ botPerson = await client.testAuth()
347
+ logger.info(`[webex] authenticated as ${botPerson.displayName} (${botPerson.ref})`)
348
+ } catch (err) {
349
+ started = false
350
+ currentToken = null
351
+ botPerson = null
352
+ logger.error(`[webex] login failed: ${describe(err)}`)
353
+ throw err
354
+ }
355
+
356
+ listener = createListener(
357
+ { getToken: () => currentToken ?? '' },
358
+ { ...options.listenerOptions, ignoreSelfMessages: true },
359
+ )
360
+ let listenerConnected = false
361
+ let listenerStartupError: Error | null = null
362
+ listener.on('connected', () => {
363
+ listenerConnected = true
364
+ connected = true
365
+ })
366
+ listener.on('disconnected', (reason: string) => {
367
+ connected = false
368
+ logger.warn(`[webex] disconnected: ${reason}`)
369
+ })
370
+ listener.on('error', (err: unknown) => {
371
+ const error = err instanceof Error ? err : new Error(String(err))
372
+ if (!listenerConnected && listenerStartupError === null) listenerStartupError = error
373
+ logger.error(`[webex] listener error: ${describe(error)}`)
374
+ })
375
+ listener.on('message_created', (event: WebexListenerEventMap['message_created'][0]) => {
376
+ void handleMessage(event)
377
+ })
378
+
379
+ options.router.registerOutbound('webex', outboundCallback)
380
+ options.router.registerChannelNameResolver('webex', channelResolver)
381
+ options.router.registerSelfIdentity('webex', selfIdentityResolver)
382
+ options.router.registerHistory('webex', historyCallback)
383
+ options.router.registerFetchAttachment('webex', fetchAttachmentCallback)
384
+ options.router.registerMembership('webex', membershipResolver)
385
+
386
+ const rollbackStart = (reason: string, cause: Error): never => {
387
+ options.router.unregisterOutbound('webex', outboundCallback)
388
+ options.router.unregisterChannelNameResolver('webex', channelResolver)
389
+ options.router.unregisterSelfIdentity('webex', selfIdentityResolver)
390
+ options.router.unregisterHistory('webex', historyCallback)
391
+ options.router.unregisterFetchAttachment('webex', fetchAttachmentCallback)
392
+ options.router.unregisterMembership('webex', membershipResolver)
393
+ listener?.stop()
394
+ listener = null
395
+ botPerson = null
396
+ currentToken = null
397
+ connected = false
398
+ started = false
399
+ logger.error(`[webex] ${reason}: ${describe(cause)}`)
400
+ throw cause
401
+ }
402
+
403
+ try {
404
+ await listener.start()
405
+ } catch (err) {
406
+ rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
407
+ }
408
+ if (!listenerConnected) {
409
+ rollbackStart(
410
+ 'listener start failed silently',
411
+ listenerStartupError ?? new Error('listener.start() returned without emitting connected'),
412
+ )
413
+ }
414
+ },
415
+
416
+ async stop(): Promise<void> {
417
+ if (!started) return
418
+ started = false
419
+ options.router.unregisterOutbound('webex', outboundCallback)
420
+ options.router.unregisterChannelNameResolver('webex', channelResolver)
421
+ options.router.unregisterSelfIdentity('webex', selfIdentityResolver)
422
+ options.router.unregisterHistory('webex', historyCallback)
423
+ options.router.unregisterFetchAttachment('webex', fetchAttachmentCallback)
424
+ options.router.unregisterMembership('webex', membershipResolver)
425
+ listener?.stop()
426
+ listener = null
427
+ connected = false
428
+ if (inflightInbounds > 0) {
429
+ await new Promise<void>((resolve) => {
430
+ stopWaiters.push(resolve)
431
+ })
432
+ }
433
+ botPerson = null
434
+ currentToken = null
435
+ },
436
+
437
+ isConnected(): boolean {
438
+ return started && botPerson !== null && connected
439
+ },
440
+ }
441
+ }
442
+
443
+ function mapWebexHistoryMessage(
444
+ msg: WebexMessage,
445
+ botPersonId: string | null,
446
+ authorById: ReadonlyMap<string, string>,
447
+ ): ChannelHistoryMessage {
448
+ const attachments = (msg.files ?? []).map((ref, index) => ({ id: index + 1, kind: 'file' as const, ref }))
449
+ const body = resolveWebexBodyText(msg)
450
+ const text = attachments.length === 0 ? body : body === '' ? '[Webex attachment]' : `${body}\n[Webex attachment]`
451
+ const ts = Date.parse(msg.created)
452
+ return {
453
+ externalMessageId: msg.ref,
454
+ authorId: msg.personRef,
455
+ authorName: msg.personEmail,
456
+ text,
457
+ ts: Number.isFinite(ts) ? ts : 0,
458
+ isBot: botPersonId !== null && msg.personRef === botPersonId,
459
+ // Webex history carries parentId but not the parent's author, so a bare
460
+ // parentId cannot prove the reply targeted the agent. Only attribute it to
461
+ // the bot when the parent (resolved from the same history batch) was
462
+ // bot-authored — mirrors the live enrichWebexMessageReference rule and
463
+ // avoids marking human-authored threaded parents as replies to the agent.
464
+ replyToBotMessageId:
465
+ botPersonId !== null && msg.parentRef !== undefined && authorById.get(msg.parentRef) === botPersonId
466
+ ? msg.parentRef
467
+ : null,
468
+ ...(attachments.length > 0 ? { attachments } : {}),
469
+ }
470
+ }
471
+
472
+ function isAllowedWebexFileHost(hostname: string): boolean {
473
+ return WEBEX_ATTACHMENT_HOSTS.has(hostname) || hostname.endsWith('.webexcontent.com')
474
+ }
475
+
476
+ function clampLimit(requested: number, max: number): number {
477
+ if (!Number.isFinite(requested) || requested <= 0) return max
478
+ return Math.min(Math.floor(requested), max)
479
+ }
480
+
481
+ function describe(err: unknown): string {
482
+ return err instanceof Error ? err.message : String(err)
483
+ }
484
+
485
+ function dropHint(reason: InboundDropReason): string {
486
+ switch (reason) {
487
+ case 'empty_content':
488
+ return ' (message had no text and no files)'
489
+ case 'pre_connect':
490
+ case 'self_author':
491
+ return ''
492
+ }
493
+ }