typeclaw 0.38.0 → 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 (40) hide show
  1. package/auth.schema.json +109 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +109 -0
  4. package/src/agent/session-origin.ts +15 -2
  5. package/src/bundled-plugins/memory/README.md +12 -1
  6. package/src/bundled-plugins/memory/index.ts +39 -2
  7. package/src/channels/adapters/kakaotalk.ts +1 -1
  8. package/src/channels/adapters/webex-bot-classify.ts +20 -14
  9. package/src/channels/adapters/webex-bot-reference.ts +8 -6
  10. package/src/channels/adapters/webex-bot.ts +106 -39
  11. package/src/channels/adapters/webex-channel-resolver.ts +29 -0
  12. package/src/channels/adapters/webex-classify.ts +104 -0
  13. package/src/channels/adapters/webex-format.ts +53 -0
  14. package/src/channels/adapters/webex-id-ref.ts +32 -0
  15. package/src/channels/adapters/webex-reference.ts +49 -0
  16. package/src/channels/adapters/webex.ts +493 -0
  17. package/src/channels/manager.ts +63 -7
  18. package/src/channels/persistence.ts +67 -5
  19. package/src/channels/router.ts +8 -0
  20. package/src/channels/schema.ts +2 -0
  21. package/src/cli/channel.ts +118 -7
  22. package/src/cli/init.ts +70 -1
  23. package/src/config/channels-mutation.ts +2 -1
  24. package/src/doctor/channel-checks.ts +43 -0
  25. package/src/hostd/daemon.ts +7 -5
  26. package/src/hostd/protocol.ts +2 -2
  27. package/src/init/checkpoint.ts +1 -1
  28. package/src/init/index.ts +60 -3
  29. package/src/init/run-owner-claim.ts +1 -0
  30. package/src/init/webex-auth.ts +68 -0
  31. package/src/inspect/label.ts +13 -2
  32. package/src/inspect/render.ts +5 -3
  33. package/src/permissions/resolve.ts +38 -1
  34. package/src/role-claim/match-rule.ts +5 -1
  35. package/src/secrets/codex-auth-json.ts +52 -17
  36. package/src/secrets/encryption.ts +5 -1
  37. package/src/secrets/export-codex-auth-file.ts +26 -3
  38. package/src/secrets/schema.ts +35 -0
  39. package/src/secrets/webex-store.ts +113 -0
  40. package/typeclaw.schema.json +160 -0
@@ -7,7 +7,12 @@ import type {
7
7
  WebexPerson,
8
8
  } from 'agent-messenger/webexbot'
9
9
 
10
- import type { MembershipResolver, MembershipResolverFailure, MembershipResolverResult } from '@/channels/membership'
10
+ import {
11
+ MEMBERSHIP_ENUMERATION_CAP,
12
+ type MembershipResolver,
13
+ type MembershipResolverFailure,
14
+ type MembershipResolverResult,
15
+ } from '@/channels/membership'
11
16
  import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
12
17
  import type { ChannelRouter } from '@/channels/router'
13
18
  import type { ChannelAdapterConfig } from '@/channels/schema'
@@ -27,6 +32,7 @@ import type {
27
32
  import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
28
33
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
29
34
  import { enrichWebexMessageReference } from './webex-bot-reference'
35
+ import { resolveWebexBodyText } from './webex-format'
30
36
 
31
37
  export type WebexBotAdapterLogger = {
32
38
  info: (msg: string) => void
@@ -55,6 +61,7 @@ export type WebexBotAdapterOptions = {
55
61
  createClient?: WebexBotClientFactory
56
62
  createListener?: WebexBotListenerFactory
57
63
  listenerOptions?: Omit<WebexBotListenerOptions, 'ignoreSelfMessages'>
64
+ selfAliasesRef?: () => readonly string[]
58
65
  }
59
66
 
60
67
  export type WebexBotAdapter = {
@@ -63,44 +70,72 @@ export type WebexBotAdapter = {
63
70
  isConnected: () => boolean
64
71
  }
65
72
 
73
+ export type WebexOutboundFile = { content: Blob; filename: string }
74
+ export type WebexFileReader = (path: string) => Promise<WebexOutboundFile>
75
+
76
+ // Webex resolves any `parentId` to the thread root, so threading a reply and
77
+ // replying to a specific message land in the same thread. `replyTo` (the native
78
+ // quote anchor the router sets in native mode) is the more precise target, so it
79
+ // wins over `msg.thread` when present — both `sendMessage` and `uploadFile`
80
+ // accept `parentId`, so attachment replies thread natively too (unlike
81
+ // Discord/Telegram, where uploads land bare).
82
+ //
83
+ // `uploadFile` carries `text` + `parentId` in one multipart POST, so a
84
+ // text+single-file message is one call (Slack's `initial_comment` shape). With
85
+ // multiple files the first upload carries the text and every upload carries the
86
+ // parentId; remaining uploads are bare so the text is not duplicated.
66
87
  export function createOutboundCallback(deps: {
67
- client: Pick<WebexBotClient, 'sendMessage'>
88
+ client: Pick<WebexBotClient, 'sendMessage' | 'uploadFile'>
68
89
  logger: WebexBotAdapterLogger
69
90
  formatChannelTag: (chat: string) => Promise<string>
91
+ readFile?: WebexFileReader
92
+ resolvePath?: (path: string) => string
70
93
  }): OutboundCallback {
71
- const { client, logger, formatChannelTag } = deps
94
+ const { client, logger, formatChannelTag, resolvePath } = deps
95
+ const readFile = deps.readFile ?? defaultReadFile
72
96
  return async (msg: OutboundMessage): Promise<SendResult> => {
73
97
  if (msg.adapter !== 'webex-bot') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
74
98
  const text = msg.text ?? ''
75
99
  const attachments = msg.attachments ?? []
76
100
  if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
77
- if (text === '' && attachments.length > 0) {
78
- return { ok: false, error: 'webex-bot does not support outbound file attachments' }
79
- }
80
101
 
81
102
  const tag = await formatChannelTag(msg.chat)
82
- if (attachments.length > 0) {
83
- logger.warn(
84
- `[webex-bot] dropping ${attachments.length} outbound attachment(s) for ${tag}: agent-messenger webexbot has no upload API`,
85
- )
86
- }
87
- if (msg.thread !== null && msg.thread !== undefined) {
88
- logger.warn(
89
- `[webex-bot] sending thread reply to room root for ${tag}: WebexBotClient.sendMessage has no parentId option`,
90
- )
91
- }
103
+ const parentId = msg.replyTo?.externalMessageId ?? msg.thread ?? undefined
104
+ logger.info(
105
+ `[webex-bot] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${parentId !== undefined ? ` parent=${parentId}` : ''}`,
106
+ )
107
+
92
108
  try {
93
- const sent = await client.sendMessage(msg.chat, text, { markdown: true })
94
- logger.info(`[webex-bot] sent id=${sent.id} ${tag}`)
109
+ if (attachments.length > 0) {
110
+ for (const [index, attachment] of attachments.entries()) {
111
+ const path = resolvePath ? resolvePath(attachment.path) : attachment.path
112
+ const file = await readFile(path)
113
+ if (attachment.filename !== undefined) file.filename = attachment.filename
114
+ const carriesText = index === 0 && text !== ''
115
+ const sent = await client.uploadFile(msg.chat, file, {
116
+ ...(carriesText ? { text } : {}),
117
+ ...(parentId !== undefined ? { parentId } : {}),
118
+ })
119
+ logger.info(`[webex-bot] uploaded id=${sent.ref} filename=${file.filename} ${tag}`)
120
+ }
121
+ return { ok: true }
122
+ }
123
+
124
+ const sent = await client.sendMessage(msg.chat, text, parentId !== undefined ? { parentId } : undefined)
125
+ logger.info(`[webex-bot] sent id=${sent.ref} ${tag}`)
95
126
  return { ok: true }
96
127
  } catch (err) {
97
128
  const message = describe(err)
98
- logger.error(`[webex-bot] sendMessage failed: ${message}`)
129
+ logger.error(`[webex-bot] outbound failed: ${message}`)
99
130
  return { ok: false, error: message }
100
131
  }
101
132
  }
102
133
  }
103
134
 
135
+ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
136
+ return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
137
+ }
138
+
104
139
  export function createWebexHistoryCallback(deps: {
105
140
  client: Pick<WebexBotClient, 'listMessages'>
106
141
  logger: WebexBotAdapterLogger
@@ -122,6 +157,7 @@ export function createWebexMembershipResolver(deps: {
122
157
  client: Pick<WebexBotClient, 'listMemberships'>
123
158
  logger: WebexBotAdapterLogger
124
159
  historyCallback: HistoryCallback
160
+ botPersonIdRef: () => string | null
125
161
  now?: () => number
126
162
  }): MembershipResolver {
127
163
  const now = deps.now ?? Date.now
@@ -129,10 +165,29 @@ export function createWebexMembershipResolver(deps: {
129
165
  if (key.adapter !== 'webex-bot') return { kind: 'permanent' } satisfies MembershipResolverFailure
130
166
  if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
131
167
  try {
132
- const memberships: WebexMembership[] = await deps.client.listMemberships(key.chat, { max: 100 })
133
- const total = Math.max(0, memberships.length)
134
- const bots = 1
135
- return { humans: Math.max(0, total - bots), bots, fetchedAt: now(), truncated: true }
168
+ const memberships: WebexMembership[] = await deps.client.listMemberships(key.chat, {
169
+ max: MEMBERSHIP_ENUMERATION_CAP,
170
+ })
171
+ // Below the cap the enumeration is complete and authoritative, so it must
172
+ // NOT be marked truncated: `resolveEffectiveHumans` only trusts a fresh
173
+ // untruncated read over persisted speakers, and the `Math.max()` truncated
174
+ // path lets a stale/legacy email-keyed participant double-count the same
175
+ // human and silence the solo-human fallback.
176
+ const truncated = memberships.length >= MEMBERSHIP_ENUMERATION_CAP
177
+ // WebexMembership has no bot/person type field, so only the self bot can be
178
+ // classified; peer bots count as humans here (they still reach the agent
179
+ // via mention/reply/sticky triggers regardless of this count).
180
+ const botPersonId = deps.botPersonIdRef()
181
+ const humanMemberIds: string[] = []
182
+ let bots = 0
183
+ for (const member of memberships) {
184
+ if (botPersonId !== null && member.personRef === botPersonId) bots++
185
+ else humanMemberIds.push(member.personRef)
186
+ }
187
+ if (truncated) {
188
+ return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated }
189
+ }
190
+ return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated, humanMemberIds }
136
191
  } catch (err) {
137
192
  deps.logger.warn(`[webex-bot] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
138
193
  return await deriveMembershipFromHistory({
@@ -209,7 +264,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
209
264
 
210
265
  const channelResolver = createWebexChannelNameResolver({ client })
211
266
  const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
212
- botPerson !== null ? { id: botPerson.id, username: botPerson.emails[0] ?? botPerson.displayName } : null
267
+ botPerson !== null ? { id: botPerson.ref, username: botPerson.emails[0] ?? botPerson.displayName } : null
213
268
 
214
269
  const formatChannelTag = async (chat: string): Promise<string> => {
215
270
  const names = await channelResolver({ adapter: 'webex-bot', workspace: chat, chat, thread: null }).catch(
@@ -219,8 +274,13 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
219
274
  return label === null || label === chat ? `room=${chat}` : `room=${label}(${chat})`
220
275
  }
221
276
 
222
- const historyCallback = createWebexHistoryCallback({ client, logger, botPersonIdRef: () => botPerson?.id ?? null })
223
- const membershipResolver = createWebexMembershipResolver({ client, logger, historyCallback })
277
+ const historyCallback = createWebexHistoryCallback({ client, logger, botPersonIdRef: () => botPerson?.ref ?? null })
278
+ const membershipResolver = createWebexMembershipResolver({
279
+ client,
280
+ logger,
281
+ historyCallback,
282
+ botPersonIdRef: () => botPerson?.ref ?? null,
283
+ })
224
284
  const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
225
285
  const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger, fetchImpl })
226
286
 
@@ -228,21 +288,28 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
228
288
  inflightInbounds++
229
289
  const botSnapshot = botPerson
230
290
  try {
231
- const tag = await formatChannelTag(event.roomId)
232
- logger.info(`[webex-bot] inbound id=${event.id} author=${event.personEmail} ${tag} text_len=${event.text.length}`)
233
- const verdict = classifyInbound(event, options.configRef(), botSnapshot?.id ?? null)
291
+ const tag = await formatChannelTag(event.roomRef)
292
+ logger.info(
293
+ `[webex-bot] inbound id=${event.ref} author=${event.personEmail} ${tag} text_len=${event.text.length}`,
294
+ )
295
+ const verdict = classifyInbound(
296
+ event,
297
+ options.configRef(),
298
+ botSnapshot?.ref ?? null,
299
+ options.selfAliasesRef?.() ?? [],
300
+ )
234
301
  if (verdict.kind === 'drop') {
235
- logger.info(`[webex-bot] dropped id=${event.id} reason=${verdict.reason}${dropHint(verdict.reason)}`)
302
+ logger.info(`[webex-bot] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
236
303
  return
237
304
  }
238
305
  const payload = await enrichWebexMessageReference({
239
306
  client,
240
307
  inbound: verdict.payload,
241
- parentId: event.parentId,
242
- botPersonId: botSnapshot?.id ?? null,
308
+ parentRef: event.parentRef,
309
+ botPersonId: botSnapshot?.ref ?? null,
243
310
  })
244
311
  logger.info(
245
- `[webex-bot] routed id=${event.id} ${tag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
312
+ `[webex-bot] routed id=${event.ref} ${tag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
246
313
  )
247
314
  await options.router.route(payload)
248
315
  } catch (err) {
@@ -264,7 +331,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
264
331
  try {
265
332
  await client.login({ token: options.token })
266
333
  botPerson = await client.testAuth()
267
- logger.info(`[webex-bot] authenticated as ${botPerson.displayName} (${botPerson.id})`)
334
+ logger.info(`[webex-bot] authenticated as ${botPerson.displayName} (${botPerson.ref})`)
268
335
  } catch (err) {
269
336
  started = false
270
337
  botPerson = null
@@ -356,17 +423,17 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
356
423
 
357
424
  function mapWebexHistoryMessage(msg: WebexMessage, botPersonId: string | null): ChannelHistoryMessage {
358
425
  const attachments = (msg.files ?? []).map((ref, index) => ({ id: index + 1, kind: 'file' as const, ref }))
359
- const body = msg.text ?? msg.markdown ?? msg.html ?? ''
426
+ const body = resolveWebexBodyText(msg)
360
427
  const text = attachments.length === 0 ? body : body === '' ? '[Webex attachment]' : `${body}\n[Webex attachment]`
361
428
  const ts = Date.parse(msg.created)
362
429
  return {
363
- externalMessageId: msg.id,
364
- authorId: msg.personId,
430
+ externalMessageId: msg.ref,
431
+ authorId: msg.personRef,
365
432
  authorName: msg.personEmail,
366
433
  text,
367
434
  ts: Number.isFinite(ts) ? ts : 0,
368
- isBot: botPersonId !== null && msg.personId === botPersonId,
369
- replyToBotMessageId: msg.parentId ?? null,
435
+ isBot: botPersonId !== null && msg.personRef === botPersonId,
436
+ replyToBotMessageId: msg.parentRef ?? null,
370
437
  ...(attachments.length > 0 ? { attachments } : {}),
371
438
  }
372
439
  }
@@ -0,0 +1,29 @@
1
+ import type { WebexClient } from 'agent-messenger/webex'
2
+
3
+ import type { ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
+
5
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
6
+
7
+ export function createWebexChannelNameResolver(deps: {
8
+ client: Pick<WebexClient, 'getSpace'>
9
+ ttlMs?: number
10
+ now?: () => number
11
+ }): ChannelNameResolver {
12
+ const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS
13
+ const now = deps.now ?? Date.now
14
+ const cache = new Map<string, { value: string; expiresAt: number }>()
15
+
16
+ return async (key): Promise<ResolvedChannelNames> => {
17
+ if (key.adapter !== 'webex') return {}
18
+ const cached = cache.get(key.chat)
19
+ if (cached && cached.expiresAt > now()) return { chatName: cached.value }
20
+ try {
21
+ const space = await deps.client.getSpace(key.chat)
22
+ if (space.title === '') return {}
23
+ cache.set(key.chat, { value: space.title, expiresAt: now() + ttlMs })
24
+ return { chatName: space.title }
25
+ } catch {
26
+ return {}
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,104 @@
1
+ // WebexListenerEventMap requires agent-messenger/webex (PR #239); resolves via linked upstream.
2
+ import type { WebexListenerEventMap } from 'agent-messenger/webex'
3
+
4
+ import { matchesAnyAlias } from '@/channels/engagement'
5
+ import type { ChannelAdapterConfig } from '@/channels/schema'
6
+ import type { InboundAttachment, InboundMessage } from '@/channels/types'
7
+
8
+ export type WebexInboundMessage = WebexListenerEventMap['message_created'][0]
9
+
10
+ export type InboundDropReason = 'self_author' | 'empty_content' | 'pre_connect'
11
+
12
+ export type InboundClassification =
13
+ | { kind: 'drop'; reason: InboundDropReason }
14
+ | { kind: 'route'; payload: InboundMessage }
15
+
16
+ // `botPersonRef` is the bot's decoded UUID ref (from WebexPerson.ref), matched
17
+ // against the event's *Ref fields so identity comparison happens entirely in
18
+ // ref-space — the same currency typeclaw now stores as ChannelKey/authorId.
19
+ export function classifyInbound(
20
+ event: WebexInboundMessage,
21
+ _config: ChannelAdapterConfig,
22
+ botPersonRef: string | null,
23
+ selfAliases: readonly string[] = [],
24
+ ): InboundClassification {
25
+ if (botPersonRef !== null && event.personRef === botPersonRef) {
26
+ return { kind: 'drop', reason: 'self_author' }
27
+ }
28
+
29
+ const { text, attachments } = splitInbound(event)
30
+ if (text === '') return { kind: 'drop', reason: 'empty_content' }
31
+
32
+ if (botPersonRef === null) {
33
+ return { kind: 'drop', reason: 'pre_connect' }
34
+ }
35
+
36
+ const isDm = event.roomType === 'direct'
37
+ const structuredBotMention = event.mentionedPeopleRefs.includes(botPersonRef) || event.mentionedGroups.includes('all')
38
+ const aliasMatched = !structuredBotMention && matchesAnyAlias(text, selfAliases)
39
+ const isBotMention = structuredBotMention || aliasMatched
40
+ const mentionsOthers = event.mentionedPeopleRefs.length > 0 && !event.mentionedPeopleRefs.includes(botPersonRef)
41
+ const ts = Date.parse(event.created)
42
+
43
+ return {
44
+ kind: 'route',
45
+ payload: {
46
+ adapter: 'webex',
47
+ // Webex message events do not include an org/team id; the room ref is the
48
+ // stable permission bucket for group spaces while DMs use the shared key.
49
+ // The decoded UUID ref is stored (not the base64 REST id) so the persisted
50
+ // key is human-readable; the SDK re-encodes it for outbound calls.
51
+ workspace: isDm ? '@dm' : event.roomRef,
52
+ chat: event.roomRef,
53
+ thread: null,
54
+ text,
55
+ ...(attachments.length > 0 ? { attachments } : {}),
56
+ externalMessageId: event.ref,
57
+ authorId: event.personRef,
58
+ authorName: event.personEmail,
59
+ authorIsBot: false,
60
+ isBotMention,
61
+ // Webex Mercury only exposes the parent ref inline, not the parent author.
62
+ // When the reply has a structured bot mention we can identify it as
63
+ // bot-directed; otherwise leave the parent unattributed instead of guessing.
64
+ // Alias matches are mention-equivalent for engagement, but they do not prove
65
+ // the parent is bot-authored; enrichment fetches the parent and attributes it.
66
+ replyToBotMessageId: event.parentRef !== undefined && structuredBotMention ? event.parentRef : null,
67
+ mentionsOthers,
68
+ replyToOtherMessageId: null,
69
+ isDm,
70
+ ts: Number.isFinite(ts) ? ts : 0,
71
+ },
72
+ }
73
+ }
74
+
75
+ type SplitInbound = { text: string; attachments: InboundAttachment[] }
76
+
77
+ function splitInbound(event: WebexInboundMessage): SplitInbound {
78
+ const attachments = event.files.map((ref: string, index: number) => ({
79
+ id: index + 1,
80
+ kind: 'file' as const,
81
+ ref,
82
+ filename: filenameFromUrl(ref) ?? `webex-file-${index + 1}`,
83
+ }))
84
+ if (attachments.length === 0) return { text: event.text, attachments: [] }
85
+ const summary = attachments.map(renderPlaceholder).join('\n')
86
+ const text = event.text === '' ? summary : `${event.text}\n${summary}`
87
+ return { text, attachments }
88
+ }
89
+
90
+ function filenameFromUrl(ref: string): string | null {
91
+ try {
92
+ const url = new URL(ref)
93
+ const name = url.pathname.split('/').filter(Boolean).pop()
94
+ return name === undefined || name === '' ? null : name
95
+ } catch {
96
+ return null
97
+ }
98
+ }
99
+
100
+ function renderPlaceholder(attachment: InboundAttachment): string {
101
+ const parts: string[] = [`Webex attachment #${attachment.id}: ${attachment.kind}`]
102
+ if (attachment.filename !== undefined) parts.push(`name=${attachment.filename}`)
103
+ return `[${parts.join(' ')}]`
104
+ }
@@ -0,0 +1,53 @@
1
+ import type { WebexMessage } from 'agent-messenger/webex'
2
+
3
+ // Webex's E2E (internal conversation) path renders agent markdown as an HTML
4
+ // `content` field that some clients display verbatim, so messages sent with
5
+ // `markdown: true` leak literal `<br/>` and `&apos;`. typeclaw sends plain text
6
+ // outbound; inbound we still read the HTML `html` field as a fallback, so this
7
+ // undoes that HTML. Protocol HTML (not natural language) -> ASCII literal set.
8
+
9
+ // Normalize ONLY the HTML `html` fallback: `text`/`markdown` are author-clean and
10
+ // must stay raw, or literal `&`/`<` the user typed would be corrupted.
11
+ export function resolveWebexBodyText(msg: Pick<WebexMessage, 'text' | 'markdown' | 'html'>): string {
12
+ if (msg.text !== undefined && msg.text !== '') return msg.text
13
+ if (msg.markdown !== undefined && msg.markdown !== '') return msg.markdown
14
+ if (msg.html !== undefined && msg.html !== '') return normalizeWebexHtmlFallbackText(msg.html)
15
+ return ''
16
+ }
17
+
18
+ export function normalizeWebexHtmlFallbackText(value: string): string {
19
+ const withBreaks = value
20
+ .replace(/<br\s*\/?>/gi, '\n')
21
+ .replace(/<\/p>\s*<p[^>]*>/gi, '\n\n')
22
+ .replace(/<\/?[^>]+>/g, '')
23
+ return decodeHtmlEntities(withBreaks)
24
+ }
25
+
26
+ function decodeHtmlEntities(value: string): string {
27
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (match, entity: string) => {
28
+ const lower = entity.toLowerCase()
29
+ if (lower.startsWith('#x')) return codePoint(Number.parseInt(lower.slice(2), 16))
30
+ if (lower.startsWith('#')) return codePoint(Number.parseInt(lower.slice(1), 10))
31
+ switch (lower) {
32
+ case 'amp':
33
+ return '&'
34
+ case 'lt':
35
+ return '<'
36
+ case 'gt':
37
+ return '>'
38
+ case 'quot':
39
+ return '"'
40
+ case 'apos':
41
+ return "'"
42
+ case 'nbsp':
43
+ return ' '
44
+ default:
45
+ return match
46
+ }
47
+ })
48
+ }
49
+
50
+ function codePoint(value: number): string {
51
+ if (!Number.isFinite(value) || value < 0 || value > 0x10ffff) return ''
52
+ return String.fromCodePoint(value)
53
+ }
@@ -0,0 +1,32 @@
1
+ import { decodeWebexId } from 'agent-messenger/webex'
2
+ import type { WebexRestIdType } from 'agent-messenger/webex'
3
+
4
+ // Webex REST ids are base64url of `ciscospark://<cluster>/<TYPE>/<uuid>`. The
5
+ // opaque blob is unreadable in `inspect` and — worst — in hand-authored
6
+ // permission rules (`webex:* author:Y2lzY29zcGFyazov...`). A `ref` is the
7
+ // decoded trailing value: a UUID for ROOM/MESSAGE, a UUID OR an email for
8
+ // PEOPLE (legacy "Hydra" accounts encode the email).
9
+ //
10
+ // `decodeWebexId` comes from agent-messenger and is null-safe on non-ids.
11
+ // `toRef` and `isWebexIdOfType` are local wrappers: upstream's own `toRef`
12
+ // THROWS on a value that is not a valid REST id (e.g. a bare uuid already in
13
+ // ref form), but every typeclaw call site feeds it values that may already be
14
+ // refs or non-webex tokens, so we need the fall-open contract instead.
15
+ //
16
+ // `ref` is for human-facing surfaces only; the canonical base64 id stays the
17
+ // wire/session currency.
18
+
19
+ export { decodeWebexId } from 'agent-messenger/webex'
20
+ export type { DecodedWebexId, WebexRestIdType } from 'agent-messenger/webex'
21
+
22
+ export function toRef(id: string): string {
23
+ const decoded = decodeWebexId(id)
24
+ return decoded === null ? id : decoded.uuid
25
+ }
26
+
27
+ // Refuses cross-type collisions: a decoded ROOM uuid must never satisfy an
28
+ // `author:` (PEOPLE) rule even if the trailing uuid strings happen to match.
29
+ export function isWebexIdOfType(id: string, type: WebexRestIdType): boolean {
30
+ const decoded = decodeWebexId(id)
31
+ return decoded !== null && decoded.type === type
32
+ }
@@ -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
+ }