typeclaw 0.43.1 → 0.45.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.
Files changed (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
@@ -0,0 +1,49 @@
1
+ import type { DiscordBotClient } from 'agent-messenger/discordbot'
2
+
3
+ import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
+
5
+ export function createDiscordEditMessageCallback(deps: {
6
+ client: Pick<DiscordBotClient, 'editMessage'>
7
+ }): EditMessageCallback {
8
+ return async (req): Promise<EditMessageResult> => {
9
+ if (req.adapter !== 'discord-bot') {
10
+ return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
11
+ }
12
+ // A Discord thread is its own channel id, so a message posted into a thread
13
+ // must be PATCHed against the thread, not its parent — mirroring the
14
+ // `thread ?? chat` routing the send/message-get paths use. Editing against
15
+ // `chat` alone would 404 on any threaded message.
16
+ const channelId = req.thread ?? req.chat
17
+ try {
18
+ await deps.client.editMessage(channelId, req.messageId, req.text)
19
+ } catch (err) {
20
+ return { ok: false, error: describe(err), code: classifyEditError(err) }
21
+ }
22
+ return { ok: true }
23
+ }
24
+ }
25
+
26
+ // Discord only lets a bot edit its OWN messages: a PATCH on someone else's
27
+ // message returns 50005 (Cannot edit a message authored by another user),
28
+ // mapped to permission-denied. 10008/10003 are the gone-message/channel cases.
29
+ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
30
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : ''
31
+ switch (code) {
32
+ case '10003': // Unknown Channel
33
+ case '10008': // Unknown Message
34
+ case 'http_404':
35
+ return 'not-found'
36
+ case '50005': // Cannot edit a message authored by another user
37
+ case '50001': // Missing Access
38
+ case '50013': // Missing Permissions
39
+ case 'http_403':
40
+ case 'http_401':
41
+ return 'permission-denied'
42
+ default:
43
+ return 'not-found'
44
+ }
45
+ }
46
+
47
+ function describe(err: unknown): string {
48
+ return err instanceof Error ? err.message : String(err)
49
+ }
@@ -48,6 +48,7 @@ import {
48
48
  type InboundDropReason,
49
49
  renderPlaceholder,
50
50
  } from './discord-bot-classify'
51
+ import { createDiscordEditMessageCallback } from './discord-bot-edit'
51
52
  import { convertDiscordTables } from './discord-bot-format'
52
53
  import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-bot-reactions'
53
54
  import { enrichDiscordMessageReferences } from './discord-bot-reference'
@@ -1078,6 +1079,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1078
1079
 
1079
1080
  const reactionCallback = createDiscordReactionCallback({ client })
1080
1081
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
1082
+ const editMessageCallback = createDiscordEditMessageCallback({ client })
1081
1083
 
1082
1084
  const interactionHandler = createInteractionHandler({
1083
1085
  router: options.router,
@@ -1231,6 +1233,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1231
1233
  options.router.registerHistory('discord-bot', historyCallback)
1232
1234
  options.router.registerMessageGet('discord-bot', messageGetCallback)
1233
1235
  options.router.registerList('discord-bot', listCallback)
1236
+ options.router.registerEditMessage('discord-bot', editMessageCallback)
1234
1237
  options.router.registerFetchAttachment('discord-bot', fetchAttachmentCallback)
1235
1238
  options.router.registerMembership('discord-bot', membershipResolver)
1236
1239
 
@@ -1251,6 +1254,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1251
1254
  options.router.unregisterHistory('discord-bot', historyCallback)
1252
1255
  options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1253
1256
  options.router.unregisterList('discord-bot', listCallback)
1257
+ options.router.unregisterEditMessage('discord-bot', editMessageCallback)
1254
1258
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1255
1259
  options.router.unregisterMembership('discord-bot', membershipResolver)
1256
1260
  listener = null
@@ -1274,6 +1278,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1274
1278
  options.router.unregisterHistory('discord-bot', historyCallback)
1275
1279
  options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1276
1280
  options.router.unregisterList('discord-bot', listCallback)
1281
+ options.router.unregisterEditMessage('discord-bot', editMessageCallback)
1277
1282
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1278
1283
  options.router.unregisterMembership('discord-bot', membershipResolver)
1279
1284
  if (inflightInbounds > 0) {
@@ -0,0 +1,51 @@
1
+ import type { DiscordClient } from 'agent-messenger/discord'
2
+
3
+ import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
+
5
+ export function createDiscordUserEditMessageCallback(deps: {
6
+ client: Pick<DiscordClient, 'editMessage'>
7
+ }): EditMessageCallback {
8
+ return async (req): Promise<EditMessageResult> => {
9
+ if (req.adapter !== 'discord') {
10
+ return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'not-supported' }
11
+ }
12
+ // A Discord thread is its own channel id, so a message posted into a thread
13
+ // must be PATCHed against the thread, not its parent — mirroring the
14
+ // `thread ?? chat` routing the send/message-get paths use. Editing against
15
+ // `chat` alone would 404 on any threaded message.
16
+ const channelId = req.thread ?? req.chat
17
+ try {
18
+ await deps.client.editMessage(channelId, req.messageId, req.text)
19
+ } catch (err) {
20
+ return { ok: false, error: describe(err), code: classifyEditError(err) }
21
+ }
22
+ return { ok: true }
23
+ }
24
+ }
25
+
26
+ // Discord only lets you edit your OWN messages: a PATCH on someone else's
27
+ // message returns 50005 (Cannot edit a message authored by another user),
28
+ // mapped to permission-denied. 10008/10003 are the gone-message/channel cases.
29
+ // The user client throws DiscordError with the Discord API error code, or
30
+ // `http_<status>` when the body carries no code (same shape as discord-bot).
31
+ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok: false })['code']> {
32
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : ''
33
+ switch (code) {
34
+ case '10003': // Unknown Channel
35
+ case '10008': // Unknown Message
36
+ case 'http_404':
37
+ return 'not-found'
38
+ case '50005': // Cannot edit a message authored by another user
39
+ case '50001': // Missing Access
40
+ case '50013': // Missing Permissions
41
+ case 'http_403':
42
+ case 'http_401':
43
+ return 'permission-denied'
44
+ default:
45
+ return 'not-found'
46
+ }
47
+ }
48
+
49
+ function describe(err: unknown): string {
50
+ return err instanceof Error ? err.message : String(err)
51
+ }
@@ -28,6 +28,7 @@ import { describeError } from './describe-error'
28
28
  import { createDiscordAuthorResolver } from './discord-author-resolver'
29
29
  import { createDiscordChannelResolver } from './discord-channel-resolver'
30
30
  import { classifyInbound, type InboundDropReason } from './discord-classify'
31
+ import { createDiscordUserEditMessageCallback } from './discord-edit'
31
32
  import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-reactions'
32
33
 
33
34
  export type DiscordAdapterLogger = {
@@ -215,6 +216,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
215
216
  })
216
217
  const reactionCallback = createDiscordReactionCallback({ client })
217
218
  const removeReactionCallback = createDiscordRemoveReactionCallback({ client })
219
+ const editMessageCallback = createDiscordUserEditMessageCallback({ client })
218
220
 
219
221
  const handleMessage = async (event: DiscordGatewayMessageCreateEvent): Promise<void> => {
220
222
  inflightInbounds++
@@ -367,6 +369,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
367
369
  router.registerMembership('discord', membershipResolver)
368
370
  router.registerReaction('discord', reactionCallback)
369
371
  router.registerRemoveReaction('discord', removeReactionCallback)
372
+ router.registerEditMessage('discord', editMessageCallback)
370
373
  }
371
374
 
372
375
  function unregisterCallbacks(router: ChannelRouter): void {
@@ -379,6 +382,7 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
379
382
  router.unregisterMembership('discord', membershipResolver)
380
383
  router.unregisterReaction('discord', reactionCallback)
381
384
  router.unregisterRemoveReaction('discord', removeReactionCallback)
385
+ router.unregisterEditMessage('discord', editMessageCallback)
382
386
  }
383
387
  }
384
388
 
@@ -10,7 +10,7 @@ import type { DeliveryDedup } from './dedup'
10
10
  import { isGithubEventAllowed } from './event-allowlist'
11
11
  import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
12
12
  import { fetchSelfReviewBlocking } from './review-state'
13
- import { listUnresolvedSelfReviewThreads } from './review-thread-resolver'
13
+ import { listUnresolvedSelfReviewThreads, type UnresolvedSelfReviewThread } from './review-thread-resolver'
14
14
 
15
15
  export type GithubInboundLogger = { info: (m: string) => void; warn: (m: string) => void; error: (m: string) => void }
16
16
 
@@ -280,15 +280,14 @@ function scheduleReviewFollowup(input: {
280
280
  else options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
281
281
  }
282
282
 
283
- const rootCommentIds = threads.threads.map((t) => t.rootCommentId)
284
- if (rootCommentIds.length === 0 && !selfBlocking) return
283
+ if (threads.threads.length === 0 && !selfBlocking) return
285
284
  options.route(
286
285
  withApprovalPolicy(
287
286
  buildReviewFollowupInbound({
288
287
  repository,
289
288
  pullNumber,
290
289
  headSha,
291
- rootCommentIds,
290
+ threads: threads.threads,
292
291
  selfBlocking,
293
292
  title: readString(pr, 'title'),
294
293
  }),
@@ -307,15 +306,15 @@ function buildReviewFollowupInbound(input: {
307
306
  repository: { owner: string; name: string }
308
307
  pullNumber: number
309
308
  headSha: string
310
- rootCommentIds: readonly number[]
309
+ threads: readonly UnresolvedSelfReviewThread[]
311
310
  selfBlocking: boolean
312
311
  title: string | null
313
312
  }): InboundMessage {
314
- const { repository, pullNumber, headSha, rootCommentIds, selfBlocking, title } = input
313
+ const { repository, pullNumber, headSha, threads, selfBlocking, title } = input
315
314
  const titleSegment = title !== null && title.trim() !== '' ? `: "${title}"` : ''
316
315
  const text =
317
316
  `PR #${pullNumber}${titleSegment} received new commits (now at ${headSha.slice(0, 7)}). ` +
318
- followupInstruction(rootCommentIds, selfBlocking)
317
+ followupInstruction(threads, selfBlocking)
319
318
 
320
319
  return {
321
320
  adapter: 'github',
@@ -336,14 +335,15 @@ function buildReviewFollowupInbound(input: {
336
335
  }
337
336
  }
338
337
 
339
- function followupInstruction(rootCommentIds: readonly number[], selfBlocking: boolean): string {
338
+ function followupInstruction(threads: readonly UnresolvedSelfReviewThread[], selfBlocking: boolean): string {
340
339
  const threadPart =
341
- rootCommentIds.length > 0
342
- ? `You have ${rootCommentIds.length} unresolved review thread(s) you authored on this PR ` +
343
- `(root comment id(s): ${rootCommentIds.join(', ')}). For each, check whether the new commits ` +
344
- `addressed your concern. If addressed, reply on that thread via channel_send with a short ` +
345
- `acknowledgement and resolve_review_thread: true (the thread id is the root comment id); ` +
346
- `if not, leave it open. `
340
+ threads.length > 0
341
+ ? `You have ${threads.length} unresolved review thread(s) you authored on this PR. ` +
342
+ `For each, check whether the new commits addressed your concern, then act on THAT thread ` +
343
+ `by passing its root comment id as \`thread\` to channel_send: if addressed, reply with a short ` +
344
+ `acknowledgement and resolve_review_thread: true; if not, reply with resolve_review_thread: false ` +
345
+ `(or leave it). Use the id — not the file/line — as \`thread\`; the file/line is only to tell the ` +
346
+ `threads apart:\n${threads.map(renderThreadLine).join('\n')}\n`
347
347
  : ''
348
348
  // A held CHANGES_REQUESTED never clears itself: GitHub keeps the block until a
349
349
  // fresh APPROVE/COMMENT/dismiss, so a blocking follow-up must always end with a
@@ -360,6 +360,12 @@ function followupInstruction(rootCommentIds: readonly number[], selfBlocking: bo
360
360
  return `${threadPart}${blockingPart}${tail}`
361
361
  }
362
362
 
363
+ function renderThreadLine(thread: UnresolvedSelfReviewThread): string {
364
+ const where = thread.path !== null ? ` on ${thread.path}${thread.line !== null ? `:${thread.line}` : ''}` : ''
365
+ const concern = thread.snippet !== null ? ` — "${thread.snippet}"` : ''
366
+ return `- thread ${thread.rootCommentId}${where}${concern}`
367
+ }
368
+
363
369
  export async function verifySignature(body: string, secret: string, sigHeader: string): Promise<boolean> {
364
370
  const expected = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`
365
371
  const a = Buffer.from(expected)
@@ -9,7 +9,7 @@ const GRAPHQL_ENDPOINT = `${GITHUB_API_BASE}/graphql`
9
9
  // carry more, so the resolver paginates until it matches the root comment id
10
10
  // or exhausts the pages — stopping early on a 404-equivalent (thread absent)
11
11
  // rather than fabricating a node id.
12
- const THREADS_QUERY = `query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId author{__typename login}}}}}}}}`
12
+ const THREADS_QUERY = `query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved path line comments(first:1){nodes{databaseId body author{__typename login}}}}}}}}`
13
13
 
14
14
  const RESOLVE_MUTATION = `mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{id isResolved}}}`
15
15
 
@@ -19,6 +19,9 @@ type ReviewThreadNode = {
19
19
  rootCommentId: number | null
20
20
  rootAuthorLogin: string | null
21
21
  rootAuthorIsBot: boolean
22
+ path: string | null
23
+ line: number | null
24
+ rootBody: string | null
22
25
  }
23
26
 
24
27
  type ThreadLookup =
@@ -147,7 +150,25 @@ async function findThread(fetchImpl: typeof fetch, token: string, target: Resolv
147
150
  return lookup
148
151
  }
149
152
 
150
- export type UnresolvedSelfReviewThread = { threadId: string; rootCommentId: number }
153
+ export type UnresolvedSelfReviewThread = {
154
+ threadId: string
155
+ rootCommentId: number
156
+ path: string | null
157
+ line: number | null
158
+ snippet: string | null
159
+ }
160
+
161
+ // One line of the root comment, capped, so the follow-up prompt can name each
162
+ // thread by its concern instead of a bare id — without dumping a multi-paragraph
163
+ // review comment into the system-facing instruction.
164
+ const SNIPPET_MAX_CHARS = 140
165
+
166
+ function firstLineSnippet(body: string | null): string | null {
167
+ if (body === null) return null
168
+ const firstLine = body.split('\n', 1)[0]?.trim() ?? ''
169
+ if (firstLine === '') return null
170
+ return firstLine.length > SNIPPET_MAX_CHARS ? `${firstLine.slice(0, SNIPPET_MAX_CHARS)}…` : firstLine
171
+ }
151
172
 
152
173
  export type ListUnresolvedSelfReviewThreadsResult =
153
174
  | { ok: true; threads: UnresolvedSelfReviewThread[] }
@@ -174,7 +195,13 @@ export async function listUnresolvedSelfReviewThreads(deps: {
174
195
  for (const node of nodes) {
175
196
  if (node.isResolved || node.rootCommentId === null) continue
176
197
  if (!isSelfAuthor(node, deps.selfLogin)) continue
177
- threads.push({ threadId: node.id, rootCommentId: node.rootCommentId })
198
+ threads.push({
199
+ threadId: node.id,
200
+ rootCommentId: node.rootCommentId,
201
+ path: node.path,
202
+ line: node.line,
203
+ snippet: firstLineSnippet(node.rootBody),
204
+ })
178
205
  }
179
206
  return 'continue'
180
207
  },
@@ -260,6 +287,9 @@ async function parseThreadsPage(response: Response): Promise<ThreadsPage> {
260
287
  rootCommentId: root?.databaseId ?? null,
261
288
  rootAuthorLogin: root?.author?.login ?? null,
262
289
  rootAuthorIsBot: root?.author?.__typename === 'Bot',
290
+ path: n.path ?? null,
291
+ line: n.line ?? null,
292
+ rootBody: root?.body ?? null,
263
293
  }
264
294
  })
265
295
  return { kind: 'ok', nodes, hasNextPage: connection.pageInfo.hasNextPage, endCursor: connection.pageInfo.endCursor }
@@ -316,7 +346,11 @@ type GraphqlThreadsResponse = {
316
346
  nodes: Array<{
317
347
  id: string
318
348
  isResolved: boolean
319
- comments: { nodes: Array<{ databaseId?: number; author?: { __typename?: string; login?: string } }> }
349
+ path?: string | null
350
+ line?: number | null
351
+ comments: {
352
+ nodes: Array<{ databaseId?: number; body?: string; author?: { __typename?: string; login?: string } }>
353
+ }
320
354
  }>
321
355
  }
322
356
  }
@@ -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
- let reply: string
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
- try {
226
- await deps.postReply({ chat: input.channel, thread: input.threadTs, text: reply })
227
- } catch (err) {
228
- deps.logger.warn(`[slack-bot] thread-command reply post failed: ${describeError(err)}`)
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