Map Grok task envelopes to subagent lineage
- Detect xAI Task tool calls as native subagents - Project child session IDs and buffered chunks into the orchestration tree - Add replay fixture coverage for Grok subagent lineage
This commit is contained in:
1 parent
1467717c12
commit
706c819cf3
9 files changed
+630
-4
No files matched your search
@@ -11,6 +11,7 @@ import {
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
type OrchestrationV2RuntimeRequest,
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2TurnItem,
|
||||
type OrchestrationV2UserInputQuestion,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -53,6 +54,11 @@ import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
|
||||
import { makeProviderFailure } from "../ProviderFailure.ts";
|
||||
import { acpSelectionTransition } from "../ProviderSelectionTransition.ts";
|
||||
import {
|
||||
makeSubagentChildThread,
|
||||
makeSubagentConversationArtifacts,
|
||||
subagentThreadTitle,
|
||||
} from "../SubagentProjection.ts";
|
||||
import {
|
||||
ProviderAdapterEnsureThreadError,
|
||||
ProviderAdapterForkThreadError,
|
||||
@@ -120,9 +126,22 @@ export interface AcpAdapterV2Flavor {
|
||||
readonly registerExtensions?: (
|
||||
context: AcpAdapterV2ExtensionContext,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly extractSubagentUpdate?: (
|
||||
toolCall: AcpToolCallState,
|
||||
) => AcpAdapterV2SubagentUpdate | undefined;
|
||||
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpAdapterV2SubagentUpdate {
|
||||
readonly nativeTaskId: string;
|
||||
readonly prompt: string;
|
||||
readonly title: string | null;
|
||||
readonly model: string | null;
|
||||
readonly status: "running" | "completed" | "failed";
|
||||
readonly childSessionId: string | null;
|
||||
readonly result: string | null;
|
||||
}
|
||||
|
||||
export interface AcpAdapterV2Options {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly flavor: AcpAdapterV2Flavor;
|
||||
@@ -537,6 +556,9 @@ interface ActiveAcpTurn {
|
||||
readonly reasoning: ActiveTextStream;
|
||||
readonly tools: Map<string, AcpToolCallState>;
|
||||
readonly toolStartedAt: Map<string, DateTime.Utc>;
|
||||
readonly subagents: Map<string, ActiveAcpSubagent>;
|
||||
readonly subagentsBySessionId: Map<string, ActiveAcpSubagent>;
|
||||
readonly pendingSubagentNotifications: Map<string, Array<EffectAcpSchema.SessionNotification>>;
|
||||
plan: {
|
||||
readonly id: OrchestrationV2PlanArtifact["id"];
|
||||
readonly startedAt: DateTime.Utc;
|
||||
@@ -545,6 +567,17 @@ interface ActiveAcpTurn {
|
||||
finalized: boolean;
|
||||
}
|
||||
|
||||
interface ActiveAcpSubagent {
|
||||
task: OrchestrationV2Subagent;
|
||||
readonly childThreadId: ThreadId;
|
||||
readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
|
||||
readonly turnItemId: OrchestrationV2TurnItem["id"];
|
||||
readonly turnItemOrdinal: number;
|
||||
childSessionId: string | null;
|
||||
assistantText: string;
|
||||
nextChildOrdinal: number;
|
||||
}
|
||||
|
||||
type PendingRuntimeRequest = {
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly runtimeRequest: OrchestrationV2RuntimeRequest;
|
||||
@@ -809,6 +842,297 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
yield* emitTextSegment(context, kind, false);
|
||||
});
|
||||
|
||||
const emitSubagentAssistant = Effect.fnUntraced(function* (
|
||||
subagent: ActiveAcpSubagent,
|
||||
text: string,
|
||||
) {
|
||||
if (text.length === 0) return;
|
||||
subagent.assistantText += text;
|
||||
const now = yield* DateTime.now;
|
||||
const nativeItemId = `${subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id}:result`;
|
||||
const artifacts = makeSubagentConversationArtifacts({
|
||||
messageId: idAllocator.derive.messageFromProviderItem({ driver, nativeItemId }),
|
||||
turnItemId: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId }),
|
||||
threadId: subagent.childThreadId,
|
||||
rootNodeId: subagent.childRootNodeId,
|
||||
providerThreadId: subagent.task.providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" },
|
||||
role: "assistant",
|
||||
text: subagent.assistantText,
|
||||
ordinal: subagent.nextChildOrdinal,
|
||||
now,
|
||||
});
|
||||
yield* emitProviderEvent({ type: "message.updated", driver, message: artifacts.message });
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver,
|
||||
turnItem: artifacts.turnItem,
|
||||
});
|
||||
});
|
||||
|
||||
const projectSubagentNotification = Effect.fnUntraced(function* (
|
||||
subagent: ActiveAcpSubagent,
|
||||
notification: EffectAcpSchema.SessionNotification,
|
||||
) {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
|
||||
yield* emitSubagentAssistant(subagent, update.content.text);
|
||||
}
|
||||
});
|
||||
|
||||
const emitSubagent = Effect.fnUntraced(function* (
|
||||
context: ActiveAcpTurn,
|
||||
update: AcpAdapterV2SubagentUpdate,
|
||||
) {
|
||||
const existing = context.subagents.get(update.nativeTaskId);
|
||||
const now = yield* DateTime.now;
|
||||
const nativeItemRef = {
|
||||
driver,
|
||||
nativeId: update.nativeTaskId,
|
||||
strength: "strong" as const,
|
||||
};
|
||||
const nodeId =
|
||||
existing?.task.id ??
|
||||
idAllocator.derive.nodeFromProviderItem({
|
||||
driver,
|
||||
nativeItemId: update.nativeTaskId,
|
||||
});
|
||||
const childThreadId =
|
||||
existing?.childThreadId ??
|
||||
idAllocator.derive.threadFromProviderThread({
|
||||
driver,
|
||||
nativeThreadId: `${nativeThreadId(driver, context.input.providerThread)}:task:${update.nativeTaskId}`,
|
||||
});
|
||||
const childRootNodeId =
|
||||
existing?.childRootNodeId ??
|
||||
idAllocator.derive.nodeFromProviderItem({
|
||||
driver,
|
||||
nativeItemId: `${update.nativeTaskId}:child-root`,
|
||||
});
|
||||
const turnItemId =
|
||||
existing?.turnItemId ??
|
||||
idAllocator.derive.turnItemFromProviderItem({
|
||||
driver,
|
||||
nativeItemId: update.nativeTaskId,
|
||||
});
|
||||
const turnItemOrdinal =
|
||||
existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(context, update.nativeTaskId));
|
||||
const taskStatus = update.status;
|
||||
const task: OrchestrationV2Subagent = {
|
||||
...(existing?.task ?? {
|
||||
id: nodeId,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
parentNodeId: context.input.rootNodeId,
|
||||
origin: "provider_native" as const,
|
||||
createdBy: "agent" as const,
|
||||
driver,
|
||||
providerInstanceId: context.input.modelSelection.instanceId,
|
||||
providerThreadId: null,
|
||||
childThreadId,
|
||||
nativeTaskRef: nativeItemRef,
|
||||
prompt: update.prompt,
|
||||
title: update.title,
|
||||
model: update.model,
|
||||
result: null,
|
||||
startedAt: now,
|
||||
}),
|
||||
status: taskStatus,
|
||||
result: existing?.assistantText || update.result,
|
||||
completedAt: taskStatus === "running" ? null : now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const subagent: ActiveAcpSubagent = existing ?? {
|
||||
task,
|
||||
childThreadId,
|
||||
childRootNodeId,
|
||||
turnItemId,
|
||||
turnItemOrdinal,
|
||||
childSessionId: null,
|
||||
assistantText: "",
|
||||
nextChildOrdinal: 101,
|
||||
};
|
||||
subagent.task = task;
|
||||
context.subagents.set(update.nativeTaskId, subagent);
|
||||
|
||||
if (existing === undefined) {
|
||||
yield* emitProviderEvent({
|
||||
type: "app_thread.created",
|
||||
driver,
|
||||
appThread: makeSubagentChildThread({
|
||||
parentThread: context.input.appThread,
|
||||
childThreadId,
|
||||
parentNodeId: nodeId,
|
||||
activeProviderThreadId: null,
|
||||
providerInstanceId: context.input.modelSelection.instanceId,
|
||||
modelSelection: {
|
||||
...context.input.modelSelection,
|
||||
model: update.model ?? context.input.modelSelection.model,
|
||||
},
|
||||
title: subagentThreadTitle({
|
||||
parentTitle: context.input.appThread.title,
|
||||
title: update.title,
|
||||
prompt: update.prompt,
|
||||
ordinal: context.subagents.size,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
}),
|
||||
});
|
||||
const promptNativeItemId = `${update.nativeTaskId}:prompt`;
|
||||
const promptArtifacts = makeSubagentConversationArtifacts({
|
||||
messageId: idAllocator.derive.messageFromProviderItem({
|
||||
driver,
|
||||
nativeItemId: promptNativeItemId,
|
||||
}),
|
||||
turnItemId: idAllocator.derive.turnItemFromProviderItem({
|
||||
driver,
|
||||
nativeItemId: promptNativeItemId,
|
||||
}),
|
||||
threadId: childThreadId,
|
||||
rootNodeId: childRootNodeId,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: { driver, nativeId: promptNativeItemId, strength: "weak" },
|
||||
role: "user",
|
||||
text: update.prompt,
|
||||
ordinal: 100,
|
||||
now,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "message.updated",
|
||||
driver,
|
||||
message: promptArtifacts.message,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver,
|
||||
turnItem: promptArtifacts.turnItem,
|
||||
});
|
||||
}
|
||||
|
||||
if (update.childSessionId !== null && subagent.childSessionId === null) {
|
||||
subagent.childSessionId = update.childSessionId;
|
||||
context.subagentsBySessionId.set(update.childSessionId, subagent);
|
||||
const providerThread = makeProviderThread({
|
||||
driver,
|
||||
providerInstanceId: context.input.modelSelection.instanceId,
|
||||
idAllocator,
|
||||
appThreadId: childThreadId,
|
||||
providerSessionId: input.providerSessionId,
|
||||
nativeThreadId: update.childSessionId,
|
||||
forkedFrom: {
|
||||
providerThreadId: context.input.providerThread.id,
|
||||
providerTurnId: context.providerTurnId,
|
||||
},
|
||||
now,
|
||||
});
|
||||
subagent.task = { ...subagent.task, providerThreadId: providerThread.id };
|
||||
yield* emitProviderEvent({
|
||||
type: "provider_thread.updated",
|
||||
driver,
|
||||
providerThread: { ...providerThread, status: "idle" },
|
||||
});
|
||||
const buffered = context.pendingSubagentNotifications.get(update.childSessionId) ?? [];
|
||||
context.pendingSubagentNotifications.delete(update.childSessionId);
|
||||
yield* Effect.forEach(
|
||||
buffered,
|
||||
(notification) => projectSubagentNotification(subagent, notification),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
taskStatus !== "running" &&
|
||||
subagent.assistantText.length === 0 &&
|
||||
update.result !== null
|
||||
) {
|
||||
yield* emitSubagentAssistant(subagent, update.result);
|
||||
}
|
||||
const result = subagent.assistantText || update.result;
|
||||
subagent.task = {
|
||||
...subagent.task,
|
||||
status: taskStatus,
|
||||
result,
|
||||
completedAt: taskStatus === "running" ? null : now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const providerThreadId = subagent.task.providerThreadId;
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver,
|
||||
node: {
|
||||
id: nodeId,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
parentNodeId: context.input.rootNodeId,
|
||||
rootNodeId: context.input.rootNodeId,
|
||||
kind: "subagent",
|
||||
status: taskStatus,
|
||||
countsForRun: false,
|
||||
providerThreadId: context.input.providerThread.id,
|
||||
providerTurnId: context.providerTurnId,
|
||||
nativeItemRef,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: subagent.task.startedAt,
|
||||
completedAt: subagent.task.completedAt,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver,
|
||||
node: {
|
||||
id: childRootNodeId,
|
||||
threadId: childThreadId,
|
||||
runId: null,
|
||||
parentNodeId: null,
|
||||
rootNodeId: childRootNodeId,
|
||||
kind: "root_turn",
|
||||
status: taskStatus,
|
||||
countsForRun: false,
|
||||
providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: subagent.task.startedAt,
|
||||
completedAt: subagent.task.completedAt,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({ type: "subagent.updated", driver, subagent: subagent.task });
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver,
|
||||
turnItem: {
|
||||
id: turnItemId,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
nodeId,
|
||||
providerThreadId: context.input.providerThread.id,
|
||||
providerTurnId: context.providerTurnId,
|
||||
nativeItemRef,
|
||||
parentItemId: null,
|
||||
ordinal: turnItemOrdinal,
|
||||
status: taskStatus,
|
||||
title: subagent.task.title,
|
||||
startedAt: subagent.task.startedAt,
|
||||
completedAt: subagent.task.completedAt,
|
||||
updatedAt: now,
|
||||
type: "subagent",
|
||||
subagentId: subagent.task.id,
|
||||
origin: "provider_native",
|
||||
driver,
|
||||
providerInstanceId: context.input.modelSelection.instanceId,
|
||||
childThreadId,
|
||||
prompt: subagent.task.prompt,
|
||||
result,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const emitTool = Effect.fnUntraced(function* (
|
||||
context: ActiveAcpTurn,
|
||||
incoming: AcpToolCallState,
|
||||
@@ -817,6 +1141,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
const previous = context.tools.get(incoming.toolCallId);
|
||||
const toolCall = mergeToolCallState(previous, incoming);
|
||||
context.tools.set(toolCall.toolCallId, toolCall);
|
||||
const subagentUpdate = flavor.extractSubagentUpdate?.(toolCall);
|
||||
if (subagentUpdate !== undefined) {
|
||||
yield* emitSubagent(context, subagentUpdate);
|
||||
return;
|
||||
}
|
||||
const status = toolStatus(toolCall.status);
|
||||
const now = yield* DateTime.now;
|
||||
const nativeItemId = `${nativeThreadId(driver, context.input.providerThread)}:tool:${toolCall.toolCallId}`;
|
||||
@@ -1116,7 +1445,21 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
return;
|
||||
}
|
||||
if (context.finalized) return;
|
||||
if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return;
|
||||
if (notification.sessionId !== (yield* Ref.get(activeSessionId))) {
|
||||
if (flavor.extractSubagentUpdate === undefined) return;
|
||||
if (update.sessionUpdate !== "agent_message_chunk" || update.content.type !== "text") {
|
||||
return;
|
||||
}
|
||||
const subagent = context.subagentsBySessionId.get(notification.sessionId);
|
||||
if (subagent !== undefined) {
|
||||
yield* projectSubagentNotification(subagent, notification);
|
||||
return;
|
||||
}
|
||||
const buffered = context.pendingSubagentNotifications.get(notification.sessionId) ?? [];
|
||||
buffered.push(notification);
|
||||
context.pendingSubagentNotifications.set(notification.sessionId, buffered);
|
||||
return;
|
||||
}
|
||||
switch (update.sessionUpdate) {
|
||||
case "agent_message_chunk":
|
||||
if (update.content.type === "text") {
|
||||
@@ -1817,6 +2160,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
reasoning: { current: null, nextSegment: 0 },
|
||||
tools: new Map(),
|
||||
toolStartedAt: new Map(),
|
||||
subagents: new Map(),
|
||||
subagentsBySessionId: new Map(),
|
||||
pendingSubagentNotifications: new Map(),
|
||||
plan: null,
|
||||
interrupted: false,
|
||||
finalized: false,
|
||||
|
||||
@@ -45,9 +45,11 @@ describe("GrokAdapterV2 capabilities", () => {
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools);
|
||||
});
|
||||
|
||||
it("leaves non-native features available to orchestrator fallbacks", () => {
|
||||
it("declares Grok Task envelopes as native subagents", () => {
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread);
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.subagents.exposesSubagentThreadIds);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.subagents.emitsSubagentLifecycle);
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.turns.supportsActiveSteering);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsInterrupt);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsSteeringByInterruptRestart);
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import {
|
||||
extractXAiAskUserQuestionIdentity,
|
||||
extractXAiAskUserQuestions,
|
||||
extractXAiAcpSubagentUpdate,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
XAiAskUserQuestionRequest,
|
||||
@@ -64,7 +65,9 @@ export const GrokProviderCapabilitiesV2 = {
|
||||
},
|
||||
subagents: {
|
||||
...AcpProviderCapabilitiesV2.subagents,
|
||||
supportsSubagents: false,
|
||||
supportsSubagents: true,
|
||||
exposesSubagentThreadIds: true,
|
||||
emitsSubagentLifecycle: true,
|
||||
},
|
||||
tools: {
|
||||
...AcpProviderCapabilitiesV2.tools,
|
||||
@@ -140,6 +143,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
childProcessSpawner: options.childProcessSpawner,
|
||||
})),
|
||||
registerExtensions: registerGrokAcpExtensions,
|
||||
extractSubagentUpdate: extractXAiAcpSubagentUpdate,
|
||||
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
|
||||
};
|
||||
return makeAcpAdapterV2({
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"grok_subagent_lineage","metadata":{"generatedBy":"compiled-provider-log","sourceThreadId":"571b464b-0b43-47f4-a710-23d915aa6a5b","sourceTurnId":"3a20e836-9e7a-4858-9cdb-2e1e7d3e35c6","sourceNativeSessionId":"019f0220-b386-78b3-bc57-dc127c023559","normalization":"Large audit result chunks were truncated while preserving source session IDs, task IDs, ordering, and text boundaries."}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","models":{"currentModelId":"grok-composer-2.5-fast","availableModels":[{"modelId":"grok-composer-2.5-fast","name":"Grok Composer 2.5 Fast"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","prompt":[{"type":"text","text":"audit this codebase"}]}}}
|
||||
{"type":"emit_inbound","label":"task.server.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","update":{"sessionUpdate":"tool_call","toolCallId":"call-28397a12-0446-478e-a180-b06aefb56734-composer_call_kFjs8","title":"Task","rawInput":{"description":"Explore server architecture","prompt":"Audit the apps/server package and return a structured summary.","subagent_type":"generalPurpose","model":"composer-2.5-fast"}}}}}
|
||||
{"type":"emit_inbound","label":"task.web.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","update":{"sessionUpdate":"tool_call","toolCallId":"call-28397a12-0446-478e-a180-b06aefb56734-composer_call_Olv1X","title":"Task","rawInput":{"description":"Explore web client architecture","prompt":"Audit the apps/web package and return a structured summary.","subagent_type":"generalPurpose","model":"composer-2.5-fast"}}}}}
|
||||
{"type":"emit_inbound","label":"child.server.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-e192-7c41-9e9d-b406bc3459c8","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I'll audit `apps/server` by mapping its layout first, then reading entry points, WebSocket/auth/session code, and tests.\n"}}}}}
|
||||
{"type":"emit_inbound","label":"child.web.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-e197-7833-a8e4-ad38f2bd5b4c","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Auditing `apps/web`: mapping package structure and searching source for state, WebSocket, components, performance, and tests.\n"}}}}}
|
||||
{"type":"emit_inbound","label":"child.server.result","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-e192-7c41-9e9d-b406bc3459c8","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"# `apps/server` Audit Summary\n\nLayered Effect architecture with WebSocket RPC and durable provider sessions."}}}}}
|
||||
{"type":"emit_inbound","label":"child.web.result","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-e197-7833-a8e4-ad38f2bd5b4c","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"# `apps/web` Audit Summary\n\nHybrid Effect Atom and Zustand state with centralized reconnect handling."}}}}}
|
||||
{"type":"emit_inbound","label":"task.server.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-28397a12-0446-478e-a180-b06aefb56734-composer_call_kFjs8","status":"completed","rawOutput":{"type":"Text","text":"Server audit complete.\n\nAgent ID: 019f0220-e192-7c41-9e9d-b406bc3459c8 (can be used with the `resume` parameter to send a follow-up after it completes)"}}}}}
|
||||
{"type":"emit_inbound","label":"task.web.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-28397a12-0446-478e-a180-b06aefb56734-composer_call_Olv1X","status":"completed","rawOutput":{"type":"Text","text":"Web audit complete.\n\nAgent ID: 019f0220-e197-7833-a8e4-ad38f2bd5b4c (can be used with the `resume` parameter to send a follow-up after it completes)"}}}}}
|
||||
{"type":"emit_inbound","label":"parent.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"019f0220-b386-78b3-bc57-dc127c023559","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Audit complete."}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { OrchestratorFixtureInput } from "../shared.ts";
|
||||
|
||||
export const GROK_SUBAGENT_LINEAGE_PROMPT = "audit this codebase";
|
||||
|
||||
export function grokSubagentLineageInput(): OrchestratorFixtureInput {
|
||||
return {
|
||||
steps: [{ type: "message", text: GROK_SUBAGENT_LINEAGE_PROMPT }],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertBaseProjection,
|
||||
assertExecutionNodeKinds,
|
||||
assertNoExtraAppRunsForProviderChildren,
|
||||
assertTurnItemTypes,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
const EXPECTED_CHILDREN = [
|
||||
{
|
||||
title: "Explore server architecture",
|
||||
sessionId: "019f0220-e192-7c41-9e9d-b406bc3459c8",
|
||||
first: "I'll audit `apps/server` by mapping its layout first",
|
||||
second: "# `apps/server` Audit Summary",
|
||||
},
|
||||
{
|
||||
title: "Explore web client architecture",
|
||||
sessionId: "019f0220-e197-7833-a8e4-ad38f2bd5b4c",
|
||||
first: "Auditing `apps/web`: mapping package structure",
|
||||
second: "# `apps/web` Audit Summary",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function assertGrokSubagentLineageOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
|
||||
const parent = projectionFor(result, transcript.scenario);
|
||||
assertTurnItemTypes(parent, ["user_message", "subagent", "subagent", "assistant_message"]);
|
||||
assertExecutionNodeKinds(parent, ["root_turn", "subagent", "subagent", "assistant_message"]);
|
||||
assertNoExtraAppRunsForProviderChildren({ projection: parent, expectedAppRuns: 1 });
|
||||
assert.lengthOf(parent.subagents, 2);
|
||||
assert.lengthOf(result.shellSnapshot.threads, 3);
|
||||
assert.notInclude(
|
||||
parent.messages.map((message) => message.text).join("\n"),
|
||||
"Audit Summary",
|
||||
"interleaved child output must not leak into the parent timeline",
|
||||
);
|
||||
|
||||
for (const expected of EXPECTED_CHILDREN) {
|
||||
const subagent = parent.subagents.find((candidate) => candidate.title === expected.title);
|
||||
assert.isDefined(subagent);
|
||||
assert.equal(subagent.status, "completed");
|
||||
assert.equal(subagent.origin, "provider_native");
|
||||
assert.equal(subagent.driver, "grok");
|
||||
assert.isNotNull(subagent.childThreadId);
|
||||
assert.isNotNull(subagent.providerThreadId);
|
||||
assert.include(subagent.result ?? "", expected.first);
|
||||
assert.include(subagent.result ?? "", expected.second);
|
||||
if (subagent.childThreadId === null || subagent.providerThreadId === null) {
|
||||
throw new Error(`Grok subagent ${expected.title} is missing lineage`);
|
||||
}
|
||||
|
||||
const child = result.projections.get(subagent.childThreadId);
|
||||
assert.isDefined(child);
|
||||
assert.equal(child.thread.lineage.parentThreadId, parent.thread.id);
|
||||
assert.equal(child.thread.lineage.relationshipToParent, "subagent");
|
||||
assert.equal(child.thread.lineage.rootThreadId, parent.thread.lineage.rootThreadId);
|
||||
assert.equal(child.thread.activeProviderThreadId, subagent.providerThreadId);
|
||||
assert.lengthOf(child.runs, 0);
|
||||
assert.lengthOf(child.providerThreads, 1);
|
||||
assert.equal(child.providerThreads[0]?.nativeThreadRef?.nativeId, expected.sessionId);
|
||||
const forkedFrom = child.providerThreads[0]?.forkedFrom;
|
||||
if (forkedFrom == null) {
|
||||
throw new Error(`Grok subagent ${expected.title} is missing provider lineage`);
|
||||
}
|
||||
assert.notEqual(forkedFrom.providerThreadId, subagent.providerThreadId);
|
||||
assert.isTrue(
|
||||
parent.providerTurns.some(
|
||||
(turn) =>
|
||||
turn.id === forkedFrom.providerTurnId &&
|
||||
turn.providerThreadId === forkedFrom.providerThreadId,
|
||||
),
|
||||
"the native child session must fork from the parent provider turn",
|
||||
);
|
||||
assertTurnItemTypes(child, ["user_message", "assistant_message"]);
|
||||
const assistant = child.messages.find((message) => message.role === "assistant");
|
||||
assert.isDefined(assistant);
|
||||
assert.isBelow(assistant.text.indexOf(expected.first), assistant.text.indexOf(expected.second));
|
||||
for (const other of EXPECTED_CHILDREN) {
|
||||
if (other.sessionId !== expected.sessionId) {
|
||||
assert.notInclude(
|
||||
assistant.text,
|
||||
other.second,
|
||||
"interleaved chunks must remain isolated to their native child session",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import { grokSubagentLineageInput } from "./grok_subagent_lineage/input.ts";
|
||||
import { assertGrokSubagentLineageOutput } from "./grok_subagent_lineage/output.ts";
|
||||
import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts";
|
||||
import { assertMessageSteeringOutput } from "./message_steering/codex_output.ts";
|
||||
import { assertCursorMessageSteeringOutput } from "./message_steering/cursor_output.ts";
|
||||
@@ -73,6 +75,21 @@ import {
|
||||
} from "./shared.ts";
|
||||
|
||||
export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
{
|
||||
name: "grok_subagent_lineage",
|
||||
buildInput: grokSubagentLineageInput,
|
||||
providers: [
|
||||
{
|
||||
driver: ProviderDriverKind.make("grok"),
|
||||
transcriptFile: new URL("./grok_subagent_lineage/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: {
|
||||
...GROK_MODEL_SELECTION,
|
||||
model: "grok-composer-2.5-fast",
|
||||
},
|
||||
assertOutput: assertGrokSubagentLineageOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "acp_elicitation",
|
||||
buildInput: planQuestionsInput,
|
||||
|
||||
@@ -10,6 +10,7 @@ import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
extractXAiAcpSubagentUpdate,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
@@ -38,6 +39,65 @@ const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
describe("XAiAcpExtension", () => {
|
||||
it("recognizes Grok Task starts as native subagents", () => {
|
||||
expect(
|
||||
extractXAiAcpSubagentUpdate({
|
||||
toolCallId: "task-1",
|
||||
title: "Task",
|
||||
status: "inProgress",
|
||||
data: {
|
||||
rawInput: {
|
||||
description: "Explore server architecture",
|
||||
prompt: "Audit apps/server.",
|
||||
subagent_type: "generalPurpose",
|
||||
model: "composer-2.5-fast",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
nativeTaskId: "task-1",
|
||||
prompt: "Audit apps/server.",
|
||||
title: "Explore server architecture",
|
||||
model: "composer-2.5-fast",
|
||||
status: "running",
|
||||
childSessionId: null,
|
||||
result: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts Grok child session lineage from completed Task output", () => {
|
||||
expect(
|
||||
extractXAiAcpSubagentUpdate({
|
||||
toolCallId: "task-1",
|
||||
title: "Task",
|
||||
status: "completed",
|
||||
data: {
|
||||
rawInput: {
|
||||
description: "Explore server architecture",
|
||||
prompt: "Audit apps/server.",
|
||||
subagent_type: "generalPurpose",
|
||||
},
|
||||
rawOutput: {
|
||||
type: "Text",
|
||||
text: [
|
||||
"Server audit complete.",
|
||||
"",
|
||||
"Agent ID: 019f0220-e192-7c41-9e9d-b406bc3459c8 (resume supported)",
|
||||
].join("\n"),
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
nativeTaskId: "task-1",
|
||||
prompt: "Audit apps/server.",
|
||||
title: "Explore server architecture",
|
||||
model: null,
|
||||
status: "completed",
|
||||
childSessionId: "019f0220-e192-7c41-9e9d-b406bc3459c8",
|
||||
result: "Server audit complete.",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts questions from the real xAI ask_user_question payload shape", () => {
|
||||
const questions = extractXAiAskUserQuestions({
|
||||
sessionId: "session-1",
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as Schema from "effect/Schema";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
|
||||
const XAiPromptCompleteNotification = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
@@ -25,6 +26,81 @@ interface PendingXAiPromptCompletion {
|
||||
const completedXAiPromptIdLimit = 128;
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
|
||||
export interface XAiAcpSubagentUpdate {
|
||||
readonly nativeTaskId: string;
|
||||
readonly prompt: string;
|
||||
readonly title: string | null;
|
||||
readonly model: string | null;
|
||||
readonly status: "running" | "completed" | "failed";
|
||||
readonly childSessionId: string | null;
|
||||
readonly result: string | null;
|
||||
}
|
||||
|
||||
function unknownRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function xAiTaskOutputText(toolCall: AcpToolCallState): string | undefined {
|
||||
const rawOutput = unknownRecord(toolCall.data.rawOutput);
|
||||
const rawOutputText = nonEmptyString(rawOutput?.text);
|
||||
if (rawOutputText !== undefined) return rawOutputText;
|
||||
const content = toolCall.data.content;
|
||||
if (!Array.isArray(content)) return undefined;
|
||||
const text = content
|
||||
.flatMap((entry) => {
|
||||
const record = unknownRecord(entry);
|
||||
const nested = unknownRecord(record?.content);
|
||||
return nonEmptyString(nested?.text) ?? nonEmptyString(record?.text) ?? [];
|
||||
})
|
||||
.join("\n")
|
||||
.trim();
|
||||
return text.length > 0 ? text : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognizes Grok's private `Task` tool envelope without teaching the generic
|
||||
* ACP adapter about xAI tool names or result formatting.
|
||||
*/
|
||||
export function extractXAiAcpSubagentUpdate(
|
||||
toolCall: AcpToolCallState,
|
||||
): XAiAcpSubagentUpdate | undefined {
|
||||
const rawInput = unknownRecord(toolCall.data.rawInput);
|
||||
const isTask =
|
||||
toolCall.title === "Task" ||
|
||||
rawInput?.variant === "CursorTask" ||
|
||||
nonEmptyString(rawInput?.subagent_type) !== undefined;
|
||||
if (!isTask || rawInput === undefined) return undefined;
|
||||
|
||||
const output = xAiTaskOutputText(toolCall);
|
||||
const childSessionId =
|
||||
output?.match(/(?:^|\n)Agent ID:\s*([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\b/i)?.[1] ??
|
||||
null;
|
||||
const result =
|
||||
output?.replace(/(?:^|\n)Agent ID:\s*[0-9a-f-]+[^\n]*(?:\n|$)/gi, "\n").trim() || null;
|
||||
const status =
|
||||
toolCall.status === "failed"
|
||||
? "failed"
|
||||
: toolCall.status === "completed"
|
||||
? "completed"
|
||||
: "running";
|
||||
|
||||
return {
|
||||
nativeTaskId: toolCall.toolCallId,
|
||||
prompt: nonEmptyString(rawInput.prompt) ?? "",
|
||||
title: nonEmptyString(rawInput.description) ?? null,
|
||||
model: nonEmptyString(rawInput.model) ?? null,
|
||||
status,
|
||||
childSessionId,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
description: Schema.optional(Schema.String),
|
||||
|
||||
Reference in new issue
Block a user