fix: allow concurrent and unrestricted Runtime sessions

Local embedded OpenCode serialized otherwise independent conversations, and GoodBuddy could stop long Runtime tasks after fixed tool, activity, model-call, or accumulated display-output limits.

Different conversations can now run concurrently while requests in the same conversation stay ordered. Dynamic MCP tools remain isolated to the current request. OpenCode, Continue, managed ACP, and the Agent model gateway no longer stop native execution at GoodBuddy-defined call counts or prompt-wide output totals; display copies truncate and transport queues apply backpressure instead. Prompt-wide quota fields are removed from the current contracts.

Per-call model settings, provider request timeouts, cancellation, and same-conversation ordering remain unchanged.

Release note: 修复本机 OpenCode 不同会话互相等待的问题,并移除 GoodBuddy 对单次 Runtime 工具、活动和模型调用次数的人为上限;长输出现在只截断展示或施加传输背压,不再取消原生任务。
This commit is contained in:
mesalogo
2026-09-03 17:17:09 +08:00
parent b1e3101857
commit 8b9dbf55df
32 changed files with 687 additions and 549 deletions
+33 -21
View File
@@ -1544,7 +1544,7 @@ describe('AcpRemoteRuntime', () => {
})
})
it('bounds native subagent output per event and per request', async () => {
it('bounds native subagent output per event without a request-wide stop', async () => {
const client: { value?: AgentSideConnection } = {}
const server = fakeServer({
prompt: async ({ sessionId }) => {
@@ -1620,10 +1620,12 @@ describe('AcpRemoteRuntime', () => {
async () => 'once'
)
)
).rejects.toThrow('远端 Runtime 请求输出超过安全上限')
).resolves.toContainEqual(
expect.objectContaining({ type: 'done' })
)
})
it('rejects more than 100 distinct remote tool calls', async () => {
it('accepts more than 100 distinct remote tool calls', async () => {
const client: { value?: AgentSideConnection } = {}
const server = fakeServer({
prompt: async ({ sessionId }) => {
@@ -1634,7 +1636,7 @@ describe('AcpRemoteRuntime', () => {
sessionUpdate: 'tool_call',
toolCallId: `call-${index}`,
title: 'tool',
status: 'in_progress'
status: 'completed'
}
})
}
@@ -1643,17 +1645,18 @@ describe('AcpRemoteRuntime', () => {
})
client.value = server.client
await expect(
collect(
runtime(server).run(
request,
new AbortController().signal,
async () => 'once'
)
const events = await collect(
runtime(server).run(
request,
new AbortController().signal,
async () => 'once'
)
).rejects.toThrow(
'远端 Runtime 单次运行的工具调用超过 100 个'
)
expect(
events.filter((event) => event.type === 'tool')
).toHaveLength(101)
expect(events.at(-1)).toMatchObject({ type: 'done' })
})
it('does not impose a default wall-clock deadline on remote prompts', async () => {
@@ -2235,7 +2238,7 @@ describe('AcpRemoteRuntime', () => {
])
})
it('cancels and truncates a flood when the consumer is slow', async () => {
it('backpressures a flood without cancelling the Runtime', async () => {
const store = new MemoryRuntimeSessionBindingStore()
const client: { value?: AgentSideConnection } = {}
const cancel = vi.fn(async () => {})
@@ -2276,15 +2279,26 @@ describe('AcpRemoteRuntime', () => {
done: false
})
await new Promise((resolve) => setTimeout(resolve, 10))
await expect(stream.next()).rejects.toThrow('输出已截断')
const events = []
while (true) {
const next = await stream.next()
if (next.done) {
break
}
events.push(next.value)
}
expect(
events.filter((event) => event.type === 'text')
).toHaveLength(20)
expect(events.at(-1)).toMatchObject({ type: 'done' })
expect(server.setInboundPaused).toHaveBeenCalledWith(true)
expect(server.setInboundPaused).not.toHaveBeenCalledWith(false)
expect(cancel).toHaveBeenCalledOnce()
expect(server.setInboundPaused).toHaveBeenCalledWith(false)
expect(cancel).not.toHaveBeenCalled()
await expect(
store.getByConversation(request.conversationId)
).resolves.toMatchObject({
state: 'outcome-unknown',
activePromptOperationId: request.requestId
state: 'ready',
activePromptOperationId: undefined
})
})
@@ -2504,8 +2518,6 @@ describe('AcpRemoteRuntime Agent-owned prompts', () => {
capabilities: { imageInput: false },
limits: {
maximumOutputTokens: 4_096,
maximumModelCalls: 100,
maximumTotalOutputTokens: 409_600,
requestTimeoutMilliseconds: 60_000
}
}
+4 -55
View File
@@ -15,9 +15,6 @@ import {
import type {
AgentRuntimeStatus
} from '../../shared/contracts'
import {
maximumConversationToolActivities
} from '../../shared/assistant-contracts'
import {
assertRemotePromptAcceptanceMatchesPreparation,
REMOTE_SEMANTIC_TRANSCRIPT_LIMITS,
@@ -148,7 +145,6 @@ type ActivePrompt = {
updates: QueuedSessionUpdate[]
pendingUpdateBytes: number
inboundPaused: boolean
outputCharacters: number
toolCalls: Map<
string,
{
@@ -1846,19 +1842,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
this.options.maxPendingUpdateBytes ??
DEFAULT_MAX_PENDING_UPDATE_BYTES
)
if (
prompt.updates.length >= maximumItems ||
prompt.pendingUpdateBytes + bytes > maximumBytes
) {
const overflow = new Error(
'远端 Runtime 待消费事件超过安全上限,输出已截断且请求状态未知'
)
prompt.interruption = overflow
prompt.interrupt?.(overflow)
prompt.wake?.()
prompt.wake = undefined
throw overflow
}
let consume: (() => void) | undefined
const consumed = new Promise<void>((resolve) => {
consume = resolve
@@ -2030,19 +2013,13 @@ export class AcpRemoteRuntime implements AgentRuntime {
})
}
private limitEvent(
prompt: ActivePrompt,
event: RuntimePublicEvent
): RuntimePublicEvent {
private limitEvent(event: RuntimePublicEvent): RuntimePublicEvent {
const maximum =
this.options.maxEventCharacters ??
DEFAULT_MAX_EVENT_CHARACTERS
let characters = 0
if (event.type === 'text' || event.type === 'reasoning') {
characters = event.delta.length
if (characters > maximum) {
if (event.delta.length > maximum) {
event = { ...event, delta: `${event.delta.slice(0, maximum)}…` }
characters = maximum + 1
}
} else if (event.type === 'tool') {
const fieldMaximum = Math.max(1, Math.floor(maximum / 3))
@@ -2056,10 +2033,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
output: bounded(event.output),
error: bounded(event.error)
}
characters =
(event.input?.length ?? 0) +
(event.output?.length ?? 0) +
(event.error?.length ?? 0)
} else if (event.type === 'subagent') {
const fieldMaximum = Math.max(1, Math.floor(maximum / 2))
const bounded = (value: string | undefined): string | undefined =>
@@ -2071,10 +2044,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
output: bounded(event.output),
error: bounded(event.error)
}
characters =
(event.reason?.length ?? 0) +
(event.output?.length ?? 0) +
(event.error?.length ?? 0)
} else if (event.type === 'status') {
if (event.message.length > maximum) {
event = {
@@ -2082,15 +2051,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
message: `${event.message.slice(0, maximum)}…`
}
}
characters = event.message.length
}
prompt.outputCharacters += characters
if (
prompt.outputCharacters >
(this.options.maxRequestOutputBytes ??
DEFAULT_MAX_REQUEST_OUTPUT_BYTES)
) {
throw new Error('远端 Runtime 请求输出超过安全上限')
}
return event
}
@@ -2120,15 +2080,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
) {
const callId = update.toolCallId.slice(0, 256)
const previous = prompt.toolCalls.get(callId)
if (
!previous &&
prompt.toolCalls.size >=
maximumConversationToolActivities
) {
throw new Error(
'远端 Runtime 单次运行的工具调用超过 100 个'
)
}
const retainedMaximum =
this.options.maxEventCharacters ??
DEFAULT_MAX_EVENT_CHARACTERS
@@ -2359,7 +2310,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
updates: [],
pendingUpdateBytes: 0,
inboundPaused: false,
outputCharacters: 0,
toolCalls: new Map(),
open: true,
completed: false,
@@ -2559,7 +2509,7 @@ export class AcpRemoteRuntime implements AgentRuntime {
)
const mapped = this.mapUpdate(prompt, notification.update)
if (mapped !== undefined) {
publicEvents.push(this.limitEvent(prompt, mapped))
publicEvents.push(this.limitEvent(mapped))
}
} else if (transcriptEvent.kind === 'prompt-terminal') {
const terminal = transcriptTerminal(
@@ -2764,7 +2714,6 @@ export class AcpRemoteRuntime implements AgentRuntime {
updates: [],
pendingUpdateBytes: 0,
inboundPaused: false,
outputCharacters: 0,
toolCalls: new Map(),
open: true,
completed: false,
@@ -2867,7 +2816,7 @@ export class AcpRemoteRuntime implements AgentRuntime {
}
const event = this.mapUpdate(prompt, update)
if (event) {
yield this.limitEvent(prompt, event)
yield this.limitEvent(event)
}
}
await this.awaitOperation(
+70 -49
View File
@@ -1176,7 +1176,7 @@ describe('ContinueHostAdapter', () => {
expect(killed).toBe(true)
})
it('fails when the patched host reports dropped stream events', async () => {
it('completes from final history when the patched stream is truncated', async () => {
const distribution = await createDistribution()
let stateRequests = 0
vi.stubGlobal(
@@ -1185,11 +1185,23 @@ describe('ContinueHostAdapter', () => {
if (String(input).endsWith('/state')) {
stateRequests += 1
return Response.json({
session: { history: [] },
isProcessing: stateRequests > 1,
session: {
history:
stateRequests === 1
? []
: [
{
message: {
role: 'assistant',
content: 'CONTINUE_OK'
}
}
]
},
isProcessing: false,
messageQueueLength: 0,
pendingPermission: null,
goodbuddyEventsOverflow: stateRequests > 1
goodbuddyEventsOverflow: stateRequests === 2
})
}
return Response.json({})
@@ -1224,27 +1236,15 @@ describe('ContinueHostAdapter', () => {
new AbortController().signal,
async () => 'deny'
)
).rejects.toThrow('流式事件超过安全限制')
).resolves.toMatchObject({
text: 'CONTINUE_OK',
streamTruncated: true
})
})
it.each([
{
label: 'event count',
limits: {
maximumStreamEvents: 1,
maximumStreamEventBytes: 10_000
}
},
{
label: 'event bytes',
limits: {
maximumStreamEvents: 10,
maximumStreamEventBytes: 60
}
}
])(
'enforces cumulative streamed $label across state polls',
async ({ limits }) => {
it(
'truncates cumulative streamed bytes without stopping the run',
async () => {
const distribution = await createDistribution()
let stateRequests = 0
vi.stubGlobal(
@@ -1253,8 +1253,20 @@ describe('ContinueHostAdapter', () => {
if (String(input).endsWith('/state')) {
stateRequests += 1
return Response.json({
session: { history: [] },
isProcessing: stateRequests > 1,
session: {
history:
stateRequests < 3
? []
: [
{
message: {
role: 'assistant',
content: '1234567890CONTINUE_OK'
}
}
]
},
isProcessing: stateRequests === 2,
messageQueueLength: 0,
pendingPermission: null,
goodbuddyEvents:
@@ -1291,8 +1303,7 @@ describe('ContinueHostAdapter', () => {
}
},
{
...limits,
maximumToolCalls: 100,
maximumStreamEventBytes: 60,
terminateProcessTree: vi.fn().mockResolvedValue(undefined)
}
)
@@ -1308,14 +1319,18 @@ describe('ContinueHostAdapter', () => {
}
}
)
).rejects.toThrow('流式事件超过安全限制')
).resolves.toMatchObject({
text: '1234567890CONTINUE_OK',
streamedText: true,
streamTruncated: true
})
expect(forwarded).toEqual([
{ type: 'text', delta: '1234567890' }
])
}
)
it('enforces cumulative unique tool calls before forwarding a later batch', async () => {
it('forwards more than 100 unique tool calls', async () => {
const distribution = await createDistribution()
let stateRequests = 0
vi.stubGlobal(
@@ -1324,20 +1339,30 @@ describe('ContinueHostAdapter', () => {
if (String(input).endsWith('/state')) {
stateRequests += 1
return Response.json({
session: { history: [] },
isProcessing: stateRequests > 1,
session: {
history:
stateRequests === 1
? []
: [
{
message: {
role: 'assistant',
content: 'TOOLS_OK'
}
}
]
},
isProcessing: false,
messageQueueLength: 0,
pendingPermission: null,
goodbuddyEvents:
stateRequests > 1
? [
{
type: 'tool',
callId: `call-${stateRequests}`,
name: 'Bash',
state: 'running'
}
]
stateRequests === 2
? Array.from({ length: 101 }, (_, index) => ({
type: 'tool',
callId: `call-${index + 1}`,
name: 'Bash',
state: 'completed'
}))
: []
})
}
@@ -1369,9 +1394,7 @@ describe('ContinueHostAdapter', () => {
}
},
{
maximumStreamEvents: 10,
maximumStreamEventBytes: 10_000,
maximumToolCalls: 1,
maximumStreamEventBytes: 1_000_000,
terminateProcessTree: vi.fn().mockResolvedValue(undefined)
}
)
@@ -1387,11 +1410,11 @@ describe('ContinueHostAdapter', () => {
}
}
)
).rejects.toThrow('工具调用超过 100 个')
expect(forwarded).toHaveLength(1)
expect(forwarded[0]).toMatchObject({
).resolves.toMatchObject({ text: 'TOOLS_OK' })
expect(forwarded).toHaveLength(101)
expect(forwarded.at(-1)).toMatchObject({
type: 'tool',
tool: { callId: 'call-2' }
tool: { callId: 'call-101' }
})
})
@@ -1461,9 +1484,7 @@ describe('ContinueHostAdapter', () => {
}
},
{
maximumStreamEvents: 10,
maximumStreamEventBytes: 10_000,
maximumToolCalls: 10,
terminateProcessTree
}
)
+19 -56
View File
@@ -26,9 +26,6 @@ import type {
RuntimeNativeSnapshot,
RuntimeSettings
} from '../../shared/contracts'
import {
maximumConversationToolActivities
} from '../../shared/assistant-contracts'
import {
continueConfigurationPresetSchema,
runtimeNativeInventoryLimits,
@@ -69,9 +66,7 @@ const maximumConfiguredMcpServers =
runtimeNativeInventoryLimits.mcpServers
const maximumConfiguredRules = runtimeNativeInventoryLimits.rules
const maximumConfiguredPrompts = runtimeNativeInventoryLimits.prompts
const maximumStreamEvents = 5_000
const maximumStreamEventBytes = 2 * 1024 * 1024
const maximumToolCalls = maximumConversationToolActivities
const defaultControlRequestTimeoutMs = 30_000
const knowledgeMcpName = 'goodbuddy-knowledge'
const customMcpName = 'goodbuddy-custom-mcp'
@@ -142,7 +137,7 @@ const continueHostQuestionSchema = z
const stateSchema = z.object({
session: z.object({
history: z.array(z.unknown()).max(5_000),
history: z.array(z.unknown()),
usage: sessionUsageSchema.optional()
}),
isProcessing: z.boolean(),
@@ -152,12 +147,11 @@ const stateSchema = z.object({
toolName: z.string().min(1).max(128),
toolArgs: z.record(z.string(), z.unknown()),
requestId: z.string().min(1).max(256),
toolCallPreview: z.array(z.unknown()).max(100).optional()
toolCallPreview: z.array(z.unknown()).optional()
})
.nullable(),
goodbuddyEvents: z
.array(continueHostStreamEventSchema)
.max(maximumStreamEvents)
.optional(),
goodbuddyEventsOverflow: z.boolean().optional(),
goodbuddyQuestion: continueHostQuestionSchema.nullable().optional()
@@ -199,6 +193,7 @@ export type ContinueHostTool = {
export type ContinueHostRunResult = {
text: string
streamedText?: true
streamTruncated?: true
usage?: ContinueHostUsage
tools?: ContinueHostTool[]
}
@@ -249,9 +244,7 @@ export type ContinueHostAdapterOptions = {
export type ContinueHostAdapterDependencies = {
terminateProcessTree: typeof terminateProcessTreeAndWait
maximumStreamEvents: number
maximumStreamEventBytes: number
maximumToolCalls: number
controlRequestTimeoutMs: number
}
@@ -713,9 +706,6 @@ function extractContinueTools(
if (!callId || typeof name !== 'string' || !name.trim()) {
continue
}
if (!tools.has(callId) && tools.size >= 100) {
throw new Error('Continue 单次运行的工具调用超过 100 个')
}
const status = state.status
const normalizedState =
status === 'done' || status === 'completed'
@@ -834,9 +824,7 @@ export class ContinueHostAdapter {
) {
this.dependencies = {
terminateProcessTree: terminateProcessTreeAndWait,
maximumStreamEvents,
maximumStreamEventBytes,
maximumToolCalls,
controlRequestTimeoutMs: defaultControlRequestTimeoutMs,
...dependencies
}
@@ -985,7 +973,7 @@ export class ContinueHostAdapter {
patched = replaceExactly(
patched,
streamCallbacksMarker,
'a={onContent:u=>{if(!u)return;let l=String(u);e.goodbuddyEventsBytes+=Buffer.byteLength(l);l.length<=1e5&&e.goodbuddyEvents.length<5e3&&e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push({type:"text",delta:l}):e.goodbuddyEventsOverflow=!0},onContentComplete:u=>{},onToolStart:(u,l,c)=>{if(!c)return;let d={type:"tool",callId:c,name:u,state:"running",input:(()=>{try{return JSON.stringify(l).slice(0,4e3)}catch{return"[无法序列化]"}})()};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(d));e.goodbuddyEvents.length<5e3&&e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(d):e.goodbuddyEventsOverflow=!0},onToolResult:(u,l,c,d)=>{if(!d)return;let p={type:"tool",callId:d,name:l,state:c==="done"?"completed":"failed",output:String(u).slice(0,16e3)};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(p));e.goodbuddyEvents.length<5e3&&e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(p):e.goodbuddyEventsOverflow=!0},onToolError:(u,l,c)=>{if(!c)return;let d={type:"tool",callId:c,name:l??"unknown",state:"failed",error:String(u).slice(0,1e3)};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(d));e.goodbuddyEvents.length<5e3&&e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(d):e.goodbuddyEventsOverflow=!0},onToolPermissionRequest:'
'a={onContent:u=>{if(!u)return;let l=String(u);e.goodbuddyEventsBytes+=Buffer.byteLength(l);l.length<=1e5&&e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push({type:"text",delta:l}):e.goodbuddyEventsOverflow=!0},onContentComplete:u=>{},onToolStart:(u,l,c)=>{if(!c)return;let d={type:"tool",callId:c,name:u,state:"running",input:(()=>{try{return JSON.stringify(l).slice(0,4e3)}catch{return"[无法序列化]"}})()};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(d));e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(d):e.goodbuddyEventsOverflow=!0},onToolResult:(u,l,c,d)=>{if(!d)return;let p={type:"tool",callId:d,name:l,state:c==="done"?"completed":"failed",output:String(u).slice(0,16e3)};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(p));e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(p):e.goodbuddyEventsOverflow=!0},onToolError:(u,l,c)=>{if(!c)return;let d={type:"tool",callId:c,name:l??"unknown",state:"failed",error:String(u).slice(0,1e3)};e.goodbuddyEventsBytes+=Buffer.byteLength(JSON.stringify(d));e.goodbuddyEventsBytes<=2097152?e.goodbuddyEvents.push(d):e.goodbuddyEventsOverflow=!0},onToolPermissionRequest:'
)
patched = replaceExactly(
patched,
@@ -1584,7 +1572,7 @@ export class ContinueHostAdapter {
let observedTools: ContinueHostTool[] = []
const reportedQuestionIds = new Set<string>()
let streamedText = false
let streamEventCount = 0
let streamTruncated = false
let streamEventBytes = 0
const observedToolCallIds = new Set<string>()
try {
@@ -1635,38 +1623,28 @@ export class ContinueHostAdapter {
signal: executionSignal
})
)
if (state.goodbuddyEventsOverflow) {
throw new Error('Continue 宿主流式事件超过安全限制')
}
const streamEvents = state.goodbuddyEvents ?? []
streamTruncated ||= state.goodbuddyEventsOverflow === true
let streamEvents = state.goodbuddyEvents ?? []
const batchStreamEventBytes = Buffer.byteLength(
JSON.stringify(streamEvents)
)
const nextStreamEventCount =
streamEventCount + streamEvents.length
const nextStreamEventBytes =
streamEventBytes + batchStreamEventBytes
if (
nextStreamEventBytes >
this.dependencies.maximumStreamEventBytes
) {
streamTruncated = true
streamEvents = []
} else {
streamEventBytes = nextStreamEventBytes
}
const nextToolCallIds = new Set(observedToolCallIds)
for (const event of streamEvents) {
if (event.type === 'tool') {
nextToolCallIds.add(event.callId)
}
}
if (
nextStreamEventCount >
this.dependencies.maximumStreamEvents ||
nextStreamEventBytes >
this.dependencies.maximumStreamEventBytes
) {
throw new Error('Continue 宿主流式事件超过安全限制')
}
if (
nextToolCallIds.size > this.dependencies.maximumToolCalls
) {
throw new Error('Continue 单次运行的工具调用超过 100 个')
}
streamEventCount = nextStreamEventCount
streamEventBytes = nextStreamEventBytes
for (const callId of nextToolCallIds) {
observedToolCallIds.add(callId)
}
@@ -1677,11 +1655,6 @@ export class ContinueHostAdapter {
for (const tool of historyTools) {
observedToolCallIds.add(tool.callId)
}
if (
observedToolCallIds.size > this.dependencies.maximumToolCalls
) {
throw new Error('Continue 单次运行的工具调用超过 100 个')
}
observedTools = mergeContinueTools(
observedTools,
historyTools
@@ -1744,12 +1717,6 @@ export class ContinueHostAdapter {
}
const pending = state.pendingPermission
if (pending && !handledPermissionIds.has(pending.requestId)) {
if (
handledPermissionIds.size >=
this.dependencies.maximumToolCalls
) {
throw new Error('Continue 单次运行的工具调用超过 100 个')
}
handledPermissionIds.add(pending.requestId)
const pendingCallId =
observedTools.find(
@@ -1761,13 +1728,6 @@ export class ContinueHostAdapter {
if (
!observedTools.some((tool) => tool.callId === pendingCallId)
) {
if (
!observedToolCallIds.has(pendingCallId) &&
observedToolCallIds.size >=
this.dependencies.maximumToolCalls
) {
throw new Error('Continue 单次运行的工具调用超过 100 个')
}
observedToolCallIds.add(pendingCallId)
observedTools = [
...observedTools,
@@ -1829,6 +1789,9 @@ export class ContinueHostAdapter {
return {
text,
...(streamedText ? { streamedText: true as const } : {}),
...(streamTruncated
? { streamTruncated: true as const }
: {}),
...(usage ? { usage } : {}),
...(observedTools.length > 0
? { tools: observedTools }
+10 -6
View File
@@ -1134,7 +1134,7 @@ describe('ContinueAgentRuntime', () => {
).rejects.toThrow('已失效或不存在')
})
it('fails instead of silently dropping an overflowing stream queue', async () => {
it('drains more than 1,000 queued stream events without stopping the run', async () => {
mocks.runHost.mockImplementation(
async (
_prompt,
@@ -1160,11 +1160,15 @@ describe('ContinueAgentRuntime', () => {
new AbortController().signal
)
await expect(async () => {
for await (const _event of stream) {
void _event
}
}).rejects.toThrow('流式事件积压超过安全限制')
const events: RuntimeEvent[] = []
for await (const event of stream) {
events.push(event)
}
expect(
events.filter((event) => event.type === 'text')
).toHaveLength(1_001)
expect(events.at(-1)).toMatchObject({ type: 'done' })
})
it('aborts the host run when stream consumption ends early', async () => {
+19 -7
View File
@@ -64,7 +64,6 @@ export type ContinueRuntimeOptions = {
// The prompt reaches the Continue host through a local HTTP POST body, so no
// platform command-line limit applies to it.
const MAX_CONTINUE_PROMPT_CHARACTERS = 128_000
const MAX_QUEUED_STREAM_EVENTS = 1_000
const scopedReadToolNameSet = new Set<string>(scopedReadToolNames)
function continueToolFailureMessage(tool: ContinueHostTool): string {
@@ -548,6 +547,7 @@ export class ContinueAgentRuntime implements AgentRuntime {
}
let result: ContinueHostRunResult
const emittedTools = new Map<string, ContinueHostTool>()
let emittedText = ''
const requestQuestionIds = new Set<string>()
try {
const host = this.getHostAdapter(
@@ -574,9 +574,6 @@ export class ContinueAgentRuntime implements AgentRuntime {
const hostController = new AbortController()
const hostSignal = AbortSignal.any([signal, hostController.signal])
const onEvent = (event: ContinueHostStreamEvent): void => {
if (queuedEvents.length >= MAX_QUEUED_STREAM_EVENTS) {
throw new Error('Continue 流式事件积压超过安全限制')
}
queuedEvents.push(event)
wakeStream?.()
wakeStream = undefined
@@ -623,6 +620,7 @@ export class ContinueAgentRuntime implements AgentRuntime {
emittedTools.set(event.tool.callId, event.tool)
}
if (event.type === 'text') {
emittedText += event.delta
yield {
requestId: request.requestId,
type: 'text',
@@ -742,11 +740,25 @@ export class ContinueAgentRuntime implements AgentRuntime {
yield finalEvent
}
}
if (!result.streamedText) {
if (result.streamTruncated) {
yield {
requestId: request.requestId,
type: 'text',
delta: result.text
type: 'status',
message:
'Continue 输出较长,已截断部分流式展示;任务已继续完成'
}
}
if (!result.streamedText || result.streamTruncated) {
const remainingText =
result.streamTruncated && result.text.startsWith(emittedText)
? result.text.slice(emittedText.length)
: result.text
if (remainingText) {
yield {
requestId: request.requestId,
type: 'text',
delta: remainingText
}
}
}
if (result.usage) {
+81 -29
View File
@@ -2035,7 +2035,7 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
await runtime.dispose()
})
it('fails before emitting text that exceeds the aggregate output budget', async () => {
it('truncates oversized text display without stopping the run', async () => {
const setup = runClient([
{
id: 'first-text',
@@ -2056,29 +2056,50 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
field: 'text',
delta: 'b'.repeat(600_000)
}
},
{
id: 'idle',
type: 'session.idle',
properties: { sessionID: 'session-1' }
}
])
const runtime = embeddedRuntime(setup.client)
const stream = runtime.run(
{
requestId: '3f496642-f47d-4e0a-8944-a32c77b0d6ef',
conversationId: 'conversation-1',
prompt: 'test',
workMode: 'execute'
},
new AbortController().signal
)
const events = await collectRun(runtime, 'execute')
const text = events
.flatMap((event) => event.type === 'text' ? [event.delta] : [])
.join('')
await stream.next()
const firstText = await stream.next()
expect(firstText.value).toMatchObject({
type: 'text',
delta: expect.stringMatching(/^a+$/u)
expect(Buffer.byteLength(text)).toBe(1024 * 1024)
expect(events).toContainEqual({
requestId: '3f496642-f47d-4e0a-8944-a32c77b0d6ef',
type: 'status',
message:
'OpenCode 输出较长,已停止继续展示文本;任务仍在继续'
})
await expect(stream.next()).rejects.toThrow(
'文本与推理输出超过 1 MB 安全限制'
)
expect(setup.session.abort).toHaveBeenCalled()
expect(events.at(-1)).toMatchObject({ type: 'done' })
expect(setup.session.abort).not.toHaveBeenCalled()
await runtime.dispose()
})
it('completes more than 100 distinct tool calls in one run', async () => {
const setup = runClient([
...Array.from({ length: 101 }, (_, index) =>
completedToolEvent(`call-${index + 1}`)
),
{
id: 'idle',
type: 'session.idle',
properties: { sessionID: 'session-1' }
}
])
const runtime = embeddedRuntime(setup.client)
const events = await collectRun(runtime, 'execute')
expect(
events.filter((event) => event.type === 'tool')
).toHaveLength(101)
expect(events.at(-1)).toMatchObject({ type: 'done' })
await runtime.dispose()
})
@@ -2184,6 +2205,8 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
read: false,
write: false,
bash: false,
'goodbuddy-data-*': false,
'goodbuddy-custom-*': false,
[knowledgeToolId]: true
}
}),
@@ -2264,7 +2287,7 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
await runtime.dispose()
})
it('serializes overlapping embedded MCP registration and discovery', async () => {
it('runs embedded conversations concurrently with request-scoped MCP registrations', async () => {
const setup = runClient([
{
id: 'idle',
@@ -2357,13 +2380,19 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
'conversation-two',
'second-token'
)
await new Promise((resolve) => setTimeout(resolve, 10))
expect(mcpAdd).toHaveBeenCalledTimes(1)
resolveFirstAdd()
await first
await vi.waitFor(() => expect(mcpAdd).toHaveBeenCalledTimes(2))
await second
try {
await vi.waitFor(
() => expect(mcpAdd).toHaveBeenCalledTimes(2),
{ timeout: 500 }
)
await vi.waitFor(
() => expect(setup.session.promptAsync).toHaveBeenCalledOnce(),
{ timeout: 500 }
)
} finally {
resolveFirstAdd()
}
await Promise.all([first, second])
expect(
mcpAdd.mock.calls.map(
([input]) =>
@@ -2483,6 +2512,8 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
write: false,
bash: false,
task: false,
'goodbuddy-data-*': false,
'goodbuddy-custom-*': false,
skill: true
}
}),
@@ -2557,11 +2588,30 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
title: 'GoodBuddy 对话',
directory: process.cwd(),
permission: [
{ permission: '*', pattern: '*', action: 'allow' }
{ permission: '*', pattern: '*', action: 'allow' },
{
permission: 'goodbuddy-data-*',
pattern: '*',
action: 'deny'
},
{
permission: 'goodbuddy-custom-*',
pattern: '*',
action: 'deny'
}
]
},
{ signal: expect.any(AbortSignal) }
)
expect(session.promptAsync).toHaveBeenCalledWith(
expect.objectContaining({
tools: {
'goodbuddy-data-*': false,
'goodbuddy-custom-*': false
}
}),
expect.anything()
)
expect(permissionReply).toHaveBeenCalledOnce()
expect(permissionReply).toHaveBeenCalledWith(
{
@@ -2926,7 +2976,9 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
read: false,
write: false,
bash: false,
task: false
task: false,
'goodbuddy-data-*': false,
'goodbuddy-custom-*': false
}
}),
expect.anything()
+76 -86
View File
@@ -22,9 +22,6 @@ import type {
AgentRuntimeStatus,
SubagentEvent
} from '../../shared/contracts'
import {
maximumConversationToolActivities
} from '../../shared/assistant-contracts'
import {
boundedRuntimeIdentifierSchema,
runtimeNativeInventoryLimits,
@@ -78,7 +75,6 @@ const MAX_PERMISSION_PATTERNS = 32
const MAX_PERMISSION_PATTERN_LENGTH = 1_024
const MAX_PERMISSION_PATTERNS_BYTES = 8 * 1_024
const MAX_PERMISSION_METADATA_BYTES = 8 * 1_024
const MAX_TOOL_CALLS_PER_RUN = maximumConversationToolActivities
const MAX_EXECUTION_OUTPUT_BYTES = 1024 * 1024
const MAX_QUESTION_REQUEST_BYTES = 32 * 1_024
const MAX_QUESTIONS_PER_REQUEST = 4
@@ -99,6 +95,15 @@ const TEMPORARY_MCP_PREFIXES = [
'goodbuddy-data-',
'goodbuddy-custom-'
] as const
const temporaryMcpToolOverrides = Object.fromEntries(
TEMPORARY_MCP_PREFIXES.map((prefix) => [`${prefix}*`, false])
)
const temporaryMcpDenyRules: PermissionRuleset =
TEMPORARY_MCP_PREFIXES.map((prefix) => ({
permission: `${prefix}*`,
pattern: '*',
action: 'deny'
}))
const OPENCODE_INTERNAL_TOOL_IDS = new Set(['invalid'])
const OPENCODE_BUILTIN_TOOL_KINDS: Readonly<
Partial<Record<string, RuntimeNativeTool['kind']>>
@@ -719,7 +724,6 @@ export class OpenCodeRuntime implements AgentRuntime {
upstreamQuestionId: string
}
>()
private embeddedRunTail: Promise<void> = Promise.resolve()
private readonly conversationRunTails = new Map<string, Promise<void>>()
private readonly dependencies: OpenCodeRuntimeDependencies
@@ -751,36 +755,6 @@ export class OpenCodeRuntime implements AgentRuntime {
return this.usesEmbeddedPermissionMediation()
}
private async acquireEmbeddedRun(
signal: AbortSignal
): Promise<() => void> {
signal.throwIfAborted()
const previous = this.embeddedRunTail
let release!: () => void
const current = new Promise<void>((resolve) => {
release = resolve
})
this.embeddedRunTail = previous.then(
() => current,
() => current
)
let abort!: () => void
const aborted = new Promise<never>((_resolve, reject) => {
abort = () => reject(signal.reason)
})
signal.addEventListener('abort', abort, { once: true })
try {
await Promise.race([previous, aborted])
signal.throwIfAborted()
return release
} catch (error) {
release()
throw error
} finally {
signal.removeEventListener('abort', abort)
}
}
private async acquireConversationRun(
conversationId: string,
signal: AbortSignal
@@ -1835,12 +1809,8 @@ export class OpenCodeRuntime implements AgentRuntime {
const executionSignal = deadline
? AbortSignal.any([signal, deadline.signal])
: signal
let releaseEmbedded: (() => void) | undefined
let releaseConversation: (() => void) | undefined
try {
releaseEmbedded = this.usesEmbeddedPermissionMediation()
? await this.acquireEmbeddedRun(executionSignal)
: undefined
releaseConversation = await this.acquireConversationRun(
request.conversationId,
executionSignal
@@ -1856,7 +1826,6 @@ export class OpenCodeRuntime implements AgentRuntime {
clearTimeout(deadlineTimer)
}
releaseConversation?.()
releaseEmbedded?.()
}
}
@@ -2054,6 +2023,9 @@ export class OpenCodeRuntime implements AgentRuntime {
request.workMode === 'execute'
? [
...executePermissionRules,
...(this.usesEmbeddedPermissionMediation()
? temporaryMcpDenyRules
: []),
...nativeSkillPermissionRules,
...knowledgeToolIds.map((toolId) => ({
permission: toolId,
@@ -2075,7 +2047,7 @@ export class OpenCodeRuntime implements AgentRuntime {
...readOnlyPermissionRules,
...nativeSkillPermissionRules
]
let disabledTools: Record<string, boolean> | undefined
let toolOverrides: Record<string, boolean> | undefined
if (request.workMode !== 'execute') {
const tools = await this.controlRequest(
'读取工具清单',
@@ -2089,15 +2061,23 @@ export class OpenCodeRuntime implements AgentRuntime {
if (tools.error || !tools.data) {
throw new Error('OpenCode 无法确认工具已禁用,已阻止只读请求')
}
disabledTools = {
toolOverrides = {
...Object.fromEntries(
tools.data.map((toolId) => [toolId, false])
),
...temporaryMcpToolOverrides,
...Object.fromEntries(
knowledgeToolIds.map((toolId) => [toolId, true])
),
...(nativeSkillIds.length > 0 ? { skill: true } : {})
}
} else if (this.usesEmbeddedPermissionMediation()) {
toolOverrides = {
...temporaryMcpToolOverrides,
...Object.fromEntries(
knowledgeToolIds.map((toolId) => [toolId, true])
)
}
}
const session = await this.getSessionId(
client,
@@ -2165,12 +2145,28 @@ export class OpenCodeRuntime implements AgentRuntime {
const reasoningPartIds = new Set<string>()
const reportedQuestionIds = new Map<string, string>()
let aggregateOutputBytes = 0
const consumeOutputBudget = (delta: string): void => {
aggregateOutputBytes += Buffer.byteLength(delta)
if (aggregateOutputBytes > MAX_EXECUTION_OUTPUT_BYTES) {
throw new Error(
'OpenCode 单次运行的文本与推理输出超过 1 MB 安全限制'
)
let outputTruncated = false
const retainOutputDelta = (
delta: string
): { delta: string; truncated: boolean } => {
if (outputTruncated) {
return { delta: '', truncated: false }
}
const bytes = Buffer.from(delta)
const remaining =
MAX_EXECUTION_OUTPUT_BYTES - aggregateOutputBytes
if (bytes.byteLength <= remaining) {
aggregateOutputBytes += bytes.byteLength
return { delta, truncated: false }
}
outputTruncated = true
aggregateOutputBytes = MAX_EXECUTION_OUTPUT_BYTES
return {
delta: bytes
.subarray(0, Math.max(0, remaining))
.toString('utf8')
.replace(/\uFFFD+$/u, ''),
truncated: true
}
}
let hasResponseTextAfterFailure = false
@@ -2228,8 +2224,8 @@ export class OpenCodeRuntime implements AgentRuntime {
nativeSkillIds.length > 0
? undefined
: this.options.skillInstructions || undefined,
...(disabledTools
? { tools: disabledTools }
...(toolOverrides
? { tools: toolOverrides }
: {}),
parts: [
{ type: 'text' as const, text: promptText },
@@ -2276,7 +2272,6 @@ export class OpenCodeRuntime implements AgentRuntime {
'thinking'
].includes(event.properties.field)
if (reasoning || event.properties.field === 'text') {
consumeOutputBudget(event.properties.delta)
if (
!reasoning &&
/\S/u.test(event.properties.delta) &&
@@ -2286,10 +2281,21 @@ export class OpenCodeRuntime implements AgentRuntime {
) {
hasResponseTextAfterFailure = true
}
yield {
requestId: request.requestId,
type: reasoning ? 'reasoning' : 'text',
delta: event.properties.delta
const retained = retainOutputDelta(event.properties.delta)
if (retained.delta) {
yield {
requestId: request.requestId,
type: reasoning ? 'reasoning' : 'text',
delta: retained.delta
}
}
if (retained.truncated) {
yield {
requestId: request.requestId,
type: 'status',
message:
'OpenCode 输出较长,已停止继续展示文本;任务仍在继续'
}
}
}
}
@@ -2307,12 +2313,6 @@ export class OpenCodeRuntime implements AgentRuntime {
throw new Error('OpenCode 工具调用 ID 格式无效')
}
const toolName = part.tool.slice(0, 200)
if (
!toolStates.has(callId) &&
toolStates.size >= MAX_TOOL_CALLS_PER_RUN
) {
throw new Error('OpenCode 单次运行的工具调用超过 100 个')
}
const state =
part.state.status === 'error' ? 'failed' : part.state.status
if (state === 'failed') {
@@ -2372,11 +2372,21 @@ export class OpenCodeRuntime implements AgentRuntime {
event.properties.sessionID === sessionId &&
event.properties.delta
) {
consumeOutputBudget(event.properties.delta)
yield {
requestId: request.requestId,
type: 'reasoning',
delta: event.properties.delta
const retained = retainOutputDelta(event.properties.delta)
if (retained.delta) {
yield {
requestId: request.requestId,
type: 'reasoning',
delta: retained.delta
}
}
if (retained.truncated) {
yield {
requestId: request.requestId,
type: 'status',
message:
'OpenCode 输出较长,已停止继续展示文本;任务仍在继续'
}
}
}
@@ -2469,14 +2479,6 @@ export class OpenCodeRuntime implements AgentRuntime {
properties.id.length <= MAX_PERMISSION_NAME_LENGTH &&
!repliedPermissionIds.has(properties.id)
) {
if (
repliedPermissionIds.size >= MAX_TOOL_CALLS_PER_RUN
) {
throw new Error(
'OpenCode 单次运行的权限请求超过 100 个',
{ cause: error }
)
}
const permissionId = properties.id
repliedPermissionIds.add(properties.id)
const rejection = await this.controlRequest(
@@ -2505,21 +2507,12 @@ export class OpenCodeRuntime implements AgentRuntime {
if (repliedPermissionIds.has(permissionRequest.id)) {
continue
}
if (repliedPermissionIds.size >= MAX_TOOL_CALLS_PER_RUN) {
throw new Error('OpenCode 单次运行的权限请求超过 100 个')
}
repliedPermissionIds.add(permissionRequest.id)
const callId = (
permissionRequest.tool?.callID ?? permissionRequest.id
)
const toolName = permissionRequest.permission.slice(0, 200)
if (
!toolStates.has(callId) &&
toolStates.size >= MAX_TOOL_CALLS_PER_RUN
) {
throw new Error('OpenCode 单次运行的工具调用超过 100 个')
}
toolStates.set(callId, { name: toolName, state: 'pending' })
yield {
requestId: request.requestId,
@@ -2772,10 +2765,8 @@ export class OpenCodeRuntime implements AgentRuntime {
const executionSignal = deadline
? AbortSignal.any([signal, deadline.signal])
: signal
let releaseEmbedded: (() => void) | undefined
let releaseConversation: (() => void) | undefined
try {
releaseEmbedded = await this.acquireEmbeddedRun(executionSignal)
releaseConversation = await this.acquireConversationRun(
request.conversationId,
executionSignal
@@ -2932,7 +2923,6 @@ export class OpenCodeRuntime implements AgentRuntime {
clearTimeout(deadlineTimer)
}
releaseConversation?.()
releaseEmbedded?.()
}
}
@@ -1256,6 +1256,11 @@ describe.runIf(enabled)('runtime end-to-end', () => {
)
.join('')
).toContain('Prism Relay')
const modelCalls = events.filter(
(event) => event.type === 'model-usage'
).length
expect(modelCalls).toBe(2)
console.info(`REAL_OPENCODE_MCP_MODEL_CALLS=${modelCalls}`)
} finally {
await runtime.dispose()
await gateway.dispose()