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.
- package/README.md +2 -2
- package/auth.schema.json +109 -0
- package/package.json +2 -2
- package/secrets.schema.json +109 -0
- package/src/agent/session-origin.ts +16 -2
- package/src/bundled-plugins/memory/README.md +12 -1
- package/src/bundled-plugins/memory/index.ts +39 -2
- package/src/channels/adapters/kakaotalk.ts +1 -1
- package/src/channels/adapters/webex-bot-channel-resolver.ts +29 -0
- package/src/channels/adapters/webex-bot-classify.ts +98 -0
- package/src/channels/adapters/webex-bot-reference.ts +49 -0
- package/src/channels/adapters/webex-bot.ts +462 -0
- package/src/channels/adapters/webex-channel-resolver.ts +29 -0
- package/src/channels/adapters/webex-classify.ts +104 -0
- package/src/channels/adapters/webex-format.ts +53 -0
- package/src/channels/adapters/webex-id-ref.ts +32 -0
- package/src/channels/adapters/webex-reference.ts +49 -0
- package/src/channels/adapters/webex.ts +493 -0
- package/src/channels/manager.ts +75 -4
- package/src/channels/persistence.ts +67 -5
- package/src/channels/router.ts +9 -0
- package/src/channels/schema.ts +17 -1
- package/src/cli/channel.ts +155 -8
- package/src/cli/init.ts +129 -6
- package/src/config/channels-mutation.ts +11 -2
- package/src/doctor/channel-checks.ts +56 -1
- package/src/hostd/daemon.ts +7 -5
- package/src/hostd/protocol.ts +2 -2
- package/src/init/checkpoint.ts +1 -1
- package/src/init/index.ts +97 -17
- package/src/init/run-owner-claim.ts +2 -0
- package/src/init/webex-auth.ts +68 -0
- package/src/inspect/label.ts +13 -2
- package/src/inspect/render.ts +5 -3
- package/src/permissions/match-rule.ts +7 -3
- package/src/permissions/resolve.ts +44 -5
- package/src/role-claim/match-rule.ts +7 -2
- package/src/secrets/codex-auth-json.ts +52 -17
- package/src/secrets/defaults.ts +1 -0
- package/src/secrets/encryption.ts +5 -1
- package/src/secrets/export-codex-auth-file.ts +26 -3
- package/src/secrets/schema.ts +35 -0
- package/src/secrets/webex-store.ts +113 -0
- package/typeclaw.schema.json +321 -1
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
import { WebexBotClient, WebexBotListener } from 'agent-messenger/webexbot'
|
|
2
|
+
import type {
|
|
3
|
+
WebexBotListenerOptions,
|
|
4
|
+
WebexBotListenerEventMap,
|
|
5
|
+
WebexMembership,
|
|
6
|
+
WebexMessage,
|
|
7
|
+
WebexPerson,
|
|
8
|
+
} from 'agent-messenger/webexbot'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
MEMBERSHIP_ENUMERATION_CAP,
|
|
12
|
+
type MembershipResolver,
|
|
13
|
+
type MembershipResolverFailure,
|
|
14
|
+
type MembershipResolverResult,
|
|
15
|
+
} from '@/channels/membership'
|
|
16
|
+
import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
|
|
17
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
18
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
19
|
+
import type {
|
|
20
|
+
ChannelHistoryMessage,
|
|
21
|
+
ChannelSelfIdentityResolver,
|
|
22
|
+
FetchAttachmentCallback,
|
|
23
|
+
FetchHistoryArgs,
|
|
24
|
+
FetchHistoryResult,
|
|
25
|
+
HistoryCallback,
|
|
26
|
+
OutboundCallback,
|
|
27
|
+
OutboundMessage,
|
|
28
|
+
ResolvedChannelNames,
|
|
29
|
+
SendResult,
|
|
30
|
+
} from '@/channels/types'
|
|
31
|
+
|
|
32
|
+
import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
|
|
33
|
+
import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
|
|
34
|
+
import { enrichWebexMessageReference } from './webex-bot-reference'
|
|
35
|
+
import { resolveWebexBodyText } from './webex-format'
|
|
36
|
+
|
|
37
|
+
export type WebexBotAdapterLogger = {
|
|
38
|
+
info: (msg: string) => void
|
|
39
|
+
warn: (msg: string) => void
|
|
40
|
+
error: (msg: string) => void
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const consoleLogger: WebexBotAdapterLogger = {
|
|
44
|
+
info: (m) => console.log(m),
|
|
45
|
+
warn: (m) => console.warn(m),
|
|
46
|
+
error: (m) => console.error(m),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type WebexBotClientFactory = () => WebexBotClient
|
|
50
|
+
export type WebexBotListenerFactory = (
|
|
51
|
+
client: Pick<WebexBotClient, 'getToken'>,
|
|
52
|
+
options: WebexBotListenerOptions,
|
|
53
|
+
) => WebexBotListener
|
|
54
|
+
|
|
55
|
+
export type WebexBotAdapterOptions = {
|
|
56
|
+
router: ChannelRouter
|
|
57
|
+
configRef: () => ChannelAdapterConfig
|
|
58
|
+
token: string
|
|
59
|
+
logger?: WebexBotAdapterLogger
|
|
60
|
+
fetchImpl?: typeof fetch
|
|
61
|
+
createClient?: WebexBotClientFactory
|
|
62
|
+
createListener?: WebexBotListenerFactory
|
|
63
|
+
listenerOptions?: Omit<WebexBotListenerOptions, 'ignoreSelfMessages'>
|
|
64
|
+
selfAliasesRef?: () => readonly string[]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type WebexBotAdapter = {
|
|
68
|
+
start: () => Promise<void>
|
|
69
|
+
stop: () => Promise<void>
|
|
70
|
+
isConnected: () => boolean
|
|
71
|
+
}
|
|
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.
|
|
87
|
+
export function createOutboundCallback(deps: {
|
|
88
|
+
client: Pick<WebexBotClient, 'sendMessage' | 'uploadFile'>
|
|
89
|
+
logger: WebexBotAdapterLogger
|
|
90
|
+
formatChannelTag: (chat: string) => Promise<string>
|
|
91
|
+
readFile?: WebexFileReader
|
|
92
|
+
resolvePath?: (path: string) => string
|
|
93
|
+
}): OutboundCallback {
|
|
94
|
+
const { client, logger, formatChannelTag, resolvePath } = deps
|
|
95
|
+
const readFile = deps.readFile ?? defaultReadFile
|
|
96
|
+
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
97
|
+
if (msg.adapter !== 'webex-bot') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
98
|
+
const text = msg.text ?? ''
|
|
99
|
+
const attachments = msg.attachments ?? []
|
|
100
|
+
if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
|
|
101
|
+
|
|
102
|
+
const tag = await formatChannelTag(msg.chat)
|
|
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
|
+
|
|
108
|
+
try {
|
|
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}`)
|
|
126
|
+
return { ok: true }
|
|
127
|
+
} catch (err) {
|
|
128
|
+
const message = describe(err)
|
|
129
|
+
logger.error(`[webex-bot] outbound failed: ${message}`)
|
|
130
|
+
return { ok: false, error: message }
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
|
|
136
|
+
return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function createWebexHistoryCallback(deps: {
|
|
140
|
+
client: Pick<WebexBotClient, 'listMessages'>
|
|
141
|
+
logger: WebexBotAdapterLogger
|
|
142
|
+
botPersonIdRef: () => string | null
|
|
143
|
+
}): HistoryCallback {
|
|
144
|
+
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
145
|
+
try {
|
|
146
|
+
const messages = await deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
|
|
147
|
+
return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse() }
|
|
148
|
+
} catch (err) {
|
|
149
|
+
const message = describe(err)
|
|
150
|
+
deps.logger.warn(`[webex-bot] history fetch failed: ${message}`)
|
|
151
|
+
return { ok: false, error: message }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function createWebexMembershipResolver(deps: {
|
|
157
|
+
client: Pick<WebexBotClient, 'listMemberships'>
|
|
158
|
+
logger: WebexBotAdapterLogger
|
|
159
|
+
historyCallback: HistoryCallback
|
|
160
|
+
botPersonIdRef: () => string | null
|
|
161
|
+
now?: () => number
|
|
162
|
+
}): MembershipResolver {
|
|
163
|
+
const now = deps.now ?? Date.now
|
|
164
|
+
return async (key): Promise<MembershipResolverResult> => {
|
|
165
|
+
if (key.adapter !== 'webex-bot') return { kind: 'permanent' } satisfies MembershipResolverFailure
|
|
166
|
+
if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
|
|
167
|
+
try {
|
|
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 }
|
|
191
|
+
} catch (err) {
|
|
192
|
+
deps.logger.warn(`[webex-bot] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
|
|
193
|
+
return await deriveMembershipFromHistory({
|
|
194
|
+
fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
|
|
195
|
+
now,
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const WEBEX_ATTACHMENT_HOSTS = new Set(['webexapis.com', 'api.ciscospark.com'])
|
|
202
|
+
|
|
203
|
+
export function createFetchAttachmentCallback(deps: {
|
|
204
|
+
token: string
|
|
205
|
+
logger: WebexBotAdapterLogger
|
|
206
|
+
fetchImpl?: typeof fetch
|
|
207
|
+
}): FetchAttachmentCallback {
|
|
208
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
209
|
+
return async ({ ref, filename }) => {
|
|
210
|
+
let url: URL
|
|
211
|
+
try {
|
|
212
|
+
url = new URL(ref)
|
|
213
|
+
} catch {
|
|
214
|
+
return { ok: false, error: `invalid Webex file URL: ${ref}` }
|
|
215
|
+
}
|
|
216
|
+
// The bearer token must never leave over plaintext: an allowlisted host
|
|
217
|
+
// on http:// would still leak the credential, so gate on https before the
|
|
218
|
+
// host check.
|
|
219
|
+
if (url.protocol !== 'https:') {
|
|
220
|
+
return { ok: false, error: `Webex file URL must use https: ${url.protocol}//${url.hostname}` }
|
|
221
|
+
}
|
|
222
|
+
if (!isAllowedWebexFileHost(url.hostname)) {
|
|
223
|
+
return { ok: false, error: `not a Webex file URL: ${url.hostname}` }
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${deps.token}` } })
|
|
227
|
+
if (!res.ok) {
|
|
228
|
+
const body = await res.text().catch(() => '')
|
|
229
|
+
const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
|
|
230
|
+
deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
|
|
231
|
+
return { ok: false, error: message }
|
|
232
|
+
}
|
|
233
|
+
const buffer = Buffer.from(await res.arrayBuffer())
|
|
234
|
+
const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
|
|
235
|
+
const contentType = res.headers.get('content-type') ?? undefined
|
|
236
|
+
return {
|
|
237
|
+
ok: true,
|
|
238
|
+
buffer,
|
|
239
|
+
filename: inferredFilename,
|
|
240
|
+
...(contentType !== undefined ? { mimetype: contentType } : {}),
|
|
241
|
+
size: buffer.length,
|
|
242
|
+
}
|
|
243
|
+
} catch (err) {
|
|
244
|
+
const message = describe(err)
|
|
245
|
+
deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
|
|
246
|
+
return { ok: false, error: message }
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBotAdapter {
|
|
252
|
+
const logger = options.logger ?? consoleLogger
|
|
253
|
+
const createClient = options.createClient ?? (() => new WebexBotClient())
|
|
254
|
+
const createListener =
|
|
255
|
+
options.createListener ?? ((client, listenerOptions) => new WebexBotListener(client, listenerOptions))
|
|
256
|
+
const client = createClient()
|
|
257
|
+
const fetchImpl = options.fetchImpl ?? fetch
|
|
258
|
+
let listener: WebexBotListener | null = null
|
|
259
|
+
let botPerson: WebexPerson | null = null
|
|
260
|
+
let connected = false
|
|
261
|
+
let started = false
|
|
262
|
+
let inflightInbounds = 0
|
|
263
|
+
let stopWaiters: Array<() => void> = []
|
|
264
|
+
|
|
265
|
+
const channelResolver = createWebexChannelNameResolver({ client })
|
|
266
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
|
|
267
|
+
botPerson !== null ? { id: botPerson.ref, username: botPerson.emails[0] ?? botPerson.displayName } : null
|
|
268
|
+
|
|
269
|
+
const formatChannelTag = async (chat: string): Promise<string> => {
|
|
270
|
+
const names = await channelResolver({ adapter: 'webex-bot', workspace: chat, chat, thread: null }).catch(
|
|
271
|
+
(): ResolvedChannelNames => ({}),
|
|
272
|
+
)
|
|
273
|
+
const label = names.chatName ?? null
|
|
274
|
+
return label === null || label === chat ? `room=${chat}` : `room=${label}(${chat})`
|
|
275
|
+
}
|
|
276
|
+
|
|
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
|
+
})
|
|
284
|
+
const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
|
|
285
|
+
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger, fetchImpl })
|
|
286
|
+
|
|
287
|
+
const handleMessage = async (event: WebexInboundMessage): Promise<void> => {
|
|
288
|
+
inflightInbounds++
|
|
289
|
+
const botSnapshot = botPerson
|
|
290
|
+
try {
|
|
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
|
+
)
|
|
301
|
+
if (verdict.kind === 'drop') {
|
|
302
|
+
logger.info(`[webex-bot] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
const payload = await enrichWebexMessageReference({
|
|
306
|
+
client,
|
|
307
|
+
inbound: verdict.payload,
|
|
308
|
+
parentRef: event.parentRef,
|
|
309
|
+
botPersonId: botSnapshot?.ref ?? null,
|
|
310
|
+
})
|
|
311
|
+
logger.info(
|
|
312
|
+
`[webex-bot] routed id=${event.ref} ${tag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
|
|
313
|
+
)
|
|
314
|
+
await options.router.route(payload)
|
|
315
|
+
} catch (err) {
|
|
316
|
+
logger.error(`[webex-bot] handleInbound failed: ${describe(err)}`)
|
|
317
|
+
} finally {
|
|
318
|
+
inflightInbounds--
|
|
319
|
+
if (inflightInbounds === 0 && stopWaiters.length > 0) {
|
|
320
|
+
const waiters = stopWaiters
|
|
321
|
+
stopWaiters = []
|
|
322
|
+
for (const w of waiters) w()
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return {
|
|
328
|
+
async start(): Promise<void> {
|
|
329
|
+
if (started) return
|
|
330
|
+
started = true
|
|
331
|
+
try {
|
|
332
|
+
await client.login({ token: options.token })
|
|
333
|
+
botPerson = await client.testAuth()
|
|
334
|
+
logger.info(`[webex-bot] authenticated as ${botPerson.displayName} (${botPerson.ref})`)
|
|
335
|
+
} catch (err) {
|
|
336
|
+
started = false
|
|
337
|
+
botPerson = null
|
|
338
|
+
logger.error(`[webex-bot] login failed: ${describe(err)}`)
|
|
339
|
+
throw err
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
listener = createListener(client, { ...options.listenerOptions, ignoreSelfMessages: true })
|
|
343
|
+
let listenerConnected = false
|
|
344
|
+
let listenerStartupError: Error | null = null
|
|
345
|
+
listener.on('connected', () => {
|
|
346
|
+
listenerConnected = true
|
|
347
|
+
connected = true
|
|
348
|
+
})
|
|
349
|
+
listener.on('disconnected', (reason) => {
|
|
350
|
+
connected = false
|
|
351
|
+
logger.warn(`[webex-bot] disconnected: ${reason}`)
|
|
352
|
+
})
|
|
353
|
+
listener.on('error', (err) => {
|
|
354
|
+
const error = err instanceof Error ? err : new Error(String(err))
|
|
355
|
+
if (!listenerConnected && listenerStartupError === null) listenerStartupError = error
|
|
356
|
+
logger.error(`[webex-bot] listener error: ${describe(error)}`)
|
|
357
|
+
})
|
|
358
|
+
listener.on('message_created', (event: WebexBotListenerEventMap['message_created'][0]) => {
|
|
359
|
+
void handleMessage(event)
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
options.router.registerOutbound('webex-bot', outboundCallback)
|
|
363
|
+
options.router.registerChannelNameResolver('webex-bot', channelResolver)
|
|
364
|
+
options.router.registerSelfIdentity('webex-bot', selfIdentityResolver)
|
|
365
|
+
options.router.registerHistory('webex-bot', historyCallback)
|
|
366
|
+
options.router.registerFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
367
|
+
options.router.registerMembership('webex-bot', membershipResolver)
|
|
368
|
+
|
|
369
|
+
const rollbackStart = (reason: string, cause: Error): never => {
|
|
370
|
+
options.router.unregisterOutbound('webex-bot', outboundCallback)
|
|
371
|
+
options.router.unregisterChannelNameResolver('webex-bot', channelResolver)
|
|
372
|
+
options.router.unregisterSelfIdentity('webex-bot', selfIdentityResolver)
|
|
373
|
+
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
374
|
+
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
375
|
+
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
376
|
+
listener?.stop()
|
|
377
|
+
listener = null
|
|
378
|
+
botPerson = null
|
|
379
|
+
connected = false
|
|
380
|
+
started = false
|
|
381
|
+
logger.error(`[webex-bot] ${reason}: ${describe(cause)}`)
|
|
382
|
+
throw cause
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
try {
|
|
386
|
+
await listener.start()
|
|
387
|
+
} catch (err) {
|
|
388
|
+
rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
|
|
389
|
+
}
|
|
390
|
+
if (!listenerConnected) {
|
|
391
|
+
rollbackStart(
|
|
392
|
+
'listener start failed silently',
|
|
393
|
+
listenerStartupError ?? new Error('listener.start() returned without emitting connected'),
|
|
394
|
+
)
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
async stop(): Promise<void> {
|
|
399
|
+
if (!started) return
|
|
400
|
+
started = false
|
|
401
|
+
options.router.unregisterOutbound('webex-bot', outboundCallback)
|
|
402
|
+
options.router.unregisterChannelNameResolver('webex-bot', channelResolver)
|
|
403
|
+
options.router.unregisterSelfIdentity('webex-bot', selfIdentityResolver)
|
|
404
|
+
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
405
|
+
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
406
|
+
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
407
|
+
listener?.stop()
|
|
408
|
+
listener = null
|
|
409
|
+
connected = false
|
|
410
|
+
if (inflightInbounds > 0) {
|
|
411
|
+
await new Promise<void>((resolve) => {
|
|
412
|
+
stopWaiters.push(resolve)
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
botPerson = null
|
|
416
|
+
},
|
|
417
|
+
|
|
418
|
+
isConnected(): boolean {
|
|
419
|
+
return started && botPerson !== null && connected
|
|
420
|
+
},
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function mapWebexHistoryMessage(msg: WebexMessage, botPersonId: string | null): ChannelHistoryMessage {
|
|
425
|
+
const attachments = (msg.files ?? []).map((ref, index) => ({ id: index + 1, kind: 'file' as const, ref }))
|
|
426
|
+
const body = resolveWebexBodyText(msg)
|
|
427
|
+
const text = attachments.length === 0 ? body : body === '' ? '[Webex attachment]' : `${body}\n[Webex attachment]`
|
|
428
|
+
const ts = Date.parse(msg.created)
|
|
429
|
+
return {
|
|
430
|
+
externalMessageId: msg.ref,
|
|
431
|
+
authorId: msg.personRef,
|
|
432
|
+
authorName: msg.personEmail,
|
|
433
|
+
text,
|
|
434
|
+
ts: Number.isFinite(ts) ? ts : 0,
|
|
435
|
+
isBot: botPersonId !== null && msg.personRef === botPersonId,
|
|
436
|
+
replyToBotMessageId: msg.parentRef ?? null,
|
|
437
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function isAllowedWebexFileHost(hostname: string): boolean {
|
|
442
|
+
return WEBEX_ATTACHMENT_HOSTS.has(hostname) || hostname.endsWith('.webexcontent.com')
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function clampLimit(requested: number, max: number): number {
|
|
446
|
+
if (!Number.isFinite(requested) || requested <= 0) return max
|
|
447
|
+
return Math.min(Math.floor(requested), max)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function describe(err: unknown): string {
|
|
451
|
+
return err instanceof Error ? err.message : String(err)
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function dropHint(reason: InboundDropReason): string {
|
|
455
|
+
switch (reason) {
|
|
456
|
+
case 'empty_content':
|
|
457
|
+
return ' (message had no text and no files)'
|
|
458
|
+
case 'pre_connect':
|
|
459
|
+
case 'self_author':
|
|
460
|
+
return ''
|
|
461
|
+
}
|
|
462
|
+
}
|
|
@@ -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 `'`. 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
|
+
}
|