feat: add direct model programming agents
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Direct model conversations can now execute bounded platform-native processes and delegate one level of programming work without duplicating tools in Agent Runtimes. Process and Subagent activity follows existing workspace, mode, approval, cancellation, and lifecycle boundaries, with chat attribution and complete feature documentation. Remove the static Renderer bundle baseline gate and its build-only manifests; production builds continue to compile all processes and verify the control-plane installer. Also include the pending documentation link normalization. Release note: 直连模型现在可在 Execute 模式运行本机命令,并可委派编程 Subagent 完成修改、测试和复核;构建流程不再因静态 Renderer 包体基线阻塞。
This commit is contained in:
@@ -1386,17 +1386,24 @@ function reduceRecoveredAgentEvent(
|
||||
blocks: upsertRecoveredToolBlock(message.blocks, tool)
|
||||
}
|
||||
} else if (event.type === 'subagent') {
|
||||
const subagent: ConversationSubagentActivity = {
|
||||
const commonSubagent = {
|
||||
childTaskId: event.childTaskId,
|
||||
expertId: event.expertId,
|
||||
expertName: event.expertName,
|
||||
routingMode: event.routingMode,
|
||||
runtimeCallId: event.runtimeCallId,
|
||||
workMode: event.workMode,
|
||||
state: event.state,
|
||||
reason: event.reason,
|
||||
output: event.output,
|
||||
error: event.error
|
||||
}
|
||||
const subagent: ConversationSubagentActivity =
|
||||
'actor' in event
|
||||
? { ...commonSubagent, actor: event.actor }
|
||||
: {
|
||||
...commonSubagent,
|
||||
expertId: event.expertId,
|
||||
expertName: event.expertName
|
||||
}
|
||||
const subagents = [...(message.subagents ?? [])]
|
||||
const index = subagents.findIndex(
|
||||
(candidate) => candidate.childTaskId === event.childTaskId
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeModelUsageEvent } from '../agent/runtime'
|
||||
import {
|
||||
DIRECT_MODEL_SUBAGENT_ERROR_MAX_BYTES,
|
||||
DIRECT_MODEL_SUBAGENT_OUTPUT_MAX_BYTES,
|
||||
DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH,
|
||||
DirectModelSubagentService,
|
||||
type DirectModelSubagentEvent,
|
||||
type DirectModelSubagentParent,
|
||||
type DirectModelSubagentServiceDependencies
|
||||
} from './direct-model-subagent-service'
|
||||
import { SubagentScheduler } from './subagent-scheduler'
|
||||
|
||||
type RequestContext = {
|
||||
authorizationSnapshot: string
|
||||
}
|
||||
|
||||
const parent: DirectModelSubagentParent<RequestContext> = {
|
||||
requestId: 'parent-request',
|
||||
projectId: 'project',
|
||||
workMode: 'execute',
|
||||
requestContext: {
|
||||
authorizationSnapshot: 'snapshot'
|
||||
}
|
||||
}
|
||||
|
||||
function createHarness(
|
||||
runChild: DirectModelSubagentServiceDependencies<RequestContext>['runChild'],
|
||||
scheduler = new SubagentScheduler({
|
||||
concurrency: 2,
|
||||
queueLimit: 4,
|
||||
timeoutMs: 1_000
|
||||
})
|
||||
) {
|
||||
const events: DirectModelSubagentEvent[] = []
|
||||
const usageEvents: unknown[] = []
|
||||
const releaseConversation = vi.fn(async () => undefined)
|
||||
const service = new DirectModelSubagentService<RequestContext>({
|
||||
scheduler,
|
||||
runChild,
|
||||
releaseConversation
|
||||
})
|
||||
const run = (
|
||||
overrides: Partial<Parameters<typeof service.run>[0]> = {}
|
||||
) =>
|
||||
service.run({
|
||||
ownerId: 'owner',
|
||||
task: 'Inspect and test the focused change.',
|
||||
parent,
|
||||
signal: new AbortController().signal,
|
||||
onEvent: (event) => events.push(event),
|
||||
onModelUsage: (event) => usageEvents.push(event),
|
||||
...overrides
|
||||
})
|
||||
return {
|
||||
service,
|
||||
scheduler,
|
||||
events,
|
||||
usageEvents,
|
||||
releaseConversation,
|
||||
run
|
||||
}
|
||||
}
|
||||
|
||||
describe('DirectModelSubagentService', () => {
|
||||
it('completes with inherited context, child attribution, and no persistence dependency', async () => {
|
||||
let childInput:
|
||||
| Parameters<
|
||||
DirectModelSubagentServiceDependencies<RequestContext>['runChild']
|
||||
>[0]
|
||||
| undefined
|
||||
const usage: RuntimeModelUsageEvent = {
|
||||
requestId: 'child-model-request',
|
||||
type: 'model-usage',
|
||||
callId: 'call',
|
||||
runtime: 'model',
|
||||
provider: 'openai',
|
||||
model: 'model',
|
||||
inputTokens: 12,
|
||||
outputTokens: 7,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0
|
||||
}
|
||||
const harness = createHarness(async (input) => {
|
||||
childInput = input
|
||||
input.onOutput('completed output')
|
||||
input.onModelUsage(usage)
|
||||
})
|
||||
|
||||
const result = await harness.run()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'completed',
|
||||
output: 'completed output',
|
||||
outputTruncated: false,
|
||||
modelUsage: {
|
||||
inputTokens: 12,
|
||||
outputTokens: 7
|
||||
}
|
||||
})
|
||||
expect(result.childRunId).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
||||
)
|
||||
expect(childInput).toMatchObject({
|
||||
task: 'Inspect and test the focused change.',
|
||||
context: {
|
||||
parentRequestId: parent.requestId,
|
||||
childRunId: result.childRunId,
|
||||
projectId: parent.projectId,
|
||||
conversationId: result.conversationId,
|
||||
workMode: parent.workMode
|
||||
},
|
||||
requestContext: parent.requestContext
|
||||
})
|
||||
expect(result.conversationId).toBe(
|
||||
`direct-model-subagent:${parent.requestId}:${result.childRunId}`
|
||||
)
|
||||
expect(harness.events.map((event) => event.state)).toEqual([
|
||||
'queued',
|
||||
'running',
|
||||
'completed'
|
||||
])
|
||||
expect(harness.usageEvents).toEqual([
|
||||
expect.objectContaining({
|
||||
parentRequestId: parent.requestId,
|
||||
childRunId: result.childRunId,
|
||||
conversationId: result.conversationId,
|
||||
usage
|
||||
})
|
||||
])
|
||||
expect(harness.releaseConversation).toHaveBeenCalledOnce()
|
||||
expect(harness.releaseConversation).toHaveBeenCalledWith(
|
||||
result.conversationId,
|
||||
childInput?.context
|
||||
)
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('returns failed state with partial output and bounded errors', async () => {
|
||||
const harness = createHarness(async (input) => {
|
||||
input.onOutput('partial output')
|
||||
throw new Error('错'.repeat(3_000))
|
||||
})
|
||||
|
||||
const result = await harness.run()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
output: 'partial output',
|
||||
errorTruncated: true
|
||||
})
|
||||
expect(Buffer.byteLength(result.error ?? '')).toBeLessThanOrEqual(
|
||||
DIRECT_MODEL_SUBAGENT_ERROR_MAX_BYTES
|
||||
)
|
||||
expect(harness.events.at(-1)).toMatchObject({
|
||||
state: 'failed',
|
||||
output: 'partial output',
|
||||
error: result.error
|
||||
})
|
||||
expect(harness.releaseConversation).toHaveBeenCalledOnce()
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('bounds UTF-8 output by bytes and marks partial output explicitly', async () => {
|
||||
const harness = createHarness(async (input) => {
|
||||
input.onOutput('你'.repeat(100_000))
|
||||
input.onOutput('late output')
|
||||
})
|
||||
|
||||
const result = await harness.run()
|
||||
|
||||
expect(result.status).toBe('completed')
|
||||
expect(result.outputTruncated).toBe(true)
|
||||
expect(Buffer.byteLength(result.output)).toBeLessThanOrEqual(
|
||||
DIRECT_MODEL_SUBAGENT_OUTPUT_MAX_BYTES
|
||||
)
|
||||
expect(harness.events.at(-1)?.outputTruncated).toBe(true)
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('returns cancelled state with partial output on parent cancellation', async () => {
|
||||
const controller = new AbortController()
|
||||
const harness = createHarness(async (input) => {
|
||||
input.onOutput('partial before cancel')
|
||||
await new Promise<void>((resolve) => {
|
||||
input.signal.addEventListener('abort', () => resolve(), {
|
||||
once: true
|
||||
})
|
||||
})
|
||||
input.signal.throwIfAborted()
|
||||
})
|
||||
|
||||
const resultPromise = harness.run({ signal: controller.signal })
|
||||
await vi.waitFor(() =>
|
||||
expect(harness.events.map((event) => event.state)).toContain(
|
||||
'running'
|
||||
)
|
||||
)
|
||||
controller.abort(new Error('parent cancelled'))
|
||||
const result = await resultPromise
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'cancelled',
|
||||
output: 'partial before cancel',
|
||||
error: 'parent cancelled'
|
||||
})
|
||||
expect(harness.events.at(-1)?.state).toBe('cancelled')
|
||||
expect(harness.releaseConversation).toHaveBeenCalledOnce()
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('emits queued before the shared scheduler admits a run', async () => {
|
||||
const scheduler = new SubagentScheduler({
|
||||
concurrency: 1,
|
||||
queueLimit: 2,
|
||||
timeoutMs: 1_000
|
||||
})
|
||||
let releaseFirst!: () => void
|
||||
const firstGate = new Promise<void>((resolve) => {
|
||||
releaseFirst = resolve
|
||||
})
|
||||
const started: string[] = []
|
||||
const harness = createHarness(async (input) => {
|
||||
started.push(input.task)
|
||||
if (input.task === 'first') {
|
||||
await firstGate
|
||||
}
|
||||
input.onOutput(input.task)
|
||||
}, scheduler)
|
||||
|
||||
const first = harness.run({ task: 'first', ownerId: 'first-owner' })
|
||||
const second = harness.run({
|
||||
task: 'second',
|
||||
ownerId: 'second-owner'
|
||||
})
|
||||
await vi.waitFor(() => expect(started).toEqual(['first']))
|
||||
|
||||
expect(harness.events.map((event) => event.state)).toEqual([
|
||||
'queued',
|
||||
'queued',
|
||||
'running'
|
||||
])
|
||||
|
||||
releaseFirst()
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
expect.objectContaining({ status: 'completed', output: 'first' }),
|
||||
expect.objectContaining({ status: 'completed', output: 'second' })
|
||||
])
|
||||
expect(started).toEqual(['first', 'second'])
|
||||
scheduler.dispose()
|
||||
})
|
||||
|
||||
it('cancels only runs belonging to the released owner', async () => {
|
||||
const harness = createHarness(async (input) => {
|
||||
if (input.task === 'other') {
|
||||
input.onOutput('other completed')
|
||||
return
|
||||
}
|
||||
input.onOutput('owned partial')
|
||||
await new Promise<void>((resolve) => {
|
||||
input.signal.addEventListener('abort', () => resolve(), {
|
||||
once: true
|
||||
})
|
||||
})
|
||||
input.signal.throwIfAborted()
|
||||
})
|
||||
const owned = harness.run({
|
||||
ownerId: 'released-owner',
|
||||
task: 'owned'
|
||||
})
|
||||
const other = harness.run({
|
||||
ownerId: 'other-owner',
|
||||
task: 'other'
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(harness.events.filter(
|
||||
(event) => event.state === 'running'
|
||||
)).toHaveLength(2)
|
||||
)
|
||||
|
||||
await harness.service.releaseOwner(
|
||||
'released-owner',
|
||||
'owner released'
|
||||
)
|
||||
|
||||
await expect(owned).resolves.toMatchObject({
|
||||
status: 'cancelled',
|
||||
output: 'owned partial',
|
||||
error: 'owner released'
|
||||
})
|
||||
await expect(other).resolves.toMatchObject({
|
||||
status: 'completed',
|
||||
output: 'other completed'
|
||||
})
|
||||
expect(harness.releaseConversation).toHaveBeenCalledTimes(2)
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('releases synthetic conversations after queue rejection', async () => {
|
||||
const scheduler = new SubagentScheduler({
|
||||
concurrency: 1,
|
||||
queueLimit: 0,
|
||||
timeoutMs: 1_000
|
||||
})
|
||||
let releaseBlocker!: () => void
|
||||
const blocker = scheduler.schedule(
|
||||
() => new Promise<void>((resolve) => {
|
||||
releaseBlocker = resolve
|
||||
})
|
||||
)
|
||||
const harness = createHarness(async () => undefined, scheduler)
|
||||
|
||||
const result = await harness.run()
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.error).toContain('队列已满')
|
||||
expect(harness.events.map((event) => event.state)).toEqual([
|
||||
'queued',
|
||||
'failed'
|
||||
])
|
||||
expect(harness.releaseConversation).toHaveBeenCalledOnce()
|
||||
releaseBlocker()
|
||||
await blocker
|
||||
scheduler.dispose()
|
||||
})
|
||||
|
||||
it('validates trimmed task bounds before scheduling', async () => {
|
||||
const runChild = vi.fn(async () => undefined)
|
||||
const harness = createHarness(runChild)
|
||||
|
||||
await expect(harness.run({ task: ' ' })).rejects.toThrow(
|
||||
'任务不能为空'
|
||||
)
|
||||
await expect(harness.run({
|
||||
task: ` ${'x'.repeat(DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH)} `
|
||||
})).resolves.toMatchObject({ status: 'completed' })
|
||||
await expect(harness.run({
|
||||
task: 'x'.repeat(DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH + 1)
|
||||
})).rejects.toThrow('不能超过')
|
||||
expect(runChild).toHaveBeenCalledTimes(1)
|
||||
expect(harness.releaseConversation).toHaveBeenCalledOnce()
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
|
||||
it('uses distinct UUID identities for concurrent child runs', async () => {
|
||||
const harness = createHarness(async () => undefined)
|
||||
|
||||
const results = await Promise.all([
|
||||
harness.run({ ownerId: randomUUID() }),
|
||||
harness.run({ ownerId: randomUUID() })
|
||||
])
|
||||
|
||||
expect(results[0].childRunId).not.toBe(results[1].childRunId)
|
||||
expect(results[0].conversationId).not.toBe(
|
||||
results[1].conversationId
|
||||
)
|
||||
harness.scheduler.dispose()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,468 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import type { RuntimeModelUsageEvent } from '../agent/runtime'
|
||||
import { safeToolErrorDetail } from '../agent/approval-summary'
|
||||
import { SubagentScheduler } from './subagent-scheduler'
|
||||
|
||||
export const DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH = 100_000
|
||||
export const DIRECT_MODEL_SUBAGENT_OUTPUT_MAX_BYTES = 192 * 1024
|
||||
export const DIRECT_MODEL_SUBAGENT_ERROR_MAX_BYTES = 2 * 1024
|
||||
export const directModelSubagentInputSchema = z
|
||||
.object({
|
||||
task: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, '编程 Subagent 任务不能为空')
|
||||
.max(
|
||||
DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH,
|
||||
`编程 Subagent 任务不能超过 ${DIRECT_MODEL_SUBAGENT_TASK_MAX_LENGTH} 个字符`
|
||||
)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type DirectModelSubagentContext = {
|
||||
parentRequestId: string
|
||||
childRunId: string
|
||||
projectId?: string
|
||||
conversationId: string
|
||||
workMode: 'ask' | 'execute'
|
||||
}
|
||||
|
||||
export type DirectModelSubagentParent<TRequestContext = unknown> = {
|
||||
requestId: string
|
||||
projectId?: string
|
||||
workMode: 'ask' | 'execute'
|
||||
requestContext: TRequestContext
|
||||
}
|
||||
|
||||
export type DirectModelSubagentState =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
|
||||
export type DirectModelSubagentEvent = {
|
||||
parentRequestId: string
|
||||
childRunId: string
|
||||
conversationId: string
|
||||
workMode: 'ask' | 'execute'
|
||||
state: DirectModelSubagentState
|
||||
reason: string
|
||||
output?: string
|
||||
outputTruncated?: boolean
|
||||
error?: string
|
||||
errorTruncated?: boolean
|
||||
}
|
||||
|
||||
export type DirectModelSubagentUsageEvent = {
|
||||
parentRequestId: string
|
||||
childRunId: string
|
||||
conversationId: string
|
||||
usage: RuntimeModelUsageEvent
|
||||
}
|
||||
|
||||
export type DirectModelSubagentResult = {
|
||||
status: 'completed' | 'failed' | 'cancelled'
|
||||
childRunId: string
|
||||
conversationId: string
|
||||
output: string
|
||||
outputTruncated: boolean
|
||||
error?: string
|
||||
errorTruncated?: boolean
|
||||
modelUsage?: {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
}
|
||||
}
|
||||
|
||||
export type DirectModelSubagentRunInput<TRequestContext = unknown> = {
|
||||
ownerId: string
|
||||
task: string
|
||||
parent: DirectModelSubagentParent<TRequestContext>
|
||||
signal: AbortSignal
|
||||
onEvent: (event: DirectModelSubagentEvent) => void
|
||||
onModelUsage?: (event: DirectModelSubagentUsageEvent) => void
|
||||
}
|
||||
|
||||
export type DirectModelSubagentChildRunInput<TRequestContext = unknown> = {
|
||||
task: string
|
||||
context: DirectModelSubagentContext
|
||||
requestContext: TRequestContext
|
||||
signal: AbortSignal
|
||||
onOutput: (delta: string) => void
|
||||
onModelUsage: (usage: RuntimeModelUsageEvent) => void
|
||||
}
|
||||
|
||||
export type DirectModelSubagentServiceDependencies<TRequestContext = unknown> = {
|
||||
scheduler: SubagentScheduler
|
||||
runChild: (
|
||||
input: DirectModelSubagentChildRunInput<TRequestContext>
|
||||
) => Promise<void>
|
||||
releaseConversation: (
|
||||
conversationId: string,
|
||||
context: DirectModelSubagentContext
|
||||
) => void | Promise<void>
|
||||
}
|
||||
|
||||
type OwnerRun = {
|
||||
controller: AbortController
|
||||
settled: Promise<void>
|
||||
}
|
||||
|
||||
type MutableOutcome = {
|
||||
status: DirectModelSubagentResult['status']
|
||||
error?: string
|
||||
errorTruncated?: boolean
|
||||
}
|
||||
|
||||
function truncateUtf8(
|
||||
value: string,
|
||||
maximumBytes: number
|
||||
): { value: string; truncated: boolean } {
|
||||
const encoded = Buffer.from(value)
|
||||
if (encoded.byteLength <= maximumBytes) {
|
||||
return { value, truncated: false }
|
||||
}
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true })
|
||||
let end = maximumBytes
|
||||
while (end > 0) {
|
||||
try {
|
||||
return {
|
||||
value: decoder.decode(encoded.subarray(0, end)),
|
||||
truncated: true
|
||||
}
|
||||
} catch {
|
||||
end -= 1
|
||||
}
|
||||
}
|
||||
return { value: '', truncated: true }
|
||||
}
|
||||
|
||||
function errorDetail(error: unknown): {
|
||||
error: string
|
||||
errorTruncated: boolean
|
||||
} {
|
||||
const detail =
|
||||
safeToolErrorDetail(
|
||||
error,
|
||||
DIRECT_MODEL_SUBAGENT_ERROR_MAX_BYTES
|
||||
) ?? '编程 Subagent 执行失败'
|
||||
const bounded = truncateUtf8(
|
||||
detail,
|
||||
DIRECT_MODEL_SUBAGENT_ERROR_MAX_BYTES
|
||||
)
|
||||
return {
|
||||
error: bounded.value,
|
||||
errorTruncated: bounded.truncated
|
||||
}
|
||||
}
|
||||
|
||||
function addTokenCount(current: number, value: number): number {
|
||||
if (!Number.isSafeInteger(value) || value < 0) {
|
||||
return current
|
||||
}
|
||||
return Math.min(Number.MAX_SAFE_INTEGER, current + value)
|
||||
}
|
||||
|
||||
export class DirectModelSubagentService<TRequestContext = unknown> {
|
||||
private readonly ownerRuns = new Map<string, Set<OwnerRun>>()
|
||||
private disposed = false
|
||||
|
||||
constructor(
|
||||
private readonly dependencies:
|
||||
DirectModelSubagentServiceDependencies<TRequestContext>
|
||||
) {}
|
||||
|
||||
async run(
|
||||
input: DirectModelSubagentRunInput<TRequestContext>
|
||||
): Promise<DirectModelSubagentResult> {
|
||||
if (this.disposed) {
|
||||
throw new Error('编程 Subagent 服务已关闭')
|
||||
}
|
||||
const { task } = directModelSubagentInputSchema.parse({
|
||||
task: input.task
|
||||
})
|
||||
|
||||
const childRunId = randomUUID()
|
||||
const context: DirectModelSubagentContext = {
|
||||
parentRequestId: input.parent.requestId,
|
||||
childRunId,
|
||||
...(input.parent.projectId
|
||||
? { projectId: input.parent.projectId }
|
||||
: {}),
|
||||
conversationId:
|
||||
`direct-model-subagent:${input.parent.requestId}:${childRunId}`,
|
||||
workMode: input.parent.workMode
|
||||
}
|
||||
const controller = new AbortController()
|
||||
let settleOwnerRun!: () => void
|
||||
const ownerRun: OwnerRun = {
|
||||
controller,
|
||||
settled: new Promise<void>((resolve) => {
|
||||
settleOwnerRun = resolve
|
||||
})
|
||||
}
|
||||
this.addOwnerRun(input.ownerId, ownerRun)
|
||||
const forwardParentAbort = (): void => {
|
||||
controller.abort(input.signal.reason)
|
||||
}
|
||||
if (input.signal.aborted) {
|
||||
forwardParentAbort()
|
||||
} else {
|
||||
input.signal.addEventListener('abort', forwardParentAbort, {
|
||||
once: true
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.execute(input, task, context, controller.signal)
|
||||
} finally {
|
||||
input.signal.removeEventListener('abort', forwardParentAbort)
|
||||
this.removeOwnerRun(input.ownerId, ownerRun)
|
||||
settleOwnerRun()
|
||||
}
|
||||
}
|
||||
|
||||
async releaseOwner(
|
||||
ownerId: string,
|
||||
reason = '编程 Subagent 所属会话已释放'
|
||||
): Promise<void> {
|
||||
const runs = [...(this.ownerRuns.get(ownerId) ?? [])]
|
||||
if (runs.length === 0) {
|
||||
return
|
||||
}
|
||||
for (const run of runs) {
|
||||
run.controller.abort(new Error(reason))
|
||||
}
|
||||
await Promise.allSettled(runs.map((run) => run.settled))
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return
|
||||
}
|
||||
this.disposed = true
|
||||
await Promise.allSettled(
|
||||
[...this.ownerRuns.keys()].map((ownerId) =>
|
||||
this.releaseOwner(ownerId, '编程 Subagent 服务已关闭')
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private async execute(
|
||||
input: DirectModelSubagentRunInput<TRequestContext>,
|
||||
task: string,
|
||||
context: DirectModelSubagentContext,
|
||||
signal: AbortSignal
|
||||
): Promise<DirectModelSubagentResult> {
|
||||
let output = ''
|
||||
let outputBytes = 0
|
||||
let outputTruncated = false
|
||||
let inputTokens = 0
|
||||
let outputTokens = 0
|
||||
let usageReported = false
|
||||
let started = false
|
||||
let workOutcome: MutableOutcome | undefined
|
||||
let schedulerError: unknown
|
||||
let released = false
|
||||
let releaseError: unknown
|
||||
let finishWork!: () => void
|
||||
const workFinished = new Promise<void>((resolve) => {
|
||||
finishWork = resolve
|
||||
})
|
||||
|
||||
const emit = (
|
||||
state: DirectModelSubagentState,
|
||||
outcome?: MutableOutcome
|
||||
): void => {
|
||||
input.onEvent({
|
||||
parentRequestId: context.parentRequestId,
|
||||
childRunId: context.childRunId,
|
||||
conversationId: context.conversationId,
|
||||
workMode: context.workMode,
|
||||
state,
|
||||
reason: task.slice(0, 240),
|
||||
...((state === 'completed' ||
|
||||
state === 'failed' ||
|
||||
state === 'cancelled')
|
||||
? {
|
||||
output,
|
||||
outputTruncated,
|
||||
...(outcome?.error
|
||||
? {
|
||||
error: outcome.error,
|
||||
errorTruncated: outcome.errorTruncated
|
||||
}
|
||||
: {})
|
||||
}
|
||||
: {})
|
||||
})
|
||||
}
|
||||
|
||||
const release = async (): Promise<void> => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
released = true
|
||||
try {
|
||||
await this.dependencies.releaseConversation(
|
||||
context.conversationId,
|
||||
context
|
||||
)
|
||||
} catch (error) {
|
||||
releaseError = error
|
||||
}
|
||||
}
|
||||
|
||||
emit('queued')
|
||||
try {
|
||||
const scheduled = this.dependencies.scheduler.schedule(
|
||||
async (scheduledSignal) => {
|
||||
started = true
|
||||
emit('running')
|
||||
try {
|
||||
await this.dependencies.runChild({
|
||||
task,
|
||||
context,
|
||||
requestContext: input.parent.requestContext,
|
||||
signal: scheduledSignal,
|
||||
onOutput: (delta) => {
|
||||
if (typeof delta !== 'string') {
|
||||
throw new TypeError(
|
||||
'编程 Subagent 输出必须是字符串'
|
||||
)
|
||||
}
|
||||
if (outputTruncated) {
|
||||
return
|
||||
}
|
||||
const remaining =
|
||||
DIRECT_MODEL_SUBAGENT_OUTPUT_MAX_BYTES -
|
||||
outputBytes
|
||||
const bounded = truncateUtf8(delta, remaining)
|
||||
output += bounded.value
|
||||
outputBytes += Buffer.byteLength(bounded.value)
|
||||
outputTruncated = bounded.truncated
|
||||
},
|
||||
onModelUsage: (usage) => {
|
||||
usageReported = true
|
||||
inputTokens = addTokenCount(
|
||||
inputTokens,
|
||||
usage.inputTokens
|
||||
)
|
||||
outputTokens = addTokenCount(
|
||||
outputTokens,
|
||||
usage.outputTokens
|
||||
)
|
||||
input.onModelUsage?.({
|
||||
parentRequestId: context.parentRequestId,
|
||||
childRunId: context.childRunId,
|
||||
conversationId: context.conversationId,
|
||||
usage
|
||||
})
|
||||
}
|
||||
})
|
||||
if (scheduledSignal.aborted) {
|
||||
const detail = errorDetail(scheduledSignal.reason)
|
||||
workOutcome = {
|
||||
status: 'cancelled',
|
||||
...detail
|
||||
}
|
||||
} else {
|
||||
workOutcome = { status: 'completed' }
|
||||
}
|
||||
} catch (error) {
|
||||
const cancelled = scheduledSignal.aborted || signal.aborted
|
||||
workOutcome = {
|
||||
status: cancelled ? 'cancelled' : 'failed',
|
||||
...errorDetail(
|
||||
cancelled
|
||||
? scheduledSignal.reason ?? signal.reason ?? error
|
||||
: error
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
await release()
|
||||
if (releaseError && workOutcome?.status === 'completed') {
|
||||
workOutcome = {
|
||||
status: 'failed',
|
||||
...errorDetail(releaseError)
|
||||
}
|
||||
}
|
||||
finishWork()
|
||||
}
|
||||
return workOutcome!
|
||||
},
|
||||
signal
|
||||
)
|
||||
try {
|
||||
workOutcome = await scheduled
|
||||
} catch (error) {
|
||||
schedulerError = error
|
||||
}
|
||||
} catch (error) {
|
||||
schedulerError = error
|
||||
}
|
||||
|
||||
if (started) {
|
||||
await workFinished
|
||||
} else {
|
||||
await release()
|
||||
}
|
||||
|
||||
const outcome =
|
||||
workOutcome ??
|
||||
{
|
||||
status: signal.aborted ? 'cancelled' : 'failed',
|
||||
...errorDetail(
|
||||
signal.aborted
|
||||
? signal.reason ?? schedulerError
|
||||
: schedulerError ?? releaseError
|
||||
)
|
||||
}
|
||||
if (releaseError && !outcome.error) {
|
||||
Object.assign(outcome, errorDetail(releaseError))
|
||||
outcome.status = 'failed'
|
||||
}
|
||||
|
||||
emit(outcome.status, outcome)
|
||||
return {
|
||||
status: outcome.status,
|
||||
childRunId: context.childRunId,
|
||||
conversationId: context.conversationId,
|
||||
output,
|
||||
outputTruncated,
|
||||
...(outcome.error
|
||||
? {
|
||||
error: outcome.error,
|
||||
errorTruncated: outcome.errorTruncated
|
||||
}
|
||||
: {}),
|
||||
...(usageReported
|
||||
? {
|
||||
modelUsage: {
|
||||
inputTokens,
|
||||
outputTokens
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
private addOwnerRun(ownerId: string, run: OwnerRun): void {
|
||||
const runs = this.ownerRuns.get(ownerId) ?? new Set<OwnerRun>()
|
||||
runs.add(run)
|
||||
this.ownerRuns.set(ownerId, runs)
|
||||
}
|
||||
|
||||
private removeOwnerRun(ownerId: string, run: OwnerRun): void {
|
||||
const runs = this.ownerRuns.get(ownerId)
|
||||
if (!runs) {
|
||||
return
|
||||
}
|
||||
runs.delete(run)
|
||||
if (runs.size === 0) {
|
||||
this.ownerRuns.delete(ownerId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ describe('SubagentScheduler', () => {
|
||||
).rejects.toThrow('队列已满')
|
||||
controller.abort(new Error('cancelled'))
|
||||
await expect(queued).rejects.toThrow('cancelled')
|
||||
await expect(blocker).rejects.toThrow('120 秒')
|
||||
await expect(blocker).rejects.toThrow('1 秒')
|
||||
scheduler.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -117,7 +117,11 @@ export class SubagentScheduler {
|
||||
controller.abort(abortError(entry.signal))
|
||||
entry.signal?.addEventListener('abort', forwardAbort, { once: true })
|
||||
const timeout = setTimeout(() => {
|
||||
controller.abort(new Error('子专家任务超过 120 秒超时限制'))
|
||||
controller.abort(
|
||||
new Error(
|
||||
`子专家任务超过 ${Math.ceil(this.timeoutMs / 1_000)} 秒超时限制`
|
||||
)
|
||||
)
|
||||
}, this.timeoutMs)
|
||||
|
||||
const workPromise = Promise.resolve().then(() => {
|
||||
|
||||
Reference in New Issue
Block a user