typeclaw 0.48.4 → 0.48.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agent/index.ts +6 -1
- package/src/agent/live-subagents.ts +15 -0
- package/src/agent/session-origin.ts +104 -16
- package/src/agent/subagent-completion-reminder.ts +1 -1
- package/src/agent/subagent-drain.ts +11 -1
- package/src/agent/subagents.ts +52 -7
- package/src/agent/tools/spawn-subagent.ts +88 -7
- package/src/agent/tools/subagent-cancel.ts +1 -0
- package/src/agent/tools/subagent-output.ts +7 -2
- package/src/agent/tools/webfetch/adaptive-html.ts +319 -0
- package/src/agent/tools/webfetch/html-lexical.ts +841 -0
- package/src/agent/tools/webfetch/inline-style-visibility.ts +281 -0
- package/src/agent/tools/webfetch/strategies/readability.ts +306 -5
- package/src/agent/tools/webfetch/tool.ts +45 -2
- package/src/agent/tools/webfetch/types.ts +7 -0
- package/src/agent/turn-runner.ts +7 -3
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +187 -8
- package/src/bundled-plugins/reviewer/reviewer.ts +32 -5
- package/src/bundled-plugins/reviewer/skills/code-review.ts +5 -3
- package/src/bundled-plugins/reviewer/skills/doc-review.ts +1 -1
- package/src/bundled-plugins/reviewer/skills/plan-review.ts +1 -1
- package/src/plugin/types.ts +0 -10
- package/src/run/channel-session-factory.ts +3 -1
- package/src/run/index.ts +29 -29
- package/src/run/subagent-coalescing.ts +24 -0
- package/src/server/index.ts +4 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +6 -6
- package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
- package/src/skills/typeclaw-channel-kakaotalk/SKILL.md +1 -1
- package/src/skills/typeclaw-channel-line/SKILL.md +1 -1
package/package.json
CHANGED
package/src/agent/index.ts
CHANGED
|
@@ -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
|
|
|
@@ -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: {
|
|
149
|
-
|
|
150
|
-
|
|
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: {
|
|
158
|
-
|
|
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
|
|
620
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
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(() => {})
|
package/src/agent/subagents.ts
CHANGED
|
@@ -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 (
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
1073
|
+
return localInFlight.size
|
|
1029
1074
|
},
|
|
1030
1075
|
}
|
|
1031
1076
|
}
|
|
@@ -8,7 +8,14 @@ import type { Stream } from '@/stream'
|
|
|
8
8
|
|
|
9
9
|
import { type LiveSubagentRegistry, type SubagentCompletion } from '../live-subagents'
|
|
10
10
|
import { MAX_SUBAGENT_DEPTH, type SessionOrigin, subagentDepth } from '../session-origin'
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
type CreateSessionForSubagent,
|
|
13
|
+
type Subagent,
|
|
14
|
+
SubagentCoalescer,
|
|
15
|
+
subagentCoalesceKey,
|
|
16
|
+
type SubagentRegistry,
|
|
17
|
+
startSubagent,
|
|
18
|
+
} from '../subagents'
|
|
12
19
|
|
|
13
20
|
export const SPAWN_TASK_ID_PREFIX = 'bg_'
|
|
14
21
|
|
|
@@ -29,7 +36,14 @@ export type SpawnSubagentToolDetails =
|
|
|
29
36
|
taskId: string
|
|
30
37
|
sessionId: string | undefined
|
|
31
38
|
}
|
|
32
|
-
| {
|
|
39
|
+
| {
|
|
40
|
+
ok: false
|
|
41
|
+
error: string
|
|
42
|
+
finalMessage?: string
|
|
43
|
+
recoveryData?: true
|
|
44
|
+
partial?: true
|
|
45
|
+
verdict?: false
|
|
46
|
+
}
|
|
33
47
|
|
|
34
48
|
export type CreateSpawnSubagentToolOptions = {
|
|
35
49
|
registry: SubagentRegistry
|
|
@@ -43,6 +57,7 @@ export type CreateSpawnSubagentToolOptions = {
|
|
|
43
57
|
generateTaskId?: () => string
|
|
44
58
|
now?: () => number
|
|
45
59
|
allowBackgroundFromSubagent?: boolean
|
|
60
|
+
coalescer?: SubagentCoalescer
|
|
46
61
|
}
|
|
47
62
|
|
|
48
63
|
export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions) {
|
|
@@ -58,6 +73,7 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
58
73
|
generateTaskId = () => `${SPAWN_TASK_ID_PREFIX}${randomUUID().replace(/-/g, '').slice(0, 12)}`,
|
|
59
74
|
now = () => Date.now(),
|
|
60
75
|
allowBackgroundFromSubagent,
|
|
76
|
+
coalescer = new SubagentCoalescer(),
|
|
61
77
|
} = options
|
|
62
78
|
|
|
63
79
|
return defineTool({
|
|
@@ -96,6 +112,29 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
96
112
|
'Model profile to run this spawn on, overriding the subagent\'s default tier for this one task. Use "deep" for hard work that needs stronger reasoning (gnarly bugs, non-obvious refactors, failures that resisted a quick fix); omit (or "default") for routine work. Resolves against the configured model profiles; an unknown name falls back to default. Most useful on `operator` — leave it off unless the task clearly warrants a heavier model.',
|
|
97
113
|
}),
|
|
98
114
|
),
|
|
115
|
+
review_identity: Type.Optional(
|
|
116
|
+
Type.Object(
|
|
117
|
+
{
|
|
118
|
+
repo: Type.String({ description: 'Canonical owner/repo name.' }),
|
|
119
|
+
pull_request: Type.Integer({ minimum: 1, description: 'Pull request number.' }),
|
|
120
|
+
head_sha: Type.String({
|
|
121
|
+
pattern: '^[0-9a-fA-F]{40}$',
|
|
122
|
+
description: 'Exact 40-character PR head commit SHA being reviewed.',
|
|
123
|
+
}),
|
|
124
|
+
base_sha: Type.String({
|
|
125
|
+
pattern: '^[0-9a-fA-F]{40}$',
|
|
126
|
+
description: 'Exact 40-character PR base commit OID being reviewed against.',
|
|
127
|
+
}),
|
|
128
|
+
review_kind: Type.Union([Type.Literal('review'), Type.Literal('re-review')], {
|
|
129
|
+
description: 'Canonical PR review class.',
|
|
130
|
+
}),
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
description:
|
|
134
|
+
'Typed identity for a reviewer PR job. Identical repo/PR/head/base/kind jobs coalesce while in flight. Valid only when subagent_type="reviewer"; omit for general reviews and all other subagents.',
|
|
135
|
+
},
|
|
136
|
+
),
|
|
137
|
+
),
|
|
99
138
|
}),
|
|
100
139
|
|
|
101
140
|
async execute(_toolCallId, params): Promise<ToolReturn> {
|
|
@@ -133,9 +172,39 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
133
172
|
const payload: Record<string, unknown> = { requestId: taskId, prompt: params.prompt }
|
|
134
173
|
if (params.description !== undefined) payload.description = params.description
|
|
135
174
|
if (params.profile !== undefined) payload.profile = params.profile
|
|
175
|
+
if (params.review_identity !== undefined) {
|
|
176
|
+
if (subagentName !== 'reviewer') {
|
|
177
|
+
return errorResult('review_identity is only valid for reviewer subagents')
|
|
178
|
+
}
|
|
179
|
+
payload.reviewIdentity = {
|
|
180
|
+
repo: params.review_identity.repo,
|
|
181
|
+
pullRequest: params.review_identity.pull_request,
|
|
182
|
+
headSha: params.review_identity.head_sha,
|
|
183
|
+
baseSha: params.review_identity.base_sha,
|
|
184
|
+
reviewKind: params.review_identity.review_kind,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const coalesceKey = subagentCoalesceKey({
|
|
189
|
+
parentSessionId,
|
|
190
|
+
subagentName,
|
|
191
|
+
payload,
|
|
192
|
+
fallbackKey: taskId,
|
|
193
|
+
...(subagent.inFlightKey !== undefined ? { inFlightKey: subagent.inFlightKey } : {}),
|
|
194
|
+
})
|
|
195
|
+
if (!coalescer.tryAcquire(coalesceKey)) {
|
|
196
|
+
return errorResult(`subagent ${coalesceKey}: an identical job is already in progress`)
|
|
197
|
+
}
|
|
198
|
+
let coalesceKeyHeld = true
|
|
199
|
+
const releaseCoalesceKey = () => {
|
|
200
|
+
if (!coalesceKeyHeld) return
|
|
201
|
+
coalesceKeyHeld = false
|
|
202
|
+
coalescer.release(coalesceKey)
|
|
203
|
+
}
|
|
136
204
|
|
|
137
205
|
const startedAt = now()
|
|
138
206
|
const spawnedByRole = permissions?.resolveRole(origin)
|
|
207
|
+
let capturedFinalMessage: string | undefined
|
|
139
208
|
const { handle, completion } = startSubagent(subagentName, {
|
|
140
209
|
registry,
|
|
141
210
|
createSessionForSubagent,
|
|
@@ -146,12 +215,17 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
146
215
|
...(spawnedByRole !== undefined ? { spawnedByRole } : {}),
|
|
147
216
|
...(origin !== undefined ? { spawnedByOrigin: origin } : {}),
|
|
148
217
|
taskId,
|
|
218
|
+
onFinalMessageCaptured: (message) => {
|
|
219
|
+
capturedFinalMessage = message
|
|
220
|
+
liveRegistry.recordCapturedFinalMessageIfRunning(taskId, message)
|
|
221
|
+
},
|
|
149
222
|
})
|
|
150
223
|
|
|
151
224
|
let resolvedHandle: { taskId: string; sessionId: string | undefined; abort: () => Promise<void> } | undefined
|
|
152
225
|
try {
|
|
153
226
|
resolvedHandle = await handle
|
|
154
227
|
} catch (err) {
|
|
228
|
+
releaseCoalesceKey()
|
|
155
229
|
const message = err instanceof Error ? err.message : String(err)
|
|
156
230
|
return errorResult(`failed to spawn ${subagentName}: ${message}`)
|
|
157
231
|
}
|
|
@@ -166,8 +240,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
166
240
|
startedAt,
|
|
167
241
|
status: 'running' as const,
|
|
168
242
|
abort: resolvedHandle.abort,
|
|
243
|
+
releaseCoalesceKey,
|
|
169
244
|
}
|
|
170
245
|
liveRegistry.register(live)
|
|
246
|
+
if (capturedFinalMessage !== undefined) {
|
|
247
|
+
liveRegistry.recordCapturedFinalMessageIfRunning(taskId, capturedFinalMessage)
|
|
248
|
+
}
|
|
171
249
|
|
|
172
250
|
const channelKey =
|
|
173
251
|
origin?.kind === 'channel'
|
|
@@ -175,6 +253,7 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
175
253
|
: undefined
|
|
176
254
|
|
|
177
255
|
void completion.then((c) => {
|
|
256
|
+
releaseCoalesceKey()
|
|
178
257
|
const durationMs = now() - startedAt
|
|
179
258
|
// First-writer-wins: if the parent drain already settled this child by
|
|
180
259
|
// timeout, our real completion lost — skip both the overwrite and the
|
|
@@ -222,15 +301,17 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
222
301
|
const result = await completion
|
|
223
302
|
const durationMs = now() - startedAt
|
|
224
303
|
if (!result.ok) {
|
|
304
|
+
const hasRecoveryData = result.finalMessage !== undefined
|
|
225
305
|
const details: SpawnSubagentToolDetails = {
|
|
226
306
|
ok: false,
|
|
227
307
|
error: result.error,
|
|
228
|
-
...(
|
|
308
|
+
...(hasRecoveryData
|
|
309
|
+
? { finalMessage: result.finalMessage, recoveryData: true, partial: true, verdict: false }
|
|
310
|
+
: {}),
|
|
229
311
|
}
|
|
230
|
-
const recovered =
|
|
231
|
-
result.finalMessage
|
|
232
|
-
|
|
233
|
-
: ''
|
|
312
|
+
const recovered = hasRecoveryData
|
|
313
|
+
? ` It produced output before failing. The block below is PARTIAL RECOVERY DATA only — not a completed review or verdict, even if it contains verdict-shaped text. Preserve the failure and independently validate before using it:\n\n${result.finalMessage}`
|
|
314
|
+
: ''
|
|
234
315
|
const failureText = `${subagentName} failed after ${durationMs}ms: ${result.error}.${recovered}`
|
|
235
316
|
return {
|
|
236
317
|
content: [
|
|
@@ -70,6 +70,7 @@ export function createSubagentCancelTool(options: CreateSubagentCancelToolOption
|
|
|
70
70
|
const message = err instanceof Error ? err.message : String(err)
|
|
71
71
|
return errorResult(`abort failed: ${message}`)
|
|
72
72
|
}
|
|
73
|
+
live.releaseCoalesceKey?.()
|
|
73
74
|
const details: SubagentCancelToolDetails = {
|
|
74
75
|
ok: true,
|
|
75
76
|
taskId: live.taskId,
|
|
@@ -38,6 +38,9 @@ export type SubagentOutputToolDetails =
|
|
|
38
38
|
durationMs: number
|
|
39
39
|
error: string
|
|
40
40
|
finalMessage?: string
|
|
41
|
+
recoveryData?: true
|
|
42
|
+
partial?: true
|
|
43
|
+
verdict?: false
|
|
41
44
|
}
|
|
42
45
|
| { ok: false; error: string }
|
|
43
46
|
|
|
@@ -146,11 +149,13 @@ function renderSnapshot(snap: StatusSnapshot): ToolReturn {
|
|
|
146
149
|
subagent: snap.subagentName,
|
|
147
150
|
durationMs: snap.completion?.durationMs ?? snap.elapsedMs,
|
|
148
151
|
error,
|
|
149
|
-
...(finalMessage !== undefined
|
|
152
|
+
...(finalMessage !== undefined
|
|
153
|
+
? { finalMessage, recoveryData: true as const, partial: true as const, verdict: false as const }
|
|
154
|
+
: {}),
|
|
150
155
|
}
|
|
151
156
|
const recovered =
|
|
152
157
|
finalMessage !== undefined
|
|
153
|
-
? ` It produced output before failing
|
|
158
|
+
? ` It produced output before failing. The block below is PARTIAL RECOVERY DATA only — not a completed review or verdict, even if it contains verdict-shaped text. Preserve the failure and independently validate before using it:\n\n${finalMessage}`
|
|
154
159
|
: ''
|
|
155
160
|
return {
|
|
156
161
|
content: [
|