typeclaw 0.48.4 → 0.48.6

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 (44) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +6 -1
  3. package/src/agent/live-subagents.ts +15 -0
  4. package/src/agent/plugin-tools.ts +1 -1
  5. package/src/agent/session-origin.ts +104 -16
  6. package/src/agent/subagent-completion-reminder.ts +1 -1
  7. package/src/agent/subagent-drain.ts +11 -1
  8. package/src/agent/subagents.ts +52 -7
  9. package/src/agent/tools/post-github-review.ts +101 -1
  10. package/src/agent/tools/spawn-subagent.ts +88 -7
  11. package/src/agent/tools/subagent-cancel.ts +1 -0
  12. package/src/agent/tools/subagent-output.ts +7 -2
  13. package/src/agent/tools/webfetch/adaptive-html.ts +319 -0
  14. package/src/agent/tools/webfetch/html-lexical.ts +841 -0
  15. package/src/agent/tools/webfetch/inline-style-visibility.ts +281 -0
  16. package/src/agent/tools/webfetch/strategies/readability.ts +306 -5
  17. package/src/agent/tools/webfetch/tool.ts +45 -2
  18. package/src/agent/tools/webfetch/types.ts +7 -0
  19. package/src/agent/turn-runner.ts +7 -3
  20. package/src/bundled-plugins/github-cli-auth/gh-command.ts +187 -8
  21. package/src/bundled-plugins/memory/dreaming.ts +3 -2
  22. package/src/bundled-plugins/reviewer/reviewer.ts +32 -5
  23. package/src/bundled-plugins/reviewer/skills/code-review.ts +5 -3
  24. package/src/bundled-plugins/reviewer/skills/doc-review.ts +1 -1
  25. package/src/bundled-plugins/reviewer/skills/plan-review.ts +1 -1
  26. package/src/channels/github-review-verdict-coordinator.ts +23 -5
  27. package/src/channels/router.ts +15 -5
  28. package/src/cli/inspect.ts +2 -2
  29. package/src/container/start.ts +16 -0
  30. package/src/git/resolve-identity.ts +66 -0
  31. package/src/git/run.ts +2 -0
  32. package/src/git/system-commit.ts +2 -2
  33. package/src/inspect/item-list.ts +2 -11
  34. package/src/inspect/session-list.ts +29 -15
  35. package/src/plugin/types.ts +0 -10
  36. package/src/run/channel-session-factory.ts +3 -1
  37. package/src/run/index.ts +29 -29
  38. package/src/run/subagent-coalescing.ts +24 -0
  39. package/src/sandbox/env-exposure.ts +20 -7
  40. package/src/server/index.ts +4 -1
  41. package/src/skills/typeclaw-channel-github/SKILL.md +10 -10
  42. package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
  43. package/src/skills/typeclaw-channel-kakaotalk/SKILL.md +1 -1
  44. package/src/skills/typeclaw-channel-line/SKILL.md +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.4",
3
+ "version": "0.48.6",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -61,7 +61,7 @@ import type { SubagentBashPolicy } from './reviewer-bash-policy'
61
61
  import { loadSelf } from './self'
62
62
  import { SESSION_META_CUSTOM_TYPE, sessionMetaPayload } from './session-meta'
63
63
  import { renderSessionOrigin, type SessionOrigin, type SessionRoleContext } from './session-origin'
64
- import type { CreateSessionForSubagent, SubagentRegistry } from './subagents'
64
+ import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from './subagents'
65
65
  import {
66
66
  buildDefaultSystemPrompt,
67
67
  buildSlimSystemPrompt,
@@ -219,6 +219,7 @@ export type CreateSessionOptions = {
219
219
  // (omitting these for subagent sessions) is what prevents recursive
220
220
  // spawning.
221
221
  liveSubagentRegistry?: LiveSubagentRegistry
222
+ subagentCoalescer?: SubagentCoalescer
222
223
  subagentRegistry?: SubagentRegistry
223
224
  createSessionForSubagent?: CreateSessionForSubagent
224
225
  allowBackgroundFromSubagent?: boolean
@@ -401,6 +402,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
401
402
  permissions: options.permissions,
402
403
  stream: options.stream,
403
404
  allowBackgroundFromSubagent: options.allowBackgroundFromSubagent,
405
+ coalescer: options.subagentCoalescer,
404
406
  }),
405
407
  ]
406
408
  : [
@@ -444,6 +446,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
444
446
  getOrigin,
445
447
  permissions: options.permissions,
446
448
  stream: options.stream,
449
+ coalescer: options.subagentCoalescer,
447
450
  }),
448
451
  ...buildRoleGrantTools({
449
452
  agentDir: options.plugins?.agentDir,
@@ -845,6 +848,7 @@ export function buildSubagentOrchestrationTools(opts: {
845
848
  permissions: PermissionService | undefined
846
849
  stream: Stream | undefined
847
850
  allowBackgroundFromSubagent?: boolean
851
+ coalescer?: SubagentCoalescer
848
852
  }): ToolDefinition[] {
849
853
  if (
850
854
  opts.liveRegistry === undefined ||
@@ -867,6 +871,7 @@ export function buildSubagentOrchestrationTools(opts: {
867
871
  ...(opts.allowBackgroundFromSubagent !== undefined
868
872
  ? { allowBackgroundFromSubagent: opts.allowBackgroundFromSubagent }
869
873
  : {}),
874
+ ...(opts.coalescer !== undefined ? { coalescer: opts.coalescer } : {}),
870
875
  }),
871
876
  createSubagentOutputTool({
872
877
  liveRegistry: opts.liveRegistry,
@@ -32,6 +32,7 @@ export type LiveSubagent = {
32
32
  status: SubagentStatus
33
33
  completion?: SubagentCompletion
34
34
  abort: () => Promise<void>
35
+ releaseCoalesceKey?: () => void
35
36
  }
36
37
 
37
38
  export const MAX_EVENTS_PER_SUBAGENT = 100
@@ -96,6 +97,7 @@ export type StatusSnapshot = {
96
97
  export class LiveSubagentRegistry {
97
98
  private readonly entries = new Map<string, LiveSubagent>()
98
99
  private readonly events = new Map<string, SubagentProgressEvent[]>()
100
+ private readonly capturedFinalMessages = new Map<string, string>()
99
101
 
100
102
  register(live: LiveSubagent): void {
101
103
  if (this.entries.has(live.taskId)) {
@@ -108,6 +110,7 @@ export class LiveSubagentRegistry {
108
110
  unregister(taskId: string): void {
109
111
  this.entries.delete(taskId)
110
112
  this.events.delete(taskId)
113
+ this.capturedFinalMessages.delete(taskId)
111
114
  }
112
115
 
113
116
  get(taskId: string): LiveSubagent | undefined {
@@ -136,6 +139,17 @@ export class LiveSubagentRegistry {
136
139
  }
137
140
  }
138
141
 
142
+ recordCapturedFinalMessageIfRunning(taskId: string, finalMessage: string): boolean {
143
+ const entry = this.entries.get(taskId)
144
+ if (entry === undefined || entry.status !== 'running') return false
145
+ this.capturedFinalMessages.set(taskId, finalMessage)
146
+ return true
147
+ }
148
+
149
+ getCapturedFinalMessage(taskId: string): string | undefined {
150
+ return this.capturedFinalMessages.get(taskId)
151
+ }
152
+
139
153
  recordCompletion(taskId: string, completion: SubagentCompletion): void {
140
154
  const entry = this.entries.get(taskId)
141
155
  if (entry === undefined) return
@@ -186,6 +200,7 @@ export class LiveSubagentRegistry {
186
200
  clear(): void {
187
201
  this.entries.clear()
188
202
  this.events.clear()
203
+ this.capturedFinalMessages.clear()
189
204
  }
190
205
  }
191
206
 
@@ -1038,7 +1038,7 @@ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
1038
1038
 
1039
1039
  function resolveExposableBashEnvNames(agentDir: string): { exposable: string[]; withheld: string[] } {
1040
1040
  const declaredEnv = readEnvFile(agentDir)
1041
- const exposable = resolveExposableEnvNames(declaredEnv)
1041
+ const exposable = resolveExposableEnvNames(declaredEnv, process.env)
1042
1042
  const exposableSet = new Set(exposable)
1043
1043
  const withheld = [...declaredEnv]
1044
1044
  .filter(([name, value]) => value.length > 0 && !exposableSet.has(name))
@@ -126,6 +126,9 @@ export const PARTICIPANTS_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
126
126
  type PlatformInfo = {
127
127
  displayName: string
128
128
  mentionMode: 'angle-id' | 'at-username' | 'alias'
129
+ // This platform has no rich-text rendering, so markdown markers appear
130
+ // literally to users.
131
+ plainTextOnly: boolean
129
132
  // Whether this adapter registers a ReactionCallback, i.e. whether
130
133
  // `channel_react` actually does anything here. Gates the proactive-reaction
131
134
  // prompt guidance so we never tell a KakaoTalk/Telegram agent to react when
@@ -145,28 +148,90 @@ type PlatformInfo = {
145
148
  }
146
149
 
147
150
  const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
148
- slack: { displayName: 'Slack', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
149
- 'slack-bot': { displayName: 'Slack', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
150
- discord: { displayName: 'Discord', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
151
+ slack: {
152
+ displayName: 'Slack',
153
+ mentionMode: 'angle-id',
154
+ plainTextOnly: false,
155
+ supportsReactions: true,
156
+ supportsAttachments: true,
157
+ },
158
+ 'slack-bot': {
159
+ displayName: 'Slack',
160
+ mentionMode: 'angle-id',
161
+ plainTextOnly: false,
162
+ supportsReactions: true,
163
+ supportsAttachments: true,
164
+ },
165
+ discord: {
166
+ displayName: 'Discord',
167
+ mentionMode: 'angle-id',
168
+ plainTextOnly: false,
169
+ supportsReactions: true,
170
+ supportsAttachments: true,
171
+ },
151
172
  'discord-bot': {
152
173
  displayName: 'Discord',
153
174
  mentionMode: 'angle-id',
175
+ plainTextOnly: false,
154
176
  supportsReactions: true,
155
177
  supportsAttachments: true,
156
178
  },
157
- github: { displayName: 'GitHub', mentionMode: 'at-username', supportsReactions: true, supportsAttachments: false },
158
- instagram: { displayName: 'Instagram', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
179
+ github: {
180
+ displayName: 'GitHub',
181
+ mentionMode: 'at-username',
182
+ plainTextOnly: false,
183
+ supportsReactions: true,
184
+ supportsAttachments: false,
185
+ },
186
+ instagram: {
187
+ displayName: 'Instagram',
188
+ mentionMode: 'alias',
189
+ plainTextOnly: true,
190
+ supportsReactions: false,
191
+ supportsAttachments: false,
192
+ },
159
193
  'telegram-bot': {
160
194
  displayName: 'Telegram',
161
195
  mentionMode: 'at-username',
196
+ plainTextOnly: false,
197
+ supportsReactions: false,
198
+ supportsAttachments: true,
199
+ },
200
+ webex: {
201
+ displayName: 'Webex',
202
+ mentionMode: 'angle-id',
203
+ plainTextOnly: false,
204
+ supportsReactions: false,
205
+ supportsAttachments: true,
206
+ },
207
+ 'webex-bot': {
208
+ displayName: 'Webex',
209
+ mentionMode: 'angle-id',
210
+ plainTextOnly: false,
211
+ supportsReactions: false,
212
+ supportsAttachments: false,
213
+ },
214
+ teams: {
215
+ displayName: 'Teams',
216
+ mentionMode: 'alias',
217
+ plainTextOnly: false,
218
+ supportsReactions: false,
219
+ supportsAttachments: false,
220
+ },
221
+ line: {
222
+ displayName: 'LINE',
223
+ mentionMode: 'alias',
224
+ plainTextOnly: true,
225
+ supportsReactions: false,
226
+ supportsAttachments: false,
227
+ },
228
+ kakaotalk: {
229
+ displayName: 'KakaoTalk',
230
+ mentionMode: 'alias',
231
+ plainTextOnly: true,
162
232
  supportsReactions: false,
163
233
  supportsAttachments: true,
164
234
  },
165
- webex: { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: true },
166
- 'webex-bot': { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: false },
167
- teams: { displayName: 'Teams', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
168
- line: { displayName: 'LINE', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
169
- kakaotalk: { displayName: 'KakaoTalk', mentionMode: 'alias', supportsReactions: false, supportsAttachments: true },
170
235
  }
171
236
 
172
237
  function getPlatformInfo(adapter: AdapterId): PlatformInfo {
@@ -375,6 +440,10 @@ function renderChannelOrigin(
375
440
  'it via `channel_reply`/`gh pr comment`; that is a visible duplicate.',
376
441
  'One verdict, one surface. After submitting the review, use',
377
442
  '`skip_response({ reason: "verdict posted as review" })`.',
443
+ '',
444
+ 'GitHub renders real Markdown; use it freely.',
445
+ 'The GitHub adapter cannot send file attachments.',
446
+ 'GitHub has no typing indicator.',
378
447
  )
379
448
 
380
449
  // Models reliably address review-comment feedback and then end the turn
@@ -416,6 +485,25 @@ function renderChannelOrigin(
416
485
  )
417
486
  }
418
487
 
488
+ if (platformInfo.plainTextOnly) {
489
+ lines.push(
490
+ '',
491
+ 'This platform renders messages as PLAIN TEXT with no rich-text formatting.',
492
+ 'Write plain text from the start.',
493
+ 'Do not use markdown bold/italics, `##` headings, `|` tables, fenced code',
494
+ 'blocks, inline-code backticks, or `[label](url)` links; they appear literally.',
495
+ 'Send bare URLs; the client auto-links them.',
496
+ 'No threads and no quoted replies; every message is top-level.',
497
+ 'Keep replies short and conversational for mobile reading: lead with a',
498
+ 'one-sentence summary, then at most a few short lines.',
499
+ 'If asked for something the platform cannot do, say so plainly.',
500
+ platformInfo.supportsAttachments
501
+ ? 'Attachments can be passed via `attachments[]` on `channel_send`/`channel_reply`.'
502
+ : 'Outbound attachments and stickers are unsupported; send text or a link instead.',
503
+ ...(platformInfo.supportsAttachments ? ['Outbound stickers/emoticons are not supported.'] : []),
504
+ )
505
+ }
506
+
419
507
  const conversationLine = renderConversationLine(origin)
420
508
  if (conversationLine !== null) lines.push('', conversationLine)
421
509
 
@@ -616,18 +704,18 @@ function renderMentionGuidance(
616
704
  ]
617
705
  case 'at-username':
618
706
  return [
619
- `To mention someone in your reply, use Telegram syntax \`@username\` in plain text.`,
620
- 'Telegram usernames are a SEPARATE field from `authorId`; `<@id>` tokens',
707
+ `To mention someone in your reply, use ${platformInfo.displayName} syntax \`@username\` in plain text.`,
708
+ `${platformInfo.displayName} usernames are a SEPARATE field from \`authorId\`; \`<@id>\` tokens`,
621
709
  'in participants are inbound-only typeclaw markers, so do not echo them back as outbound mentions.',
622
710
  'If no `@username` is known, use display name; reply context carries it.',
623
711
  ...renderSelfMention(platformInfo, self),
624
712
  ]
625
713
  case 'alias':
626
714
  return [
627
- 'KakaoTalk has no in-band mention syntax. To address someone, just type their display name as plain text;',
715
+ `${platformInfo.displayName} has no in-band mention syntax. To address someone, just type their display name as plain text;`,
628
716
  "the participants block shows display names. Users get the bot's attention with configured aliases,",
629
717
  'not copied tokens. Any `<@id>` marker is inbound-only typeclaw convention;',
630
- 'do not echo them back as outbound mentions or KakaoTalk renders them literally.',
718
+ `do not echo them back as outbound mentions or ${platformInfo.displayName} renders them literally.`,
631
719
  ]
632
720
  }
633
721
  }
@@ -763,13 +851,13 @@ function renderParticipantsTrailing(platformInfo: PlatformInfo): string[] {
763
851
  case 'at-username':
764
852
  return [
765
853
  "If a current sender isn't listed, address by `@username` when known.",
766
- 'Telegram usernames are a SEPARATE field from numeric `authorId`, and',
854
+ `${platformInfo.displayName} usernames are a SEPARATE field from numeric \`authorId\`, and`,
767
855
  'not every user has one. The list is recent context, not a directory.',
768
856
  ]
769
857
  case 'alias':
770
858
  return [
771
859
  "If a current sender isn't listed, address by display name as plain text.",
772
- 'KakaoTalk has no in-band mention syntax; `authorId` is reference only',
860
+ `${platformInfo.displayName} has no in-band mention syntax; \`authorId\` is reference only`,
773
861
  'and must not be echoed back. The list is recent context, not a directory.',
774
862
  ]
775
863
  }
@@ -58,7 +58,7 @@ export function renderSubagentCompletionReminder(args: CompletionReminderArgs):
58
58
  const err = args.error ?? 'unknown error'
59
59
  const recoveryHint =
60
60
  args.hasRecoverableOutput === true
61
- ? `It produced output before failing — call subagent_output to recover it instead of redoing the work. `
61
+ ? `It produced output before failing — call subagent_output to recover it as partial recovery data, not a completed verdict, instead of redoing the work. `
62
62
  : `Use subagent_output to inspect. `
63
63
  return (
64
64
  `<system-reminder>\n` +
@@ -93,13 +93,22 @@ function expireOverdueChildren(
93
93
  if (child.startedAt > deadline) continue
94
94
  const durationMs = now() - child.startedAt
95
95
  const error = `subagent ${child.subagentName} exceeded the ${maxChildWaitMs}ms drain wait and was abandoned`
96
+ const finalMessage = drain.liveRegistry.getCapturedFinalMessage(child.taskId)
96
97
  // Claim the settlement BEFORE aborting. If the child's real completion
97
98
  // already won, skip — no double-settle, no broadcast. Awaiting abort here
98
99
  // would be the bug the ceiling exists to prevent: a wedged `session.abort()`
99
100
  // that never reaches idle would hang the drain, so fire-and-forget instead.
100
101
  // Logical settlement can precede physical teardown; startSubagent still
101
102
  // disposes the session when its own work settles.
102
- if (!drain.liveRegistry.recordCompletionIfRunning(child.taskId, { ok: false, durationMs, error })) continue
103
+ if (
104
+ !drain.liveRegistry.recordCompletionIfRunning(child.taskId, {
105
+ ok: false,
106
+ durationMs,
107
+ error,
108
+ ...(finalMessage !== undefined ? { finalMessage } : {}),
109
+ })
110
+ )
111
+ continue
103
112
  drain.stream.publish({
104
113
  target: { kind: 'broadcast' },
105
114
  payload: {
@@ -110,6 +119,7 @@ function expireOverdueChildren(
110
119
  ok: false,
111
120
  durationMs,
112
121
  error,
122
+ ...(finalMessage !== undefined ? { hasRecoverableOutput: true } : {}),
113
123
  },
114
124
  })
115
125
  void child.abort().catch(() => {})
@@ -103,6 +103,10 @@ export type SubagentShared<P = unknown> = {
103
103
  // caller. See `src/agent/reviewer-bash-policy.ts`. Omit for no restriction
104
104
  // (the historical contract — prompt-only enforcement).
105
105
  bashPolicy?: SubagentBashPolicy
106
+ // Stable logical-job key shared by every dispatch path. Subagents that omit
107
+ // it keep each spawn independent; declarations use it only when duplicate
108
+ // execution is safe to suppress for a validated payload identity.
109
+ inFlightKey?: (payload: P) => string
106
110
  }
107
111
 
108
112
  export type Subagent<P = unknown> = SubagentShared<P> & {
@@ -603,6 +607,7 @@ export function startSubagent(name: string, options: StartSubagentOptions): Star
603
607
  ...options,
604
608
  onFinalMessageCaptured: (msg) => {
605
609
  finalMessage = msg
610
+ options.onFinalMessageCaptured?.(msg)
606
611
  },
607
612
  onSessionCreated: (event) => {
608
613
  handleSettled = true
@@ -888,7 +893,7 @@ export type SubagentConsumerLogger = {
888
893
  error: (msg: string) => void
889
894
  }
890
895
 
891
- export type SubagentInFlightKey = (subagent: string, payload: unknown) => string
896
+ export type SubagentInFlightKey = (subagent: string, payload: unknown, parentSessionId?: string) => string
892
897
 
893
898
  export type CreateSubagentConsumerOptions = {
894
899
  stream: Stream
@@ -902,6 +907,7 @@ export type CreateSubagentConsumerOptions = {
902
907
  // memory-logger keyed by parentSessionId so different sessions run in parallel
903
908
  // while the same session deduplicates).
904
909
  inFlightKey?: SubagentInFlightKey
910
+ coalescer?: SubagentCoalescer
905
911
  logger?: SubagentConsumerLogger
906
912
  }
907
913
 
@@ -911,6 +917,43 @@ export type SubagentConsumer = {
911
917
  inFlightCount: () => number
912
918
  }
913
919
 
920
+ export class SubagentCoalescer {
921
+ private readonly inFlight = new Set<string>()
922
+
923
+ tryAcquire(key: string): boolean {
924
+ if (this.inFlight.has(key)) return false
925
+ this.inFlight.add(key)
926
+ return true
927
+ }
928
+
929
+ release(key: string): void {
930
+ this.inFlight.delete(key)
931
+ }
932
+
933
+ count(): number {
934
+ return this.inFlight.size
935
+ }
936
+ }
937
+
938
+ export function subagentCoalesceKey<P>(options: {
939
+ subagentName: string
940
+ payload: P
941
+ fallbackKey: string
942
+ inFlightKey?: (payload: P) => string
943
+ parentSessionId?: string
944
+ }): string {
945
+ let payloadKey = options.fallbackKey
946
+ if (options.inFlightKey !== undefined) {
947
+ try {
948
+ payloadKey = options.inFlightKey(options.payload)
949
+ } catch {
950
+ payloadKey = options.fallbackKey
951
+ }
952
+ }
953
+ const key = `${options.subagentName}:${payloadKey}`
954
+ return options.parentSessionId === undefined ? key : `${options.parentSessionId}:${key}`
955
+ }
956
+
914
957
  const consoleLogger: SubagentConsumerLogger = {
915
958
  info: (m) => console.log(m),
916
959
  warn: (m) => console.warn(m),
@@ -962,10 +1005,11 @@ export function createSubagentConsumer({
962
1005
  agentDir,
963
1006
  createSessionForSubagent,
964
1007
  inFlightKey = (name) => name,
1008
+ coalescer = new SubagentCoalescer(),
965
1009
  logger = consoleLogger,
966
1010
  }: CreateSubagentConsumerOptions): SubagentConsumer {
967
- const inFlight = new Set<string>()
968
1011
  let unsubscribe: Unsubscribe | null = null
1012
+ const localInFlight = new Set<string>()
969
1013
 
970
1014
  return {
971
1015
  start() {
@@ -984,12 +1028,12 @@ export function createSubagentConsumer({
984
1028
  logger.warn(`[subagent] no registered subagent "${name}", ignoring ${msg.id}`)
985
1029
  return
986
1030
  }
987
- const key = inFlightKey(name, msg.payload)
988
- if (inFlight.has(key)) {
1031
+ const key = inFlightKey(name, msg.payload, target.parentSessionId)
1032
+ if (!coalescer.tryAcquire(key)) {
989
1033
  logger.warn(`[subagent] ${key}: previous run still in progress, skipping`)
990
1034
  return
991
1035
  }
992
- inFlight.add(key)
1036
+ localInFlight.add(key)
993
1037
  try {
994
1038
  const spawnedByOrigin = parseSpawnedByOriginJson(target.spawnedByOriginJson, logger, name)
995
1039
  await awaitWithSubagentTimeout(
@@ -1016,7 +1060,8 @@ export function createSubagentConsumer({
1016
1060
  logger.error(`[subagent] ${key} failed: ${message}`)
1017
1061
  }
1018
1062
  } finally {
1019
- inFlight.delete(key)
1063
+ localInFlight.delete(key)
1064
+ coalescer.release(key)
1020
1065
  }
1021
1066
  })
1022
1067
  },
@@ -1025,7 +1070,7 @@ export function createSubagentConsumer({
1025
1070
  unsubscribe = null
1026
1071
  },
1027
1072
  inFlightCount() {
1028
- return inFlight.size
1073
+ return localInFlight.size
1029
1074
  },
1030
1075
  }
1031
1076
  }
@@ -14,6 +14,9 @@ type PostGithubReviewDetails = {
14
14
  ok: boolean
15
15
  error?: string
16
16
  code?: string
17
+ fallback?: 'comment'
18
+ messageId?: string
19
+ messageIds?: readonly string[]
17
20
  reviewId?: number
18
21
  state?: string
19
22
  downgraded?: boolean
@@ -63,8 +66,32 @@ export function createPostGithubReviewTool(options: {
63
66
  workspace: origin.workspace,
64
67
  prNumber,
65
68
  verdict,
69
+ retainDuplicateLease: params.event === 'REQUEST_CHANGES',
66
70
  })
67
- if (blocked !== null) return denied(logger, blocked.reason)
71
+ if (blocked !== null) {
72
+ if (
73
+ params.event === 'REQUEST_CHANGES' &&
74
+ blocked.kind === 'duplicate' &&
75
+ blocked.duplicateSource === 'standing'
76
+ ) {
77
+ try {
78
+ return await postDuplicateRequestChangesComment({
79
+ router,
80
+ origin,
81
+ sessionId,
82
+ prNumber,
83
+ body: params.body,
84
+ comments: (params.comments ?? []).map(toReviewFinding),
85
+ logger,
86
+ })
87
+ } finally {
88
+ if (blocked.leaseRetained === true) {
89
+ await verdictGuard.release({ callId: coordinationCallId, succeeded: false })
90
+ }
91
+ }
92
+ }
93
+ return denied(logger, blocked.reason)
94
+ }
68
95
  }
69
96
  const request: SubmitReviewRequest = {
70
97
  adapter: 'github',
@@ -113,6 +140,79 @@ export function createPostGithubReviewTool(options: {
113
140
  })
114
141
  }
115
142
 
143
+ async function postDuplicateRequestChangesComment(args: {
144
+ router: ChannelRouter
145
+ origin: ChannelReplyOrigin
146
+ sessionId: string
147
+ prNumber: number
148
+ body: string
149
+ comments: readonly ReviewFinding[]
150
+ logger: ChannelToolLogger
151
+ }) {
152
+ const result = await args.router.send(
153
+ {
154
+ adapter: 'github',
155
+ workspace: args.origin.workspace,
156
+ chat: args.origin.chat,
157
+ thread: null,
158
+ text: renderFallbackComment(args.body, args.comments),
159
+ },
160
+ { accountingTarget: args.origin },
161
+ )
162
+ if (!result.ok) return denied(args.logger, result.error, result.code)
163
+
164
+ recordReviewOutput({
165
+ sessionId: args.sessionId,
166
+ workspace: args.origin.workspace,
167
+ prNumber: args.prNumber,
168
+ state: 'COMMENT',
169
+ })
170
+
171
+ const details: PostGithubReviewDetails = {
172
+ ok: true,
173
+ fallback: 'comment',
174
+ ...(result.messageId !== undefined ? { messageId: result.messageId } : {}),
175
+ ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
176
+ }
177
+ return {
178
+ content: [
179
+ {
180
+ type: 'text' as const,
181
+ text: fenceToolResult(
182
+ 'GitHub PR comment posted because the existing CHANGES_REQUESTED review is still active.',
183
+ ),
184
+ },
185
+ ],
186
+ details,
187
+ }
188
+ }
189
+
190
+ function renderFallbackComment(body: string, comments: readonly ReviewFinding[]): string {
191
+ if (comments.length === 0) return body
192
+ return [
193
+ body,
194
+ '',
195
+ '---',
196
+ '',
197
+ ...comments.flatMap((comment) => [`**${markdownCodeSpan(renderLocation(comment))}**`, '', comment.body, '']),
198
+ ]
199
+ .slice(0, -1)
200
+ .join('\n')
201
+ }
202
+
203
+ function renderLocation(comment: ReviewFinding): string {
204
+ const lines = comment.startLine !== undefined ? `${comment.startLine}-${comment.line}` : String(comment.line)
205
+ const side = comment.side === 'LEFT' ? ' (old revision)' : ''
206
+ return `${comment.path.replace(/[\r\n]+/g, ' ')}:${lines}${side}`
207
+ }
208
+
209
+ function markdownCodeSpan(value: string): string {
210
+ const longestRun = Math.max(0, ...Array.from(value.matchAll(/`+/g), (match) => match[0].length))
211
+ const delimiter = '`'.repeat(longestRun + 1)
212
+ const padded = value.startsWith('`') || value.endsWith('`') ? ` ${value} ` : value
213
+ return `${delimiter}${padded}${delimiter}`
214
+ }
215
+
116
216
  function parsePrNumber(chat: string): number | null {
117
217
  const match = /^pr:(\d+)$/.exec(chat)
118
218
  if (match?.[1] === undefined) return null