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.
- package/auth.schema.json +109 -0
- package/package.json +2 -2
- package/secrets.schema.json +109 -0
- package/src/agent/session-origin.ts +15 -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-classify.ts +20 -14
- package/src/channels/adapters/webex-bot-reference.ts +8 -6
- package/src/channels/adapters/webex-bot.ts +106 -39
- 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 +63 -7
- package/src/channels/persistence.ts +67 -5
- package/src/channels/router.ts +8 -0
- package/src/channels/schema.ts +2 -0
- package/src/cli/channel.ts +118 -7
- package/src/cli/init.ts +70 -1
- package/src/config/channels-mutation.ts +2 -1
- package/src/doctor/channel-checks.ts +43 -0
- 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 +60 -3
- package/src/init/run-owner-claim.ts +1 -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/resolve.ts +38 -1
- package/src/role-claim/match-rule.ts +5 -1
- package/src/secrets/codex-auth-json.ts +52 -17
- 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 +160 -0
|
@@ -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
|
+
}
|
package/src/channels/manager.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { GithubSecretsBlock } from '@/secrets'
|
|
|
6
6
|
import { SecretsKakaoCredentialStore } from '@/secrets/kakao-store'
|
|
7
7
|
import { SecretsLineCredentialStore } from '@/secrets/line-store'
|
|
8
8
|
import { SecretsBackend } from '@/secrets/storage'
|
|
9
|
+
import { SecretsWebexCredentialStore } from '@/secrets/webex-store'
|
|
9
10
|
import type { Stream } from '@/stream'
|
|
10
11
|
|
|
11
12
|
import { createDiscordBotAdapter, type DiscordBotAdapter } from './adapters/discord-bot'
|
|
@@ -14,6 +15,7 @@ import { createKakaotalkAdapter, type KakaotalkAdapter } from './adapters/kakaot
|
|
|
14
15
|
import { createLineAdapter, type LineAdapter } from './adapters/line'
|
|
15
16
|
import { createSlackBotAdapter, type SlackBotAdapter } from './adapters/slack-bot'
|
|
16
17
|
import { createTelegramBotAdapter, type TelegramBotAdapter } from './adapters/telegram-bot'
|
|
18
|
+
import { createWebexAdapter, type WebexAdapter } from './adapters/webex'
|
|
17
19
|
import { createWebexBotAdapter, type WebexBotAdapter } from './adapters/webex-bot'
|
|
18
20
|
import type { GithubTokenBridge } from './github-token-bridge'
|
|
19
21
|
import {
|
|
@@ -72,7 +74,8 @@ export type ChannelManagerOptions = {
|
|
|
72
74
|
createLineAdapter?: typeof createLineAdapter
|
|
73
75
|
createSlackAdapter?: typeof createSlackBotAdapter
|
|
74
76
|
createTelegramAdapter?: typeof createTelegramBotAdapter
|
|
75
|
-
createWebexAdapter?: typeof
|
|
77
|
+
createWebexAdapter?: typeof createWebexAdapter
|
|
78
|
+
createWebexBotAdapter?: typeof createWebexBotAdapter
|
|
76
79
|
// Wake-up gate: forwarded to the router, which calls
|
|
77
80
|
// `permissions.has(origin, 'channel.respond')` BEFORE creating a
|
|
78
81
|
// session for any inbound. Optional here to keep direct manager-level
|
|
@@ -134,6 +137,7 @@ type AnyAdapter =
|
|
|
134
137
|
| KakaotalkAdapter
|
|
135
138
|
| SlackBotAdapter
|
|
136
139
|
| TelegramBotAdapter
|
|
140
|
+
| WebexAdapter
|
|
137
141
|
| WebexBotAdapter
|
|
138
142
|
|
|
139
143
|
// Credential signature is the comparison key for credential-rotation
|
|
@@ -171,7 +175,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
171
175
|
const createLine = options.createLineAdapter ?? createLineAdapter
|
|
172
176
|
const createSlackAdapter = options.createSlackAdapter ?? createSlackBotAdapter
|
|
173
177
|
const createTelegramAdapter = options.createTelegramAdapter ?? createTelegramBotAdapter
|
|
174
|
-
const createWebex = options.createWebexAdapter ??
|
|
178
|
+
const createWebex = options.createWebexAdapter ?? createWebexAdapter
|
|
179
|
+
const createWebexBot = options.createWebexBotAdapter ?? createWebexBotAdapter
|
|
175
180
|
|
|
176
181
|
const live = new Map<AdapterId, AdapterEntry>()
|
|
177
182
|
const perAdapterSerial = new Map<AdapterId, Promise<unknown>>()
|
|
@@ -197,6 +202,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
197
202
|
const buildCredentialSignature = (name: AdapterId): { signature: string; missing: string[] } => {
|
|
198
203
|
if (name === 'line') return buildLineSignature(options.agentDir)
|
|
199
204
|
if (name === 'kakaotalk') return buildKakaotalkSignature(options.agentDir)
|
|
205
|
+
if (name === 'webex') return buildWebexSignature(options.agentDir)
|
|
200
206
|
if (name === 'github') return buildGithubSignature(options.agentDir)
|
|
201
207
|
const requiredEnvs = TOKEN_ENV[name]
|
|
202
208
|
const parts: string[] = []
|
|
@@ -252,6 +258,15 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
252
258
|
credentialsStore: createContainerKakaoCredentialStore(options.agentDir, env),
|
|
253
259
|
})
|
|
254
260
|
}
|
|
261
|
+
if (name === 'webex') {
|
|
262
|
+
return createWebex({
|
|
263
|
+
router,
|
|
264
|
+
configRef: () => options.channelsConfigRef()[name] ?? cfg,
|
|
265
|
+
logger,
|
|
266
|
+
selfAliasesRef: () => router.getSelfAliases(),
|
|
267
|
+
credentialsStore: createContainerWebexCredentialStore(options.agentDir, env),
|
|
268
|
+
})
|
|
269
|
+
}
|
|
255
270
|
if (name === 'github') {
|
|
256
271
|
const secrets = readGithubSecrets(options.agentDir)
|
|
257
272
|
if (secrets === null) return null
|
|
@@ -279,11 +294,12 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
279
294
|
if (name === 'webex-bot') {
|
|
280
295
|
const token = env.WEBEX_BOT_TOKEN
|
|
281
296
|
if (token === undefined || token.trim() === '') return null
|
|
282
|
-
return
|
|
297
|
+
return createWebexBot({
|
|
283
298
|
router,
|
|
284
299
|
configRef: () => options.channelsConfigRef()[name] ?? cfg,
|
|
285
300
|
token,
|
|
286
301
|
logger,
|
|
302
|
+
selfAliasesRef: () => router.getSelfAliases(),
|
|
287
303
|
})
|
|
288
304
|
}
|
|
289
305
|
return null
|
|
@@ -457,7 +473,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
457
473
|
await runSerially(name, () => stopAdapter(name))
|
|
458
474
|
stopped.push(name)
|
|
459
475
|
} else if (signature !== current.credentialSignature) {
|
|
460
|
-
const reason =
|
|
476
|
+
const reason =
|
|
477
|
+
name === 'kakaotalk' || name === 'line' || name === 'webex' ? 'credential rotation' : 'token rotation'
|
|
461
478
|
restartRequired.push(`${name} (${reason})`)
|
|
462
479
|
}
|
|
463
480
|
}
|
|
@@ -468,16 +485,46 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
468
485
|
}
|
|
469
486
|
}
|
|
470
487
|
|
|
471
|
-
// Token-based adapters only.
|
|
488
|
+
// Token-based adapters only. Personal-account credentials live in
|
|
472
489
|
// secrets.json#channels.<adapter>, not in env, so they go through
|
|
473
|
-
//
|
|
474
|
-
const TOKEN_ENV: Record<Exclude<AdapterId, 'kakaotalk' | 'line' | 'github'>, readonly string[]> = {
|
|
490
|
+
// structured-block signatures instead.
|
|
491
|
+
const TOKEN_ENV: Record<Exclude<AdapterId, 'kakaotalk' | 'line' | 'github' | 'webex'>, readonly string[]> = {
|
|
475
492
|
'discord-bot': ['DISCORD_BOT_TOKEN'],
|
|
476
493
|
'slack-bot': ['SLACK_BOT_TOKEN', 'SLACK_APP_TOKEN'],
|
|
477
494
|
'telegram-bot': ['TELEGRAM_BOT_TOKEN'],
|
|
478
495
|
'webex-bot': ['WEBEX_BOT_TOKEN'],
|
|
479
496
|
}
|
|
480
497
|
|
|
498
|
+
function createContainerWebexCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsWebexCredentialStore {
|
|
499
|
+
const hostdUrl = env.TYPECLAW_HOSTD_URL
|
|
500
|
+
const restartToken = env.TYPECLAW_HOSTD_TOKEN
|
|
501
|
+
const containerName = env.TYPECLAW_CONTAINER_NAME
|
|
502
|
+
if (!hostdUrl || !restartToken || !containerName) {
|
|
503
|
+
throw new Error('Webex credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
|
|
504
|
+
}
|
|
505
|
+
return new SecretsWebexCredentialStore({
|
|
506
|
+
mode: 'container',
|
|
507
|
+
secretsPath: join(agentDir, 'secrets.json'),
|
|
508
|
+
hostdUrl,
|
|
509
|
+
restartToken,
|
|
510
|
+
containerName,
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function buildWebexSignature(agentDir: string): { signature: string; missing: string[] } {
|
|
515
|
+
const path = join(agentDir, 'secrets.json')
|
|
516
|
+
try {
|
|
517
|
+
const block = new SecretsBackend(path).tryReadChannelsSync()?.webex
|
|
518
|
+
if (!isWebexCredentialBlock(block)) {
|
|
519
|
+
return { signature: '', missing: ['secrets.json#channels.webex'] }
|
|
520
|
+
}
|
|
521
|
+
const digest = createHash('sha256').update(JSON.stringify(block)).digest('hex')
|
|
522
|
+
return { signature: `secrets.json#channels.webex@sha256:${digest}`, missing: [] }
|
|
523
|
+
} catch (err) {
|
|
524
|
+
return { signature: '', missing: [`secrets.json#channels.webex (${describe(err)})`] }
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
481
528
|
function createContainerKakaoCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsKakaoCredentialStore {
|
|
482
529
|
const hostdUrl = env.TYPECLAW_HOSTD_URL
|
|
483
530
|
const restartToken = env.TYPECLAW_HOSTD_TOKEN
|
|
@@ -584,6 +631,15 @@ function isLineCredentialBlock(value: unknown): value is { accounts: Record<stri
|
|
|
584
631
|
)
|
|
585
632
|
}
|
|
586
633
|
|
|
634
|
+
function isWebexCredentialBlock(value: unknown): value is { accounts: Record<string, unknown> } {
|
|
635
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
636
|
+
if (!('accounts' in value)) return false
|
|
637
|
+
const accounts = value.accounts
|
|
638
|
+
return (
|
|
639
|
+
typeof accounts === 'object' && accounts !== null && !Array.isArray(accounts) && Object.keys(accounts).length > 0
|
|
640
|
+
)
|
|
641
|
+
}
|
|
642
|
+
|
|
587
643
|
function describe(err: unknown): string {
|
|
588
644
|
return err instanceof Error ? err.message : String(err)
|
|
589
645
|
}
|