typeclaw 0.44.0 → 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 (37) hide show
  1. package/package.json +7 -6
  2. package/src/agent/index.ts +11 -0
  3. package/src/agent/model-fallback.ts +59 -40
  4. package/src/agent/multimodal/look-at.ts +2 -1
  5. package/src/agent/provider-error.ts +71 -18
  6. package/src/agent/retry-same-ref.ts +139 -0
  7. package/src/agent/subagents.ts +6 -2
  8. package/src/agent/tools/channel-edit.ts +144 -0
  9. package/src/agent/tools/channel-fetch-attachment.ts +6 -5
  10. package/src/agent/tools/curl-impersonate.ts +40 -1
  11. package/src/agent/tools/webfetch/fetch.ts +86 -3
  12. package/src/agent/tools/webfetch/tool.ts +26 -3
  13. package/src/agent/tools/webfetch/types.ts +8 -0
  14. package/src/agent/turn-runner.ts +65 -36
  15. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  16. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  17. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  18. package/src/channels/adapters/discord-bot.ts +5 -0
  19. package/src/channels/adapters/discord-edit.ts +51 -0
  20. package/src/channels/adapters/discord.ts +4 -0
  21. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  22. package/src/channels/adapters/slack-bot.ts +18 -6
  23. package/src/channels/adapters/slack-edit.ts +47 -0
  24. package/src/channels/adapters/slack.ts +5 -0
  25. package/src/channels/adapters/teams-edit.ts +61 -0
  26. package/src/channels/adapters/teams.ts +4 -0
  27. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  28. package/src/channels/adapters/telegram-bot.ts +5 -0
  29. package/src/channels/adapters/webex-bot.ts +5 -0
  30. package/src/channels/adapters/webex-edit.ts +47 -0
  31. package/src/channels/adapters/webex.ts +5 -0
  32. package/src/channels/continuation-willingness.ts +227 -35
  33. package/src/channels/router.ts +180 -14
  34. package/src/channels/schema.ts +24 -0
  35. package/src/channels/types.ts +36 -0
  36. package/src/server/command-runner.ts +2 -1
  37. package/src/server/index.ts +2 -1
@@ -15,10 +15,12 @@ already downloaded, so the CLI is ready to use out of the box.
15
15
 
16
16
  ## Human-in-the-loop via the dashboard
17
17
 
18
- You run inside a Docker container with no display, no clipboard, and no way to
19
- hand the keyboard over directly. The **dashboard is your only path to bring a
20
- human into a browser session** — it streams every session's live viewport,
21
- console, and command activity to a web UI the user opens on their host machine.
18
+ You run inside a Docker container. Chrome renders to the in-container virtual X
19
+ display (Xvfb, `DISPLAY=:99`), but there is no human-accessible display or
20
+ clipboard and no way to hand the keyboard over directly. The **dashboard is your
21
+ only path to bring a human into a browser session** — it streams every session's
22
+ live viewport, console, and command activity to a web UI the user opens on their
23
+ host machine.
22
24
 
23
25
  **Start the dashboard _before_ the step that needs a human, not after it fails.**
24
26
  The dashboard takes a moment to come up and the user needs time to open the URL.
@@ -91,13 +93,28 @@ you just want to show the user a single page or a captured state:
91
93
  Reserve the dashboard for cases that genuinely need live interaction or
92
94
  watching a multi-step flow unfold.
93
95
 
94
- ### Headless only
95
-
96
- Never pass `--headed` to any `agent-browser` command — the container has no X
97
- server or `$DISPLAY`, and a headed launch fails with `Missing X server or
98
- $DISPLAY / The platform failed to initialize.` The dashboard is the substitute
99
- for a headed browser. Use the default headless mode for everything, including
100
- dogfooding and Electron flows.
96
+ ### Headed vs headless
97
+
98
+ By default the container ships a virtual X server: the entrypoint spawns Xvfb
99
+ and exports `DISPLAY=:99`, so `--headed` (or `AGENT_BROWSER_HEADED=1`) launches a
100
+ real headed Chrome. Headless is fine for ordinary automation — dogfooding, form
101
+ filling, Electron flows, capturing a page you can already reach.
102
+
103
+ Prefer `--headed` when a site is guarded by a WAF/anti-bot layer (Akamai Bot
104
+ Manager, Cloudflare, PerimeterX — common on large e-commerce and portal sites).
105
+ Chrome's `--headless`/`--headless=new` modes are fingerprinted by these stacks
106
+ via signals no UA spoof can patch, so a headless launch draws a `403 Access
107
+ Denied` / CAPTCHA where a headed one under Xvfb passes. This is the whole reason
108
+ the container runs Xvfb. For a hard case, combine headed mode with a persistent
109
+ `--profile` and warm the session (land on the homepage, then navigate
110
+ organically) so the site's trust cookie is issued before you hit the target
111
+ page.
112
+
113
+ The one exception: if the agent folder sets `docker.file.xvfb: false`, there is
114
+ no `DISPLAY` and a headed launch fails with `Missing X server or $DISPLAY / The
115
+ platform failed to initialize.` In that configuration, stay headless and use the
116
+ dashboard for anything that needs a human. If a `--headed` command ever returns
117
+ that error, the toggle is off — fall back to headless rather than retrying.
101
118
 
102
119
  ## Start here
103
120
 
@@ -3,7 +3,7 @@ import type { LoadableSkill } from '@/plugin'
3
3
  export const CODE_REVIEW_SKILL_NAME = 'code-review'
4
4
 
5
5
  export const CODE_REVIEW_SKILL_DESCRIPTION =
6
- 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, and project conventions.'
6
+ 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, project conventions, and the PR title/body itself as a record — whether it captures the why behind each change for future readers.'
7
7
 
8
8
  export const CODE_REVIEW_SKILL_CONTENT = `# code-review
9
9
 
@@ -55,6 +55,26 @@ A finding without context is noise. Before forming findings:
55
55
  3. **Read the project's conventions.** \`AGENTS.md\`, \`CONTRIBUTING.md\`, \`CLAUDE.md\`, \`README.md\`, the test layout, the linter config. Deviation from established convention is a finding worth raising; following convention is not worth praising.
56
56
  4. **Read the tests.** Existing tests show what the project considers important to verify. New tests show what the author considers important to lock in. The gap between them is often where the bugs hide.
57
57
 
58
+ ## Review the PR title and body as an artifact, not just as context
59
+
60
+ Steps above use the PR title and body as *input* — the author's stated intent, which you check the code against. But the description is also a **deliverable in its own right, and it is part of your review scope.** Most harnesses only diff code and never review the prose; you are the one pass that can, so treat the title and body as a first-class review target alongside the diff.
61
+
62
+ Why this matters — the frame that decides your findings here:
63
+
64
+ - **A PR is a record, not a showcase.** Its dominant purpose is not to display the code or even to solicit code review — it is to **record the translation from the business need into the code change**: *why* this change became necessary, what business or product context forced it, what decision was made and what was rejected. The code shows *what* changed; the body is the only place *why* survives. When the why is absent, it is gone the moment the author forgets it.
65
+ - **The audience is the reviewer and future-self, who do NOT share the author's context.** The current reviewer, a teammate six months from now, or the author themselves later, all read this record under real cognitive load, missing the context that was obvious the day it was written. A good body exists to *lower that load*. Judge the body by whether a reader without the author's head can reconstruct why each change was made.
66
+ - **The concrete failure is a change whose context is silently dropped.** A large task drags in incidental side changes; the low-importance ones lose their rationale first, and later someone does redundant or wrong work because the record never explained the earlier decision (e.g. a field added in one PR with no note that it duplicates an existing one, so a later PR "fixes" a problem that was actually intentional). This is the highest-value thing to catch: a change in the diff that the body leaves **unexplained or unconnected to its reason**.
67
+
68
+ What to look for in the title and body:
69
+
70
+ 1. **Rationale for every meaningful change, not just the headline one.** The primary change is usually explained. The finding is the *secondary* change — a schema tweak, a config flip, a "while I was here" refactor, a new field — that appears in the diff with no corresponding why in the body. Anchor the finding to the diff hunk whose rationale is missing, and name what a future reader would fail to reconstruct.
71
+ 2. **Title accuracy and scope match.** Does the title name what the change actually does? Does the body's described scope match the diff — nothing significant in the diff that the body never mentions, and nothing promised in the body that the diff never delivers? A title that says A while the diff also does B is a scope/record defect: the B change is now unfindable by anyone searching the history for it.
72
+ 3. **Meaning-unit separation.** When the diff bundles several unrelated logical changes under one description, the context for each is harder to recover and the record is degraded even if every line is correct. Flag it as a record problem — the fix may be to split the PR, or at minimum to give each logical unit its own explained section in the body — not as a code defect.
73
+ 4. **Decision and trade-off capture.** For a change that chose one approach over an obvious alternative, or that is a deliberate one-way door (schema, public API, migration), does the body record the decision and why? A silent irreversible decision is a record gap worth raising even when the code is correct.
74
+ 5. **Linked context integrity.** Referenced issues/tickets/prior PRs actually correspond to this change; a load-bearing claim in the body ("as decided in #123") points where it says it does. A dangling or wrong reference breaks the record's chain.
75
+
76
+ Keep the anti-noise line from below firmly in view: **do not confuse restating the description with reviewing it.** Summarizing what the PR does back to the author is noise (see "What NOT to find"). The review work here is the *gap* — a change with no recorded reason, a title that misleads, a bundled scope that buries context, a decision left unexplained. Anchor these to the specific diff hunk or the quoted body passage; use \`location="general"\` only for a whole-description defect (e.g. an empty body on a non-trivial change) and say why in the \`<issue>\`. Calibrate severity to consequence, not to prose taste: an unexplained behavior-changing hunk or a title that hides a real change is a \`concern\` (a \`blocker\` when the missing context is what stops a future reader from avoiding a concrete mistake); a thin-but-adequate body is at most a \`nit\`. A body's writing quality is not the target — its function as a record is.
77
+
58
78
  ## What to look for
59
79
 
60
80
  Prioritize in this order:
@@ -77,7 +97,7 @@ Prioritize in this order:
77
97
  - **Settled convention objections.** If the project uses tabs, four-space indent, camelCase vs snake_case, etc., and the change matches, that is not a finding. Only the deviation is.
78
98
  - **Generic best-practice essays.** "Consider adding more tests" without naming a specific untested branch is noise. "Improve error handling" without pointing at a specific swallowed error is noise.
79
99
  - **Restating the code.** "This function reads the file and returns its contents" is not a finding.
80
- - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know.
100
+ - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know. (This forbids *echoing* the body, not *reviewing* it: judging whether the body records the why, matches the diff, and separates its meaning units is in scope — see "Review the PR title and body as an artifact". The line is echo vs. evaluate.)
81
101
  - **Already-acknowledged gaps.** A weakness the author already flagged with a \`TODO\`/\`FIXME\` in the diff, or named in the PR body as out of scope, is not a finding — they're already aware. Only raise it if you have new information: the gap is worse than they think, or it's a blocker they've mislabeled as deferrable. Say which.
82
102
 
83
103
  ## Severity hints specific to code
@@ -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
 
@@ -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
@@ -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
+ }