Skip to content

Commit 003420b

Browse files
feat(agent-core): stream agent background task events into output buffer
Wire up the child agent's event stream so that AgentBackgroundTask can append formatted events to the output sink in real time. - Add subscribeToEvents callback to SubagentHandle in subagent-host.ts - Wrap agent.emitEvent to fan out to subscribed callbacks - Add eventSource option to AgentBackgroundTask and format select AgentEvents (turn.started/ended, tool.call.started, tool.result, error) as human-readable lines in the task output buffer - Pass handle.subscribeToEvents from the Agent collaboration tool - Fix pre-existing duplicate key in subagent-host test fakeSession
1 parent f8dc052 commit 003420b

4 files changed

Lines changed: 68 additions & 2 deletions

File tree

‎packages/agent-core/src/agent/background/agent-task.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { sleep } from '@antfu/utils';
22

3+
import type { AgentEvent } from '#/rpc';
34
import { errorMessage, isAbortError } from '../../loop/errors';
45
import {
56
type BackgroundTask,
@@ -20,6 +21,7 @@ export interface AgentBackgroundTaskOptions {
2021
readonly abort?: () => void;
2122
readonly agentId?: string;
2223
readonly subagentType?: string;
24+
readonly eventSource?: ((callback: (event: AgentEvent) => void) => (() => void)) | undefined;
2325
}
2426

2527
export class AgentBackgroundTask implements BackgroundTask {
@@ -29,6 +31,7 @@ export class AgentBackgroundTask implements BackgroundTask {
2931
readonly agentId?: string;
3032
readonly subagentType?: string;
3133
private readonly abort?: () => void;
34+
private readonly eventSource?: ((callback: (event: AgentEvent) => void) => (() => void)) | undefined;
3235

3336
constructor(
3437
private readonly completion: Promise<{ result: string }>,
@@ -39,6 +42,7 @@ export class AgentBackgroundTask implements BackgroundTask {
3942
this.abort = options.abort;
4043
this.agentId = options.agentId;
4144
this.subagentType = options.subagentType;
45+
this.eventSource = options.eventSource;
4246
}
4347

4448
async start(sink: BackgroundTaskSink): Promise<void> {
@@ -61,6 +65,16 @@ export class AgentBackgroundTask implements BackgroundTask {
6165
raceInputs.push(sleep(timeoutMs).then(() => deadlineTimeout));
6266
}
6367

68+
let unsubscribeEvents: (() => void) | undefined;
69+
if (this.eventSource !== undefined) {
70+
unsubscribeEvents = this.eventSource((event) => {
71+
const line = formatAgentEvent(event);
72+
if (line !== undefined) {
73+
sink.appendOutput(line + '\n');
74+
}
75+
});
76+
}
77+
6478
try {
6579
const outcome = await Promise.race(raceInputs);
6680
if (outcome === deadlineTimeout) {
@@ -78,6 +92,7 @@ export class AgentBackgroundTask implements BackgroundTask {
7892
await sink.settle({ status: 'failed', stopReason: errorMessage(error) });
7993
} finally {
8094
sink.signal.removeEventListener('abort', requestAbort);
95+
unsubscribeEvents?.();
8196
}
8297
}
8398

@@ -90,3 +105,26 @@ export class AgentBackgroundTask implements BackgroundTask {
90105
};
91106
}
92107
}
108+
109+
function formatAgentEvent(event: AgentEvent): string | undefined {
110+
switch (event.type) {
111+
case 'turn.started':
112+
return `[turn ${event.turnId} started]`;
113+
case 'turn.ended':
114+
return `[turn ${event.turnId} ended: ${event.reason}]`;
115+
case 'tool.call.started': {
116+
const args = typeof event.args === 'string' ? event.args : JSON.stringify(event.args);
117+
const preview = args.length > 200 ? args.slice(0, 200) + '…' : args;
118+
return `[tool] ${event.name}(${preview})`;
119+
}
120+
case 'tool.result': {
121+
const output = typeof event.output === 'string' ? event.output : JSON.stringify(event.output);
122+
const preview = output.length > 200 ? output.slice(0, 200) + '…' : output;
123+
return `[result] ${event.toolCallId}: ${preview}`;
124+
}
125+
case 'error':
126+
return `[error] ${'message' in event ? String(event.message) : String(event)}`;
127+
default:
128+
return undefined;
129+
}
130+
}

‎packages/agent-core/src/session/subagent-host.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
} from '../utils/abort';
2222
import { collectGitContext } from './git-context';
2323
import type { Session } from './index';
24+
import type { AgentEvent } from '#/rpc';
2425
import {
2526
SubagentBatch,
2627
type SubagentResult,
@@ -94,6 +95,7 @@ export type SubagentHandle = {
9495
readonly profileName: string;
9596
readonly resumed: boolean;
9697
readonly completion: Promise<SubagentCompletion>;
98+
readonly subscribeToEvents?: ((callback: (event: AgentEvent) => void) => (() => void)) | undefined;
9799
};
98100

99101
export class SessionSubagentHost {
@@ -119,6 +121,7 @@ export class SessionSubagentHost {
119121
{ type: 'sub', generate: parent.rawGenerate },
120122
{ parentAgentId: this.ownerAgentId, swarmItem: options.swarmItem },
121123
);
124+
const subscribeToEvents = this.wrapAgentEmitEvent(agent);
122125
const completion = this.runWithActiveChild(id, options, async (runOptions) => {
123126
this.emitSubagentSpawned(parent, id, profile.name, runOptions);
124127
try {
@@ -134,12 +137,14 @@ export class SessionSubagentHost {
134137
profileName: profile.name,
135138
resumed: false,
136139
completion,
140+
subscribeToEvents,
137141
};
138142
}
139143

140144
async resume(agentId: string, options: RunSubagentOptions): Promise<SubagentHandle> {
141145
options.signal.throwIfAborted();
142146
const { parent, child, profileName } = await this.ensureIdleSubagent(agentId);
147+
const subscribeToEvents = this.wrapAgentEmitEvent(child);
143148
const completion = this.runWithActiveChild(agentId, options, async (runOptions) => {
144149
this.emitSubagentSpawned(parent, agentId, profileName, runOptions);
145150
try {
@@ -150,7 +155,7 @@ export class SessionSubagentHost {
150155
throw error;
151156
}
152157
});
153-
return { agentId, profileName, resumed: true, completion };
158+
return { agentId, profileName, resumed: true, completion, subscribeToEvents };
154159
}
155160

156161
async retry(agentId: string, options: RunSubagentOptions): Promise<SubagentHandle> {
@@ -175,6 +180,29 @@ export class SessionSubagentHost {
175180
return { agentId, profileName, resumed: true, completion };
176181
}
177182

183+
private wrapAgentEmitEvent(
184+
agent: Agent,
185+
): (callback: (event: AgentEvent) => void) => (() => void) {
186+
const callbacks = new Set<(event: AgentEvent) => void>();
187+
const originalEmitEvent = agent.emitEvent.bind(agent);
188+
agent.emitEvent = (event: AgentEvent): void => {
189+
originalEmitEvent(event);
190+
for (const cb of callbacks) {
191+
try {
192+
cb(event);
193+
} catch {
194+
// best-effort: ignore individual callback failures
195+
}
196+
}
197+
};
198+
return (cb) => {
199+
callbacks.add(cb);
200+
return () => {
201+
callbacks.delete(cb);
202+
};
203+
};
204+
}
205+
178206
private async ensureIdleSubagent(
179207
agentId: string,
180208
): Promise<{ readonly parent: Agent; readonly child: Agent; readonly profileName: string }> {

‎packages/agent-core/src/tools/builtin/collaboration/agent.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ export class AgentTool implements BuiltinTool<AgentToolInput> {
233233
abort: () => {
234234
backgroundController?.abort();
235235
},
236+
eventSource: handle.subscribeToEvents,
236237
}),
237238
);
238239
} catch (error) {

‎packages/agent-core/test/session/subagent-host.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1452,7 +1452,6 @@ function fakeSession(
14521452
agents.set('agent-0', child);
14531453
}
14541454
return {
1455-
options: {},
14561455
agents,
14571456
options: { kimiHomeDir: undefined },
14581457
metadata: {

0 commit comments

Comments
 (0)