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
@@ -64,10 +64,12 @@ import {
64
64
  } from './persistence'
65
65
  import {
66
66
  ADAPTER_READ_CAPABILITIES,
67
+ ADAPTER_WRITE_CAPABILITIES,
67
68
  QUOTED_REPLY_EXCERPT_MAX_CHARS,
68
69
  type AdapterId,
69
70
  type ChannelAdapterConfig,
70
71
  type ReadCapability,
72
+ type WriteCapability,
71
73
  } from './schema'
72
74
  import type {
73
75
  ChannelHistoryMessage,
@@ -75,6 +77,9 @@ import type {
75
77
  ChannelNameResolver,
76
78
  ChannelSelfIdentity,
77
79
  ChannelSelfIdentityResolver,
80
+ EditMessageCallback,
81
+ EditMessageRequest,
82
+ EditMessageResult,
78
83
  FetchAttachmentArgs,
79
84
  FetchAttachmentCallback,
80
85
  FetchAttachmentResult,
@@ -952,6 +957,18 @@ type LiveSession = {
952
957
  // turn can never trigger a nudge on a later one. `null` when no such reply
953
958
  // ended this turn.
954
959
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
960
+ // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
961
+ // set `continue: true` — the machine-readable "I'll keep working this turn"
962
+ // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
963
+ // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
964
+ // independent of what natural-language phrase the ack used, so a persona speaking
965
+ // any language/register is covered where the willingness phrase table would miss.
966
+ // `turnSeq`-stamped so a stale promise can't fire on a later turn. `sendCount` is
967
+ // `successfulChannelSends` AT the ack (which already counts the ack itself); the
968
+ // recovery fires only while it still equals the live count — a later substantive
969
+ // send (e.g. a `channel_send` final answer) bumps the count and invalidates the
970
+ // promise, so an empty stop after the real answer is NOT re-nudged.
971
+ continueReplyTurn: { turnSeq: number; sendCount: number } | null
955
972
  // Stamped by router abort sites and read by `validateChannelTurn` for
956
973
  // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
957
974
  // abort provenance from an earlier turn can never leak into a later retry.
@@ -1203,6 +1220,16 @@ export type ChannelRouter = {
1203
1220
  registerList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1204
1221
  unregisterList: (adapter: ChannelKey['adapter'], cb: ListCallback) => void
1205
1222
  listChannels: (adapter: ChannelKey['adapter'], args: ListChannelsArgs) => Promise<ListChannelsResult>
1223
+ // Message editing is opt-in per adapter, Set-based like reactions/outbound so
1224
+ // future multi-account setups can register more than one. A missing callback
1225
+ // resolves to `code: 'not-supported'`, or `code: 'adapter-unavailable'` when
1226
+ // the static write-capability table (ADAPTER_WRITE_CAPABILITIES) says this
1227
+ // adapter edits but no live callback exists (failed start). Kept off the
1228
+ // outbound path: an edit mutates an existing post, so it must not flow through
1229
+ // send()'s flood/cap/dup/sticky guards.
1230
+ registerEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1231
+ unregisterEditMessage: (adapter: ChannelKey['adapter'], cb: EditMessageCallback) => void
1232
+ editMessage: (req: EditMessageRequest) => Promise<EditMessageResult>
1206
1233
  registerFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1207
1234
  unregisterFetchAttachment: (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback) => void
1208
1235
  fetchAttachment: (adapter: ChannelKey['adapter'], args: FetchAttachmentArgs) => Promise<FetchAttachmentResult>
@@ -1550,6 +1577,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1550
1577
  const historyCallbacks = new Map<ChannelKey['adapter'], Set<HistoryCallback>>()
1551
1578
  const messageGetCallbacks = new Map<ChannelKey['adapter'], MessageGetCallback>()
1552
1579
  const listCallbacks = new Map<ChannelKey['adapter'], ListCallback>()
1580
+ const editMessageCallbacks = new Map<ChannelKey['adapter'], Set<EditMessageCallback>>()
1553
1581
  const fetchAttachmentCallbacks = new Map<ChannelKey['adapter'], Set<FetchAttachmentCallback>>()
1554
1582
  const reviewThreadResolvers = new Map<ChannelKey['adapter'], ReviewThreadResolver>()
1555
1583
  const reviewStateResolvers = new Map<ChannelKey['adapter'], ReviewStateResolver>()
@@ -2098,6 +2126,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2098
2126
  emptyStopAfterToolWorkArmed: false,
2099
2127
  willingnessNudges: 0,
2100
2128
  lastTerminalReplyAbort: null,
2129
+ continueReplyTurn: null,
2101
2130
  abortReasonThisTurn: null,
2102
2131
  nextPromptMaxTokens: undefined,
2103
2132
  skippedTurn: null,
@@ -2486,6 +2515,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2486
2515
  const details = context.result.details as { ok?: unknown; continue?: unknown } | undefined
2487
2516
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2488
2517
  const keepTurnAlive = details?.continue === true
2518
+ if (succeeded && keepTurnAlive) {
2519
+ live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2520
+ }
2489
2521
  if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true) {
2490
2522
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2491
2523
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
@@ -2705,6 +2737,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2705
2737
  }
2706
2738
  }
2707
2739
 
2740
+ // ensureLive() installs a session BEFORE the engage/observe decision, so a
2741
+ // bystander agent that only OBSERVED a thread still holds an exact-thread
2742
+ // session with nothing running. Without this gate that agent aborts its idle
2743
+ // session and posts "stopped" in a multi-agent channel. Mirrors exactly what
2744
+ // stopCurrentChannelTurn cancels: in-flight drain, queued prompts, reminders.
2745
+ const hasStoppableWork = (live: LiveSession): boolean =>
2746
+ live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
2747
+
2708
2748
  const maybePostDeferredProviderError = async (
2709
2749
  live: LiveSession,
2710
2750
  sentReplyThisTurn: boolean,
@@ -2874,6 +2914,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2874
2914
  live.skipLockedSendTurn = null
2875
2915
  live.disengagedTurn = null
2876
2916
  live.emptyTurnFallbackTurn = null
2917
+ live.continueReplyTurn = null
2877
2918
  live.policyDeniedToolSendsThisTurn.clear()
2878
2919
  resetReviewTurn(live.sessionId)
2879
2920
  const isRealUserTurn = batch.length > 0
@@ -3786,6 +3827,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3786
3827
  ? `${capability}-adapter-unavailable: the "${adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`
3787
3828
  : `${capability}-not-supported`
3788
3829
 
3830
+ const isWriteCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: WriteCapability): boolean =>
3831
+ configuredAdapters.has(adapter) && ADAPTER_WRITE_CAPABILITIES[adapter].includes(capability)
3832
+
3789
3833
  const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
3790
3834
  const callbacks = historyCallbacks.get(adapter)
3791
3835
  if (!callbacks || callbacks.size === 0) {
@@ -3852,6 +3896,59 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3852
3896
  }
3853
3897
  }
3854
3898
 
3899
+ const registerEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3900
+ let set = editMessageCallbacks.get(adapter)
3901
+ if (!set) {
3902
+ set = new Set()
3903
+ editMessageCallbacks.set(adapter, set)
3904
+ }
3905
+ set.add(cb)
3906
+ }
3907
+
3908
+ const unregisterEditMessage = (adapter: ChannelKey['adapter'], cb: EditMessageCallback): void => {
3909
+ editMessageCallbacks.get(adapter)?.delete(cb)
3910
+ }
3911
+
3912
+ const editMessage = async (req: EditMessageRequest): Promise<EditMessageResult> => {
3913
+ // Strip leaked `<think>` blocks before the edit reaches any adapter, exactly
3914
+ // as the send path does via normalizeSendText — an edit is another way text
3915
+ // reaches the chat, so it must not become a hole that writes raw reasoning a
3916
+ // send would have suppressed. A replacement that is ONLY a think block leaves
3917
+ // nothing visible, so refuse rather than blank the message.
3918
+ const normalized = normalizeSendText(req.text)
3919
+ if (normalized === undefined) {
3920
+ return { ok: false, error: 'message-edit-empty-after-normalization', code: 'not-found' }
3921
+ }
3922
+ const normalizedReq = normalized === req.text ? req : { ...req, text: normalized }
3923
+ const callbacks = editMessageCallbacks.get(req.adapter)
3924
+ if (!callbacks || callbacks.size === 0) {
3925
+ return isWriteCapabilityUnavailable(req.adapter, 'message-edit')
3926
+ ? {
3927
+ ok: false,
3928
+ error: `message-edit-adapter-unavailable: the "${req.adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`,
3929
+ code: 'adapter-unavailable',
3930
+ }
3931
+ : { ok: false, error: 'message-edit-not-supported', code: 'not-supported' }
3932
+ }
3933
+ const snapshot = Array.from(callbacks)
3934
+ let lastError: EditMessageResult & { ok: false } = { ok: false, error: 'message-edit-not-supported' }
3935
+ for (const cb of snapshot) {
3936
+ try {
3937
+ const result = await raceWithTimeout(
3938
+ cb(normalizedReq),
3939
+ fetchHistoryTimeoutMs,
3940
+ `[channels] ${req.adapter} edit message`,
3941
+ )
3942
+ if (result.ok) return result
3943
+ lastError = result
3944
+ } catch (err) {
3945
+ logger.warn(`[channels] edit message threw for ${req.adapter}: ${describe(err)}`)
3946
+ lastError = { ok: false, error: `edit message failed: ${describe(err)}` }
3947
+ }
3948
+ }
3949
+ return lastError
3950
+ }
3951
+
3855
3952
  const registerFetchAttachment = (adapter: ChannelKey['adapter'], cb: FetchAttachmentCallback): void => {
3856
3953
  let set = fetchAttachmentCallbacks.get(adapter)
3857
3954
  if (!set) {
@@ -4356,6 +4453,47 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4356
4453
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
4357
4454
  maybeNudgeContinuationWillingness(live)
4358
4455
 
4456
+ // A `channel_reply({ continue: true })` progress ack landed this turn (the
4457
+ // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
4458
+ // by installChannelReplyTerminalHook), the model did more work, then ended on a
4459
+ // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
4460
+ // the phrase-gated `channel_send` branch below, but keyed on the `continue: true`
4461
+ // FLAG instead of a natural-language willingness phrase. The flag is the robust
4462
+ // signal: it fires regardless of the ack's language or register, closing the gap
4463
+ // where a persona speaking a phrasing outside the willingness table (e.g. casual
4464
+ // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
4465
+ // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
4466
+ // lets a retry that re-emitted `continue: true` and re-stranded spend the shared
4467
+ // budget toward the visible fallback instead of bailing silent. Same
4468
+ // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
4469
+ // inbound supersedes this turn's silence), and same nudge/fallback path as the
4470
+ // send-ack branch. Placed FIRST so the flag catch wins when both signals are
4471
+ // present; the phrase branch remains the only recovery for `channel_send`, which
4472
+ // stamps no flag. The `sendCount === successfulChannelSends` check requires the
4473
+ // continue-reply to STILL be the latest successful send: if a later substantive
4474
+ // send (e.g. a `channel_send` final answer) landed after the ack, the user was
4475
+ // already answered and a trailing empty stop must NOT be re-nudged.
4476
+ if (
4477
+ live.promptQueue.length === 0 &&
4478
+ live.currentTurnAuthorId !== null &&
4479
+ live.continueReplyTurn?.turnSeq === live.turnSeq &&
4480
+ live.continueReplyTurn.sendCount === live.successfulChannelSends &&
4481
+ isFreshEmptyStopAfterSend(live) &&
4482
+ (attemptMadeToolCall(live.session) || live.willingnessNudges > 0)
4483
+ ) {
4484
+ if (live.willingnessNudges < MAX_WILLINGNESS_NUDGES) {
4485
+ live.willingnessNudges++
4486
+ logger.warn(
4487
+ `[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
4488
+ `cause=empty_stop_after_continue_reply`,
4489
+ )
4490
+ live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4491
+ } else {
4492
+ await postEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4493
+ }
4494
+ return
4495
+ }
4496
+
4359
4497
  // A `channel_send` ack that promised to keep working, fresh post-ack work,
4360
4498
  // then an EMPTY `stop` leaf: the model computed the answer in its reasoning
4361
4499
  // / tool results but never sent it (the Kimi/Fireworks empty-completion
@@ -5130,6 +5268,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5130
5268
  if (resolved.kind === 'ambiguous') {
5131
5269
  return { kind: 'ambiguous', matchCount: resolved.count }
5132
5270
  }
5271
+ // A resolved session that isn't actually running has nothing for /stop to
5272
+ // cancel; report it as no-live-session so bystander agents stay silent.
5273
+ if (lowered === 'stop' && !hasStoppableWork(resolved.session)) {
5274
+ return { kind: 'no-live-session' }
5275
+ }
5133
5276
  live = resolved.session
5134
5277
  } else if (commandInfo.wantsLiveSession) {
5135
5278
  // Best-effort: resolve a session if exactly one matches, but never fail
@@ -5452,6 +5595,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5452
5595
  registerList,
5453
5596
  unregisterList,
5454
5597
  listChannels,
5598
+ registerEditMessage,
5599
+ unregisterEditMessage,
5600
+ editMessage,
5455
5601
  registerFetchAttachment,
5456
5602
  unregisterFetchAttachment,
5457
5603
  fetchAttachment,
@@ -6097,10 +6243,19 @@ export type ResolveLiveSessionResult =
6097
6243
  // return 'ambiguous' so the caller can refuse to act rather than abort an
6098
6244
  // arbitrary session.
6099
6245
  //
6100
- // Why the fallback: Slack slash commands carry channel_id but no thread_ts,
6101
- // so a slash invocation from a thread-keyed live session would otherwise
6102
- // report no-live-session. Discord doesn't hit this — Discord treats threads
6103
- // as channels, so the exact-key path already resolves.
6246
+ // Why the fallback: Slack slash commands carry channel_id but no thread_ts
6247
+ // (`thread: null`), so a slash invocation from a thread-keyed live session
6248
+ // would otherwise report no-live-session. Discord doesn't hit this — Discord
6249
+ // treats threads as channels, so the exact-key path already resolves.
6250
+ //
6251
+ // Why the fallback is thread-null-ONLY: a `!stop` typed INSIDE a Slack thread
6252
+ // carries the real `thread_ts`, so it pinpoints one exact thread. Falling back
6253
+ // to "any session in this channel" for a thread-specific key would let the
6254
+ // command hit an UNRELATED session in a different thread (or a channel-level
6255
+ // observe-only session) — the multi-agent bug where a bystander bot that only
6256
+ // observed the thread aborts its own idle session and posts "stopped". A
6257
+ // non-null thread that misses the exact lookup therefore returns 'none', never
6258
+ // the cross-thread fallback.
6104
6259
  //
6105
6260
  // Why ambiguity-rejection: "first match wins" map-iteration semantics would
6106
6261
  // abort an arbitrary thread when multiple thread-keyed sessions coexist in
@@ -6114,6 +6269,8 @@ export function resolveLiveSessionForCommand(
6114
6269
  const exact = liveSessions.get(channelKeyId(key))
6115
6270
  if (exact && !exact.destroyed) return { kind: 'found', session: exact }
6116
6271
 
6272
+ if (key.thread !== null) return { kind: 'none' }
6273
+
6117
6274
  const matches: LiveSession[] = []
6118
6275
  for (const candidate of liveSessions.values()) {
6119
6276
  if (candidate.destroyed) continue
@@ -6375,20 +6532,29 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
6375
6532
  return false
6376
6533
  }
6377
6534
 
6378
- // True when the turn-end leaf is a FRESH empty `stop` (no text, no tool call,
6379
- // distinct from the leaf in place at the last successful send) AND the most
6380
- // recent send to this target was a continuation-willingness ack. This is the
6381
- // `channel_send` analogue of the `channel_reply` willingness path: the model
6382
- // acked "I'll check…", did post-ack work, then the follow-up came back as a
6383
- // clean empty completion that would otherwise be read as a deliberate `NO_REPLY`.
6384
- // The fresh-leaf check (`!== lastSendLeafId`) is what separates this degeneration
6385
- // from a legitimate ack-then-stop where the model meant to wait for the user.
6386
- function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6535
+ // The turn-end leaf is a FRESH empty `stop` — an assistant message with no visible
6536
+ // text and no tool call, distinct from the leaf in place at the last successful
6537
+ // send. "Fresh" (`!== lastSendLeafId`) is what separates a post-send degeneration
6538
+ // (the model did more work, then dropped its conclusion) from a legitimate
6539
+ // ack-then-stop where the model meant to wait for the user (leaf unchanged since
6540
+ // the send). The two willingness paths below layer their own promise-signal on top
6541
+ // of this shape: `channel_reply({ continue: true })` via `continueReplyTurn`, and
6542
+ // `channel_send` acks via the willingness phrase table.
6543
+ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6387
6544
  const leaf = live.session.sessionManager.getLeafEntry()
6388
6545
  if (!leaf || leaf.type !== 'message' || leaf.message.role !== 'assistant') return false
6389
6546
  if (leaf.message.stopReason !== 'stop') return false
6390
6547
  if (hasToolCall(leaf.message) || visibleAssistantText(leaf.message).trim() !== '') return false
6391
- if (leaf.id === live.lastSendLeafId) return false
6548
+ return leaf.id !== live.lastSendLeafId
6549
+ }
6550
+
6551
+ // The `channel_send` analogue of the `continue: true` recovery: the most recent
6552
+ // send to this target was a continuation-willingness ack (by phrase), then the
6553
+ // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
6554
+ // `continue: true` flag and stamps no semantic marker, so the phrase table is the
6555
+ // only "I promised to keep working" signal available for that shape.
6556
+ function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6557
+ if (!isFreshEmptyStopAfterSend(live)) return false
6392
6558
  const ackText = live.lastSentText.get(consecutiveSendKey(live.key.chat, live.key.thread))
6393
6559
  return ackText !== undefined && detectContinuationWillingness(ackText)
6394
6560
  }
@@ -42,6 +42,30 @@ export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapabilit
42
42
  'webex-bot': ['history'],
43
43
  }
44
44
 
45
+ export type WriteCapability = 'message-edit'
46
+
47
+ // Mirror of ADAPTER_READ_CAPABILITIES for write-side capabilities that must
48
+ // survive a failed start(). Only adapters whose underlying SDK exposes a
49
+ // message-edit primitive appear here; the router uses this to answer
50
+ // `adapter-unavailable` (configured but not running — re-auth may help) vs
51
+ // `not-supported` (this adapter never edits) for a missing callback. The
52
+ // schema.test.ts guard re-derives each entry from the adapter's
53
+ // `.registerEditMessage(` call and fails if the table drifts.
54
+ export const ADAPTER_WRITE_CAPABILITIES: Record<AdapterId, readonly WriteCapability[]> = {
55
+ discord: ['message-edit'],
56
+ 'discord-bot': ['message-edit'],
57
+ github: [],
58
+ instagram: [],
59
+ line: [],
60
+ kakaotalk: [],
61
+ slack: ['message-edit'],
62
+ 'slack-bot': ['message-edit'],
63
+ teams: ['message-edit'],
64
+ 'telegram-bot': ['message-edit'],
65
+ webex: ['message-edit'],
66
+ 'webex-bot': ['message-edit'],
67
+ }
68
+
45
69
  const engagementTriggerSchema = z.enum(['mention', 'reply', 'dm'])
46
70
 
47
71
  const stickinessSchema = z.union([
@@ -272,6 +272,42 @@ export type SendResult =
272
272
 
273
273
  export type OutboundCallback = (msg: OutboundMessage) => Promise<SendResult>
274
274
 
275
+ // A request to edit (replace the text of) a message the bot already posted.
276
+ // `messageId` is the platform-native id the send handed back as
277
+ // `SendResult.messageId` (Slack `ts`, Discord snowflake, Telegram `message_id`,
278
+ // Webex message id) — the same id shape an inbound carries as
279
+ // `externalMessageId`. `thread` is context only: none of the supported SDK edit
280
+ // calls require it (Slack/Discord/Telegram/Webex address the message by
281
+ // channel+id or room+id), so adapters may ignore it. Editing is opt-in per
282
+ // adapter — only adapters whose SDK exposes an edit primitive register a
283
+ // callback; the rest resolve to `code: 'not-supported'`.
284
+ export type EditMessageRequest = {
285
+ adapter: AdapterId
286
+ workspace: string
287
+ chat: string
288
+ thread?: string | null
289
+ messageId: string
290
+ text: string
291
+ }
292
+
293
+ // `not-found` is an expected miss (message deleted, wrong id, or too old to
294
+ // edit) the tool surfaces as a soft error. `not-supported` means the adapter
295
+ // does not implement editing at all. `adapter-unavailable` means the adapter IS
296
+ // configured and DOES implement editing, but currently has no live callback
297
+ // (e.g. it failed to start), mirroring `getMessage`'s three-way distinction so
298
+ // the agent only sees the actionable re-auth hint when re-auth would help.
299
+ // `permission-denied` is a hard refusal from the platform (e.g. editing a
300
+ // message the bot does not own).
301
+ export type EditMessageResult =
302
+ | { ok: true }
303
+ | {
304
+ ok: false
305
+ error: string
306
+ code?: 'not-found' | 'not-supported' | 'adapter-unavailable' | 'permission-denied'
307
+ }
308
+
309
+ export type EditMessageCallback = (req: EditMessageRequest) => Promise<EditMessageResult>
310
+
275
311
  export type TypingTarget = {
276
312
  adapter: AdapterId
277
313
  workspace: string
@@ -8,6 +8,7 @@ import {
8
8
  type SessionOrigin,
9
9
  } from '@/agent'
10
10
  import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
11
+ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
11
12
  import type { ChannelRouter } from '@/channels/router'
12
13
  import type { McpManager } from '@/mcp'
13
14
  import type { PermissionService } from '@/permissions'
@@ -427,7 +428,7 @@ export async function runPromptForCommand(args: {
427
428
  : `${renderTurnTimeAnchor()}\n\n${args.text}`
428
429
  applyTurnThinkingLevel(session, args.text, session.thinkingLevel)
429
430
  try {
430
- await session.prompt(turnText)
431
+ await promptWithSameRefRetryOnly(session, turnText)
431
432
  } finally {
432
433
  await snapshot.hooks.runSessionTurnEnd(turnEvent)
433
434
  }
@@ -18,6 +18,7 @@ import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
18
18
  import { detectProviderError, isFailoverWorthy } from '@/agent/provider-error'
19
19
  import { requestContainerRestart } from '@/agent/restart'
20
20
  import { consumeRestartHandoff, type RestartHandoff } from '@/agent/restart-handoff'
21
+ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
21
22
  import { sessionMetaPayload } from '@/agent/session-meta'
22
23
  import type { SessionOrigin } from '@/agent/session-origin'
23
24
  import { parseSubagentCompletedPayload, renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
@@ -816,7 +817,7 @@ export function createServer({
816
817
  ? `${renderTurnTimeAnchor()}\n\n${msg.text}\n\n${retrievalContext.results}`
817
818
  : `${renderTurnTimeAnchor()}\n\n${msg.text}`
818
819
  applyTurnThinkingLevel(state.session, msg.text, state.turnThinkingDefault, state.lastQuestionSignal)
819
- await state.session.prompt(turnText)
820
+ await promptWithSameRefRetryOnly(state.session, turnText)
820
821
  // A usable turn seeds the next turn's escalation; a failed leaf must
821
822
  // CLEAR the prior signal (not just skip), else an older question
822
823
  // leaks across the failed turn and wrongly escalates the next one.