Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(heterogeneous-agent): extract shared ACP session and stream lifecycle (#18480)

AmAzing-ecc4b0761c97
diff --git a/packages/heterogeneous-agents/src/adapters/acpCommon.ts b/packages/heterogeneous-agents/src/adapters/acpCommon.ts
new file mode 100644
index 00000000000..52e46d702c6
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/acpCommon.ts
@@ -0,0 +1,81 @@
+import { isRecord, toRecord } from '@lobechat/utils/object';
+
+import type { HeterogeneousAgentEvent, ToolCallPayload } from '../types';
+
+/**
+ * Shared stream/step lifecycle for ACP `sessionUpdate` adapters.
+ *
+ * ACP does not frame model rounds explicitly, so adapters detect step
+ * boundaries themselves (tool completion, response completion, …) and set
+ * {@link pendingStepBoundary}. The next `ensureStream(true)` call consumes the
+ * boundary: it closes the open stream, bumps `stepIndex`, resets the per-step
+ * tool list, and re-opens a stream whose `stream_start` payload comes from the
+ * adapter-provided builder (which appends `newStep` for steps > 0).
+ */
+export class AcpStreamLifecycle {
+ /** Set by the adapter when the next model round must open a new step. */
+ pendingStepBoundary = false;
+ stepIndex = 0;
+ /** Tool calls announced within the current step (reset at each boundary). */
+ stepTools: ToolCallPayload[] = [];
+ streamOpen = false;
+
+ constructor(private readonly buildStreamStartData: (stepIndex: number) => unknown) {}
+
+ event(type: HeterogeneousAgentEvent['type'], data: unknown): HeterogeneousAgentEvent {
+ return { data, stepIndex: this.stepIndex, timestamp: Date.now(), type };
+ }
+
+ ensureStream(consumeStepBoundary: boolean): HeterogeneousAgentEvent[] {
+ const events: HeterogeneousAgentEvent[] = [];
+ if (consumeStepBoundary && this.pendingStepBoundary) {
+ events.push(...this.closeStream());
+ this.pendingStepBoundary = false;
+ this.stepIndex += 1;
+ this.stepTools = [];
+ }
+ if (this.streamOpen) return events;
+
+ this.streamOpen = true;
+ events.push(this.event('stream_start', this.buildStreamStartData(this.stepIndex)));
+ return events;
+ }
+
+ closeStream(data: unknown = {}): HeterogeneousAgentEvent[] {
+ if (!this.streamOpen) return [];
+ this.streamOpen = false;
+ return [this.event('stream_end', data)];
+ }
+}
+
+/**
+ * Read the text out of one ACP ContentBlock-ish value: plain strings, `text`
+ * blocks, nested `content` wrappers, and the `diff` / `output` string fields
+ * some agents put on tool-call content.
+ */
+export const acpContentBlockText = (value: unknown): string => {
+ if (typeof value === 'string') return value;
+ if (!isRecord(value)) return '';
+ if (value.type === 'text' && typeof value.text === 'string') return value.text;
+ if (typeof value.content === 'string') return value.content;
+ if (isRecord(value.content)) return acpContentBlockText(value.content);
+ if (typeof value.diff === 'string') return value.diff;
+ if (typeof value.output === 'string') return value.output;
+ return '';
+};
+
+/**
+ * ACP extension marker for replayed history: `_meta.isReplay` on either the
+ * notification `params` or the nested `update`.
+ */
+export const isAcpReplayMessage = (raw: unknown): boolean => {
+ const params = toRecord(toRecord(raw)?.params);
+ const update = toRecord(params?.update);
+ return toRecord(params?._meta)?.isReplay === true || toRecord(update?._meta)?.isReplay === true;
+};
+
+/** ACP extension dedup marker: `_meta.eventId` on the notification `params`. */
+export const acpEventIdOf = (raw: unknown): string | undefined => {
+ const meta = toRecord(toRecord(toRecord(raw)?.params)?._meta);
+ return typeof meta?.eventId === 'string' ? meta.eventId : undefined;
+};
diff --git a/packages/heterogeneous-agents/src/adapters/grokBuild.ts b/packages/heterogeneous-agents/src/adapters/grokBuild.ts
index 0bf1a79e248..ce2f04eb69c 100644
--- a/packages/heterogeneous-agents/src/adapters/grokBuild.ts
+++ b/packages/heterogeneous-agents/src/adapters/grokBuild.ts
@@ -1,3 +1,5 @@
+import { isRecord } from '@lobechat/utils/object';
+
import {
buildHeterogeneousAgentAuthRequiredError,
getHeterogeneousAgentConfigOrThrow,
@@ -8,11 +10,16 @@ import type {
HeterogeneousAgentEvent,
StepCompleteData,
StreamChunkData,
- StreamStartData,
ToolCallPayload,
ToolResultData,
UsageData,
} from '../types';
+import {
+ acpContentBlockText,
+ acpEventIdOf,
+ AcpStreamLifecycle,
+ isAcpReplayMessage,
+} from './acpCommon';
const GROK_BUILD_IDENTIFIER = 'grok-build';
const GROK_BUILD_AUTH_DOCS_URL =
@@ -40,9 +47,6 @@ interface GrokToolResultState {
rawOutput?: unknown;
}
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === 'object' && value !== null && !Array.isArray(value);
-
const finiteNumber = (value: unknown): number =>
typeof value === 'number' && Number.isFinite(value) ? value : 0;
@@ -91,58 +95,33 @@ const stringifyUnknown = (value: unknown): string => {
}
};
-const contentBlockText = (value: unknown): string => {
- if (typeof value === 'string') return value;
- if (!isRecord(value)) return '';
- if (value.type === 'text' && typeof value.text === 'string') return value.text;
- if (typeof value.content === 'string') return value.content;
- if (isRecord(value.content)) return contentBlockText(value.content);
- if (typeof value.diff === 'string') return value.diff;
- if (typeof value.output === 'string') return value.output;
- return '';
-};
-
const toolResultContent = (update: GrokToolResultState): string => {
const content = Array.isArray(update.content)
- ? update.content.map(contentBlockText).filter(Boolean).join('\n\n')
- : contentBlockText(update.content);
+ ? update.content.map(acpContentBlockText).filter(Boolean).join('\n\n')
+ : acpContentBlockText(update.content);
return content || stringifyUnknown(update.rawOutput);
};
-const isReplay = (raw: Record<string, unknown>): boolean => {
- const params = isRecord(raw.params) ? raw.params : undefined;
- const update = isRecord(params?.update) ? params.update : undefined;
- const paramsMeta = isRecord(params?._meta) ? params._meta : undefined;
- const updateMeta = isRecord(update?._meta) ? update._meta : undefined;
- return paramsMeta?.isReplay === true || updateMeta?.isReplay === true;
-};
-
-const eventIdOf = (raw: Record<string, unknown>): string | undefined => {
- const params = isRecord(raw.params) ? raw.params : undefined;
- const meta = isRecord(params?._meta) ? params._meta : undefined;
- return typeof meta?.eventId === 'string' ? meta.eventId : undefined;
-};
-
/** Maps ACP v1 JSON-RPC messages from Grok Build into the shared event contract. */
export class GrokBuildAdapter implements AgentEventAdapter {
sessionId?: string;
private completedToolCallIds = new Set<string>();
- private pendingStepBoundary = false;
private seenEventIds = new Set<string>();
private settled = false;
private lastTurnUsage?: { stepIndex: number; usage: UsageData };
- private started = false;
- private stepIndex = 0;
- private stepToolCalls: ToolCallPayload[] = [];
- private streamOpen = false;
+ private readonly stream = new AcpStreamLifecycle((stepIndex) => ({
+ provider: GROK_BUILD_IDENTIFIER,
+ sessionId: this.sessionId,
+ ...(stepIndex > 0 ? { newStep: true } : {}),
+ }));
private toolPayloadById = new Map<string, ToolCallPayload>();
private toolResultStateById = new Map<string, GrokToolResultState>();
adapt(raw: unknown): HeterogeneousAgentEvent[] {
- if (!isRecord(raw) || isReplay(raw)) return [];
+ if (!isRecord(raw) || isAcpReplayMessage(raw)) return [];
- const eventId = eventIdOf(raw);
+ const eventId = acpEventIdOf(raw);
if (eventId) {
if (this.seenEventIds.has(eventId)) return [];
this.seenEventIds.add(eventId);
@@ -176,7 +155,7 @@ export class GrokBuildAdapter implements AgentEventAdapter {
flush(): HeterogeneousAgentEvent[] {
if (this.settled) return [];
- return this.closeStream();
+ return this.stream.closeStream();
}
private handleNotification(paramsValue: unknown): HeterogeneousAgentEvent[] {
@@ -188,22 +167,22 @@ export class GrokBuildAdapter implements AgentEventAdapter {
switch (update.sessionUpdate) {
case 'agent_message_chunk': {
- const text = contentBlockText(update.content);
+ const text = acpContentBlockText(update.content);
if (!text) return [];
return [
- ...this.ensureStream(true),
- this.makeEvent('stream_chunk', {
+ ...this.stream.ensureStream(true),
+ this.stream.event('stream_chunk', {
chunkType: 'text',
content: text,
} satisfies StreamChunkData),
];
}
case 'agent_thought_chunk': {
- const reasoning = contentBlockText(update.content);
+ const reasoning = acpContentBlockText(update.content);
if (!reasoning) return [];
return [
- ...this.ensureStream(true),
- this.makeEvent('stream_chunk', {
+ ...this.stream.ensureStream(true),
+ this.stream.event('stream_chunk', {
chunkType: 'reasoning',
reasoning,
} satisfies StreamChunkData),
@@ -248,15 +227,15 @@ export class GrokBuildAdapter implements AgentEventAdapter {
};
this.toolPayloadById.set(toolCallId, tool);
this.mergeToolResultState(toolCallId, update);
- this.stepToolCalls.push(tool);
+ this.stream.stepTools.push(tool);
return [
- ...this.ensureStream(false),
- this.makeEvent('stream_chunk', {
+ ...this.stream.ensureStream(false),
+ this.stream.event('stream_chunk', {
chunkType: 'tools_calling',
- toolsCalling: [...this.stepToolCalls],
+ toolsCalling: [...this.stream.stepTools],
} satisfies StreamChunkData),
- this.makeEvent('tool_start', { toolCalling: tool, toolCallId }),
+ this.stream.event('tool_start', { toolCalling: tool, toolCallId }),
];
}
@@ -275,15 +254,15 @@ export class GrokBuildAdapter implements AgentEventAdapter {
// necessarily belongs to the next model round, so keep that boundary here
// as well. `ensureStream(false)` leaves it pending through the remaining
// parallel tool updates; the next text/thought chunk consumes it.
- this.pendingStepBoundary = true;
+ this.stream.pendingStepBoundary = true;
const isError = update.status === 'failed';
const content = toolResultContent(resultState);
const result: ToolResultData = { content, isError, toolCallId };
return [
- ...this.ensureStream(false),
- this.makeEvent('tool_result', result),
- this.makeEvent('tool_end', {
+ ...this.stream.ensureStream(false),
+ this.stream.event('tool_result', result),
+ this.stream.event('tool_end', {
isSuccess: !isError,
payload: { toolCalling: tool },
result: { content, success: !isError },
@@ -317,16 +296,16 @@ export class GrokBuildAdapter implements AgentEventAdapter {
// A pending boundary belongs after the tools requested by the previous
// model response. Reaching the next response completion proves that the
// next model round exists even when it emitted no text/thought chunks.
- const events = this.ensureStream(true);
+ const events = this.stream.ensureStream(true);
const usage = toUsageData(update.usage);
- this.lastTurnUsage = usage ? { stepIndex: this.stepIndex, usage } : undefined;
+ this.lastTurnUsage = usage ? { stepIndex: this.stream.stepIndex, usage } : undefined;
const data: StepCompleteData = {
phase: 'turn_metadata',
provider: GROK_BUILD_IDENTIFIER,
...(usage ? { usage } : {}),
};
- this.pendingStepBoundary = (update.stopReason ?? update.stop_reason) === 'tool_use';
- return [...events, this.makeEvent('step_complete', data)];
+ this.stream.pendingStepBoundary = (update.stopReason ?? update.stop_reason) === 'tool_use';
+ return [...events, this.stream.event('step_complete', data)];
}
private handlePromptResult(result: Record<string, unknown>): HeterogeneousAgentEvent[] {
@@ -337,7 +316,9 @@ export class GrokBuildAdapter implements AgentEventAdapter {
const usage = toUsageData(meta?.usage ?? meta);
const model = typeof meta?.modelId === 'string' ? meta.modelId : undefined;
const turnUsage =
- this.lastTurnUsage?.stepIndex === this.stepIndex ? this.lastTurnUsage.usage : undefined;
+ this.lastTurnUsage?.stepIndex === this.stream.stepIndex
+ ? this.lastTurnUsage.usage
+ : undefined;
const resultUsage: StepCompleteData = {
phase: 'result_usage',
provider: GROK_BUILD_IDENTIFIER,
@@ -345,10 +326,10 @@ export class GrokBuildAdapter implements AgentEventAdapter {
};
return [
- ...this.ensureStream(false),
+ ...this.stream.ensureStream(false),
...(model
? [
- this.makeEvent('step_complete', {
+ this.stream.event('step_complete', {
model,
phase: 'turn_metadata',
provider: GROK_BUILD_IDENTIFIER,
@@ -356,10 +337,10 @@ export class GrokBuildAdapter implements AgentEventAdapter {
} satisfies StepCompleteData),
]
: []),
- this.makeEvent('step_complete', resultUsage),
- ...this.closeStream(),
- this.makeEvent('visible_output_end', {}),
- this.makeEvent('agent_runtime_end', {
+ this.stream.event('step_complete', resultUsage),
+ ...this.stream.closeStream(),
+ this.stream.event('visible_output_end', {}),
+ this.stream.event('agent_runtime_end', {
reason: result.stopReason === 'cancelled' ? 'cancelled' : 'complete',
transport: 'acp-stdio',
}),
@@ -394,37 +375,6 @@ export class GrokBuildAdapter implements AgentEventAdapter {
stderr: detail,
};
- return [...this.closeStream(), this.makeEvent('error', data)];
- }
-
- private ensureStream(consumeStepBoundary: boolean): HeterogeneousAgentEvent[] {
- const events: HeterogeneousAgentEvent[] = [];
- if (consumeStepBoundary && this.pendingStepBoundary) {
- events.push(...this.closeStream());
- this.pendingStepBoundary = false;
- this.stepIndex += 1;
- this.stepToolCalls = [];
- }
- if (this.streamOpen) return events;
-
- this.started = true;
- this.streamOpen = true;
- const data: StreamStartData & { newStep?: boolean } = {
- provider: GROK_BUILD_IDENTIFIER,
- sessionId: this.sessionId,
- ...(this.stepIndex > 0 ? { newStep: true } : {}),
- };
- events.push(this.makeEvent('stream_start', data));
- return events;
- }
-
- private closeStream(): HeterogeneousAgentEvent[] {
- if (!this.started || !this.streamOpen) return [];
- this.streamOpen = false;
- return [this.makeEvent('stream_end', {})];
- }
-
- private makeEvent(type: HeterogeneousAgentEvent['type'], data: unknown): HeterogeneousAgentEvent {
- return { data, stepIndex: this.stepIndex, timestamp: Date.now(), type };
+ return [...this.stream.closeStream(), this.stream.event('error', data)];
}
}
diff --git a/packages/heterogeneous-agents/src/adapters/traeAcp.test.ts b/packages/heterogeneous-agents/src/adapters/traeAcp.test.ts
index e12e78bb206..21f0165e05f 100644
--- a/packages/heterogeneous-agents/src/adapters/traeAcp.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/traeAcp.test.ts
@@ -237,4 +237,29 @@ describe('TraeAcpAdapter', () => {
{ reason: 'interrupted', stopReason: 'cancelled' },
]);
});
+
+ it('parameterizes provider, event prefix, and per-payload identifier for other ACP agents', () => {
+ const adapter = new TraeAcpAdapter({ eventPrefix: 'cursor', provider: 'cursor' });
+ adapter.adapt({ sessionId: 'cursor-session-1', type: 'cursor_session' });
+
+ const events = [
+ ...adapter.adapt({
+ identifier: 'claude-code',
+ rawInput: { questions: [] },
+ sessionUpdate: 'tool_call',
+ title: 'askUserQuestion',
+ toolCallId: 'ask-1',
+ }),
+ ...adapter.adapt({ stopReason: 'end_turn', type: 'cursor_prompt_completed' }),
+ ];
+
+ expect(adapter.sessionId).toBe('cursor-session-1');
+ expect(dataFor(events, 'stream_start')).toEqual([
+ { provider: 'cursor', sessionId: 'cursor-session-1' },
+ ]);
+ expect(dataFor(events, 'tool_start')[0]).toMatchObject({
+ toolCalling: { apiName: 'askUserQuestion', id: 'ask-1', identifier: 'claude-code' },
+ });
+ expect(dataFor(events, 'agent_runtime_end')).toEqual([{ stopReason: 'end_turn' }]);
+ });
});
diff --git a/packages/heterogeneous-agents/src/adapters/traeAcp.ts b/packages/heterogeneous-agents/src/adapters/traeAcp.ts
index 8bd69dc65e2..64e01a948a3 100644
--- a/packages/heterogeneous-agents/src/adapters/traeAcp.ts
+++ b/packages/heterogeneous-agents/src/adapters/traeAcp.ts
@@ -6,8 +6,20 @@ import type {
ToolResultData,
ToolStateChunkData,
} from '../types';
+import { AcpStreamLifecycle } from './acpCommon';
-const PROVIDER = 'trae';
+const DEFAULT_PROVIDER = 'trae';
+
+/**
+ * Parameterization for reusing this adapter across standard-ACP agents:
+ * `provider` stamps stream/tool events, `eventPrefix` selects the synthetic
+ * session-lifecycle payloads (`{prefix}_session` / `{prefix}_prompt_completed`
+ * / `{prefix}_error`) the owning session emits.
+ */
+export interface AcpSessionAdapterOptions {
+ eventPrefix?: string;
+ provider?: string;
+}
interface TraeAcpPayload {
[key: string]: unknown;
@@ -76,19 +88,33 @@ const toolContent = (content: unknown, fallback: unknown): string => {
return result || stringify(fallback);
};
+/**
+ * Maps the standard ACP `sessionUpdate` vocabulary into the shared event
+ * contract. TRAE is the default provider; other standard-ACP agents reuse it
+ * via {@link AcpSessionAdapterOptions}.
+ */
export class TraeAcpAdapter implements AgentEventAdapter {
sessionId?: string;
+ private readonly eventPrefix: string;
+ private readonly provider: string;
private completedTools = new Set<string>();
private model?: string;
- private pendingStepBoundary = false;
private pendingTools = new Set<string>();
private snapshotSeq = new Map<string, number>();
- private stepIndex = 0;
- private streamOpen = false;
+ private readonly stream = new AcpStreamLifecycle((stepIndex) => ({
+ ...(this.model ? { model: this.model } : {}),
+ ...(stepIndex > 0 ? { newStep: true } : {}),
+ provider: this.provider,
+ sessionId: this.sessionId,
+ }));
private terminal = false;
private toolResultStateById = new Map<string, TraeAcpToolResultState>();
- private tools: ToolCallPayload[] = [];
+
+ constructor(options: AcpSessionAdapterOptions = {}) {
+ this.provider = options.provider ?? DEFAULT_PROVIDER;
+ this.eventPrefix = options.eventPrefix ?? this.provider;
+ }
adapt(value: unknown): HeterogeneousAgentEvent[] {
if (!value || typeof value !== 'object' || this.terminal) return [];
@@ -97,21 +123,23 @@ export class TraeAcpAdapter implements AgentEventAdapter {
if (typeof raw.model === 'string') this.model = raw.model;
return [];
}
- if (raw.type === 'trae_session') {
+ if (raw.type === `${this.eventPrefix}_session`) {
if (typeof raw.sessionId === 'string') this.sessionId = raw.sessionId;
if (typeof raw.model === 'string') this.model = raw.model;
return [];
}
- if (raw.type === 'trae_prompt_completed') return this.complete(raw.stopReason);
- if (raw.type === 'trae_error') return this.fail(stringify(raw.message) || 'TRAE ACP failed');
+ if (raw.type === `${this.eventPrefix}_prompt_completed`) return this.complete(raw.stopReason);
+ if (raw.type === `${this.eventPrefix}_error`) {
+ return this.fail(stringify(raw.message) || `${this.provider} ACP failed`);
+ }
switch (raw.sessionUpdate) {
case 'agent_message_chunk': {
const text = (raw.content as { text?: unknown } | null)?.text;
return typeof text === 'string' && text
? [
- ...this.ensureStream(true),
- this.event('stream_chunk', {
+ ...this.stream.ensureStream(true),
+ this.stream.event('stream_chunk', {
chunkType: 'text',
content: text,
} satisfies StreamChunkData),
@@ -122,8 +150,8 @@ export class TraeAcpAdapter implements AgentEventAdapter {
const reasoning = (raw.content as { text?: unknown } | null)?.text;
return typeof reasoning === 'string' && reasoning
? [
- ...this.ensureStream(true),
- this.event('stream_chunk', {
+ ...this.stream.ensureStream(true),
+ this.stream.event('stream_chunk', {
chunkType: 'reasoning',
reasoning,
} satisfies StreamChunkData),
@@ -157,7 +185,7 @@ export class TraeAcpAdapter implements AgentEventAdapter {
this.snapshotSeq.set(id, snapshotSeq);
return [
...startEvents,
- this.event('stream_chunk', {
+ this.stream.event('stream_chunk', {
chunkType: 'tool_state',
pluginState: { ...raw },
snapshotMode: 'replace',
@@ -178,14 +206,14 @@ export class TraeAcpAdapter implements AgentEventAdapter {
);
const events = [
...startEvents,
- this.event('tool_result', {
+ this.stream.event('tool_result', {
content: result,
isError: !isSuccess,
toolCallId: id,
} satisfies ToolResultData),
- this.event('tool_end', { isSuccess, toolCallId: id }),
+ this.stream.event('tool_end', { isSuccess, toolCallId: id }),
];
- if (this.pendingTools.size === 0) this.pendingStepBoundary = true;
+ if (this.pendingTools.size === 0) this.stream.pendingStepBoundary = true;
return events;
}
@@ -202,20 +230,21 @@ export class TraeAcpAdapter implements AgentEventAdapter {
apiName: apiName ?? 'unknown',
arguments: stringify(raw.rawInput ?? raw.input ?? raw.parameters ?? {}),
id,
- identifier: PROVIDER,
+ identifier:
+ typeof raw.identifier === 'string' && raw.identifier ? raw.identifier : this.provider,
type: 'default',
};
- const streamEvents = this.ensureStream(true);
+ const streamEvents = this.stream.ensureStream(true);
this.pendingTools.add(id);
- this.tools.push(payload);
+ this.stream.stepTools.push(payload);
return [
...streamEvents,
- this.event('stream_chunk', {
+ this.stream.event('stream_chunk', {
chunkType: 'tools_calling',
- toolsCalling: [...this.tools],
+ toolsCalling: [...this.stream.stepTools],
} satisfies StreamChunkData),
- this.event('tool_start', { toolCalling: payload, toolCallId: id }),
+ this.stream.event('tool_start', { toolCalling: payload, toolCallId: id }),
];
}
@@ -231,37 +260,9 @@ export class TraeAcpAdapter implements AgentEventAdapter {
return state;
}
- private ensureStream(consumeStepBoundary: boolean): HeterogeneousAgentEvent[] {
- const events: HeterogeneousAgentEvent[] = [];
- if (consumeStepBoundary && this.pendingStepBoundary) {
- events.push(...this.closeStream());
- this.pendingStepBoundary = false;
- this.stepIndex += 1;
- this.tools = [];
- }
- if (this.streamOpen) return events;
-
- this.streamOpen = true;
- events.push(
- this.event('stream_start', {
- ...(this.model ? { model: this.model } : {}),
- ...(this.stepIndex > 0 ? { newStep: true } : {}),
- provider: PROVIDER,
- sessionId: this.sessionId,
- }),
- );
- return events;
- }
-
- private closeStream(data: unknown = {}): HeterogeneousAgentEvent[] {
- if (!this.streamOpen) return [];
- this.streamOpen = false;
- return [this.event('stream_end', data)];
- }
-
private closePending(): HeterogeneousAgentEvent[] {
const events = [...this.pendingTools].map((toolCallId) =>
- this.event('tool_end', { isSuccess: false, toolCallId }),
+ this.stream.event('tool_end', { isSuccess: false, toolCallId }),
);
this.pendingTools.clear();
return events;
@@ -274,9 +275,9 @@ export class TraeAcpAdapter implements AgentEventAdapter {
stopReason === 'cancelled' ? { reason: 'interrupted', stopReason } : { stopReason };
return [
...this.closePending(),
- ...this.closeStream({ stopReason }),
- this.event('visible_output_end', {}),
- this.event('agent_runtime_end', runtimeEndData),
+ ...this.stream.closeStream({ stopReason }),
+ this.stream.event('visible_output_end', {}),
+ this.stream.event('agent_runtime_end', runtimeEndData),
];
}
@@ -285,13 +286,9 @@ export class TraeAcpAdapter implements AgentEventAdapter {
this.terminal = true;
return [
...this.closePending(),
- ...this.closeStream(),
- this.event('visible_output_end', {}),
- this.event('error', { agentType: PROVIDER, error: message, message }),
+ ...this.stream.closeStream(),
+ this.stream.event('visible_output_end', {}),
+ this.stream.event('error', { agentType: this.provider, error: message, message }),
];
}
-
- private event(type: HeterogeneousAgentEvent['type'], data: unknown): HeterogeneousAgentEvent {
- return { data, stepIndex: this.stepIndex, timestamp: Date.now(), type };
- }
}
diff --git a/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts b/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts
new file mode 100644
index 00000000000..1bdf897eb44
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts
@@ -0,0 +1,280 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { isRecord } from '@lobechat/utils/object';
+
+import type { AcpRpcMessage } from './acpStdioClient';
+import { AcpStdioClient } from './acpStdioClient';
+import type { AgentStreamPipelineOptions } from './agentStreamPipeline';
+import { AgentStreamPipeline } from './agentStreamPipeline';
+import type { HeterogeneousAgentRuntimeStatus } from './claudeAgentSdkSession';
+
+/** The ACP major protocol version this client speaks (https://agentclientprotocol.com). */
+export const ACP_PROTOCOL_VERSION = 1;
+
+const DEFAULT_CANCEL_GRACE_MS = 2_000;
+
+/** One entry of a `session/request_permission` `options` array. */
+export interface AcpPermissionOption {
+ kind?: unknown;
+ optionId?: unknown;
+}
+
+/** Parse the `options` array of a `session/request_permission` request. */
+export const parseAcpPermissionOptions = (params: unknown): AcpPermissionOption[] => {
+ const options = isRecord(params) ? params.options : undefined;
+ if (!Array.isArray(options)) return [];
+ return options.flatMap((value) => (isRecord(value) ? [value as AcpPermissionOption] : []));
+};
+
+/**
+ * Pick a permission option by ordered preference tiers. Returns the winning
+ * option's id, or `undefined` when no tier matched — or when the first
+ * matching tier's option carries no usable string `optionId` (mirrors the
+ * `a ?? b ?? c` fall-through the per-agent policies used before extraction:
+ * later tiers are not consulted once an earlier tier matched).
+ */
+export const selectAcpPermissionOption = (
+ params: unknown,
+ preferences: ((option: AcpPermissionOption) => boolean)[],
+): string | undefined => {
+ const options = parseAcpPermissionOptions(params);
+ for (const matches of preferences) {
+ const selected = options.find((option) => matches(option));
+ if (selected) return typeof selected.optionId === 'string' ? selected.optionId : undefined;
+ }
+ return undefined;
+};
+
+/** Options shared by every ACP agent session, independent of the vendor. */
+export interface AcpAgentSessionOptions {
+ args: string[];
+ clientVersion: string;
+ commandPath: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
+ onRawMessage: (line: string) => Promise<void> | void;
+ onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
+ onSessionId: (sessionId: string) => void;
+ onStderr: (data: string) => Promise<void> | void;
+ operationId: string;
+ requestTimeoutMs?: number;
+ resumeSessionId?: string;
+ sessionId: string;
+}
+
+/** Per-agent invariants a subclass passes to the base constructor. */
+export interface AcpAgentSessionConfig {
+ /** Full child argv (agent-fixed flags already applied around user args). */
+ args: string[];
+ /** Grace period between `session/cancel` and force-closing the process. */
+ cancelGraceMs?: number;
+ /** `AgentStreamPipeline` construction params (`operationId` is appended from options). */
+ pipeline: Omit<AgentStreamPipelineOptions, 'operationId'>;
+ processLabel: string;
+ transport: HeterogeneousAgentRuntimeStatus['transport'];
+}
+
+/**
+ * Shared ACP v1 agent lifecycle layered on {@link AcpStdioClient}:
+ *
+ * initialize (+ version/capability validation) → session/new | session/load
+ * → session/prompt → session/update streaming → session/cancel
+ *
+ * The base owns everything the protocol standardizes — transport wiring,
+ * request/notification plumbing, prompt-turn settlement, cancellation grace,
+ * and runtime-status reporting. Vendor deltas (extension `_meta` payloads,
+ * auth, model selection, replay policy, reverse-request policy) live in the
+ * protocol-phase hooks implemented by each agent's subclass.
+ */
+export abstract class AcpAgentSession<
+ TInitializeResult,
+ TOptions extends AcpAgentSessionOptions = AcpAgentSessionOptions,
+> {
+ protected readonly client: AcpStdioClient;
+ protected readonly pipeline: AgentStreamPipeline;
+ /** The agent-native session id, set as soon as session setup resolves it. */
+ protected acpSessionId?: string;
+
+ private readonly cancelGraceMs: number;
+ private readonly transport: HeterogeneousAgentRuntimeStatus['transport'];
+ private cancelTimer?: ReturnType<typeof setTimeout>;
+ private hostClosed = false;
+ private lastStatus?: HeterogeneousAgentRuntimeStatus['state'];
+
+ protected constructor(
+ protected readonly options: TOptions,
+ config: AcpAgentSessionConfig,
+ ) {
+ this.cancelGraceMs = config.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
+ this.transport = config.transport;
+ this.pipeline = new AgentStreamPipeline({
+ ...config.pipeline,
+ operationId: options.operationId,
+ });
+ this.client = new AcpStdioClient({
+ args: config.args,
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ env: options.env,
+ onMessage: (message) => this.handleAgentMessage(message),
+ onRawMessage: options.onRawMessage,
+ onServerRequest: (message) => this.handleServerRequest(message),
+ onStderr: options.onStderr,
+ processLabel: config.processLabel,
+ requestTimeoutMs: options.requestTimeoutMs,
+ });
+ }
+
+ get pid(): number | undefined {
+ return this.client.pid;
+ }
+
+ protected get closedByHost(): boolean {
+ return this.hostClosed;
+ }
+
+ /** Run one full prompt turn. Resolves silently when the host closed the session mid-run. */
+ async run(): Promise<void> {
+ this.emitStatus('starting');
+ try {
+ await this.prepareRun?.();
+ const initialized = await this.initializeConnection();
+ const sessionId = await this.establishSession(initialized);
+ this.acpSessionId = sessionId;
+ this.emitStatus('running');
+ this.onBeforePrompt?.();
+ const result = await this.client.request<unknown>(
+ 'session/prompt',
+ await this.buildPromptParams(sessionId),
+ false,
+ );
+ await this.settlePrompt(result);
+ if (this.hostClosed) return;
+ await this.emitEvents(await this.pipeline.flush());
+ if (this.hostClosed) return;
+ this.emitStatus('idle');
+ } catch (cause) {
+ if (this.hostClosed) return;
+ const error = cause instanceof Error ? cause : new Error(String(cause));
+ await this.onRunFailure?.(error);
+ this.emitStatus('error');
+ throw error;
+ } finally {
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
+ this.client.close();
+ this.emitStatus('closed');
+ }
+ }
+
+ /**
+ * Request graceful cancellation via the `session/cancel` notification; the
+ * agent is expected to resolve the pending `session/prompt` with the
+ * `cancelled` stop reason. Force-closes after the grace period.
+ */
+ interrupt(): void {
+ const sessionId = this.acpSessionId;
+ if (!sessionId) {
+ this.close();
+ return;
+ }
+ this.client.notify('session/cancel', this.buildCancelParams(sessionId));
+ this.cancelTimer ??= setTimeout(() => this.close(), this.cancelGraceMs);
+ this.cancelTimer.unref?.();
+ }
+
+ /** Host-forced shutdown: suppresses further events and kills the child. */
+ close(signal: NodeJS.Signals = 'SIGTERM'): void {
+ if (this.hostClosed) return;
+ this.hostClosed = true;
+ this.onHostClose?.();
+ this.client.close(signal);
+ this.emitStatus('closed');
+ }
+
+ /** Start the child (idempotent), send `initialize`, and validate the result. */
+ protected async initializeConnection(): Promise<TInitializeResult> {
+ await this.client.start();
+ const initialized = await this.client.request<TInitializeResult>(
+ 'initialize',
+ this.buildInitializeParams(),
+ );
+ this.validateInitialized(initialized);
+ return initialized;
+ }
+
+ /**
+ * Settle the prompt turn after the `session/prompt` response arrives. The
+ * default drains the already-received message queue; agents whose CLIs leak
+ * trailing notifications or need synthetic terminal events override this.
+ */
+ protected async settlePrompt(_result: unknown): Promise<void> {
+ await this.client.drain();
+ }
+
+ /** `session/cancel` params; agents append extension `_meta` by overriding. */
+ protected buildCancelParams(sessionId: string): unknown {
+ return { sessionId };
+ }
+
+ /** Serialize a payload as one JSONL line into the adapter pipeline and emit the result. */
+ protected async pushToPipeline(payload: unknown): Promise<void> {
+ if (this.hostClosed) return;
+ const events = await this.pipeline.push(`${JSON.stringify(payload)}\n`);
+ await this.emitEvents(events);
+ }
+
+ protected async emitEvents(events: AgentStreamEvent[]): Promise<void> {
+ if (!this.hostClosed && events.length > 0) await this.options.onEvents(events);
+ }
+
+ protected emitStatus(state: HeterogeneousAgentRuntimeStatus['state']): void {
+ if (this.lastStatus === 'closed' || state === this.lastStatus) return;
+ this.lastStatus = state;
+ this.options.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: Date.now(),
+ operationId: this.options.operationId,
+ sessionId: this.options.sessionId,
+ state,
+ transport: this.transport,
+ });
+ }
+
+ /** `initialize` request params (client capabilities, client info, extensions). */
+ protected abstract buildInitializeParams(): unknown;
+
+ /**
+ * Validate the `initialize` response — protocol version and any
+ * capabilities the pending run depends on. Throw to abort before any
+ * session is created.
+ */
+ protected abstract validateInitialized(initialized: TInitializeResult): void;
+
+ /**
+ * Everything between `initialize` and `session/prompt`: authentication,
+ * `session/new` / `session/load`, model selection, and `onSessionId`
+ * notification. Returns the agent-native session id to prompt against.
+ */
+ protected abstract establishSession(initialized: TInitializeResult): Promise<string>;
+
+ /** `session/prompt` request params. */
+ protected abstract buildPromptParams(sessionId: string): Promise<unknown> | unknown;
+
+ /** Route an agent-initiated message (notification or response) into the pipeline. */
+ protected abstract handleAgentMessage(message: AcpRpcMessage): Promise<void> | void;
+
+ /** Answer an agent→client request (`session/request_permission`, extensions). */
+ protected abstract handleServerRequest(message: AcpRpcMessage): Promise<unknown> | unknown;
+
+ /** Optional async setup that must precede spawning the child (e.g. prompt materialization). */
+ protected prepareRun?(): Promise<void>;
+
+ /** Invoked right before the `session/prompt` request is written. */
+ protected onBeforePrompt?(): void;
+
+ /** Emit synthetic terminal events for a failed run before the error is rethrown. */
+ protected onRunFailure?(error: Error): Promise<void>;
+
+ /** Extra cleanup when the host force-closes the session. */
+ protected onHostClose?(): void;
+}
diff --git a/packages/heterogeneous-agents/src/spawn/grokAcpSession.ts b/packages/heterogeneous-agents/src/spawn/grokAcpSession.ts
index 25b7f65c7d3..b80884cb129 100644
--- a/packages/heterogeneous-agents/src/spawn/grokAcpSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/grokAcpSession.ts
@@ -1,18 +1,20 @@
import { pathToFileURL } from 'node:url';
-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { getAnyCliFlagValue, GROK_BUILD_REASONING_EFFORT_FLAGS } from '@lobechat/types';
+import { isAcpReplayMessage } from '../adapters/acpCommon';
import type { AgentPromptInput } from '../protocol';
+import type { AcpAgentSessionOptions } from './acpAgentSession';
+import {
+ ACP_PROTOCOL_VERSION,
+ AcpAgentSession,
+ selectAcpPermissionOption,
+} from './acpAgentSession';
import type { AcpRpcMessage } from './acpStdioClient';
-import { AcpServerRequestError, AcpStdioClient } from './acpStdioClient';
-import { AgentStreamPipeline } from './agentStreamPipeline';
-import type { HeterogeneousAgentRuntimeStatus } from './claudeAgentSdkSession';
+import { AcpServerRequestError } from './acpStdioClient';
import type { NormalizeImageOptions } from './input';
import { normalizeImage } from './input';
-const ACP_PROTOCOL_VERSION = 1;
-const ACP_CANCEL_GRACE_MS = 2_000;
const GROK_ACP_TRANSPORT = 'acp-stdio' as const;
const GROK_MODEL_FLAGS = ['-m', '--model'] as const;
const SUPPORTED_AUTH_METHODS = ['cached_token', 'xai.api_key'] as const;
@@ -41,26 +43,8 @@ interface AcpNewSessionResult {
sessionId?: string;
}
-interface AcpPermissionOption {
- kind?: string;
- optionId?: string;
-}
-
-export interface GrokAcpSessionOptions {
- args: string[];
- clientVersion: string;
- commandPath: string;
- cwd: string;
- env: NodeJS.ProcessEnv;
- onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
- onRawMessage: (line: string) => Promise<void> | void;
- onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
- onSessionId: (sessionId: string) => void;
- onStderr: (data: string) => Promise<void> | void;
- operationId: string;
+export interface GrokAcpSessionOptions extends AcpAgentSessionOptions {
prompt: GrokAcpContentBlock[];
- resumeSessionId?: string;
- sessionId: string;
}
export const buildGrokAcpArgs = (args: string[] = []): string[] => [
@@ -106,185 +90,120 @@ export const buildGrokAcpPrompt = async (
return content;
};
-/** Grok Build's ACP v1 lifecycle layered on the reusable stdio transport. */
-export class GrokAcpSession {
- private readonly client: AcpStdioClient;
- private readonly pipeline: AgentStreamPipeline;
- private acpSessionId?: string;
- private cancelTimer?: ReturnType<typeof setTimeout>;
- private closedByHost = false;
- private lastStatus?: HeterogeneousAgentRuntimeStatus['state'];
-
- constructor(private readonly options: GrokAcpSessionOptions) {
- this.pipeline = new AgentStreamPipeline({
- agentType: 'grok-build',
- cwd: options.cwd,
- operationId: options.operationId,
- });
- this.client = new AcpStdioClient({
+/** Grok Build's ACP v1 lifecycle (auth + `_meta` extensions) on the shared session base. */
+export class GrokAcpSession extends AcpAgentSession<AcpInitializeResult, GrokAcpSessionOptions> {
+ constructor(options: GrokAcpSessionOptions) {
+ super(options, {
args: buildGrokAcpArgs(options.args),
- commandPath: options.commandPath,
- cwd: options.cwd,
- env: options.env,
- onMessage: (message) => this.handleRpcMessage(message),
- onRawMessage: options.onRawMessage,
- onServerRequest: (message) => this.handleServerRequest(message),
- onStderr: options.onStderr,
+ pipeline: { agentType: 'grok-build', cwd: options.cwd },
processLabel: 'Grok Build ACP',
+ transport: GROK_ACP_TRANSPORT,
});
}
- get pid(): number | undefined {
- return this.client.pid;
- }
-
get sessionId(): string | undefined {
return this.acpSessionId;
}
- async run(): Promise<void> {
- this.emitStatus('starting');
-
- try {
- await this.client.start();
- const initialized = await this.client.request<AcpInitializeResult>('initialize', {
- _meta: {
- clientType: 'lobehub',
- clientVersion: this.options.clientVersion,
- },
- clientCapabilities: { fs: {}, terminal: false },
- protocolVersion: ACP_PROTOCOL_VERSION,
- });
- if (
- initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&
- initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)
- ) {
- throw new Error(
- `Unsupported Grok Build ACP protocol version: ${String(initialized.protocolVersion)}`,
- );
- }
-
- const authMethod = this.resolveAuthMethod(initialized);
- if (authMethod) {
- await this.client.request('authenticate', {
- _meta: { headless: true },
- methodId: authMethod,
- });
- } else if (initialized.authMethods?.length) {
- throw new Error('Authentication required. Run `grok login`, then retry.');
- }
-
- let acpSessionId: string;
- const model = getAnyCliFlagValue(this.options.args, GROK_MODEL_FLAGS)?.trim();
- const effort = getAnyCliFlagValue(
- this.options.args,
- GROK_BUILD_REASONING_EFFORT_FLAGS,
- )?.trim();
- if (this.options.resumeSessionId) {
- await this.client.request('session/load', {
- _meta: {
- noReplay: true,
- ...(effort && !model ? { reasoningEffort: effort } : {}),
- },
- cwd: this.options.cwd,
- mcpServers: [],
- sessionId: this.options.resumeSessionId,
- });
- acpSessionId = this.options.resumeSessionId;
- } else {
- const session = await this.client.request<AcpNewSessionResult>('session/new', {
- _meta: { yoloMode: true },
- cwd: this.options.cwd,
- mcpServers: [],
- });
- if (!session.sessionId) throw new Error('Grok Build ACP returned no session id');
- acpSessionId = session.sessionId;
- }
+ protected buildInitializeParams(): unknown {
+ return {
+ _meta: {
+ clientType: 'lobehub',
+ clientVersion: this.options.clientVersion,
+ },
+ clientCapabilities: { fs: {}, terminal: false },
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ };
+ }
- if (this.options.resumeSessionId && model) {
- await this.client.request('session/set_model', {
- ...(effort ? { _meta: { reasoningEffort: effort } } : {}),
- modelId: model,
- sessionId: acpSessionId,
- });
- }
+ protected validateInitialized(initialized: AcpInitializeResult): void {
+ if (
+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&
+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)
+ ) {
+ throw new Error(
+ `Unsupported Grok Build ACP protocol version: ${String(initialized.protocolVersion)}`,
+ );
+ }
+ }
- this.acpSessionId = acpSessionId;
- this.options.onSessionId(acpSessionId);
- this.emitStatus('running');
+ protected async establishSession(initialized: AcpInitializeResult): Promise<string> {
+ const authMethod = this.resolveAuthMethod(initialized);
+ if (authMethod) {
+ await this.client.request('authenticate', {
+ _meta: { headless: true },
+ methodId: authMethod,
+ });
+ } else if (initialized.authMethods?.length) {
+ throw new Error('Authentication required. Run `grok login`, then retry.');
+ }
- await this.client.request(
- 'session/prompt',
- {
- _meta: { promptId: this.options.operationId },
- prompt: this.options.prompt,
- sessionId: acpSessionId,
+ let acpSessionId: string;
+ const model = getAnyCliFlagValue(this.options.args, GROK_MODEL_FLAGS)?.trim();
+ const effort = getAnyCliFlagValue(this.options.args, GROK_BUILD_REASONING_EFFORT_FLAGS)?.trim();
+ if (this.options.resumeSessionId) {
+ await this.client.request('session/load', {
+ _meta: {
+ noReplay: true,
+ ...(effort && !model ? { reasoningEffort: effort } : {}),
},
- false,
- );
- await this.client.drain();
- if (this.closedByHost) return;
- await this.emitEvents(await this.pipeline.flush());
- if (this.closedByHost) return;
- this.emitStatus('idle');
- } catch (error) {
- if (this.closedByHost) return;
-
- this.emitStatus('error');
- throw error;
- } finally {
- if (this.cancelTimer) clearTimeout(this.cancelTimer);
- this.client.close();
- if (!this.closedByHost) this.emitStatus('closed');
+ cwd: this.options.cwd,
+ mcpServers: [],
+ sessionId: this.options.resumeSessionId,
+ });
+ acpSessionId = this.options.resumeSessionId;
+ } else {
+ const session = await this.client.request<AcpNewSessionResult>('session/new', {
+ _meta: { yoloMode: true },
+ cwd: this.options.cwd,
+ mcpServers: [],
+ });
+ if (!session.sessionId) throw new Error('Grok Build ACP returned no session id');
+ acpSessionId = session.sessionId;
}
- }
- interrupt(): void {
- if (!this.acpSessionId) {
- this.close();
- return;
+ if (this.options.resumeSessionId && model) {
+ await this.client.request('session/set_model', {
+ ...(effort ? { _meta: { reasoningEffort: effort } } : {}),
+ modelId: model,
+ sessionId: acpSessionId,
+ });
}
- this.client.notify('session/cancel', {
- _meta: { cancelTrigger: 'ctrl_c' },
- sessionId: this.acpSessionId,
- });
- this.cancelTimer ??= setTimeout(() => this.close(), ACP_CANCEL_GRACE_MS);
- this.cancelTimer.unref?.();
+ this.acpSessionId = acpSessionId;
+ this.options.onSessionId(acpSessionId);
+ return acpSessionId;
+ }
+
+ protected buildPromptParams(sessionId: string): unknown {
+ return {
+ _meta: { promptId: this.options.operationId },
+ prompt: this.options.prompt,
+ sessionId,
+ };
}
- close(signal: NodeJS.Signals = 'SIGTERM'): void {
- if (this.closedByHost) return;
- this.closedByHost = true;
- this.client.close(signal);
- this.emitStatus('closed');
+ protected override buildCancelParams(sessionId: string): unknown {
+ return {
+ _meta: { cancelTrigger: 'ctrl_c' },
+ sessionId,
+ };
}
- private async handleRpcMessage(message: AcpRpcMessage): Promise<void> {
- if (this.closedByHost || this.isReplayMessage(message)) return;
- const events = await this.pipeline.push(`${JSON.stringify(message)}\n`);
- if (this.closedByHost) return;
- await this.emitEvents(events);
+ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {
+ if (isAcpReplayMessage(message)) return;
+ await this.pushToPipeline(message);
}
- private handleServerRequest(message: AcpRpcMessage): unknown {
+ protected handleServerRequest(message: AcpRpcMessage): unknown {
switch (message.method) {
case 'session/request_permission': {
- const params = this.asRecord(message.params);
- const permissionOptions = Array.isArray(params?.options)
- ? params.options.flatMap((option) => {
- const value = this.asRecord(option);
- return value ? [value as AcpPermissionOption] : [];
- })
- : [];
- const selected =
- permissionOptions.find(({ kind }) => kind === 'allow_always') ??
- permissionOptions.find(({ kind }) => kind === 'allow_once');
+ const optionId = selectAcpPermissionOption(message.params, [
+ ({ kind }) => kind === 'allow_always',
+ ({ kind }) => kind === 'allow_once',
+ ]);
return {
- outcome:
- typeof selected?.optionId === 'string'
- ? { optionId: selected.optionId, outcome: 'selected' }
- : { outcome: 'cancelled' },
+ outcome: optionId ? { optionId, outcome: 'selected' } : { outcome: 'cancelled' },
};
}
case 'x.ai/ask_user_question': {
@@ -318,35 +237,4 @@ export class GrokAcpSession {
}
return SUPPORTED_AUTH_METHODS.find((methodId) => ids.has(methodId));
}
-
- private isReplayMessage(message: AcpRpcMessage): boolean {
- const params = this.asRecord(message.params);
- const paramsMeta = this.asRecord(params?._meta);
- const update = this.asRecord(params?.update);
- const updateMeta = this.asRecord(update?._meta);
- return paramsMeta?.isReplay === true || updateMeta?.isReplay === true;
- }
-
- private async emitEvents(events: AgentStreamEvent[]): Promise<void> {
- if (!this.closedByHost && events.length > 0) await this.options.onEvents(events);
- }
-
- private emitStatus(state: HeterogeneousAgentRuntimeStatus['state']): void {
- if (this.lastStatus === 'closed' || state === this.lastStatus) return;
- this.lastStatus = state;
- this.options.onRuntimeStatus({
- activeTasks: [],
- lastEventAt: Date.now(),
- operationId: this.options.operationId,
- sessionId: this.options.sessionId,
- state,
- transport: GROK_ACP_TRANSPORT,
- });
- }
-
- private asRecord(value: unknown): Record<string, unknown> | undefined {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : undefined;
- }
}
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 0d5250a209a..8b23d1c41bd 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -26,6 +26,15 @@ export {
isCodexAppServerCompatibilityError,
} from '../codex';
export type { UsageData } from '../types';
+export {
+ ACP_PROTOCOL_VERSION,
+ AcpAgentSession,
+ type AcpAgentSessionConfig,
+ type AcpAgentSessionOptions,
+ type AcpPermissionOption,
+ parseAcpPermissionOptions,
+ selectAcpPermissionOption,
+} from './acpAgentSession';
export {
type AcpRpcErrorData,
type AcpRpcMessage,
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
index 58cb22525e7..c6f2da1592b 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -176,7 +176,9 @@ const createGrokAcpProc = ({
return { proc, requests };
};
-const createFakeAcpProc = () => {
+const createFakeAcpProc = ({
+ promptAutoComplete = true,
+}: { promptAutoComplete?: boolean } = {}) => {
const proc = new EventEmitter() as any;
const stdout = new PassThrough();
const stderr = new PassThrough();
@@ -229,6 +231,7 @@ const createFakeAcpProc = () => {
return;
}
case 'session/prompt': {
+ if (!promptAutoComplete) return;
send({
method: 'session/update',
params: {
@@ -553,6 +556,33 @@ describe('spawnAgent', () => {
}
});
+ it('preserves SIGKILL when force-stopping a TRAE ACP run', async () => {
+ const fake = createFakeAcpProc({ promptAutoComplete: false });
+ nextFakeProc = fake.proc;
+ const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ try {
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = await spawnAgent({
+ agentType: 'trae',
+ operationId: 'op-trae-force-stop',
+ prompt: 'keep running',
+ });
+ await vi.waitFor(() => {
+ expect(fake.requests.some(({ method }) => method === 'session/prompt')).toBe(true);
+ });
+
+ handle.kill('SIGKILL');
+
+ // The ACP spawn bridge reports host kills as signal exits, uniformly
+ // across ACP agents.
+ expect(processKill).toHaveBeenCalledWith(-12_345, 'SIGKILL');
+ await expect(handle.exit).resolves.toEqual({ code: null, signal: 'SIGKILL' });
+ } finally {
+ processKill.mockRestore();
+ }
+ });
+
it('allows the official canonical trae-cli command to run through ACP', async () => {
const fake = createFakeAcpProc();
nextFakeProc = fake.proc;
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index e40d4fdac0c..3c0f103ea8e 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -405,12 +405,31 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {
}
};
-const spawnGrokAcpAgent = async (
- options: SpawnAgentOptions,
- command: string,
- cwd: string,
-): Promise<SpawnAgentHandle> => {
- const prompt = await buildGrokAcpPrompt(options.prompt, options.inputOptions);
+/** Guarded raw-stdout tee: diagnostic sink failures must not affect the ACP run. */
+const teeAcpRawStdout =
+ (onRawStdout?: (chunk: Buffer) => void) =>
+ (line: string): void => {
+ if (!onRawStdout) return;
+ try {
+ onRawStdout(Buffer.from(line));
+ } catch {
+ // raw dump is diagnostic-only; never let it disrupt the run
+ }
+ };
+
+/**
+ * Bridge a bidirectional ACP session onto the ordinary `SpawnAgentHandle`
+ * contract shared by the one-shot CLI spawns.
+ *
+ * Exit/error policy (uniform for every ACP agent):
+ * - Host kills resolve `exit` as `{ code: null, signal }`.
+ * - ACP request failures are first adapted into a terminal error event and
+ * then reject the session's run() promise. Once that structured event is
+ * queued, the iterable ends normally so callers can apply their error
+ * policy; transport failures with no terminal event still throw from the
+ * iterator.
+ */
+const createAcpSpawnBridge = () => {
const stderr = new PassThrough();
const queue: AgentStreamEvent[] = [];
let emittedTerminalError = false;
@@ -427,50 +446,14 @@ const spawnGrokAcpAgent = async (
const getHostExit = (): { code: null; signal: NodeJS.Signals } | undefined =>
hostSignal ? { code: null, signal: hostSignal } : undefined;
- const session = new GrokAcpSession({
- args: options.extraArgs ?? [],
- clientVersion: 'lobehub-cli',
- commandPath: command,
- cwd,
- env: { ...process.env, ...options.env },
- onEvents: (events) => {
- if (events.some(({ type }) => type === 'error')) emittedTerminalError = true;
- queue.push(...events);
- wake();
- },
- onRawMessage: (line) => options.onRawStdout?.(Buffer.from(line)),
- onRuntimeStatus: () => {},
- onSessionId: () => {},
- onStderr: (data) => {
- stderr.write(data);
- },
- operationId: options.operationId,
- prompt,
- resumeSessionId: options.resumeSessionId,
- sessionId: options.operationId,
- });
-
- const exit = session
- .run()
- .then(() => getHostExit() ?? { code: 0, signal: null })
- .catch((error) => {
- const hostExit = getHostExit();
- if (hostExit) return hostExit;
-
- // ACP request failures are first adapted into a terminal error event and
- // then reject the request promise. Once that structured event is queued,
- // end the iterable normally so callers can apply their error policy.
- // Transport failures with no terminal event must still throw.
- if (!emittedTerminalError) {
- streamError = error instanceof Error ? error : new Error(String(error));
- }
- return { code: 1, signal: null };
- })
- .finally(() => {
- streamEnded = true;
- stderr.end();
- wake();
- });
+ const onEvents = (events: AgentStreamEvent[]): void => {
+ if (events.some(({ type }) => type === 'error')) emittedTerminalError = true;
+ queue.push(...events);
+ wake();
+ };
+ const onStderr = (data: string): void => {
+ stderr.write(data);
+ };
const events: AsyncIterable<AgentStreamEvent> = {
[Symbol.asyncIterator]() {
@@ -490,21 +473,76 @@ const spawnGrokAcpAgent = async (
},
};
- return {
- events,
- exit,
- kill: (signal = 'SIGINT') => {
+ const attach = (session: {
+ close: (signal?: NodeJS.Signals) => void;
+ interrupt: () => void;
+ run: () => Promise<void>;
+ }): Pick<SpawnAgentHandle, 'exit' | 'kill'> => {
+ const exit: SpawnAgentHandle['exit'] = session
+ .run()
+ .then(() => getHostExit() ?? { code: 0, signal: null })
+ .catch((error) => {
+ const hostExit = getHostExit();
+ if (hostExit) return hostExit;
+
+ if (!emittedTerminalError) {
+ streamError = error instanceof Error ? error : new Error(String(error));
+ }
+ return { code: 1, signal: null };
+ })
+ .finally(() => {
+ streamEnded = true;
+ stderr.end();
+ wake();
+ });
+
+ const kill = (signal: NodeJS.Signals = 'SIGINT'): void => {
hostSignal = signal;
if (signal === 'SIGINT') session.interrupt();
else session.close(signal);
- },
+ };
+ return { exit, kill };
+ };
+
+ return { attach, events, onEvents, onStderr, stderr };
+};
+
+const spawnGrokAcpAgent = async (
+ options: SpawnAgentOptions,
+ command: string,
+ cwd: string,
+): Promise<SpawnAgentHandle> => {
+ const prompt = await buildGrokAcpPrompt(options.prompt, options.inputOptions);
+ const bridge = createAcpSpawnBridge();
+ const session = new GrokAcpSession({
+ args: options.extraArgs ?? [],
+ clientVersion: 'lobehub-cli',
+ commandPath: command,
+ cwd,
+ env: { ...process.env, ...options.env },
+ onEvents: bridge.onEvents,
+ onRawMessage: teeAcpRawStdout(options.onRawStdout),
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ onStderr: bridge.onStderr,
+ operationId: options.operationId,
+ prompt,
+ resumeSessionId: options.resumeSessionId,
+ sessionId: options.operationId,
+ });
+ const { exit, kill } = bridge.attach(session);
+
+ return {
+ events: bridge.events,
+ exit,
+ kill,
get pid() {
return session.pid;
},
get sessionId() {
return session.sessionId;
},
- stderr,
+ stderr: bridge.stderr,
};
};
@@ -748,16 +786,7 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<Spa
}
const prompt = await buildTraeAcpPrompt(options.prompt, options.inputOptions);
- const stderr = new PassThrough();
- const queue: AgentStreamEvent[] = [];
- let ended = false;
- let wakeup: (() => void) | undefined;
- const wake = () => {
- wakeup?.();
- wakeup = undefined;
- };
-
- let nativeSessionId: string | undefined;
+ const bridge = createAcpSpawnBridge();
const session = new TraeAcpSession({
args: options.extraArgs ?? [],
clientVersion: '1.0.0',
@@ -768,72 +797,28 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<Spa
...(commandStatus.resolvedPathEnv ? { PATH: commandStatus.resolvedPathEnv } : {}),
},
initialModel: options.initialModel,
- onEvents: (events) => {
- queue.push(...events);
- wake();
- },
- onRawMessage: (line) => {
- if (!options.onRawStdout) return;
- try {
- options.onRawStdout(Buffer.from(line));
- } catch {
- // Diagnostic tee failures must not affect the ACP run.
- }
- },
+ onEvents: bridge.onEvents,
+ onRawMessage: teeAcpRawStdout(options.onRawStdout),
onRuntimeStatus: () => {},
- onSessionId: (sessionId) => {
- nativeSessionId = sessionId;
- },
- onStderr: (data) => {
- stderr.write(data);
- },
+ onSessionId: () => {},
+ onStderr: bridge.onStderr,
operationId: options.operationId,
prompt,
resumeSessionId: options.resumeSessionId,
sessionId: options.operationId,
});
-
- const exit = session
- .run()
- .then(
- () => ({ code: 0, signal: null }),
- () => ({ code: 1, signal: null }),
- )
- .finally(() => {
- ended = true;
- stderr.end();
- wake();
- });
-
- const events: AsyncIterable<AgentStreamEvent> = {
- [Symbol.asyncIterator]() {
- return {
- async next(): Promise<IteratorResult<AgentStreamEvent>> {
- while (queue.length === 0 && !ended) {
- await new Promise<void>((resolve) => {
- wakeup = resolve;
- });
- }
- const event = queue.shift();
- return event ? { done: false, value: event } : { done: true, value: undefined };
- },
- };
- },
- };
+ const { exit, kill } = bridge.attach(session);
return {
- events,
+ events: bridge.events,
exit,
- kill: (signal: NodeJS.Signals = 'SIGINT') => {
- if (signal === 'SIGINT') void session.interrupt();
- else session.close();
- },
+ kill,
get pid() {
return session.pid;
},
get sessionId() {
- return nativeSessionId;
+ return session.nativeSessionId;
},
- stderr,
+ stderr: bridge.stderr,
};
};
diff --git a/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts b/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts
index 747f5890975..f3958cae5aa 100644
--- a/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts
@@ -1,14 +1,16 @@
-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import type { HeterogeneousAgentModel } from '@lobechat/types';
+import type { AcpAgentSessionOptions } from './acpAgentSession';
+import {
+ ACP_PROTOCOL_VERSION,
+ AcpAgentSession,
+ selectAcpPermissionOption,
+} from './acpAgentSession';
import type { AcpRpcMessage } from './acpStdioClient';
-import { AcpServerRequestError, AcpStdioClient } from './acpStdioClient';
-import { AgentStreamPipeline } from './agentStreamPipeline';
-import type { HeterogeneousAgentRuntimeStatus } from './claudeAgentSdkSession';
+import { AcpServerRequestError } from './acpStdioClient';
import type { AgentPromptInput, BuildAgentInputOptions } from './input';
import { normalizeImage } from './input';
-const ACP_PROTOCOL_VERSION = 1;
const NOTIFICATION_DRAIN_QUIET_MS = 250;
const NOTIFICATION_DRAIN_TIMEOUT_MS = 2000;
const TRANSPORT = 'trae-acp' as const;
@@ -97,11 +99,6 @@ interface TraeAcpSetConfigOptionResult {
configOptions?: unknown;
}
-interface TraeAcpPermissionOption {
- kind?: unknown;
- optionId?: unknown;
-}
-
export interface TraeAcpModelCatalog {
configId?: string;
currentModelId?: string;
@@ -189,127 +186,34 @@ export const parseTraeAcpModelCatalog = (
};
};
-export interface TraeAcpSessionOptions {
- args: string[];
- clientVersion: string;
- commandPath: string;
- cwd: string;
- env: NodeJS.ProcessEnv;
+export interface TraeAcpSessionOptions extends AcpAgentSessionOptions {
initialModel?: string;
inputOptions?: BuildAgentInputOptions;
- onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
onModel?: (model: string) => void;
- onRawMessage: (line: string) => Promise<void> | void;
- onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
- onSessionId: (sessionId: string) => void;
- onStderr: (data: string) => Promise<void> | void;
- operationId: string;
prompt: AgentPromptInput | TraeAcpPromptBlock[];
- requestTimeoutMs?: number;
- resumeSessionId?: string;
- sessionId: string;
}
-export class TraeAcpSession {
- private readonly client: AcpStdioClient;
- private readonly pipeline: AgentStreamPipeline;
+/** TRAE's ACP v1 lifecycle: model config-options and legacy model API on the shared base. */
+export class TraeAcpSession extends AcpAgentSession<
+ TraeAcpInitializeResult,
+ TraeAcpSessionOptions
+> {
private acceptUpdates = false;
- private closedByHost = false;
- private interruptTimer?: ReturnType<typeof setTimeout>;
private lastSessionUpdateAt = 0;
private modelDiscovery?: TraeAcpSession;
- private session?: string;
+ private resolvedPrompt: TraeAcpPromptBlock[] = [];
- constructor(private readonly options: TraeAcpSessionOptions) {
- this.pipeline = new AgentStreamPipeline({
- agentType: 'trae',
- operationId: options.operationId,
- });
- this.client = new AcpStdioClient({
+ constructor(options: TraeAcpSessionOptions) {
+ super(options, {
args: buildTraeAcpArgs(options.args),
- commandPath: options.commandPath,
- cwd: options.cwd,
- env: options.env,
- onMessage: (message) => this.handleRpcMessage(message),
- onRawMessage: options.onRawMessage,
- onServerRequest: (message) => this.handleServerRequest(message),
- onStderr: options.onStderr,
+ pipeline: { agentType: 'trae' },
processLabel: 'TRAE ACP',
- requestTimeoutMs: options.requestTimeoutMs,
+ transport: TRANSPORT,
});
}
get nativeSessionId(): string | undefined {
- return this.session;
- }
-
- get pid(): number | undefined {
- return this.client.pid;
- }
-
- async run(): Promise<void> {
- this.status('starting');
- try {
- const prompt = await this.resolvePrompt();
- const initialized = await this.initialize();
- if (
- prompt.some((block) => block.type === 'image') &&
- initialized?.agentCapabilities?.promptCapabilities?.image !== true
- ) {
- throw new Error('TRAE ACP agent does not support image prompt blocks');
- }
- if (this.options.resumeSessionId && initialized?.agentCapabilities?.loadSession !== true) {
- throw new Error('TRAE ACP agent does not support loading sessions');
- }
-
- const sessionResult = await this.client.request<TraeAcpSessionResult>(
- this.options.resumeSessionId ? 'session/load' : 'session/new',
- {
- cwd: this.options.cwd,
- mcpServers: [],
- ...(this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}),
- },
- );
- const sessionId = sessionResult?.sessionId ?? this.options.resumeSessionId;
- if (!sessionId) throw new Error('TRAE ACP returned no session id');
- this.session = sessionId;
- this.options.onSessionId(sessionId);
-
- const model = await this.applyInitialModel(sessionId, sessionResult);
- if (model) {
- this.pipeline.configureSession({ model });
- this.options.onModel?.(model);
- }
- await this.emit({
- model,
- sessionId,
- type: 'trae_session',
- });
- this.status('running');
- // session/load may replay historical updates before returning. Keep setup
- // notifications gated until the new prompt is about to start.
- this.acceptUpdates = true;
- const response = await this.client.request<TraeAcpPromptResult>(
- 'session/prompt',
- { prompt, sessionId },
- false,
- );
- await this.drainNotifications();
- await this.client.drain();
- await this.emit({ stopReason: response?.stopReason, type: 'trae_prompt_completed' });
- await this.emitEvents(await this.pipeline.flush());
- this.status('idle');
- } catch (cause) {
- if (this.closedByHost) return;
- const error = cause instanceof Error ? cause : new Error(String(cause));
- await this.emit({ message: error.message, type: 'trae_error' });
- await this.emitEvents(await this.pipeline.flush());
- throw error;
- } finally {
- if (this.interruptTimer) clearTimeout(this.interruptTimer);
- this.client.close();
- this.status('closed');
- }
+ return this.acpSessionId;
}
/** Create a short-lived ACP session and read its agent-provided model selector. */
@@ -317,60 +221,12 @@ export class TraeAcpSession {
return (await this.discoverModelCatalog()).models;
}
- private async discoverModelCatalog(): Promise<TraeAcpModelCatalog> {
- try {
- const initialized = await this.initialize();
- const sessionResult = await this.client.request<TraeAcpSessionResult>('session/new', {
- cwd: this.options.cwd,
- mcpServers: [],
- });
- if (!sessionResult?.sessionId) throw new Error('TRAE ACP returned no session id');
-
- const catalog = parseTraeAcpModelCatalog(sessionResult);
- if (!catalog) throw new Error('TRAE ACP did not expose a model configuration option');
-
- if (initialized?.agentCapabilities?.sessionCapabilities?.close) {
- await this.client.request('session/close', { sessionId: sessionResult.sessionId });
- }
- return catalog;
- } finally {
- this.client.close();
- }
- }
-
- async interrupt(): Promise<void> {
- if (!this.session) {
- this.close();
- return;
- }
- this.client.notify('session/cancel', { sessionId: this.session });
- this.interruptTimer = setTimeout(() => this.close(), 2000);
- this.interruptTimer.unref?.();
- }
-
- close(): void {
- this.closedByHost = true;
- this.modelDiscovery?.close();
- this.client.close();
- }
-
- private async resolvePrompt(): Promise<TraeAcpPromptBlock[]> {
- const prompt = this.options.prompt;
- if (
- Array.isArray(prompt) &&
- prompt.every(
- (block) =>
- 'type' in block && (block.type === 'text' || ('data' in block && block.type === 'image')),
- )
- ) {
- return prompt as TraeAcpPromptBlock[];
- }
- return buildTraeAcpPrompt(prompt as AgentPromptInput, this.options.inputOptions);
+ protected async prepareRun(): Promise<void> {
+ this.resolvedPrompt = await this.resolvePrompt();
}
- private async initialize(): Promise<TraeAcpInitializeResult> {
- await this.client.start();
- const initialized = await this.client.request<TraeAcpInitializeResult>('initialize', {
+ protected buildInitializeParams(): unknown {
+ return {
clientCapabilities: {},
clientInfo: {
name: 'lobehub',
@@ -378,7 +234,10 @@ export class TraeAcpSession {
version: this.options.clientVersion,
},
protocolVersion: ACP_PROTOCOL_VERSION,
- });
+ };
+ }
+
+ protected validateInitialized(initialized: TraeAcpInitializeResult): void {
if (
typeof initialized?.protocolVersion === 'number' &&
initialized.protocolVersion !== ACP_PROTOCOL_VERSION
@@ -387,13 +246,76 @@ export class TraeAcpSession {
`TRAE ACP returned unsupported protocol version: ${initialized.protocolVersion}`,
);
}
- return initialized;
}
- private async handleRpcMessage(message: AcpRpcMessage): Promise<void> {
+ protected async establishSession(initialized: TraeAcpInitializeResult): Promise<string> {
+ if (
+ this.resolvedPrompt.some((block) => block.type === 'image') &&
+ initialized?.agentCapabilities?.promptCapabilities?.image !== true
+ ) {
+ throw new Error('TRAE ACP agent does not support image prompt blocks');
+ }
+ if (this.options.resumeSessionId && initialized?.agentCapabilities?.loadSession !== true) {
+ throw new Error('TRAE ACP agent does not support loading sessions');
+ }
+
+ const sessionResult = await this.client.request<TraeAcpSessionResult>(
+ this.options.resumeSessionId ? 'session/load' : 'session/new',
+ {
+ cwd: this.options.cwd,
+ mcpServers: [],
+ ...(this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}),
+ },
+ );
+ const sessionId = sessionResult?.sessionId ?? this.options.resumeSessionId;
+ if (!sessionId) throw new Error('TRAE ACP returned no session id');
+ this.acpSessionId = sessionId;
+ this.options.onSessionId(sessionId);
+
+ const model = await this.applyInitialModel(sessionId, sessionResult);
+ if (model) {
+ this.pipeline.configureSession({ model });
+ this.options.onModel?.(model);
+ }
+ await this.pushToPipeline({
+ model,
+ sessionId,
+ type: 'trae_session',
+ });
+ return sessionId;
+ }
+
+ protected onBeforePrompt(): void {
+ // session/load may replay historical updates before returning. Keep setup
+ // notifications gated until the new prompt is about to start.
+ this.acceptUpdates = true;
+ }
+
+ protected buildPromptParams(sessionId: string): unknown {
+ return { prompt: this.resolvedPrompt, sessionId };
+ }
+
+ protected override async settlePrompt(result: unknown): Promise<void> {
+ await this.drainNotifications();
+ await this.client.drain();
+ await this.pushToPipeline({
+ stopReason: (result as TraeAcpPromptResult | undefined)?.stopReason,
+ type: 'trae_prompt_completed',
+ });
+ }
+
+ protected async onRunFailure(error: Error): Promise<void> {
+ await this.pushToPipeline({ message: error.message, type: 'trae_error' });
+ await this.emitEvents(await this.pipeline.flush());
+ }
+
+ protected onHostClose(): void {
+ this.modelDiscovery?.close();
+ }
+
+ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {
if (message.method !== 'session/update') return;
- const suppress = !this.acceptUpdates;
- if (suppress) return;
+ if (!this.acceptUpdates) return;
this.lastSessionUpdateAt = Date.now();
const update = (message.params as { update?: unknown } | undefined)?.update;
@@ -408,36 +330,56 @@ export class TraeAcpSession {
this.options.onModel?.(catalog.currentModelId);
}
}
- await this.emit(update as Record<string, unknown>);
+ await this.pushToPipeline(update as Record<string, unknown>);
}
- private handleServerRequest(message: AcpRpcMessage): unknown {
+ protected handleServerRequest(message: AcpRpcMessage): unknown {
if (message.method === 'session/request_permission') {
- const params = message.params as { options?: unknown } | undefined;
- const options = Array.isArray(params?.options)
- ? params.options.map((value) => value as TraeAcpPermissionOption | null)
- : [];
- const selected =
- options.find(
- (option) =>
- option?.optionId === 'allow_session' || option?.optionId === 'approve_for_session',
- ) ??
- options.find((option) => option?.kind === 'allow_once') ??
- options.find((option) => option?.kind === 'reject_once');
- if (typeof selected?.optionId === 'string') {
- return { outcome: { optionId: selected.optionId, outcome: 'selected' } };
- }
+ const optionId = selectAcpPermissionOption(message.params, [
+ (option) =>
+ option.optionId === 'allow_session' || option.optionId === 'approve_for_session',
+ (option) => option.kind === 'allow_once',
+ (option) => option.kind === 'reject_once',
+ ]);
+ if (optionId) return { outcome: { optionId, outcome: 'selected' } };
throw new AcpServerRequestError(-32_603, 'No safe permission option was offered');
}
throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);
}
- private async emit(payload: Record<string, unknown>): Promise<void> {
- await this.emitEvents(await this.pipeline.push(`${JSON.stringify(payload)}\n`));
+ private async discoverModelCatalog(): Promise<TraeAcpModelCatalog> {
+ try {
+ const initialized = await this.initializeConnection();
+ const sessionResult = await this.client.request<TraeAcpSessionResult>('session/new', {
+ cwd: this.options.cwd,
+ mcpServers: [],
+ });
+ if (!sessionResult?.sessionId) throw new Error('TRAE ACP returned no session id');
+
+ const catalog = parseTraeAcpModelCatalog(sessionResult);
+ if (!catalog) throw new Error('TRAE ACP did not expose a model configuration option');
+
+ if (initialized?.agentCapabilities?.sessionCapabilities?.close) {
+ await this.client.request('session/close', { sessionId: sessionResult.sessionId });
+ }
+ return catalog;
+ } finally {
+ this.client.close();
+ }
}
- private async emitEvents(events: AgentStreamEvent[]): Promise<void> {
- if (events.length) await this.options.onEvents(events);
+ private async resolvePrompt(): Promise<TraeAcpPromptBlock[]> {
+ const prompt = this.options.prompt;
+ if (
+ Array.isArray(prompt) &&
+ prompt.every(
+ (block) =>
+ 'type' in block && (block.type === 'text' || ('data' in block && block.type === 'image')),
+ )
+ ) {
+ return prompt as TraeAcpPromptBlock[];
+ }
+ return buildTraeAcpPrompt(prompt as AgentPromptInput, this.options.inputOptions);
}
private async applyInitialModel(
@@ -512,17 +454,6 @@ export class TraeAcpSession {
if (Date.now() - quietSince >= NOTIFICATION_DRAIN_QUIET_MS) return;
}
}
-
- private status(state: HeterogeneousAgentRuntimeStatus['state']): void {
- this.options.onRuntimeStatus({
- activeTasks: [],
- lastEventAt: Date.now(),
- operationId: this.options.operationId,
- sessionId: this.options.sessionId,
- state,
- transport: TRANSPORT,
- });
- }
}
export const listTraeAcpModels = async (