typeclaw 0.39.1 → 0.39.3
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 +110 -0
- package/package.json +2 -2
- package/secrets.schema.json +110 -0
- package/src/agent/index.ts +44 -19
- package/src/agent/plugin-tools.ts +12 -12
- package/src/agent/session-origin.ts +2 -0
- package/src/agent/todo/store.ts +21 -1
- package/src/agent/tools/channel-reply.ts +18 -5
- package/src/agent/tools/channel-send.ts +13 -2
- package/src/bundled-plugins/doc-render/render.ts +2 -2
- package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
- package/src/channels/adapters/discord-author-resolver.ts +52 -0
- package/src/channels/adapters/discord-bot.ts +1 -1
- package/src/channels/adapters/discord-channel-resolver.ts +44 -0
- package/src/channels/adapters/discord-classify.ts +121 -0
- package/src/channels/adapters/discord-reactions.ts +138 -0
- package/src/channels/adapters/discord.ts +416 -0
- package/src/channels/adapters/github/outbound.ts +23 -4
- package/src/channels/adapters/kakaotalk.ts +8 -1
- package/src/channels/adapters/line.ts +1 -1
- package/src/channels/adapters/slack-author-resolver.ts +54 -0
- package/src/channels/adapters/slack-bot.ts +3 -1
- package/src/channels/adapters/slack-channel-resolver.ts +49 -0
- package/src/channels/adapters/slack-classify.ts +83 -0
- package/src/channels/adapters/slack-reactions.ts +126 -0
- package/src/channels/adapters/slack.ts +416 -0
- package/src/channels/adapters/telegram-bot.ts +2 -1
- package/src/channels/adapters/webex-bot.ts +5 -2
- package/src/channels/adapters/webex.ts +55 -2
- package/src/channels/github-review-turn-ledger.ts +32 -0
- package/src/channels/github-verdict-activity.ts +60 -0
- package/src/channels/index.ts +6 -0
- package/src/channels/manager.ts +130 -6
- package/src/channels/pr-verdict-activity-bridge.ts +43 -0
- package/src/channels/router.ts +218 -20
- package/src/channels/schema.ts +4 -0
- package/src/channels/types.ts +17 -1
- package/src/cli/builtins.ts +1 -0
- package/src/cli/channel.ts +170 -18
- package/src/cli/index.ts +11 -0
- package/src/cli/init.ts +2 -0
- package/src/cli/update-check.ts +14 -0
- package/src/cli/update-notify.ts +91 -0
- package/src/cli/update-suppression.ts +19 -0
- package/src/compose/logs.ts +20 -6
- package/src/config/channels-mutation.ts +3 -1
- package/src/config/config.ts +51 -0
- package/src/config/index.ts +1 -0
- package/src/container/logs.ts +19 -4
- package/src/container/shared.ts +108 -5
- package/src/container/start.ts +218 -33
- package/src/doctor/channel-checks.ts +57 -3
- package/src/hostd/daemon.ts +22 -5
- package/src/hostd/index.ts +11 -1
- package/src/hostd/paths.ts +4 -0
- package/src/hostd/protocol.ts +15 -2
- package/src/init/auto-upgrade.ts +38 -4
- package/src/init/cli-version.ts +31 -2
- package/src/init/discord-auth.ts +50 -0
- package/src/init/dockerfile.ts +18 -5
- package/src/init/index.ts +140 -42
- package/src/init/reconcile-plugin-deps.ts +30 -5
- package/src/init/run-owner-claim.ts +2 -0
- package/src/init/slack-auth.ts +51 -0
- package/src/init/windows-dev-link.ts +64 -0
- package/src/mcp/manager.ts +94 -7
- package/src/mcp/tools.ts +7 -4
- package/src/permissions/resolve.ts +2 -0
- package/src/role-claim/match-rule.ts +2 -0
- package/src/run/index.ts +74 -29
- package/src/secrets/discord-store.ts +96 -0
- package/src/secrets/schema.ts +34 -0
- package/src/secrets/slack-store.ts +96 -0
- package/src/server/command-runner.ts +21 -0
- package/src/skills/typeclaw-cron/SKILL.md +13 -2
- package/src/tui/format.ts +0 -19
- package/src/tui/index.ts +2 -8
- package/src/update/check.ts +192 -0
- package/typeclaw.schema.json +332 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { SlackRTMMessageEvent } from 'agent-messenger/slack'
|
|
2
|
+
|
|
3
|
+
import { matchesAnyAlias } from '@/channels/engagement'
|
|
4
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
5
|
+
import type { InboundMessage } from '@/channels/types'
|
|
6
|
+
|
|
7
|
+
import { slackTsToMillis } from './slack-bot-time'
|
|
8
|
+
import { encodeSlackReactionRef } from './slack-reactions'
|
|
9
|
+
|
|
10
|
+
export type SlackInboundMessageEvent = SlackRTMMessageEvent
|
|
11
|
+
|
|
12
|
+
export type InboundDropReason = 'self_author' | 'no_user' | 'slack_system_message' | 'empty_text' | 'pre_connect'
|
|
13
|
+
|
|
14
|
+
export type InboundClassification =
|
|
15
|
+
| { kind: 'drop'; reason: InboundDropReason }
|
|
16
|
+
| { kind: 'route'; payload: InboundMessage }
|
|
17
|
+
|
|
18
|
+
export type SlackInboundContext = {
|
|
19
|
+
teamId: string
|
|
20
|
+
selfUserId: string | null
|
|
21
|
+
selfAliases?: readonly string[]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function classifyInbound(
|
|
25
|
+
event: SlackInboundMessageEvent,
|
|
26
|
+
_config: ChannelAdapterConfig,
|
|
27
|
+
context: SlackInboundContext,
|
|
28
|
+
): InboundClassification {
|
|
29
|
+
if (context.selfUserId !== null && event.user === context.selfUserId) return { kind: 'drop', reason: 'self_author' }
|
|
30
|
+
if (event.user === undefined || event.user === '') return { kind: 'drop', reason: 'no_user' }
|
|
31
|
+
if (!isRouteableSlackMessageSubtype(event.subtype)) return { kind: 'drop', reason: 'slack_system_message' }
|
|
32
|
+
if ((event.text ?? '') === '') return { kind: 'drop', reason: 'empty_text' }
|
|
33
|
+
if (context.selfUserId === null) return { kind: 'drop', reason: 'pre_connect' }
|
|
34
|
+
|
|
35
|
+
const rawText = event.text ?? ''
|
|
36
|
+
const isDm = event.channel.startsWith('D')
|
|
37
|
+
const workspace = isDm ? '@dm' : context.teamId
|
|
38
|
+
const hasGroupMention = GROUP_MENTION_PATTERN.test(rawText)
|
|
39
|
+
const isBotMention = hasGroupMention || rawText.includes(`<@${context.selfUserId}>`)
|
|
40
|
+
const aliasMatched = !isBotMention && matchesAnyAlias(rawText, context.selfAliases ?? [])
|
|
41
|
+
const thread = event.thread_ts ?? (!isDm && (isBotMention || aliasMatched) ? event.ts : null)
|
|
42
|
+
const mentionedUserIds = extractMentionedUserIds(rawText)
|
|
43
|
+
const mentionsOthers = mentionedUserIds.length > 0 && !mentionedUserIds.includes(context.selfUserId)
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
kind: 'route',
|
|
47
|
+
payload: {
|
|
48
|
+
adapter: 'slack',
|
|
49
|
+
workspace,
|
|
50
|
+
chat: event.channel,
|
|
51
|
+
thread,
|
|
52
|
+
text: rawText,
|
|
53
|
+
externalMessageId: event.ts,
|
|
54
|
+
reactionRef: encodeSlackReactionRef({ channel: event.channel, ts: event.ts }),
|
|
55
|
+
authorId: event.user,
|
|
56
|
+
authorName: event.user,
|
|
57
|
+
authorIsBot: false,
|
|
58
|
+
isBotMention,
|
|
59
|
+
// RTM user-session replies do not include parent_user_id; a pure classifier
|
|
60
|
+
// cannot prove parent authorship without an async Slack lookup.
|
|
61
|
+
replyToBotMessageId: null,
|
|
62
|
+
mentionsOthers,
|
|
63
|
+
replyToOtherMessageId: null,
|
|
64
|
+
isDm,
|
|
65
|
+
ts: slackTsToMillis(event.ts),
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function isRouteableSlackMessageSubtype(subtype: string | undefined): boolean {
|
|
71
|
+
return subtype === undefined || subtype === 'me_message'
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const MENTION_PATTERN = /<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g
|
|
75
|
+
const GROUP_MENTION_PATTERN = /<!(?:here|channel|everyone)(?:\|[^>]*)?>/
|
|
76
|
+
|
|
77
|
+
function extractMentionedUserIds(text: string): string[] {
|
|
78
|
+
const seen = new Set<string>()
|
|
79
|
+
for (const match of text.matchAll(MENTION_PATTERN)) {
|
|
80
|
+
seen.add(match[1]!)
|
|
81
|
+
}
|
|
82
|
+
return Array.from(seen)
|
|
83
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { SlackClient } from 'agent-messenger/slack'
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
ReactionCallback,
|
|
5
|
+
ReactionErrorCode,
|
|
6
|
+
ReactionRef,
|
|
7
|
+
ReactionResult,
|
|
8
|
+
RemoveReactionCallback,
|
|
9
|
+
} from '@/channels/types'
|
|
10
|
+
|
|
11
|
+
export type SlackReactionTarget = { channel: string; ts: string }
|
|
12
|
+
export type SlackReactionRemovalTarget = { channel: string; ts: string; emoji: string }
|
|
13
|
+
|
|
14
|
+
export function encodeSlackReactionRef(target: SlackReactionTarget): ReactionRef {
|
|
15
|
+
return { adapter: 'slack', value: JSON.stringify(target) }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function decodeSlackReactionRef(ref: ReactionRef): SlackReactionTarget | null {
|
|
19
|
+
if (ref.adapter !== 'slack') return null
|
|
20
|
+
const parsed = parseRecord(ref.value)
|
|
21
|
+
if (parsed === null || parsed.op !== undefined) return null
|
|
22
|
+
const channel = typeof parsed.channel === 'string' ? parsed.channel : null
|
|
23
|
+
const ts = typeof parsed.ts === 'string' ? parsed.ts : null
|
|
24
|
+
if (channel === null || ts === null) return null
|
|
25
|
+
return { channel, ts }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function encodeSlackRemovalRef(target: SlackReactionRemovalTarget): ReactionRef {
|
|
29
|
+
return { adapter: 'slack', value: JSON.stringify({ op: 'remove', ...target }) }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function decodeSlackRemovalRef(ref: ReactionRef): SlackReactionRemovalTarget | null {
|
|
33
|
+
if (ref.adapter !== 'slack') return null
|
|
34
|
+
const parsed = parseRecord(ref.value)
|
|
35
|
+
if (parsed === null || parsed.op !== 'remove') return null
|
|
36
|
+
const channel = typeof parsed.channel === 'string' ? parsed.channel : null
|
|
37
|
+
const ts = typeof parsed.ts === 'string' ? parsed.ts : null
|
|
38
|
+
const emoji = typeof parsed.emoji === 'string' ? parsed.emoji : null
|
|
39
|
+
if (channel === null || ts === null || emoji === null) return null
|
|
40
|
+
return { channel, ts, emoji }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createSlackReactionCallback(deps: { client: Pick<SlackClient, 'addReaction'> }): ReactionCallback {
|
|
44
|
+
return async (req): Promise<ReactionResult> => {
|
|
45
|
+
if (req.adapter !== 'slack') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
|
|
46
|
+
const target = decodeSlackReactionRef(req.reactionRef)
|
|
47
|
+
if (target === null) return { ok: false, error: 'unparseable slack reaction ref', code: 'unsupported' }
|
|
48
|
+
const emoji = normalizeEmoji(req.emoji)
|
|
49
|
+
try {
|
|
50
|
+
await deps.client.addReaction(target.channel, target.ts, emoji)
|
|
51
|
+
} catch (err) {
|
|
52
|
+
const code = slackErrorCode(err)
|
|
53
|
+
if (code === 'already_reacted') return { ok: true, reactionRef: encodeSlackRemovalRef({ ...target, emoji }) }
|
|
54
|
+
return { ok: false, error: describe(err), code: classifySlackError(code) }
|
|
55
|
+
}
|
|
56
|
+
return { ok: true, reactionRef: encodeSlackRemovalRef({ ...target, emoji }) }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createSlackRemoveReactionCallback(deps: {
|
|
61
|
+
client: Pick<SlackClient, 'removeReaction'>
|
|
62
|
+
}): RemoveReactionCallback {
|
|
63
|
+
return async (req): Promise<ReactionResult> => {
|
|
64
|
+
if (req.adapter !== 'slack') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
|
|
65
|
+
const target = decodeSlackRemovalRef(req.reactionRef)
|
|
66
|
+
if (target === null) return { ok: false, error: 'unparseable slack reaction removal ref', code: 'unsupported' }
|
|
67
|
+
try {
|
|
68
|
+
await deps.client.removeReaction(target.channel, target.ts, target.emoji)
|
|
69
|
+
} catch (err) {
|
|
70
|
+
const code = slackErrorCode(err)
|
|
71
|
+
if (code === 'no_reaction') return { ok: true }
|
|
72
|
+
return { ok: false, error: describe(err), code: classifySlackError(code) }
|
|
73
|
+
}
|
|
74
|
+
return { ok: true }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function normalizeEmoji(emoji: string): string {
|
|
79
|
+
return emoji.replace(/^:|:$/g, '')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function slackErrorCode(err: unknown): string | null {
|
|
83
|
+
if (typeof err === 'object' && err !== null && 'code' in err) {
|
|
84
|
+
const code = (err as { code: unknown }).code
|
|
85
|
+
if (typeof code === 'string') return code
|
|
86
|
+
}
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function classifySlackError(code: string | null): ReactionErrorCode {
|
|
91
|
+
switch (code) {
|
|
92
|
+
case 'invalid_name':
|
|
93
|
+
case 'no_item_specified':
|
|
94
|
+
return 'unsupported'
|
|
95
|
+
case 'missing_scope':
|
|
96
|
+
case 'not_in_channel':
|
|
97
|
+
case 'is_archived':
|
|
98
|
+
case 'not_authed':
|
|
99
|
+
case 'invalid_auth':
|
|
100
|
+
return 'permission-denied'
|
|
101
|
+
case 'message_not_found':
|
|
102
|
+
case 'channel_not_found':
|
|
103
|
+
return 'not-found'
|
|
104
|
+
case 'ratelimited':
|
|
105
|
+
case 'rate_limited':
|
|
106
|
+
return 'rate-limited'
|
|
107
|
+
default:
|
|
108
|
+
return 'transient'
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function parseRecord(value: string): Record<string, unknown> | null {
|
|
113
|
+
let parsed: unknown
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(value)
|
|
116
|
+
} catch {
|
|
117
|
+
return null
|
|
118
|
+
}
|
|
119
|
+
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
|
|
120
|
+
? (parsed as Record<string, unknown>)
|
|
121
|
+
: null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function describe(err: unknown): string {
|
|
125
|
+
return err instanceof Error ? err.message : String(err)
|
|
126
|
+
}
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
import { basename } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
SlackClient,
|
|
5
|
+
SlackListener,
|
|
6
|
+
type SlackMessage,
|
|
7
|
+
type SlackRTMMessageEvent,
|
|
8
|
+
type SlackRTMReactionEvent,
|
|
9
|
+
} from 'agent-messenger/slack'
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
MEMBERSHIP_ENUMERATION_CAP,
|
|
13
|
+
type MembershipResolver,
|
|
14
|
+
type MembershipResolverFailure,
|
|
15
|
+
type MembershipResolverResult,
|
|
16
|
+
} from '@/channels/membership'
|
|
17
|
+
import { deriveMembershipFromHistory } from '@/channels/membership-from-history'
|
|
18
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
19
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
20
|
+
import type {
|
|
21
|
+
ChannelHistoryMessage,
|
|
22
|
+
ChannelSelfIdentityResolver,
|
|
23
|
+
FetchAttachmentCallback,
|
|
24
|
+
FetchHistoryArgs,
|
|
25
|
+
FetchHistoryResult,
|
|
26
|
+
HistoryCallback,
|
|
27
|
+
OutboundCallback,
|
|
28
|
+
OutboundMessage,
|
|
29
|
+
ResolvedChannelNames,
|
|
30
|
+
SendResult,
|
|
31
|
+
} from '@/channels/types'
|
|
32
|
+
import { chunkMarkdown } from '@/markdown'
|
|
33
|
+
import type { SlackAccountRecord } from '@/secrets/schema'
|
|
34
|
+
|
|
35
|
+
import { createSlackAuthorResolver } from './slack-author-resolver'
|
|
36
|
+
import { slackTsToMillis } from './slack-bot-time'
|
|
37
|
+
import { createSlackChannelResolver } from './slack-channel-resolver'
|
|
38
|
+
import { classifyInbound, type InboundDropReason } from './slack-classify'
|
|
39
|
+
import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-reactions'
|
|
40
|
+
|
|
41
|
+
export type SlackAdapterLogger = {
|
|
42
|
+
info: (msg: string) => void
|
|
43
|
+
warn: (msg: string) => void
|
|
44
|
+
error: (msg: string) => void
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const consoleLogger: SlackAdapterLogger = {
|
|
48
|
+
info: (m) => console.log(m),
|
|
49
|
+
warn: (m) => console.warn(m),
|
|
50
|
+
error: (m) => console.error(m),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type SlackCredentialStore = {
|
|
54
|
+
getAccount(id?: string): Promise<SlackAccountRecord | null>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type SlackAdapterOptions = {
|
|
58
|
+
router: ChannelRouter
|
|
59
|
+
configRef: () => ChannelAdapterConfig
|
|
60
|
+
logger?: SlackAdapterLogger
|
|
61
|
+
selfAliasesRef?: () => readonly string[]
|
|
62
|
+
credentialsStore?: SlackCredentialStore
|
|
63
|
+
createClient?: () => SlackClient
|
|
64
|
+
createListener?: (client: SlackClient) => SlackListener
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type SlackAdapter = {
|
|
68
|
+
start: () => Promise<void>
|
|
69
|
+
stop: () => Promise<void>
|
|
70
|
+
isConnected: () => boolean
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type SlackFileReader = (path: string) => Promise<Buffer>
|
|
74
|
+
|
|
75
|
+
export function createSlackOutboundCallback(deps: {
|
|
76
|
+
client: Pick<SlackClient, 'sendMessage' | 'uploadFile'>
|
|
77
|
+
logger: SlackAdapterLogger
|
|
78
|
+
formatChannelTag: (chat: string) => Promise<string>
|
|
79
|
+
readFile?: SlackFileReader
|
|
80
|
+
resolvePath?: (path: string) => string
|
|
81
|
+
}): OutboundCallback {
|
|
82
|
+
const readFile = deps.readFile ?? defaultReadFile
|
|
83
|
+
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
84
|
+
if (msg.adapter !== 'slack') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
85
|
+
const text = msg.text ?? ''
|
|
86
|
+
const attachments = msg.attachments ?? []
|
|
87
|
+
if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
|
|
88
|
+
const tag = await deps.formatChannelTag(msg.chat)
|
|
89
|
+
const threadTs = msg.replyTo?.externalMessageId ?? msg.thread ?? undefined
|
|
90
|
+
deps.logger.info(
|
|
91
|
+
`[slack] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${threadTs !== undefined ? ` thread=${threadTs}` : ''}`,
|
|
92
|
+
)
|
|
93
|
+
try {
|
|
94
|
+
if (text !== '') {
|
|
95
|
+
for (const chunk of chunkMarkdown(text, 11_500)) await deps.client.sendMessage(msg.chat, chunk, threadTs)
|
|
96
|
+
}
|
|
97
|
+
for (const attachment of attachments) {
|
|
98
|
+
const path = deps.resolvePath ? deps.resolvePath(attachment.path) : attachment.path
|
|
99
|
+
const buffer = await readFile(path)
|
|
100
|
+
const filename = attachment.filename ?? basename(path)
|
|
101
|
+
await deps.client.uploadFile([msg.chat], buffer, filename)
|
|
102
|
+
}
|
|
103
|
+
return { ok: true }
|
|
104
|
+
} catch (err) {
|
|
105
|
+
const message = describe(err)
|
|
106
|
+
deps.logger.error(`[slack] outbound failed: ${message}`)
|
|
107
|
+
return { ok: false, error: message }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function createSlackHistoryCallback(deps: {
|
|
113
|
+
client: Pick<SlackClient, 'getMessages'>
|
|
114
|
+
logger: SlackAdapterLogger
|
|
115
|
+
}): HistoryCallback {
|
|
116
|
+
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
117
|
+
try {
|
|
118
|
+
const messages = await deps.client.getMessages(args.chat, { limit: clampLimit(args.limit, 100) })
|
|
119
|
+
return { ok: true, messages: messages.map(mapSlackHistoryMessage).reverse() }
|
|
120
|
+
} catch (err) {
|
|
121
|
+
const message = describe(err)
|
|
122
|
+
deps.logger.warn(`[slack] history fetch failed: ${message}`)
|
|
123
|
+
return { ok: false, error: message }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createSlackMembershipResolver(deps: {
|
|
129
|
+
client: Pick<SlackClient, 'listChannelMembers'>
|
|
130
|
+
logger: SlackAdapterLogger
|
|
131
|
+
historyCallback: HistoryCallback
|
|
132
|
+
selfUserIdRef: () => string | null
|
|
133
|
+
now?: () => number
|
|
134
|
+
}): MembershipResolver {
|
|
135
|
+
const now = deps.now ?? Date.now
|
|
136
|
+
return async (key): Promise<MembershipResolverResult> => {
|
|
137
|
+
if (key.adapter !== 'slack') return { kind: 'permanent' } satisfies MembershipResolverFailure
|
|
138
|
+
if (key.workspace === '@dm') return { humans: 1, bots: 1, fetchedAt: now(), truncated: false }
|
|
139
|
+
try {
|
|
140
|
+
const members = await deps.client.listChannelMembers(key.chat)
|
|
141
|
+
const capped = members.slice(0, MEMBERSHIP_ENUMERATION_CAP)
|
|
142
|
+
const selfUserId = deps.selfUserIdRef()
|
|
143
|
+
let bots = 0
|
|
144
|
+
const humanMemberIds: string[] = []
|
|
145
|
+
for (const member of capped) {
|
|
146
|
+
if (selfUserId !== null && member === selfUserId) bots++
|
|
147
|
+
else humanMemberIds.push(member)
|
|
148
|
+
}
|
|
149
|
+
const truncated = members.length >= MEMBERSHIP_ENUMERATION_CAP
|
|
150
|
+
if (truncated) return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated }
|
|
151
|
+
return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated, humanMemberIds }
|
|
152
|
+
} catch (err) {
|
|
153
|
+
deps.logger.warn(`[slack] membership channel=${key.chat} failed: ${describe(err)}; deriving from recent history`)
|
|
154
|
+
return await deriveMembershipFromHistory({
|
|
155
|
+
fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
|
|
156
|
+
now,
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function createSlackFetchAttachmentCallback(deps: {
|
|
163
|
+
client: Pick<SlackClient, 'downloadFile'>
|
|
164
|
+
logger: SlackAdapterLogger
|
|
165
|
+
}): FetchAttachmentCallback {
|
|
166
|
+
return async ({ ref, filename }) => {
|
|
167
|
+
try {
|
|
168
|
+
const { buffer, file } = await deps.client.downloadFile(ref)
|
|
169
|
+
return {
|
|
170
|
+
ok: true,
|
|
171
|
+
buffer,
|
|
172
|
+
filename: filename ?? file.name ?? 'attachment',
|
|
173
|
+
mimetype: file.mimetype,
|
|
174
|
+
size: buffer.length,
|
|
175
|
+
}
|
|
176
|
+
} catch (err) {
|
|
177
|
+
const message = describe(err)
|
|
178
|
+
deps.logger.error(`[slack] fetchAttachment failed for ${ref}: ${message}`)
|
|
179
|
+
return { ok: false, error: message }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
185
|
+
const logger = options.logger ?? consoleLogger
|
|
186
|
+
const createClient = options.createClient ?? (() => new SlackClient())
|
|
187
|
+
const createListener = options.createListener ?? ((client) => new SlackListener(client))
|
|
188
|
+
const client = createClient()
|
|
189
|
+
let listener: SlackListener | null = null
|
|
190
|
+
let selfUserId: string | null = null
|
|
191
|
+
let selfName: string | null = null
|
|
192
|
+
let teamId = ''
|
|
193
|
+
let teamName: string | null = null
|
|
194
|
+
let connected = false
|
|
195
|
+
let started = false
|
|
196
|
+
let inflightInbounds = 0
|
|
197
|
+
let stopWaiters: Array<() => void> = []
|
|
198
|
+
|
|
199
|
+
const channelResolver = createSlackChannelResolver({ client, teamNameRef: () => teamName })
|
|
200
|
+
const authorResolver = createSlackAuthorResolver({ client })
|
|
201
|
+
const selfIdentityResolver: ChannelSelfIdentityResolver = () =>
|
|
202
|
+
selfUserId !== null ? { id: selfUserId, username: selfName ?? selfUserId } : null
|
|
203
|
+
const formatChannelTag = async (chat: string): Promise<string> => {
|
|
204
|
+
const names = await channelResolver({ adapter: 'slack', workspace: teamId, chat, thread: null }).catch(
|
|
205
|
+
(): ResolvedChannelNames => ({}),
|
|
206
|
+
)
|
|
207
|
+
const label = names.chatName ?? null
|
|
208
|
+
return label === null || label === chat ? `channel=${chat}` : `channel=${label}(${chat})`
|
|
209
|
+
}
|
|
210
|
+
const historyCallback = createSlackHistoryCallback({ client, logger })
|
|
211
|
+
const membershipResolver = createSlackMembershipResolver({
|
|
212
|
+
client,
|
|
213
|
+
logger,
|
|
214
|
+
historyCallback,
|
|
215
|
+
selfUserIdRef: () => selfUserId,
|
|
216
|
+
})
|
|
217
|
+
const outboundCallback = createSlackOutboundCallback({ client, logger, formatChannelTag })
|
|
218
|
+
const fetchAttachmentCallback = createSlackFetchAttachmentCallback({ client, logger })
|
|
219
|
+
const reactionCallback = createSlackReactionCallback({ client })
|
|
220
|
+
const removeReactionCallback = createSlackRemoveReactionCallback({ client })
|
|
221
|
+
|
|
222
|
+
const handleMessage = async (event: SlackRTMMessageEvent): Promise<void> => {
|
|
223
|
+
inflightInbounds++
|
|
224
|
+
try {
|
|
225
|
+
const tag = await formatChannelTag(event.channel)
|
|
226
|
+
logger.info(
|
|
227
|
+
`[slack] inbound id=${event.ts} author=${event.user ?? '(none)'} ${tag} text_len=${(event.text ?? '').length}`,
|
|
228
|
+
)
|
|
229
|
+
const verdict = classifyInbound(event, options.configRef(), {
|
|
230
|
+
teamId,
|
|
231
|
+
selfUserId,
|
|
232
|
+
selfAliases: options.selfAliasesRef?.() ?? [],
|
|
233
|
+
})
|
|
234
|
+
if (verdict.kind === 'drop') {
|
|
235
|
+
logger.info(`[slack] dropped id=${event.ts} reason=${verdict.reason}${dropHint(verdict.reason)}`)
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
const payload = { ...verdict.payload, authorName: await authorResolver.resolve(verdict.payload.authorId) }
|
|
239
|
+
logger.info(`[slack] routed id=${event.ts} ${tag} mention=${payload.isBotMention}`)
|
|
240
|
+
await options.router.route(payload)
|
|
241
|
+
} catch (err) {
|
|
242
|
+
logger.error(`[slack] handleInbound failed: ${describe(err)}`)
|
|
243
|
+
} finally {
|
|
244
|
+
inflightInbounds--
|
|
245
|
+
if (inflightInbounds === 0 && stopWaiters.length > 0) {
|
|
246
|
+
const waiters = stopWaiters
|
|
247
|
+
stopWaiters = []
|
|
248
|
+
for (const w of waiters) w()
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const handleReaction = (kind: 'added' | 'removed', event: SlackRTMReactionEvent): void => {
|
|
254
|
+
logger.info(`[slack] reaction_${kind} channel=${event.item.channel} ts=${event.item.ts} emoji=${event.reaction}`)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
async start(): Promise<void> {
|
|
259
|
+
if (started) return
|
|
260
|
+
started = true
|
|
261
|
+
try {
|
|
262
|
+
const account = await (options.credentialsStore ?? null)?.getAccount()
|
|
263
|
+
if (account === null || account === undefined) {
|
|
264
|
+
throw new Error('no Slack account in secrets.json#channels.slack (run typeclaw init to authenticate)')
|
|
265
|
+
}
|
|
266
|
+
await client.login({ token: account.token, cookie: account.cookie })
|
|
267
|
+
const auth = await client.testAuth()
|
|
268
|
+
selfUserId = auth.user_id
|
|
269
|
+
selfName = auth.user ?? auth.user_id
|
|
270
|
+
teamId = auth.team_id
|
|
271
|
+
teamName = auth.team ?? account.workspace_name ?? null
|
|
272
|
+
logger.info(`[slack] authenticated as ${selfName} (${selfUserId}) team=${teamName ?? teamId}`)
|
|
273
|
+
} catch (err) {
|
|
274
|
+
started = false
|
|
275
|
+
selfUserId = null
|
|
276
|
+
teamId = ''
|
|
277
|
+
logger.error(`[slack] login failed: ${describe(err)}`)
|
|
278
|
+
throw err
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
listener = createListener(client)
|
|
282
|
+
let listenerConnected = false
|
|
283
|
+
let listenerStartupError: Error | null = null
|
|
284
|
+
listener.on('connected', (info) => {
|
|
285
|
+
listenerConnected = true
|
|
286
|
+
connected = true
|
|
287
|
+
selfUserId = info.self.id
|
|
288
|
+
teamId = info.team.id
|
|
289
|
+
})
|
|
290
|
+
listener.on('disconnected', () => {
|
|
291
|
+
connected = false
|
|
292
|
+
logger.warn('[slack] disconnected')
|
|
293
|
+
})
|
|
294
|
+
listener.on('error', (err) => {
|
|
295
|
+
if (!listenerConnected && listenerStartupError === null) listenerStartupError = err
|
|
296
|
+
logger.error(`[slack] listener error: ${describe(err)}`)
|
|
297
|
+
})
|
|
298
|
+
listener.on('message', (event) => void handleMessage(event))
|
|
299
|
+
listener.on('reaction_added', (event) => handleReaction('added', event))
|
|
300
|
+
listener.on('reaction_removed', (event) => handleReaction('removed', event))
|
|
301
|
+
|
|
302
|
+
options.router.registerOutbound('slack', outboundCallback)
|
|
303
|
+
options.router.setTypingCapability('slack', false)
|
|
304
|
+
options.router.registerChannelNameResolver('slack', channelResolver)
|
|
305
|
+
options.router.registerSelfIdentity('slack', selfIdentityResolver)
|
|
306
|
+
options.router.registerHistory('slack', historyCallback)
|
|
307
|
+
options.router.registerFetchAttachment('slack', fetchAttachmentCallback)
|
|
308
|
+
options.router.registerMembership('slack', membershipResolver)
|
|
309
|
+
options.router.registerReaction('slack', reactionCallback)
|
|
310
|
+
options.router.registerRemoveReaction('slack', removeReactionCallback)
|
|
311
|
+
|
|
312
|
+
const rollbackStart = (reason: string, cause: Error): never => {
|
|
313
|
+
options.router.unregisterOutbound('slack', outboundCallback)
|
|
314
|
+
options.router.setTypingCapability('slack', false)
|
|
315
|
+
options.router.unregisterChannelNameResolver('slack', channelResolver)
|
|
316
|
+
options.router.unregisterSelfIdentity('slack', selfIdentityResolver)
|
|
317
|
+
options.router.unregisterHistory('slack', historyCallback)
|
|
318
|
+
options.router.unregisterFetchAttachment('slack', fetchAttachmentCallback)
|
|
319
|
+
options.router.unregisterMembership('slack', membershipResolver)
|
|
320
|
+
options.router.unregisterReaction('slack', reactionCallback)
|
|
321
|
+
options.router.unregisterRemoveReaction('slack', removeReactionCallback)
|
|
322
|
+
listener?.stop()
|
|
323
|
+
listener = null
|
|
324
|
+
selfUserId = null
|
|
325
|
+
connected = false
|
|
326
|
+
started = false
|
|
327
|
+
logger.error(`[slack] ${reason}: ${describe(cause)}`)
|
|
328
|
+
throw cause
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
try {
|
|
332
|
+
await listener.start()
|
|
333
|
+
} catch (err) {
|
|
334
|
+
rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
|
|
335
|
+
}
|
|
336
|
+
if (!listenerConnected) {
|
|
337
|
+
rollbackStart(
|
|
338
|
+
'listener start failed silently',
|
|
339
|
+
listenerStartupError ?? new Error('listener.start() returned without emitting connected'),
|
|
340
|
+
)
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
|
|
344
|
+
async stop(): Promise<void> {
|
|
345
|
+
if (!started) return
|
|
346
|
+
started = false
|
|
347
|
+
options.router.unregisterOutbound('slack', outboundCallback)
|
|
348
|
+
options.router.setTypingCapability('slack', false)
|
|
349
|
+
options.router.unregisterChannelNameResolver('slack', channelResolver)
|
|
350
|
+
options.router.unregisterSelfIdentity('slack', selfIdentityResolver)
|
|
351
|
+
options.router.unregisterHistory('slack', historyCallback)
|
|
352
|
+
options.router.unregisterFetchAttachment('slack', fetchAttachmentCallback)
|
|
353
|
+
options.router.unregisterMembership('slack', membershipResolver)
|
|
354
|
+
options.router.unregisterReaction('slack', reactionCallback)
|
|
355
|
+
options.router.unregisterRemoveReaction('slack', removeReactionCallback)
|
|
356
|
+
listener?.stop()
|
|
357
|
+
listener = null
|
|
358
|
+
connected = false
|
|
359
|
+
if (inflightInbounds > 0) {
|
|
360
|
+
await new Promise<void>((resolve) => {
|
|
361
|
+
stopWaiters.push(resolve)
|
|
362
|
+
})
|
|
363
|
+
}
|
|
364
|
+
selfUserId = null
|
|
365
|
+
},
|
|
366
|
+
|
|
367
|
+
isConnected(): boolean {
|
|
368
|
+
return started && selfUserId !== null && connected
|
|
369
|
+
},
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async function defaultReadFile(path: string): Promise<Buffer> {
|
|
374
|
+
return Buffer.from(await Bun.file(path).arrayBuffer())
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function mapSlackHistoryMessage(msg: SlackMessage): ChannelHistoryMessage {
|
|
378
|
+
const attachments = (msg.files ?? []).map((file, index) => ({
|
|
379
|
+
id: index + 1,
|
|
380
|
+
kind: 'file' as const,
|
|
381
|
+
ref: file.id,
|
|
382
|
+
filename: file.name,
|
|
383
|
+
mimetype: file.mimetype,
|
|
384
|
+
}))
|
|
385
|
+
return {
|
|
386
|
+
externalMessageId: msg.ts,
|
|
387
|
+
authorId: msg.user ?? msg.username ?? 'unknown',
|
|
388
|
+
authorName: msg.username ?? msg.user ?? 'unknown',
|
|
389
|
+
text: msg.text,
|
|
390
|
+
ts: slackTsToMillis(msg.ts),
|
|
391
|
+
isBot: false,
|
|
392
|
+
replyToBotMessageId: null,
|
|
393
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function clampLimit(requested: number, max: number): number {
|
|
398
|
+
if (!Number.isFinite(requested) || requested <= 0) return max
|
|
399
|
+
return Math.min(Math.floor(requested), max)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function describe(err: unknown): string {
|
|
403
|
+
return err instanceof Error ? err.message : String(err)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function dropHint(reason: InboundDropReason): string {
|
|
407
|
+
switch (reason) {
|
|
408
|
+
case 'empty_text':
|
|
409
|
+
return ' (message had no text)'
|
|
410
|
+
case 'pre_connect':
|
|
411
|
+
case 'self_author':
|
|
412
|
+
case 'no_user':
|
|
413
|
+
case 'slack_system_message':
|
|
414
|
+
return ''
|
|
415
|
+
}
|
|
416
|
+
}
|
|
@@ -260,7 +260,8 @@ export function createOutboundCallback(deps: {
|
|
|
260
260
|
if (replyToId !== undefined) sendOptions.reply_to_message_id = replyToId
|
|
261
261
|
const sent = await client.sendMessage(msg.chat, rendered, sendOptions)
|
|
262
262
|
logger.info(`[telegram-bot] sent message_id=${sent.message_id} ${tag}`)
|
|
263
|
-
|
|
263
|
+
const id = String(sent.message_id)
|
|
264
|
+
return { ok: true, messageId: id, messageIds: [id] }
|
|
264
265
|
} catch (err) {
|
|
265
266
|
const message = describe(err)
|
|
266
267
|
logger.error(`[telegram-bot] sendMessage failed: ${message}`)
|
|
@@ -107,6 +107,7 @@ export function createOutboundCallback(deps: {
|
|
|
107
107
|
|
|
108
108
|
try {
|
|
109
109
|
if (attachments.length > 0) {
|
|
110
|
+
const uploadedRefs: string[] = []
|
|
110
111
|
for (const [index, attachment] of attachments.entries()) {
|
|
111
112
|
const path = resolvePath ? resolvePath(attachment.path) : attachment.path
|
|
112
113
|
const file = await readFile(path)
|
|
@@ -116,14 +117,16 @@ export function createOutboundCallback(deps: {
|
|
|
116
117
|
...(carriesText ? { text } : {}),
|
|
117
118
|
...(parentId !== undefined ? { parentId } : {}),
|
|
118
119
|
})
|
|
120
|
+
uploadedRefs.push(sent.ref)
|
|
119
121
|
logger.info(`[webex-bot] uploaded id=${sent.ref} filename=${file.filename} ${tag}`)
|
|
120
122
|
}
|
|
121
|
-
|
|
123
|
+
// First upload carries the text and is the thread parent, so it is the reply anchor.
|
|
124
|
+
return { ok: true, messageId: uploadedRefs[0], messageIds: uploadedRefs }
|
|
122
125
|
}
|
|
123
126
|
|
|
124
127
|
const sent = await client.sendMessage(msg.chat, text, parentId !== undefined ? { parentId } : undefined)
|
|
125
128
|
logger.info(`[webex-bot] sent id=${sent.ref} ${tag}`)
|
|
126
|
-
return { ok: true }
|
|
129
|
+
return { ok: true, messageId: sent.ref, messageIds: [sent.ref] }
|
|
127
130
|
} catch (err) {
|
|
128
131
|
const message = describe(err)
|
|
129
132
|
logger.error(`[webex-bot] outbound failed: ${message}`)
|