typeclaw 0.37.6 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +2 -2
- package/src/agent/attention-escalation.ts +590 -0
- package/src/agent/session-origin.ts +11 -7
- package/src/agent/subagents.ts +2 -0
- package/src/agent/system-prompt.ts +2 -2
- package/src/channels/adapters/webex-bot-channel-resolver.ts +29 -0
- package/src/channels/adapters/webex-bot-classify.ts +92 -0
- package/src/channels/adapters/webex-bot-reference.ts +47 -0
- package/src/channels/adapters/webex-bot.ts +395 -0
- package/src/channels/manager.ts +15 -0
- package/src/channels/router.ts +10 -1
- package/src/channels/schema.ts +15 -1
- package/src/cli/channel.ts +38 -2
- package/src/cli/init.ts +67 -6
- package/src/cli/restart.ts +1 -0
- package/src/cli/start.ts +1 -0
- package/src/config/channels-mutation.ts +9 -1
- package/src/config/config.ts +12 -10
- package/src/container/start.ts +17 -4
- package/src/cron/consumer.ts +7 -0
- package/src/doctor/channel-checks.ts +13 -1
- package/src/doctor/checks.ts +13 -1
- package/src/init/dockerfile.ts +51 -3
- package/src/init/index.ts +39 -16
- package/src/init/run-owner-claim.ts +1 -0
- package/src/permissions/match-rule.ts +7 -3
- package/src/permissions/resolve.ts +6 -4
- package/src/role-claim/match-rule.ts +2 -1
- package/src/secrets/defaults.ts +1 -0
- package/src/server/command-runner.ts +2 -0
- package/src/server/index.ts +9 -0
- package/typeclaw.schema.json +161 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { WebexBotClient } from 'agent-messenger/webexbot'
|
|
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<WebexBotClient, '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-bot') 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,92 @@
|
|
|
1
|
+
import type { WebexBotListenerEventMap } from 'agent-messenger/webexbot'
|
|
2
|
+
|
|
3
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
4
|
+
import type { InboundAttachment, InboundMessage } from '@/channels/types'
|
|
5
|
+
|
|
6
|
+
export type WebexInboundMessage = WebexBotListenerEventMap['message_created'][0]
|
|
7
|
+
|
|
8
|
+
export type InboundDropReason = 'self_author' | 'empty_content' | 'pre_connect'
|
|
9
|
+
|
|
10
|
+
export type InboundClassification =
|
|
11
|
+
| { kind: 'drop'; reason: InboundDropReason }
|
|
12
|
+
| { kind: 'route'; payload: InboundMessage }
|
|
13
|
+
|
|
14
|
+
export function classifyInbound(
|
|
15
|
+
event: WebexInboundMessage,
|
|
16
|
+
_config: ChannelAdapterConfig,
|
|
17
|
+
botPersonId: string | null,
|
|
18
|
+
): InboundClassification {
|
|
19
|
+
if (botPersonId !== null && event.personId === botPersonId) {
|
|
20
|
+
return { kind: 'drop', reason: 'self_author' }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const { text, attachments } = splitInbound(event)
|
|
24
|
+
if (text === '') return { kind: 'drop', reason: 'empty_content' }
|
|
25
|
+
|
|
26
|
+
if (botPersonId === null) {
|
|
27
|
+
return { kind: 'drop', reason: 'pre_connect' }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const isDm = event.roomType === 'direct'
|
|
31
|
+
const isBotMention = event.mentionedPeople.includes(botPersonId) || event.mentionedGroups.includes('all')
|
|
32
|
+
const mentionsOthers = event.mentionedPeople.length > 0 && !event.mentionedPeople.includes(botPersonId)
|
|
33
|
+
const ts = Date.parse(event.created)
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
kind: 'route',
|
|
37
|
+
payload: {
|
|
38
|
+
adapter: 'webex-bot',
|
|
39
|
+
// Webex message events do not include an org/team id; the room id is the
|
|
40
|
+
// stable permission bucket for group spaces while DMs use the shared key.
|
|
41
|
+
workspace: isDm ? '@dm' : event.roomId,
|
|
42
|
+
chat: event.roomId,
|
|
43
|
+
thread: null,
|
|
44
|
+
text,
|
|
45
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
46
|
+
externalMessageId: event.id,
|
|
47
|
+
authorId: event.personId,
|
|
48
|
+
authorName: event.personEmail,
|
|
49
|
+
authorIsBot: false,
|
|
50
|
+
isBotMention,
|
|
51
|
+
// Webex Mercury only exposes parentId inline, not the parent author. When
|
|
52
|
+
// the reply auto-mentions the bot we can identify it as bot-directed;
|
|
53
|
+
// otherwise leave the parent unattributed instead of guessing.
|
|
54
|
+
replyToBotMessageId: event.parentId !== undefined && isBotMention ? event.parentId : null,
|
|
55
|
+
mentionsOthers,
|
|
56
|
+
replyToOtherMessageId: null,
|
|
57
|
+
isDm,
|
|
58
|
+
ts: Number.isFinite(ts) ? ts : 0,
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type SplitInbound = { text: string; attachments: InboundAttachment[] }
|
|
64
|
+
|
|
65
|
+
function splitInbound(event: WebexInboundMessage): SplitInbound {
|
|
66
|
+
const attachments = event.files.map((ref, index) => ({
|
|
67
|
+
id: index + 1,
|
|
68
|
+
kind: 'file' as const,
|
|
69
|
+
ref,
|
|
70
|
+
filename: filenameFromUrl(ref) ?? `webex-file-${index + 1}`,
|
|
71
|
+
}))
|
|
72
|
+
if (attachments.length === 0) return { text: event.text, attachments: [] }
|
|
73
|
+
const summary = attachments.map(renderPlaceholder).join('\n')
|
|
74
|
+
const text = event.text === '' ? summary : `${event.text}\n${summary}`
|
|
75
|
+
return { text, attachments }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function filenameFromUrl(ref: string): string | null {
|
|
79
|
+
try {
|
|
80
|
+
const url = new URL(ref)
|
|
81
|
+
const name = url.pathname.split('/').filter(Boolean).pop()
|
|
82
|
+
return name === undefined || name === '' ? null : name
|
|
83
|
+
} catch {
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function renderPlaceholder(attachment: InboundAttachment): string {
|
|
89
|
+
const parts: string[] = [`Webex attachment #${attachment.id}: ${attachment.kind}`]
|
|
90
|
+
if (attachment.filename !== undefined) parts.push(`name=${attachment.filename}`)
|
|
91
|
+
return `[${parts.join(' ')}]`
|
|
92
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { WebexBotClient } from 'agent-messenger/webexbot'
|
|
2
|
+
|
|
3
|
+
import type { InboundMessage, QuoteAnchorSource } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
// Webex Mercury delivers only the parent message id inline, not its author,
|
|
6
|
+
// so the classifier cannot tell whether a reply targets the bot. We fetch the
|
|
7
|
+
// parent here (already needed for the quote anchor) and use its author to set
|
|
8
|
+
// the reply-target fields the engagement layer reads: a non-mention reply to a
|
|
9
|
+
// bot-authored parent must engage via the `reply` trigger, and a reply to a
|
|
10
|
+
// different author must suppress the solo-human fallback. Both are no-ops if
|
|
11
|
+
// the classifier already attributed the reply (it sets replyToBotMessageId
|
|
12
|
+
// when the reply also @-mentions the bot).
|
|
13
|
+
export async function enrichWebexMessageReference(args: {
|
|
14
|
+
client: Pick<WebexBotClient, 'getMessage'>
|
|
15
|
+
inbound: InboundMessage
|
|
16
|
+
parentId?: string
|
|
17
|
+
botPersonId: string | null
|
|
18
|
+
}): Promise<InboundMessage> {
|
|
19
|
+
if (args.parentId === undefined || args.parentId === '') return args.inbound
|
|
20
|
+
try {
|
|
21
|
+
const parent = await args.client.getMessage(args.parentId)
|
|
22
|
+
const attributed = attributeReply(args.inbound, parent.id, parent.personId, args.botPersonId)
|
|
23
|
+
const source: QuoteAnchorSource = {
|
|
24
|
+
adapter: 'webex-bot',
|
|
25
|
+
authorId: parent.personId,
|
|
26
|
+
authorName: parent.personEmail,
|
|
27
|
+
text: parent.text ?? parent.markdown ?? parent.html ?? '',
|
|
28
|
+
}
|
|
29
|
+
if (source.text.trim() === '') return attributed
|
|
30
|
+
return { ...attributed, referenceContext: { kind: 'reply', sources: [source] } }
|
|
31
|
+
} catch {
|
|
32
|
+
return args.inbound
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function attributeReply(
|
|
37
|
+
inbound: InboundMessage,
|
|
38
|
+
parentId: string,
|
|
39
|
+
parentPersonId: string,
|
|
40
|
+
botPersonId: string | null,
|
|
41
|
+
): InboundMessage {
|
|
42
|
+
if (inbound.replyToBotMessageId !== null || inbound.replyToOtherMessageId !== null) return inbound
|
|
43
|
+
if (botPersonId !== null && parentPersonId === botPersonId) {
|
|
44
|
+
return { ...inbound, replyToBotMessageId: parentId }
|
|
45
|
+
}
|
|
46
|
+
return { ...inbound, replyToOtherMessageId: parentId }
|
|
47
|
+
}
|
|
@@ -0,0 +1,395 @@
|
|
|
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 type { MembershipResolver, MembershipResolverFailure, MembershipResolverResult } from '@/channels/membership'
|
|
11
|
+
import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
|
|
12
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
13
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
14
|
+
import type {
|
|
15
|
+
ChannelHistoryMessage,
|
|
16
|
+
ChannelSelfIdentityResolver,
|
|
17
|
+
FetchAttachmentCallback,
|
|
18
|
+
FetchHistoryArgs,
|
|
19
|
+
FetchHistoryResult,
|
|
20
|
+
HistoryCallback,
|
|
21
|
+
OutboundCallback,
|
|
22
|
+
OutboundMessage,
|
|
23
|
+
ResolvedChannelNames,
|
|
24
|
+
SendResult,
|
|
25
|
+
} from '@/channels/types'
|
|
26
|
+
|
|
27
|
+
import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
|
|
28
|
+
import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
|
|
29
|
+
import { enrichWebexMessageReference } from './webex-bot-reference'
|
|
30
|
+
|
|
31
|
+
export type WebexBotAdapterLogger = {
|
|
32
|
+
info: (msg: string) => void
|
|
33
|
+
warn: (msg: string) => void
|
|
34
|
+
error: (msg: string) => void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const consoleLogger: WebexBotAdapterLogger = {
|
|
38
|
+
info: (m) => console.log(m),
|
|
39
|
+
warn: (m) => console.warn(m),
|
|
40
|
+
error: (m) => console.error(m),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type WebexBotClientFactory = () => WebexBotClient
|
|
44
|
+
export type WebexBotListenerFactory = (
|
|
45
|
+
client: Pick<WebexBotClient, 'getToken'>,
|
|
46
|
+
options: WebexBotListenerOptions,
|
|
47
|
+
) => WebexBotListener
|
|
48
|
+
|
|
49
|
+
export type WebexBotAdapterOptions = {
|
|
50
|
+
router: ChannelRouter
|
|
51
|
+
configRef: () => ChannelAdapterConfig
|
|
52
|
+
token: string
|
|
53
|
+
logger?: WebexBotAdapterLogger
|
|
54
|
+
fetchImpl?: typeof fetch
|
|
55
|
+
createClient?: WebexBotClientFactory
|
|
56
|
+
createListener?: WebexBotListenerFactory
|
|
57
|
+
listenerOptions?: Omit<WebexBotListenerOptions, 'ignoreSelfMessages'>
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type WebexBotAdapter = {
|
|
61
|
+
start: () => Promise<void>
|
|
62
|
+
stop: () => Promise<void>
|
|
63
|
+
isConnected: () => boolean
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createOutboundCallback(deps: {
|
|
67
|
+
client: Pick<WebexBotClient, 'sendMessage'>
|
|
68
|
+
logger: WebexBotAdapterLogger
|
|
69
|
+
formatChannelTag: (chat: string) => Promise<string>
|
|
70
|
+
}): OutboundCallback {
|
|
71
|
+
const { client, logger, formatChannelTag } = deps
|
|
72
|
+
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
73
|
+
if (msg.adapter !== 'webex-bot') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
74
|
+
const text = msg.text ?? ''
|
|
75
|
+
const attachments = msg.attachments ?? []
|
|
76
|
+
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
|
+
|
|
81
|
+
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
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const sent = await client.sendMessage(msg.chat, text, { markdown: true })
|
|
94
|
+
logger.info(`[webex-bot] sent id=${sent.id} ${tag}`)
|
|
95
|
+
return { ok: true }
|
|
96
|
+
} catch (err) {
|
|
97
|
+
const message = describe(err)
|
|
98
|
+
logger.error(`[webex-bot] sendMessage failed: ${message}`)
|
|
99
|
+
return { ok: false, error: message }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function createWebexHistoryCallback(deps: {
|
|
105
|
+
client: Pick<WebexBotClient, 'listMessages'>
|
|
106
|
+
logger: WebexBotAdapterLogger
|
|
107
|
+
botPersonIdRef: () => string | null
|
|
108
|
+
}): HistoryCallback {
|
|
109
|
+
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
110
|
+
try {
|
|
111
|
+
const messages = await deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
|
|
112
|
+
return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse() }
|
|
113
|
+
} catch (err) {
|
|
114
|
+
const message = describe(err)
|
|
115
|
+
deps.logger.warn(`[webex-bot] history fetch failed: ${message}`)
|
|
116
|
+
return { ok: false, error: message }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function createWebexMembershipResolver(deps: {
|
|
122
|
+
client: Pick<WebexBotClient, 'listMemberships'>
|
|
123
|
+
logger: WebexBotAdapterLogger
|
|
124
|
+
historyCallback: HistoryCallback
|
|
125
|
+
now?: () => number
|
|
126
|
+
}): MembershipResolver {
|
|
127
|
+
const now = deps.now ?? Date.now
|
|
128
|
+
return async (key): Promise<MembershipResolverResult> => {
|
|
129
|
+
if (key.adapter !== 'webex-bot') return { kind: 'permanent' } satisfies MembershipResolverFailure
|
|
130
|
+
if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
|
|
131
|
+
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 }
|
|
136
|
+
} catch (err) {
|
|
137
|
+
deps.logger.warn(`[webex-bot] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
|
|
138
|
+
return await deriveMembershipFromHistory({
|
|
139
|
+
fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
|
|
140
|
+
now,
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const WEBEX_ATTACHMENT_HOSTS = new Set(['webexapis.com', 'api.ciscospark.com'])
|
|
147
|
+
|
|
148
|
+
export function createFetchAttachmentCallback(deps: {
|
|
149
|
+
token: string
|
|
150
|
+
logger: WebexBotAdapterLogger
|
|
151
|
+
fetchImpl?: typeof fetch
|
|
152
|
+
}): FetchAttachmentCallback {
|
|
153
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
154
|
+
return async ({ ref, filename }) => {
|
|
155
|
+
let url: URL
|
|
156
|
+
try {
|
|
157
|
+
url = new URL(ref)
|
|
158
|
+
} catch {
|
|
159
|
+
return { ok: false, error: `invalid Webex file URL: ${ref}` }
|
|
160
|
+
}
|
|
161
|
+
// The bearer token must never leave over plaintext: an allowlisted host
|
|
162
|
+
// on http:// would still leak the credential, so gate on https before the
|
|
163
|
+
// host check.
|
|
164
|
+
if (url.protocol !== 'https:') {
|
|
165
|
+
return { ok: false, error: `Webex file URL must use https: ${url.protocol}//${url.hostname}` }
|
|
166
|
+
}
|
|
167
|
+
if (!isAllowedWebexFileHost(url.hostname)) {
|
|
168
|
+
return { ok: false, error: `not a Webex file URL: ${url.hostname}` }
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${deps.token}` } })
|
|
172
|
+
if (!res.ok) {
|
|
173
|
+
const body = await res.text().catch(() => '')
|
|
174
|
+
const message = `webex file fetch ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`
|
|
175
|
+
deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
|
|
176
|
+
return { ok: false, error: message }
|
|
177
|
+
}
|
|
178
|
+
const buffer = Buffer.from(await res.arrayBuffer())
|
|
179
|
+
const inferredFilename = filename ?? url.pathname.split('/').pop() ?? 'attachment'
|
|
180
|
+
const contentType = res.headers.get('content-type') ?? undefined
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
buffer,
|
|
184
|
+
filename: inferredFilename,
|
|
185
|
+
...(contentType !== undefined ? { mimetype: contentType } : {}),
|
|
186
|
+
size: buffer.length,
|
|
187
|
+
}
|
|
188
|
+
} catch (err) {
|
|
189
|
+
const message = describe(err)
|
|
190
|
+
deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
|
|
191
|
+
return { ok: false, error: message }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBotAdapter {
|
|
197
|
+
const logger = options.logger ?? consoleLogger
|
|
198
|
+
const createClient = options.createClient ?? (() => new WebexBotClient())
|
|
199
|
+
const createListener =
|
|
200
|
+
options.createListener ?? ((client, listenerOptions) => new WebexBotListener(client, listenerOptions))
|
|
201
|
+
const client = createClient()
|
|
202
|
+
const fetchImpl = options.fetchImpl ?? fetch
|
|
203
|
+
let listener: WebexBotListener | null = null
|
|
204
|
+
let botPerson: WebexPerson | null = null
|
|
205
|
+
let connected = false
|
|
206
|
+
let started = false
|
|
207
|
+
let inflightInbounds = 0
|
|
208
|
+
let stopWaiters: Array<() => void> = []
|
|
209
|
+
|
|
210
|
+
const channelResolver = createWebexChannelNameResolver({ client })
|
|
211
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
|
|
212
|
+
botPerson !== null ? { id: botPerson.id, username: botPerson.emails[0] ?? botPerson.displayName } : null
|
|
213
|
+
|
|
214
|
+
const formatChannelTag = async (chat: string): Promise<string> => {
|
|
215
|
+
const names = await channelResolver({ adapter: 'webex-bot', workspace: chat, chat, thread: null }).catch(
|
|
216
|
+
(): ResolvedChannelNames => ({}),
|
|
217
|
+
)
|
|
218
|
+
const label = names.chatName ?? null
|
|
219
|
+
return label === null || label === chat ? `room=${chat}` : `room=${label}(${chat})`
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const historyCallback = createWebexHistoryCallback({ client, logger, botPersonIdRef: () => botPerson?.id ?? null })
|
|
223
|
+
const membershipResolver = createWebexMembershipResolver({ client, logger, historyCallback })
|
|
224
|
+
const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
|
|
225
|
+
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger, fetchImpl })
|
|
226
|
+
|
|
227
|
+
const handleMessage = async (event: WebexInboundMessage): Promise<void> => {
|
|
228
|
+
inflightInbounds++
|
|
229
|
+
const botSnapshot = botPerson
|
|
230
|
+
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)
|
|
234
|
+
if (verdict.kind === 'drop') {
|
|
235
|
+
logger.info(`[webex-bot] dropped id=${event.id} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
const payload = await enrichWebexMessageReference({
|
|
239
|
+
client,
|
|
240
|
+
inbound: verdict.payload,
|
|
241
|
+
parentId: event.parentId,
|
|
242
|
+
botPersonId: botSnapshot?.id ?? null,
|
|
243
|
+
})
|
|
244
|
+
logger.info(
|
|
245
|
+
`[webex-bot] routed id=${event.id} ${tag} mention=${payload.isBotMention} reply=${payload.replyToBotMessageId !== null}`,
|
|
246
|
+
)
|
|
247
|
+
await options.router.route(payload)
|
|
248
|
+
} catch (err) {
|
|
249
|
+
logger.error(`[webex-bot] handleInbound failed: ${describe(err)}`)
|
|
250
|
+
} finally {
|
|
251
|
+
inflightInbounds--
|
|
252
|
+
if (inflightInbounds === 0 && stopWaiters.length > 0) {
|
|
253
|
+
const waiters = stopWaiters
|
|
254
|
+
stopWaiters = []
|
|
255
|
+
for (const w of waiters) w()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
async start(): Promise<void> {
|
|
262
|
+
if (started) return
|
|
263
|
+
started = true
|
|
264
|
+
try {
|
|
265
|
+
await client.login({ token: options.token })
|
|
266
|
+
botPerson = await client.testAuth()
|
|
267
|
+
logger.info(`[webex-bot] authenticated as ${botPerson.displayName} (${botPerson.id})`)
|
|
268
|
+
} catch (err) {
|
|
269
|
+
started = false
|
|
270
|
+
botPerson = null
|
|
271
|
+
logger.error(`[webex-bot] login failed: ${describe(err)}`)
|
|
272
|
+
throw err
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
listener = createListener(client, { ...options.listenerOptions, ignoreSelfMessages: true })
|
|
276
|
+
let listenerConnected = false
|
|
277
|
+
let listenerStartupError: Error | null = null
|
|
278
|
+
listener.on('connected', () => {
|
|
279
|
+
listenerConnected = true
|
|
280
|
+
connected = true
|
|
281
|
+
})
|
|
282
|
+
listener.on('disconnected', (reason) => {
|
|
283
|
+
connected = false
|
|
284
|
+
logger.warn(`[webex-bot] disconnected: ${reason}`)
|
|
285
|
+
})
|
|
286
|
+
listener.on('error', (err) => {
|
|
287
|
+
const error = err instanceof Error ? err : new Error(String(err))
|
|
288
|
+
if (!listenerConnected && listenerStartupError === null) listenerStartupError = error
|
|
289
|
+
logger.error(`[webex-bot] listener error: ${describe(error)}`)
|
|
290
|
+
})
|
|
291
|
+
listener.on('message_created', (event: WebexBotListenerEventMap['message_created'][0]) => {
|
|
292
|
+
void handleMessage(event)
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
options.router.registerOutbound('webex-bot', outboundCallback)
|
|
296
|
+
options.router.registerChannelNameResolver('webex-bot', channelResolver)
|
|
297
|
+
options.router.registerSelfIdentity('webex-bot', selfIdentityResolver)
|
|
298
|
+
options.router.registerHistory('webex-bot', historyCallback)
|
|
299
|
+
options.router.registerFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
300
|
+
options.router.registerMembership('webex-bot', membershipResolver)
|
|
301
|
+
|
|
302
|
+
const rollbackStart = (reason: string, cause: Error): never => {
|
|
303
|
+
options.router.unregisterOutbound('webex-bot', outboundCallback)
|
|
304
|
+
options.router.unregisterChannelNameResolver('webex-bot', channelResolver)
|
|
305
|
+
options.router.unregisterSelfIdentity('webex-bot', selfIdentityResolver)
|
|
306
|
+
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
307
|
+
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
308
|
+
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
309
|
+
listener?.stop()
|
|
310
|
+
listener = null
|
|
311
|
+
botPerson = null
|
|
312
|
+
connected = false
|
|
313
|
+
started = false
|
|
314
|
+
logger.error(`[webex-bot] ${reason}: ${describe(cause)}`)
|
|
315
|
+
throw cause
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
await listener.start()
|
|
320
|
+
} catch (err) {
|
|
321
|
+
rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
|
|
322
|
+
}
|
|
323
|
+
if (!listenerConnected) {
|
|
324
|
+
rollbackStart(
|
|
325
|
+
'listener start failed silently',
|
|
326
|
+
listenerStartupError ?? new Error('listener.start() returned without emitting connected'),
|
|
327
|
+
)
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
async stop(): Promise<void> {
|
|
332
|
+
if (!started) return
|
|
333
|
+
started = false
|
|
334
|
+
options.router.unregisterOutbound('webex-bot', outboundCallback)
|
|
335
|
+
options.router.unregisterChannelNameResolver('webex-bot', channelResolver)
|
|
336
|
+
options.router.unregisterSelfIdentity('webex-bot', selfIdentityResolver)
|
|
337
|
+
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
338
|
+
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
339
|
+
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
340
|
+
listener?.stop()
|
|
341
|
+
listener = null
|
|
342
|
+
connected = false
|
|
343
|
+
if (inflightInbounds > 0) {
|
|
344
|
+
await new Promise<void>((resolve) => {
|
|
345
|
+
stopWaiters.push(resolve)
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
botPerson = null
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
isConnected(): boolean {
|
|
352
|
+
return started && botPerson !== null && connected
|
|
353
|
+
},
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function mapWebexHistoryMessage(msg: WebexMessage, botPersonId: string | null): ChannelHistoryMessage {
|
|
358
|
+
const attachments = (msg.files ?? []).map((ref, index) => ({ id: index + 1, kind: 'file' as const, ref }))
|
|
359
|
+
const body = msg.text ?? msg.markdown ?? msg.html ?? ''
|
|
360
|
+
const text = attachments.length === 0 ? body : body === '' ? '[Webex attachment]' : `${body}\n[Webex attachment]`
|
|
361
|
+
const ts = Date.parse(msg.created)
|
|
362
|
+
return {
|
|
363
|
+
externalMessageId: msg.id,
|
|
364
|
+
authorId: msg.personId,
|
|
365
|
+
authorName: msg.personEmail,
|
|
366
|
+
text,
|
|
367
|
+
ts: Number.isFinite(ts) ? ts : 0,
|
|
368
|
+
isBot: botPersonId !== null && msg.personId === botPersonId,
|
|
369
|
+
replyToBotMessageId: msg.parentId ?? null,
|
|
370
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function isAllowedWebexFileHost(hostname: string): boolean {
|
|
375
|
+
return WEBEX_ATTACHMENT_HOSTS.has(hostname) || hostname.endsWith('.webexcontent.com')
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function clampLimit(requested: number, max: number): number {
|
|
379
|
+
if (!Number.isFinite(requested) || requested <= 0) return max
|
|
380
|
+
return Math.min(Math.floor(requested), max)
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function describe(err: unknown): string {
|
|
384
|
+
return err instanceof Error ? err.message : String(err)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function dropHint(reason: InboundDropReason): string {
|
|
388
|
+
switch (reason) {
|
|
389
|
+
case 'empty_content':
|
|
390
|
+
return ' (message had no text and no files)'
|
|
391
|
+
case 'pre_connect':
|
|
392
|
+
case 'self_author':
|
|
393
|
+
return ''
|
|
394
|
+
}
|
|
395
|
+
}
|
package/src/channels/manager.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { createKakaotalkAdapter, type KakaotalkAdapter } from './adapters/kakaot
|
|
|
14
14
|
import { createLineAdapter, type LineAdapter } from './adapters/line'
|
|
15
15
|
import { createSlackBotAdapter, type SlackBotAdapter } from './adapters/slack-bot'
|
|
16
16
|
import { createTelegramBotAdapter, type TelegramBotAdapter } from './adapters/telegram-bot'
|
|
17
|
+
import { createWebexBotAdapter, type WebexBotAdapter } from './adapters/webex-bot'
|
|
17
18
|
import type { GithubTokenBridge } from './github-token-bridge'
|
|
18
19
|
import {
|
|
19
20
|
createChannelRouter,
|
|
@@ -71,6 +72,7 @@ export type ChannelManagerOptions = {
|
|
|
71
72
|
createLineAdapter?: typeof createLineAdapter
|
|
72
73
|
createSlackAdapter?: typeof createSlackBotAdapter
|
|
73
74
|
createTelegramAdapter?: typeof createTelegramBotAdapter
|
|
75
|
+
createWebexAdapter?: typeof createWebexBotAdapter
|
|
74
76
|
// Wake-up gate: forwarded to the router, which calls
|
|
75
77
|
// `permissions.has(origin, 'channel.respond')` BEFORE creating a
|
|
76
78
|
// session for any inbound. Optional here to keep direct manager-level
|
|
@@ -132,6 +134,7 @@ type AnyAdapter =
|
|
|
132
134
|
| KakaotalkAdapter
|
|
133
135
|
| SlackBotAdapter
|
|
134
136
|
| TelegramBotAdapter
|
|
137
|
+
| WebexBotAdapter
|
|
135
138
|
|
|
136
139
|
// Credential signature is the comparison key for credential-rotation
|
|
137
140
|
// detection on reload. Discord and Telegram each use a single bot token;
|
|
@@ -168,6 +171,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
168
171
|
const createLine = options.createLineAdapter ?? createLineAdapter
|
|
169
172
|
const createSlackAdapter = options.createSlackAdapter ?? createSlackBotAdapter
|
|
170
173
|
const createTelegramAdapter = options.createTelegramAdapter ?? createTelegramBotAdapter
|
|
174
|
+
const createWebex = options.createWebexAdapter ?? createWebexBotAdapter
|
|
171
175
|
|
|
172
176
|
const live = new Map<AdapterId, AdapterEntry>()
|
|
173
177
|
const perAdapterSerial = new Map<AdapterId, Promise<unknown>>()
|
|
@@ -272,6 +276,16 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
272
276
|
logger,
|
|
273
277
|
})
|
|
274
278
|
}
|
|
279
|
+
if (name === 'webex-bot') {
|
|
280
|
+
const token = env.WEBEX_BOT_TOKEN
|
|
281
|
+
if (token === undefined || token.trim() === '') return null
|
|
282
|
+
return createWebex({
|
|
283
|
+
router,
|
|
284
|
+
configRef: () => options.channelsConfigRef()[name] ?? cfg,
|
|
285
|
+
token,
|
|
286
|
+
logger,
|
|
287
|
+
})
|
|
288
|
+
}
|
|
275
289
|
return null
|
|
276
290
|
}
|
|
277
291
|
|
|
@@ -461,6 +475,7 @@ const TOKEN_ENV: Record<Exclude<AdapterId, 'kakaotalk' | 'line' | 'github'>, rea
|
|
|
461
475
|
'discord-bot': ['DISCORD_BOT_TOKEN'],
|
|
462
476
|
'slack-bot': ['SLACK_BOT_TOKEN', 'SLACK_APP_TOKEN'],
|
|
463
477
|
'telegram-bot': ['TELEGRAM_BOT_TOKEN'],
|
|
478
|
+
'webex-bot': ['WEBEX_BOT_TOKEN'],
|
|
464
479
|
}
|
|
465
480
|
|
|
466
481
|
function createContainerKakaoCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsKakaoCredentialStore {
|
package/src/channels/router.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { AssistantMessage } from '@mariozechner/pi-ai'
|
|
|
5
5
|
import { SessionManager } from '@mariozechner/pi-coding-agent'
|
|
6
6
|
|
|
7
7
|
import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
|
|
8
|
+
import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
|
|
8
9
|
import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
|
|
9
10
|
import { subscribeProviderErrors } from '@/agent/provider-error'
|
|
10
11
|
import type { RestartHandoff } from '@/agent/restart-handoff'
|
|
@@ -573,6 +574,10 @@ type LiveSession = {
|
|
|
573
574
|
key: ChannelKey
|
|
574
575
|
keyId: string
|
|
575
576
|
session: AgentSession
|
|
577
|
+
// The session's creation-time thinking level, captured once. A later escalated
|
|
578
|
+
// turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
|
|
579
|
+
// reset target — this preserves the real default across the session's lifetime.
|
|
580
|
+
turnThinkingDefault: AgentSession['thinkingLevel']
|
|
576
581
|
sessionId: string
|
|
577
582
|
dispose: () => Promise<void>
|
|
578
583
|
hooks: HookBus | undefined
|
|
@@ -1659,6 +1664,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1659
1664
|
key,
|
|
1660
1665
|
keyId,
|
|
1661
1666
|
session: created.session,
|
|
1667
|
+
turnThinkingDefault: created.session.thinkingLevel,
|
|
1662
1668
|
sessionId: created.sessionId,
|
|
1663
1669
|
dispose: created.dispose,
|
|
1664
1670
|
hooks: created.hooks,
|
|
@@ -2395,8 +2401,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2395
2401
|
live.policyDeniedToolSendsThisTurn.clear()
|
|
2396
2402
|
resetReviewTurn(live.sessionId)
|
|
2397
2403
|
const isRealUserTurn = batch.length > 0
|
|
2398
|
-
const
|
|
2404
|
+
const retrievalQuery = composeRetrievalQuery(batch)
|
|
2405
|
+
const retrievalContext = await fireSessionTurnStart(live, retrievalQuery)
|
|
2399
2406
|
const promptText = retrievalContext.results.length > 0 ? `${text}\n\n${retrievalContext.results}` : text
|
|
2407
|
+
applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault)
|
|
2400
2408
|
live.promptInFlight = true
|
|
2401
2409
|
try {
|
|
2402
2410
|
await live.session.prompt(promptText)
|
|
@@ -4764,6 +4772,7 @@ function formatAuthorReference(adapter: AdapterId, authorId: string, authorName:
|
|
|
4764
4772
|
case 'github':
|
|
4765
4773
|
return displayName.startsWith('@') ? displayName : `@${displayName}`
|
|
4766
4774
|
case 'telegram-bot':
|
|
4775
|
+
case 'webex-bot':
|
|
4767
4776
|
case 'line':
|
|
4768
4777
|
case 'kakaotalk':
|
|
4769
4778
|
return displayName
|