typeclaw 0.44.0 → 0.45.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/package.json +7 -6
- package/src/agent/index.ts +42 -3
- package/src/agent/loop-guard.ts +208 -10
- package/src/agent/model-fallback.ts +59 -40
- package/src/agent/multimodal/look-at.ts +2 -1
- package/src/agent/plugin-tools.ts +59 -5
- package/src/agent/provider-error.ts +78 -18
- package/src/agent/retry-same-ref.ts +205 -0
- package/src/agent/subagents.ts +34 -4
- package/src/agent/tools/channel-edit.ts +144 -0
- package/src/agent/tools/channel-fetch-attachment.ts +6 -5
- package/src/agent/tools/channel-reply.ts +15 -1
- package/src/agent/tools/channel-send.ts +17 -1
- package/src/agent/tools/curl-impersonate.ts +40 -1
- package/src/agent/tools/webfetch/fetch.ts +86 -3
- package/src/agent/tools/webfetch/tool.ts +26 -3
- package/src/agent/tools/webfetch/types.ts +8 -0
- package/src/agent/turn-runner.ts +79 -36
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
- package/src/bundled-plugins/reviewer/skills/code-review.ts +27 -2
- package/src/channels/adapters/discord-bot-edit.ts +49 -0
- package/src/channels/adapters/discord-bot.ts +30 -4
- package/src/channels/adapters/discord-edit.ts +51 -0
- package/src/channels/adapters/discord.ts +4 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +10 -1
- package/src/channels/adapters/kakaotalk-typing.ts +125 -0
- package/src/channels/adapters/kakaotalk.ts +19 -0
- package/src/channels/adapters/slack-bot-edit.ts +58 -0
- package/src/channels/adapters/slack-bot.ts +18 -6
- package/src/channels/adapters/slack-edit.ts +47 -0
- package/src/channels/adapters/slack.ts +5 -0
- package/src/channels/adapters/teams-edit.ts +61 -0
- package/src/channels/adapters/teams.ts +4 -0
- package/src/channels/adapters/telegram-bot-edit.ts +51 -0
- package/src/channels/adapters/telegram-bot.ts +5 -0
- package/src/channels/adapters/webex-bot.ts +5 -0
- package/src/channels/adapters/webex-edit.ts +47 -0
- package/src/channels/adapters/webex.ts +5 -0
- package/src/channels/continuation-willingness.ts +227 -35
- package/src/channels/router.ts +500 -20
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +36 -0
- package/src/run/llm-fetch-observer.ts +147 -9
- package/src/server/command-runner.ts +2 -1
- package/src/server/index.ts +2 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { KakaoTypingResult } from 'agent-messenger/kakaotalk'
|
|
2
|
+
|
|
3
|
+
import type { TypingCallback } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
import { describeError } from './describe-error'
|
|
6
|
+
|
|
7
|
+
export type KakaoTypingLogger = {
|
|
8
|
+
info: (msg: string) => void
|
|
9
|
+
warn: (msg: string) => void
|
|
10
|
+
error: (msg: string) => void
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Emits the LOCO ACTION packet directly from the sub-device session via
|
|
14
|
+
// `KakaoTalkClient.sendTyping` (agent-messenger#302). `type=1` is the value the
|
|
15
|
+
// official app uses for the animated "…" composing indicator; the SDK omits
|
|
16
|
+
// `linkId` unless it's an OpenChat room.
|
|
17
|
+
export type KakaoTypingSender = (chatId: string, opts?: { linkId?: string }) => Promise<KakaoTypingResult>
|
|
18
|
+
|
|
19
|
+
export type KakaoTypingCallbackHandle = {
|
|
20
|
+
callback: TypingCallback
|
|
21
|
+
// Invalidate every in-flight/queued pulse. Called on adapter stop so a pulse
|
|
22
|
+
// already accepted into a per-chat queue cannot reach the wire after teardown.
|
|
23
|
+
reset: () => void
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// KakaoTalk auto-expires the composing indicator ~5s after the last ACTION
|
|
27
|
+
// packet. The router paces the refresh via a heartbeat the adapter registers
|
|
28
|
+
// (setTypingHeartbeatInterval), so this callback holds no timer of its own.
|
|
29
|
+
// 4000ms sits ~20% below the ~5s expiry so a replacement packet lands before
|
|
30
|
+
// expiry even with scheduler/network jitter (a 5000ms interval has no margin).
|
|
31
|
+
export const KAKAO_TYPING_HEARTBEAT_MS = 4000
|
|
32
|
+
|
|
33
|
+
// Per-chat send decision, resolved live at each tick rather than from the
|
|
34
|
+
// (stale) session-key workspace:
|
|
35
|
+
// send — an authoritative DM/group chat; emit the ACTION packet.
|
|
36
|
+
// skip-open — a confirmed OpenChat; the LOCO ACTION needs a `linkId`
|
|
37
|
+
// the resolver does not surface today, so skip (logged once,
|
|
38
|
+
// mirroring markReadIfSupported).
|
|
39
|
+
// skip-unresolved — unknown or provisional entry: the resolver has not yet
|
|
40
|
+
// confirmed the kind (a chat seen on an inbound push but not
|
|
41
|
+
// surfaced by getChats is cached as a strict @kakao-group
|
|
42
|
+
// GUESS). Skip silently — sending could hit an OpenChat
|
|
43
|
+
// without its linkId, and a later refresh upgrades the entry.
|
|
44
|
+
export type KakaoTypingChatClass = 'send' | 'skip-open' | 'skip-unresolved'
|
|
45
|
+
|
|
46
|
+
export function kakaoTypingClassFromLookup(
|
|
47
|
+
lookup: { workspace: string; provisional: boolean } | null,
|
|
48
|
+
): KakaoTypingChatClass {
|
|
49
|
+
if (lookup === null || lookup.provisional) return 'skip-unresolved'
|
|
50
|
+
if (lookup.workspace === '@kakao-open') return 'skip-open'
|
|
51
|
+
return 'send'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createKakaoTypingCallback(deps: {
|
|
55
|
+
logger: KakaoTypingLogger
|
|
56
|
+
sendTyping: KakaoTypingSender
|
|
57
|
+
// Live per-chat classifier — consults the channel resolver at send time so a
|
|
58
|
+
// provisional/unknown room (or one that refreshed into OpenChat after the
|
|
59
|
+
// session key was minted) is suppressed, not judged by the stale target.
|
|
60
|
+
classifyChat: (chatId: string) => KakaoTypingChatClass
|
|
61
|
+
formatChannelTag?: (workspace: string, chat: string) => Promise<string>
|
|
62
|
+
}): KakaoTypingCallbackHandle {
|
|
63
|
+
const { logger, sendTyping, classifyChat, formatChannelTag } = deps
|
|
64
|
+
// Per-chat FIFO mirrors the webex/slack pattern: chaining each request through
|
|
65
|
+
// the per-chat tail keeps on-the-wire order matching enqueue order even under
|
|
66
|
+
// network jitter, so a slow send can't reorder behind a later tick.
|
|
67
|
+
const queues = new Map<string, Promise<void>>()
|
|
68
|
+
// Per-chat generation token, independent of any timer. A pulse captures the
|
|
69
|
+
// chat's generation when it's accepted and re-checks it immediately before
|
|
70
|
+
// sending; 'stop' and `reset` delete the generation, so a pulse already queued
|
|
71
|
+
// behind an in-flight send is dropped instead of raising the indicator after
|
|
72
|
+
// the turn (or the adapter) has stopped.
|
|
73
|
+
const activeGeneration = new Map<string, number>()
|
|
74
|
+
const openChatSkipLogged = new Set<string>()
|
|
75
|
+
let generationCounter = 0
|
|
76
|
+
|
|
77
|
+
const callback: TypingCallback = async (target) => {
|
|
78
|
+
if (target.adapter !== 'kakaotalk') return
|
|
79
|
+
// No stop API: the indicator auto-expires ~5s after the last packet and a
|
|
80
|
+
// delivered message clears it client-side, so 'stop' sends no packet. It
|
|
81
|
+
// must still invalidate any queued pulse for this chat.
|
|
82
|
+
if (target.phase !== 'tick') {
|
|
83
|
+
activeGeneration.delete(target.chat)
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
const chatClass = classifyChat(target.chat)
|
|
87
|
+
if (chatClass !== 'send') {
|
|
88
|
+
if (chatClass === 'skip-open' && !openChatSkipLogged.has(target.chat)) {
|
|
89
|
+
openChatSkipLogged.add(target.chat)
|
|
90
|
+
logger.info(`[kakaotalk:typing] skipped chat=${target.chat} reason=open_chat_link_id_unsupported`)
|
|
91
|
+
}
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!activeGeneration.has(target.chat)) activeGeneration.set(target.chat, ++generationCounter)
|
|
96
|
+
const generation = activeGeneration.get(target.chat)
|
|
97
|
+
const prev = queues.get(target.chat) ?? Promise.resolve()
|
|
98
|
+
const next = prev
|
|
99
|
+
.catch(() => {})
|
|
100
|
+
.then(async () => {
|
|
101
|
+
if (activeGeneration.get(target.chat) !== generation) return
|
|
102
|
+
const result = await sendTyping(target.chat)
|
|
103
|
+
if (!result.success) {
|
|
104
|
+
throw new Error(`kakaotalk ACTION rejected: status_code=${result.status_code}`)
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
.catch(async (err: unknown) => {
|
|
108
|
+
const tag = formatChannelTag
|
|
109
|
+
? await formatChannelTag(target.workspace, target.chat).catch(() => `chat=${target.chat}`)
|
|
110
|
+
: `chat=${target.chat}`
|
|
111
|
+
logger.warn(`[kakaotalk:typing] ${tag} phase=${target.phase} failed: ${describeError(err)}`)
|
|
112
|
+
})
|
|
113
|
+
queues.set(target.chat, next)
|
|
114
|
+
void next.finally(() => {
|
|
115
|
+
if (queues.get(target.chat) === next) queues.delete(target.chat)
|
|
116
|
+
})
|
|
117
|
+
await next
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const reset = (): void => {
|
|
121
|
+
activeGeneration.clear()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return { callback, reset }
|
|
125
|
+
}
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
type KakaoTalkListenerEventMap,
|
|
16
16
|
type KakaoTalkPushEmoticonEvent,
|
|
17
17
|
type KakaoTalkPushMessageEvent,
|
|
18
|
+
type KakaoTypingResult,
|
|
18
19
|
} from 'agent-messenger/kakaotalk'
|
|
19
20
|
import type { KakaoAccountCredentials, KakaoConfig, PendingLoginState } from 'agent-messenger/kakaotalk'
|
|
20
21
|
|
|
@@ -45,6 +46,7 @@ import { classifyInbound, type InboundDropReason } from './kakaotalk-classify'
|
|
|
45
46
|
import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
|
|
46
47
|
import { toKakaoPlainText } from './kakaotalk-format'
|
|
47
48
|
import { createKakaoMembershipResolver } from './kakaotalk-membership'
|
|
49
|
+
import { createKakaoTypingCallback, kakaoTypingClassFromLookup, KAKAO_TYPING_HEARTBEAT_MS } from './kakaotalk-typing'
|
|
48
50
|
|
|
49
51
|
// Structural duck-type of the upstream KakaoTalkClient class. The upstream
|
|
50
52
|
// type is a class with private fields, and TypeScript treats those
|
|
@@ -68,6 +70,7 @@ export interface KakaoTalkClient {
|
|
|
68
70
|
): Promise<KakaoSendResult>
|
|
69
71
|
sendAttachment(chatId: string, attachments: ReadonlyArray<AttachmentInput>): Promise<KakaoSendResult>
|
|
70
72
|
markRead(chatId: string, logId: string, opts?: { linkId?: string }): Promise<KakaoMarkReadResult>
|
|
73
|
+
sendTyping(chatId: string, opts?: { linkId?: string }): Promise<KakaoTypingResult>
|
|
71
74
|
getProfile(): Promise<KakaoProfile>
|
|
72
75
|
getMembers(chatId: string): Promise<KakaoMember[]>
|
|
73
76
|
lookupAuthorName(chatId: string, authorId: number): string | null
|
|
@@ -403,6 +406,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
403
406
|
formatChannelTag,
|
|
404
407
|
})
|
|
405
408
|
|
|
409
|
+
const typing = createKakaoTypingCallback({
|
|
410
|
+
logger,
|
|
411
|
+
sendTyping: (chatId, opts) => client.sendTyping(chatId, opts),
|
|
412
|
+
classifyChat: (chatId) => kakaoTypingClassFromLookup(channelResolver.lookupChat(chatId)),
|
|
413
|
+
formatChannelTag,
|
|
414
|
+
})
|
|
415
|
+
|
|
406
416
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ logger })
|
|
407
417
|
|
|
408
418
|
const handleMessageEvent = async (event: KakaoTalkPushMessageEvent): Promise<void> => {
|
|
@@ -669,6 +679,12 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
669
679
|
// but outboundCallback would still send via a dead client). Stop()
|
|
670
680
|
// unregisters in the inverse order.
|
|
671
681
|
options.router.registerOutbound('kakaotalk', outboundCallback)
|
|
682
|
+
options.router.registerTyping('kakaotalk', typing.callback)
|
|
683
|
+
options.router.setTypingCapability('kakaotalk', true)
|
|
684
|
+
// KakaoTalk expires the indicator ~5s after the last packet, faster than
|
|
685
|
+
// the default 8s heartbeat, so the router paces our refresh at 4s and the
|
|
686
|
+
// callback holds no timer of its own.
|
|
687
|
+
options.router.setTypingHeartbeatInterval('kakaotalk', KAKAO_TYPING_HEARTBEAT_MS)
|
|
672
688
|
options.router.registerChannelNameResolver('kakaotalk', channelResolver.resolve)
|
|
673
689
|
options.router.registerHistory('kakaotalk', historyCallback)
|
|
674
690
|
options.router.registerFetchAttachment('kakaotalk', fetchAttachmentCallback)
|
|
@@ -679,6 +695,9 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
679
695
|
if (!started) return
|
|
680
696
|
started = false
|
|
681
697
|
options.router.unregisterOutbound('kakaotalk', outboundCallback)
|
|
698
|
+
options.router.unregisterTyping('kakaotalk', typing.callback)
|
|
699
|
+
options.router.setTypingCapability('kakaotalk', false)
|
|
700
|
+
typing.reset()
|
|
682
701
|
options.router.unregisterChannelNameResolver('kakaotalk', channelResolver.resolve)
|
|
683
702
|
options.router.unregisterHistory('kakaotalk', historyCallback)
|
|
684
703
|
options.router.unregisterFetchAttachment('kakaotalk', fetchAttachmentCallback)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { SlackBotClient } from 'agent-messenger/slackbot'
|
|
2
|
+
|
|
3
|
+
import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
export function createSlackEditMessageCallback(deps: {
|
|
6
|
+
client: Pick<SlackBotClient, 'updateMessage'>
|
|
7
|
+
}): EditMessageCallback {
|
|
8
|
+
return async (req): Promise<EditMessageResult> => {
|
|
9
|
+
if (req.adapter !== 'slack-bot') {
|
|
10
|
+
return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
await deps.client.updateMessage(req.chat, req.messageId, req.text)
|
|
14
|
+
} catch (err) {
|
|
15
|
+
const code = slackErrorCode(err)
|
|
16
|
+
return { ok: false, error: withScopeHint(code, describe(err)), code: classifyEditError(code) }
|
|
17
|
+
}
|
|
18
|
+
return { ok: true }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function slackErrorCode(err: unknown): string | null {
|
|
23
|
+
if (typeof err === 'object' && err !== null && 'code' in err) {
|
|
24
|
+
const code = (err as { code: unknown }).code
|
|
25
|
+
if (typeof code === 'string') return code
|
|
26
|
+
}
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// `chat:write` is the scope the bot token needs to edit its own messages;
|
|
31
|
+
// `cant_update_message` fires when the bot did not author the target, and
|
|
32
|
+
// `message_not_found` when the ts is wrong or the post is gone.
|
|
33
|
+
function withScopeHint(code: string | null, error: string): string {
|
|
34
|
+
if (code !== 'missing_scope') return error
|
|
35
|
+
return `${error} (Slack bot token needs the \`chat:write\` scope; reinstall/reauthorize the app with that scope.)`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function classifyEditError(code: string | null): NonNullable<(EditMessageResult & { ok: false })['code']> {
|
|
39
|
+
switch (code) {
|
|
40
|
+
case 'message_not_found':
|
|
41
|
+
case 'channel_not_found':
|
|
42
|
+
return 'not-found'
|
|
43
|
+
case 'cant_update_message':
|
|
44
|
+
case 'edit_window_closed':
|
|
45
|
+
case 'missing_scope':
|
|
46
|
+
case 'not_in_channel':
|
|
47
|
+
case 'is_archived':
|
|
48
|
+
case 'not_authed':
|
|
49
|
+
case 'invalid_auth':
|
|
50
|
+
return 'permission-denied'
|
|
51
|
+
default:
|
|
52
|
+
return 'not-found'
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function describe(err: unknown): string {
|
|
57
|
+
return err instanceof Error ? err.message : String(err)
|
|
58
|
+
}
|
|
@@ -53,6 +53,7 @@ import {
|
|
|
53
53
|
type SlackInboundMessageEvent,
|
|
54
54
|
} from './slack-bot-classify'
|
|
55
55
|
import { createSlackDedupe } from './slack-bot-dedupe'
|
|
56
|
+
import { createSlackEditMessageCallback } from './slack-bot-edit'
|
|
56
57
|
import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-bot-reactions'
|
|
57
58
|
import { enrichSlackReferenceContext } from './slack-bot-reference'
|
|
58
59
|
import {
|
|
@@ -210,22 +211,29 @@ export function createThreadCommandHandler(
|
|
|
210
211
|
`[slack-bot] thread-command !${command.name} invoker=${command.invokerId} team=${command.key.workspace} channel=${command.key.chat} thread=${command.key.thread ?? '(none)'}`,
|
|
211
212
|
)
|
|
212
213
|
|
|
213
|
-
|
|
214
|
+
// null = stay silent. A shared Slack channel can host many agents; each one
|
|
215
|
+
// receives this message and runs its own executeCommand. Only the agent that
|
|
216
|
+
// actually had a running turn gets 'handled'; every bystander gets
|
|
217
|
+
// 'no-live-session'. Posting "Nothing to stop" from each bystander would spam
|
|
218
|
+
// the thread, so a no-live-session outcome posts nothing at all.
|
|
219
|
+
let reply: string | null
|
|
214
220
|
try {
|
|
215
221
|
const result = await deps.router.executeCommand(command.key, command.name, {
|
|
216
222
|
invokerId: command.invokerId,
|
|
217
223
|
})
|
|
218
|
-
reply = commandResultReply(result)
|
|
224
|
+
reply = result.kind === 'no-live-session' ? null : commandResultReply(result)
|
|
219
225
|
deps.logger.info(`[slack-bot] thread-command !${command.name} result=${result.kind}`)
|
|
220
226
|
} catch (err) {
|
|
221
227
|
deps.logger.error(`[slack-bot] thread-command !${command.name} failed: ${describeError(err)}`)
|
|
222
228
|
reply = SLACK_SLASH_REPLY_FAILED
|
|
223
229
|
}
|
|
224
230
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
231
|
+
if (reply !== null) {
|
|
232
|
+
try {
|
|
233
|
+
await deps.postReply({ chat: input.channel, thread: input.threadTs, text: reply })
|
|
234
|
+
} catch (err) {
|
|
235
|
+
deps.logger.warn(`[slack-bot] thread-command reply post failed: ${describeError(err)}`)
|
|
236
|
+
}
|
|
229
237
|
}
|
|
230
238
|
return { kind: 'executed' }
|
|
231
239
|
}
|
|
@@ -1180,6 +1188,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1180
1188
|
|
|
1181
1189
|
const reactionCallback = createSlackReactionCallback({ client })
|
|
1182
1190
|
const removeReactionCallback = createSlackRemoveReactionCallback({ client })
|
|
1191
|
+
const editMessageCallback = createSlackEditMessageCallback({ client })
|
|
1183
1192
|
|
|
1184
1193
|
const dedupe = createSlackDedupe()
|
|
1185
1194
|
|
|
@@ -1400,6 +1409,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1400
1409
|
options.router.registerHistory('slack-bot', historyCallback)
|
|
1401
1410
|
options.router.registerMessageGet('slack-bot', messageGetCallback)
|
|
1402
1411
|
options.router.registerList('slack-bot', listCallback)
|
|
1412
|
+
options.router.registerEditMessage('slack-bot', editMessageCallback)
|
|
1403
1413
|
options.router.registerFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1404
1414
|
options.router.registerMembership('slack-bot', membershipResolver)
|
|
1405
1415
|
|
|
@@ -1420,6 +1430,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1420
1430
|
options.router.unregisterHistory('slack-bot', historyCallback)
|
|
1421
1431
|
options.router.unregisterMessageGet('slack-bot', messageGetCallback)
|
|
1422
1432
|
options.router.unregisterList('slack-bot', listCallback)
|
|
1433
|
+
options.router.unregisterEditMessage('slack-bot', editMessageCallback)
|
|
1423
1434
|
options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1424
1435
|
options.router.unregisterMembership('slack-bot', membershipResolver)
|
|
1425
1436
|
listener = null
|
|
@@ -1444,6 +1455,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1444
1455
|
options.router.unregisterHistory('slack-bot', historyCallback)
|
|
1445
1456
|
options.router.unregisterMessageGet('slack-bot', messageGetCallback)
|
|
1446
1457
|
options.router.unregisterList('slack-bot', listCallback)
|
|
1458
|
+
options.router.unregisterEditMessage('slack-bot', editMessageCallback)
|
|
1447
1459
|
options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1448
1460
|
options.router.unregisterMembership('slack-bot', membershipResolver)
|
|
1449
1461
|
if (inflightInbounds > 0) {
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { SlackClient } from 'agent-messenger/slack'
|
|
2
|
+
|
|
3
|
+
import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
export function createSlackUserEditMessageCallback(deps: {
|
|
6
|
+
client: Pick<SlackClient, 'updateMessage'>
|
|
7
|
+
}): EditMessageCallback {
|
|
8
|
+
return async (req): Promise<EditMessageResult> => {
|
|
9
|
+
if (req.adapter !== 'slack') {
|
|
10
|
+
return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
await deps.client.updateMessage(req.chat, req.messageId, req.text)
|
|
14
|
+
} catch (err) {
|
|
15
|
+
const code = slackErrorCode(err)
|
|
16
|
+
return { ok: false, error: describe(err), code: classifyEditError(code) }
|
|
17
|
+
}
|
|
18
|
+
return { ok: true }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function slackErrorCode(err: unknown): string | null {
|
|
23
|
+
if (typeof err === 'object' && err !== null && 'code' in err) {
|
|
24
|
+
const code = (err as { code: unknown }).code
|
|
25
|
+
if (typeof code === 'string') return code
|
|
26
|
+
}
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function classifyEditError(code: string | null): NonNullable<(EditMessageResult & { ok: false })['code']> {
|
|
31
|
+
switch (code) {
|
|
32
|
+
case 'message_not_found':
|
|
33
|
+
case 'channel_not_found':
|
|
34
|
+
return 'not-found'
|
|
35
|
+
case 'cant_update_message':
|
|
36
|
+
case 'edit_window_closed':
|
|
37
|
+
case 'not_authed':
|
|
38
|
+
case 'invalid_auth':
|
|
39
|
+
return 'permission-denied'
|
|
40
|
+
default:
|
|
41
|
+
return 'not-found'
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function describe(err: unknown): string {
|
|
46
|
+
return err instanceof Error ? err.message : String(err)
|
|
47
|
+
}
|
|
@@ -37,6 +37,7 @@ import { createSlackAuthorResolver } from './slack-author-resolver'
|
|
|
37
37
|
import { slackTsToMillis } from './slack-bot-time'
|
|
38
38
|
import { createSlackChannelResolver } from './slack-channel-resolver'
|
|
39
39
|
import { classifyInbound, type InboundDropReason } from './slack-classify'
|
|
40
|
+
import { createSlackUserEditMessageCallback } from './slack-edit'
|
|
40
41
|
import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-reactions'
|
|
41
42
|
|
|
42
43
|
export type SlackAdapterLogger = {
|
|
@@ -223,6 +224,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
|
223
224
|
const fetchAttachmentCallback = createSlackFetchAttachmentCallback({ client, logger })
|
|
224
225
|
const reactionCallback = createSlackReactionCallback({ client })
|
|
225
226
|
const removeReactionCallback = createSlackRemoveReactionCallback({ client })
|
|
227
|
+
const editMessageCallback = createSlackUserEditMessageCallback({ client })
|
|
226
228
|
|
|
227
229
|
const handleMessage = async (event: SlackRTMMessageEvent): Promise<void> => {
|
|
228
230
|
inflightInbounds++
|
|
@@ -339,6 +341,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
|
339
341
|
options.router.registerMembership('slack', membershipResolver)
|
|
340
342
|
options.router.registerReaction('slack', reactionCallback)
|
|
341
343
|
options.router.registerRemoveReaction('slack', removeReactionCallback)
|
|
344
|
+
options.router.registerEditMessage('slack', editMessageCallback)
|
|
342
345
|
|
|
343
346
|
const rollbackStart = (reason: string, cause: Error): never => {
|
|
344
347
|
options.router.unregisterOutbound('slack', outboundCallback)
|
|
@@ -350,6 +353,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
|
350
353
|
options.router.unregisterMembership('slack', membershipResolver)
|
|
351
354
|
options.router.unregisterReaction('slack', reactionCallback)
|
|
352
355
|
options.router.unregisterRemoveReaction('slack', removeReactionCallback)
|
|
356
|
+
options.router.unregisterEditMessage('slack', editMessageCallback)
|
|
353
357
|
clearTimeout(startupTimer)
|
|
354
358
|
listener?.stop()
|
|
355
359
|
listener = null
|
|
@@ -381,6 +385,7 @@ export function createSlackAdapter(options: SlackAdapterOptions): SlackAdapter {
|
|
|
381
385
|
options.router.unregisterMembership('slack', membershipResolver)
|
|
382
386
|
options.router.unregisterReaction('slack', reactionCallback)
|
|
383
387
|
options.router.unregisterRemoveReaction('slack', removeReactionCallback)
|
|
388
|
+
options.router.unregisterEditMessage('slack', editMessageCallback)
|
|
384
389
|
listener?.stop()
|
|
385
390
|
listener = null
|
|
386
391
|
connected = false
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { TeamsClient } from 'agent-messenger/teams'
|
|
2
|
+
|
|
3
|
+
import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
import { decodeTeamsConversationKey } from './teams-key'
|
|
6
|
+
|
|
7
|
+
// The Teams user-account SDK only exposes an edit primitive for 1:1/group
|
|
8
|
+
// chats (`PUT /users/ME/conversations/{chatId}/messages/{messageId}`); there is
|
|
9
|
+
// no equivalent for team/channel posts. So a channel-keyed edit is genuinely
|
|
10
|
+
// `not-supported`, distinct from an undecodable id (soft `not-found`).
|
|
11
|
+
export function createTeamsEditMessageCallback(deps: {
|
|
12
|
+
client: Pick<TeamsClient, 'editChatMessage'>
|
|
13
|
+
}): EditMessageCallback {
|
|
14
|
+
return async (req): Promise<EditMessageResult> => {
|
|
15
|
+
if (req.adapter !== 'teams') {
|
|
16
|
+
return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
|
|
17
|
+
}
|
|
18
|
+
const decoded = decodeTeamsConversationKey(req.chat)
|
|
19
|
+
if (decoded === null) {
|
|
20
|
+
return { ok: false, error: `unsupported Teams conversation id: ${req.chat}`, code: 'not-found' }
|
|
21
|
+
}
|
|
22
|
+
if (decoded.kind !== 'chat') {
|
|
23
|
+
return { ok: false, error: 'Teams channel messages cannot be edited', code: 'not-supported' }
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text)
|
|
27
|
+
} catch (err) {
|
|
28
|
+
return { ok: false, error: describe(err), code: classifyEditError(err) }
|
|
29
|
+
}
|
|
30
|
+
return { ok: true }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// TeamsError carries its identifier on `.code` (a string), not a numeric
|
|
35
|
+
// `.status`: the request path throws `TeamsError(msg, errorBody.code ?? http_<status>)`,
|
|
36
|
+
// so a forbidden edit surfaces as `http_403`/`http_401` and an auth failure as
|
|
37
|
+
// `token_expired`/`not_authenticated`. Everything else (e.g. `http_404` for a
|
|
38
|
+
// gone/foreign message) is a soft miss.
|
|
39
|
+
function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
|
|
40
|
+
switch (errorCode(err)) {
|
|
41
|
+
case 'http_403':
|
|
42
|
+
case 'http_401':
|
|
43
|
+
case 'token_expired':
|
|
44
|
+
case 'not_authenticated':
|
|
45
|
+
return 'permission-denied'
|
|
46
|
+
default:
|
|
47
|
+
return 'not-found'
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function errorCode(err: unknown): string | null {
|
|
52
|
+
if (typeof err === 'object' && err !== null && 'code' in err) {
|
|
53
|
+
const code = (err as { code: unknown }).code
|
|
54
|
+
if (typeof code === 'string') return code
|
|
55
|
+
}
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function describe(err: unknown): string {
|
|
60
|
+
return err instanceof Error ? err.message : String(err)
|
|
61
|
+
}
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
type InboundDropReason,
|
|
24
24
|
type TeamsInboundEvent,
|
|
25
25
|
} from './teams-classify'
|
|
26
|
+
import { createTeamsEditMessageCallback } from './teams-edit'
|
|
26
27
|
import { ContainerTeamsClient } from './teams-id-token'
|
|
27
28
|
import { decodeTeamsConversationKey } from './teams-key'
|
|
28
29
|
|
|
@@ -197,6 +198,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
|
|
|
197
198
|
|
|
198
199
|
const outboundCallback = createOutboundCallback({ client, logger, reserveEcho })
|
|
199
200
|
const historyCallback = createTeamsHistoryCallback({ client, logger, selfIdRef: () => self?.id ?? null })
|
|
201
|
+
const editMessageCallback = createTeamsEditMessageCallback({ client })
|
|
200
202
|
|
|
201
203
|
const refreshChats = async (): Promise<void> => {
|
|
202
204
|
const chats = await client.listChats()
|
|
@@ -309,6 +311,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
|
|
|
309
311
|
options.router.registerOutbound('teams', outboundCallback)
|
|
310
312
|
options.router.registerSelfIdentity('teams', selfIdentityResolver)
|
|
311
313
|
options.router.registerHistory('teams', historyCallback)
|
|
314
|
+
options.router.registerEditMessage('teams', editMessageCallback)
|
|
312
315
|
|
|
313
316
|
listener = createListener(client)
|
|
314
317
|
const activeListener = listener
|
|
@@ -380,6 +383,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
|
|
|
380
383
|
options.router.unregisterOutbound('teams', outboundCallback)
|
|
381
384
|
options.router.unregisterSelfIdentity('teams', selfIdentityResolver)
|
|
382
385
|
options.router.unregisterHistory('teams', historyCallback)
|
|
386
|
+
options.router.unregisterEditMessage('teams', editMessageCallback)
|
|
383
387
|
listener?.stop()
|
|
384
388
|
listener = null
|
|
385
389
|
if (inflightInbounds > 0) {
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { TelegramBotClient } from 'agent-messenger/telegrambot'
|
|
2
|
+
|
|
3
|
+
import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
import { toTelegramMarkdownV2 } from './telegram-bot-format'
|
|
6
|
+
|
|
7
|
+
export function createTelegramEditMessageCallback(deps: {
|
|
8
|
+
client: Pick<TelegramBotClient, 'editMessageText'>
|
|
9
|
+
}): EditMessageCallback {
|
|
10
|
+
return async (req): Promise<EditMessageResult> => {
|
|
11
|
+
if (req.adapter !== 'telegram-bot') {
|
|
12
|
+
return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
|
|
13
|
+
}
|
|
14
|
+
// A telegram message id is numeric; the router carries it as the string the
|
|
15
|
+
// send handed back (String(message_id)). A non-numeric value can't address
|
|
16
|
+
// any message, so it's a not-found miss rather than an API round-trip.
|
|
17
|
+
const messageId = Number(req.messageId)
|
|
18
|
+
if (!Number.isInteger(messageId)) {
|
|
19
|
+
return { ok: false, error: `non-numeric telegram message id: ${req.messageId}`, code: 'not-found' }
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
// Render + escape through the SAME MarkdownV2 pipeline the send path uses,
|
|
23
|
+
// and pass the same parse_mode — otherwise an edit would show literal
|
|
24
|
+
// markdown where the original send rendered it (or fail on unescaped
|
|
25
|
+
// reserved chars). Keeps a sent message and its later edit visually identical.
|
|
26
|
+
const rendered = toTelegramMarkdownV2(req.text)
|
|
27
|
+
await deps.client.editMessageText({ chat_id: req.chat, message_id: messageId }, rendered, {
|
|
28
|
+
parse_mode: 'MarkdownV2',
|
|
29
|
+
})
|
|
30
|
+
} catch (err) {
|
|
31
|
+
// "message is not modified" fires when the new text equals the current
|
|
32
|
+
// body — the desired end state already holds, so treat it as success
|
|
33
|
+
// (idempotent), mirroring the reaction adapters' already-in-state handling.
|
|
34
|
+
if (describe(err).toLowerCase().includes('message is not modified')) return { ok: true }
|
|
35
|
+
return { ok: false, error: describe(err), code: classifyEditError(err) }
|
|
36
|
+
}
|
|
37
|
+
return { ok: true }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// "message to edit not found" / "message can't be edited" (too old) map to
|
|
42
|
+
// not-found; a chat-permission error to permission-denied.
|
|
43
|
+
function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
|
|
44
|
+
const message = describe(err).toLowerCase()
|
|
45
|
+
if (message.includes('not enough rights') || message.includes('forbidden')) return 'permission-denied'
|
|
46
|
+
return 'not-found'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function describe(err: unknown): string {
|
|
50
|
+
return err instanceof Error ? err.message : String(err)
|
|
51
|
+
}
|
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
|
|
19
19
|
import { describeError } from './describe-error'
|
|
20
20
|
import { classifyInbound, type InboundDropReason, TELEGRAM_WORKSPACE } from './telegram-bot-classify'
|
|
21
|
+
import { createTelegramEditMessageCallback } from './telegram-bot-edit'
|
|
21
22
|
import { toTelegramMarkdownV2 } from './telegram-bot-format'
|
|
22
23
|
|
|
23
24
|
export const TELEGRAM_API_BASE = 'https://api.telegram.org'
|
|
@@ -420,6 +421,7 @@ export function createTelegramBotAdapter(options: TelegramBotAdapterOptions): Te
|
|
|
420
421
|
})
|
|
421
422
|
|
|
422
423
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger })
|
|
424
|
+
const editMessageCallback = createTelegramEditMessageCallback({ client })
|
|
423
425
|
|
|
424
426
|
const handleMessage = async (event: TelegramMessage): Promise<void> => {
|
|
425
427
|
inflightInbounds++
|
|
@@ -536,6 +538,7 @@ export function createTelegramBotAdapter(options: TelegramBotAdapterOptions): Te
|
|
|
536
538
|
options.router.registerSelfIdentity('telegram-bot', selfIdentityResolver)
|
|
537
539
|
options.router.registerFetchAttachment('telegram-bot', fetchAttachmentCallback)
|
|
538
540
|
options.router.registerMembership('telegram-bot', membershipResolver)
|
|
541
|
+
options.router.registerEditMessage('telegram-bot', editMessageCallback)
|
|
539
542
|
|
|
540
543
|
const rollbackStart = (reason: string, cause: Error): never => {
|
|
541
544
|
options.router.unregisterOutbound('telegram-bot', outboundCallback)
|
|
@@ -545,6 +548,7 @@ export function createTelegramBotAdapter(options: TelegramBotAdapterOptions): Te
|
|
|
545
548
|
options.router.unregisterSelfIdentity('telegram-bot', selfIdentityResolver)
|
|
546
549
|
options.router.unregisterFetchAttachment('telegram-bot', fetchAttachmentCallback)
|
|
547
550
|
options.router.unregisterMembership('telegram-bot', membershipResolver)
|
|
551
|
+
options.router.unregisterEditMessage('telegram-bot', editMessageCallback)
|
|
548
552
|
listener?.stop()
|
|
549
553
|
listener = null
|
|
550
554
|
botUser = null
|
|
@@ -574,6 +578,7 @@ export function createTelegramBotAdapter(options: TelegramBotAdapterOptions): Te
|
|
|
574
578
|
options.router.unregisterSelfIdentity('telegram-bot', selfIdentityResolver)
|
|
575
579
|
options.router.unregisterFetchAttachment('telegram-bot', fetchAttachmentCallback)
|
|
576
580
|
options.router.unregisterMembership('telegram-bot', membershipResolver)
|
|
581
|
+
options.router.unregisterEditMessage('telegram-bot', editMessageCallback)
|
|
577
582
|
// Stop the listener BEFORE waiting for inflight handlers. The SDK's
|
|
578
583
|
// `stop()` aborts the in-flight `getUpdates` long-poll and
|
|
579
584
|
// increments its generation counter so any pending dispatch is
|
|
@@ -33,6 +33,7 @@ import { describeError } from './describe-error'
|
|
|
33
33
|
import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
|
|
34
34
|
import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
|
|
35
35
|
import { enrichWebexMessageReference } from './webex-bot-reference'
|
|
36
|
+
import { createWebexEditMessageCallback } from './webex-edit'
|
|
36
37
|
import { resolveWebexBodyText } from './webex-format'
|
|
37
38
|
import { createWebexPrefetchLimiter, isWebexRateLimitError, type WebexPrefetchLimiter } from './webex-prefetch-limiter'
|
|
38
39
|
|
|
@@ -312,6 +313,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
|
|
|
312
313
|
})
|
|
313
314
|
const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
|
|
314
315
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger, fetchImpl })
|
|
316
|
+
const editMessageCallback = createWebexEditMessageCallback({ adapter: 'webex-bot', client })
|
|
315
317
|
|
|
316
318
|
const handleMessage = async (event: WebexInboundMessage): Promise<void> => {
|
|
317
319
|
inflightInbounds++
|
|
@@ -395,6 +397,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
|
|
|
395
397
|
options.router.registerHistory('webex-bot', historyCallback)
|
|
396
398
|
options.router.registerFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
397
399
|
options.router.registerMembership('webex-bot', membershipResolver)
|
|
400
|
+
options.router.registerEditMessage('webex-bot', editMessageCallback)
|
|
398
401
|
|
|
399
402
|
const rollbackStart = (reason: string, cause: Error): never => {
|
|
400
403
|
options.router.unregisterOutbound('webex-bot', outboundCallback)
|
|
@@ -403,6 +406,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
|
|
|
403
406
|
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
404
407
|
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
405
408
|
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
409
|
+
options.router.unregisterEditMessage('webex-bot', editMessageCallback)
|
|
406
410
|
listener?.stop()
|
|
407
411
|
listener = null
|
|
408
412
|
botPerson = null
|
|
@@ -434,6 +438,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
|
|
|
434
438
|
options.router.unregisterHistory('webex-bot', historyCallback)
|
|
435
439
|
options.router.unregisterFetchAttachment('webex-bot', fetchAttachmentCallback)
|
|
436
440
|
options.router.unregisterMembership('webex-bot', membershipResolver)
|
|
441
|
+
options.router.unregisterEditMessage('webex-bot', editMessageCallback)
|
|
437
442
|
listener?.stop()
|
|
438
443
|
listener = null
|
|
439
444
|
connected = false
|