feat(server): Claude agent lifecycle fields + ingestion agent roster reducer
ClaudeAdapter carries subagent linkage (agentType/toolUseId/workflowName/ prompt/outputFile), handles task_updated, parses workflow_progress into child workflow_agent task events, normalizes task usage, and captures Workflow tool results (scriptPath/runId). Ingestion folds task.* events into per-thread ThreadAgentSnapshot rosters with material-transition filtering, projection hydration, orphan sweep, and 50-cap retention, appended as agent.snapshot activities. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
7e898d22df
commit
5472e9dadb
4 files changed
+726
-11
No files matched your search
@@ -9,6 +9,8 @@ import {
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
ProviderInstanceId,
|
||||
RuntimeTaskId,
|
||||
type ThreadAgentSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -43,7 +45,11 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
|
||||
import {
|
||||
foldTaskAgentEvent,
|
||||
ProviderRuntimeIngestionLive,
|
||||
pruneSettledAgents,
|
||||
} from "./ProviderRuntimeIngestion.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -318,6 +324,111 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
};
|
||||
}
|
||||
|
||||
it("folds material transitions, reactivations, and settled retention", () => {
|
||||
const agents = new Map<string, ThreadAgentSnapshot>();
|
||||
const started: Extract<ProviderRuntimeEvent, { type: "task.started" }> = {
|
||||
type: "task.started",
|
||||
eventId: asEventId("agent-started"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make("agent-1"),
|
||||
description: "Reviewer",
|
||||
taskType: "local_agent",
|
||||
},
|
||||
};
|
||||
expect(foldTaskAgentEvent(agents, started)).toBe(true);
|
||||
const usageTick: Extract<ProviderRuntimeEvent, { type: "task.progress" }> = {
|
||||
...started,
|
||||
type: "task.progress",
|
||||
eventId: asEventId("agent-progress"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make("agent-1"),
|
||||
description: "Reviewer",
|
||||
usage: { totalTokens: 10 },
|
||||
},
|
||||
};
|
||||
expect(foldTaskAgentEvent(agents, usageTick)).toBe(false);
|
||||
const completed: Extract<ProviderRuntimeEvent, { type: "task.completed" }> = {
|
||||
...started,
|
||||
type: "task.completed",
|
||||
eventId: asEventId("agent-completed"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
payload: { taskId: RuntimeTaskId.make("agent-1"), status: "completed" },
|
||||
};
|
||||
expect(foldTaskAgentEvent(agents, completed)).toBe(true);
|
||||
expect(
|
||||
foldTaskAgentEvent(agents, { ...started, eventId: asEventId("agent-reactivated") }),
|
||||
).toBe(true);
|
||||
expect(agents.get("agent-1")?.activationCount).toBe(2);
|
||||
|
||||
for (let index = 0; index < 51; index += 1) {
|
||||
agents.set(`settled-${index}`, {
|
||||
agentId: `settled-${index}`,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
kind: "subagent",
|
||||
name: `Agent ${index}`,
|
||||
status: "completed",
|
||||
firstStartedAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
|
||||
lastActivityAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
|
||||
activationCount: 1,
|
||||
recentActivity: [],
|
||||
updatedAt: `2026-01-01T00:00:${String(index).padStart(2, "0")}.000Z`,
|
||||
});
|
||||
}
|
||||
pruneSettledAgents(agents);
|
||||
expect(
|
||||
Array.from(agents.values()).filter((agent) => agent.status === "completed"),
|
||||
).toHaveLength(50);
|
||||
expect(agents.has("settled-0")).toBe(false);
|
||||
});
|
||||
|
||||
it("appends latest-wins agent rosters only on material changes and sweeps orphans", async () => {
|
||||
const harness = await createHarness();
|
||||
harness.emit({
|
||||
type: "task.started",
|
||||
eventId: asEventId("evt-agent-start"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
payload: { taskId: "agent-1", description: "Reviewer", taskType: "local_agent" },
|
||||
});
|
||||
await harness.drain();
|
||||
harness.emit({
|
||||
type: "task.progress",
|
||||
eventId: asEventId("evt-agent-usage"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
payload: { taskId: "agent-1", description: "Reviewer", usage: { totalTokens: 10 } },
|
||||
});
|
||||
await harness.drain();
|
||||
let thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
|
||||
expect(
|
||||
thread?.activities.filter((activity) => activity.kind === "agent.snapshot"),
|
||||
).toHaveLength(1);
|
||||
|
||||
harness.emit({
|
||||
type: "session.exited",
|
||||
eventId: asEventId("evt-session-exit-agents"),
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:03.000Z",
|
||||
payload: { reason: "process_exit" },
|
||||
});
|
||||
await harness.drain();
|
||||
thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
|
||||
const snapshots =
|
||||
thread?.activities.filter((activity) => activity.kind === "agent.snapshot") ?? [];
|
||||
expect(snapshots).toHaveLength(2);
|
||||
const latest = snapshots.at(-1)?.payload as { agents: Array<ThreadAgentSnapshot> } | undefined;
|
||||
expect(latest?.agents).toHaveLength(1);
|
||||
expect(latest?.agents[0]?.status).toBe("stopped");
|
||||
expect(latest?.agents[0]?.errorMessage).toBe("orphaned on session exit");
|
||||
});
|
||||
|
||||
it("maps turn started/completed events into thread session updates", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type AssistantDeliveryMode,
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
@@ -9,6 +10,12 @@ import {
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
THREAD_AGENTS_ACTIVITY_KIND,
|
||||
THREAD_AGENT_RECENT_ACTIVITY_LIMIT,
|
||||
THREAD_AGENT_TERMINAL_STATUSES,
|
||||
type ThreadAgentSnapshot,
|
||||
type ThreadAgentStatus,
|
||||
type ThreadAgentUsage,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
@@ -41,6 +48,198 @@ import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
|
||||
const AGENT_SETTLED_RETENTION_LIMIT = 50;
|
||||
const AGENT_USAGE_MATERIAL_STEP = 25_000;
|
||||
|
||||
function taskUsage(value: unknown): ThreadAgentUsage | undefined {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const usage = value as Record<string, unknown>;
|
||||
if (typeof usage.totalTokens !== "number" || usage.totalTokens < 0) return undefined;
|
||||
return {
|
||||
totalTokens: usage.totalTokens,
|
||||
...(typeof usage.inputTokens === "number" ? { inputTokens: usage.inputTokens } : {}),
|
||||
...(typeof usage.cachedInputTokens === "number"
|
||||
? { cachedInputTokens: usage.cachedInputTokens }
|
||||
: {}),
|
||||
...(typeof usage.outputTokens === "number" ? { outputTokens: usage.outputTokens } : {}),
|
||||
...(typeof usage.reasoningOutputTokens === "number"
|
||||
? { reasoningOutputTokens: usage.reasoningOutputTokens }
|
||||
: {}),
|
||||
...(typeof usage.toolUses === "number" ? { toolUses: usage.toolUses } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function taskStatus(event: ProviderRuntimeEvent): ThreadAgentStatus | undefined {
|
||||
if (event.type === "task.started") return "running";
|
||||
if (event.type === "task.completed") return event.payload.status;
|
||||
if (event.type !== "task.updated" || !event.payload.status) return undefined;
|
||||
return event.payload.status === "killed"
|
||||
? "stopped"
|
||||
: event.payload.status === "paused"
|
||||
? "idle"
|
||||
: event.payload.status;
|
||||
}
|
||||
|
||||
function taskKind(taskType: string | undefined, parentTaskId: string | undefined) {
|
||||
if (taskType === "local_agent") return "subagent" as const;
|
||||
if (taskType === "local_workflow") return "workflow" as const;
|
||||
if (taskType === "workflow_agent" || parentTaskId) return "workflow_agent" as const;
|
||||
if (taskType === "local_bash" || taskType === "shell") return "shell" as const;
|
||||
if (taskType === "monitor") return "monitor" as const;
|
||||
return "other" as const;
|
||||
}
|
||||
|
||||
function isTaskAgentEvent(
|
||||
event: ProviderRuntimeEvent,
|
||||
): event is Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ type: "task.started" | "task.progress" | "task.updated" | "task.completed" }
|
||||
> {
|
||||
return (
|
||||
event.type === "task.started" ||
|
||||
event.type === "task.progress" ||
|
||||
event.type === "task.updated" ||
|
||||
event.type === "task.completed"
|
||||
);
|
||||
}
|
||||
|
||||
function workflowPhasesEqual(
|
||||
left: ThreadAgentSnapshot["phases"],
|
||||
right: ThreadAgentSnapshot["phases"],
|
||||
): boolean {
|
||||
return (
|
||||
left === right ||
|
||||
(left !== undefined &&
|
||||
right !== undefined &&
|
||||
left.length === right.length &&
|
||||
left.every(
|
||||
(phase, index) =>
|
||||
phase.index === right[index]?.index && phase.title === right[index]?.title,
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
export function foldTaskAgentEvent(
|
||||
agents: Map<string, ThreadAgentSnapshot>,
|
||||
event: Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ type: "task.started" | "task.progress" | "task.updated" | "task.completed" }
|
||||
>,
|
||||
): boolean {
|
||||
const payload = event.payload;
|
||||
const previous = agents.get(payload.taskId);
|
||||
const status = taskStatus(event) ?? previous?.status ?? "running";
|
||||
const description = "description" in payload ? payload.description : undefined;
|
||||
const summary = "summary" in payload ? payload.summary : undefined;
|
||||
const nextUsage = "usage" in payload ? taskUsage(payload.usage) : undefined;
|
||||
const lastToolName = "lastToolName" in payload ? payload.lastToolName : undefined;
|
||||
const currentActivity = summary ?? lastToolName ?? previous?.currentActivity;
|
||||
const activityChanged =
|
||||
(summary !== undefined && summary !== previous?.currentActivity) ||
|
||||
(lastToolName !== undefined && lastToolName !== previous?.lastToolName);
|
||||
const recentActivity = activityChanged
|
||||
? [
|
||||
...(previous?.recentActivity ?? []),
|
||||
{ at: event.createdAt, summary: summary ?? lastToolName ?? "Activity updated" },
|
||||
].slice(-THREAD_AGENT_RECENT_ACTIVITY_LIMIT)
|
||||
: (previous?.recentActivity ?? []);
|
||||
const wasSettled =
|
||||
previous !== undefined &&
|
||||
(previous.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(previous.status));
|
||||
const reactivated = wasSettled && status === "running";
|
||||
const explicitEndTime = event.type === "task.updated" ? event.payload.endTime : undefined;
|
||||
const terminal = THREAD_AGENT_TERMINAL_STATUSES.has(status);
|
||||
const next: ThreadAgentSnapshot = {
|
||||
agentId: payload.taskId,
|
||||
provider: event.provider,
|
||||
kind:
|
||||
previous?.kind ??
|
||||
taskKind("taskType" in payload ? payload.taskType : undefined, payload.parentTaskId),
|
||||
name: payload.name ?? description ?? payload.workflowName ?? previous?.name ?? payload.taskId,
|
||||
...((payload.agentType ?? previous?.agentType)
|
||||
? { agentType: payload.agentType ?? previous?.agentType }
|
||||
: {}),
|
||||
...((payload.model ?? previous?.model) ? { model: payload.model ?? previous?.model } : {}),
|
||||
status,
|
||||
...(currentActivity ? { currentActivity } : {}),
|
||||
...((lastToolName ?? previous?.lastToolName)
|
||||
? { lastToolName: lastToolName ?? previous?.lastToolName }
|
||||
: {}),
|
||||
...((nextUsage ?? previous?.usage) ? { usage: nextUsage ?? previous?.usage } : {}),
|
||||
firstStartedAt: previous?.firstStartedAt ?? event.createdAt,
|
||||
lastActivityAt: event.createdAt,
|
||||
...(!reactivated && (explicitEndTime ?? (terminal ? event.createdAt : previous?.endedAt))
|
||||
? { endedAt: explicitEndTime ?? (terminal ? event.createdAt : previous?.endedAt) }
|
||||
: {}),
|
||||
activationCount: previous ? previous.activationCount + (reactivated ? 1 : 0) : 1,
|
||||
...((event.turnId ?? previous?.lastTurnId)
|
||||
? { lastTurnId: TurnId.make(String(event.turnId ?? previous?.lastTurnId)) }
|
||||
: {}),
|
||||
...((payload.parentTaskId ?? previous?.parentAgentId)
|
||||
? { parentAgentId: payload.parentTaskId ?? previous?.parentAgentId }
|
||||
: {}),
|
||||
...(payload.phaseIndex !== undefined || previous?.phaseIndex !== undefined
|
||||
? { phaseIndex: payload.phaseIndex ?? previous?.phaseIndex }
|
||||
: {}),
|
||||
...((payload.phaseTitle ?? previous?.phaseTitle)
|
||||
? { phaseTitle: payload.phaseTitle ?? previous?.phaseTitle }
|
||||
: {}),
|
||||
...((payload.phases ?? previous?.phases) ? { phases: payload.phases ?? previous?.phases } : {}),
|
||||
...((payload.scriptPath ?? previous?.scriptPath)
|
||||
? { scriptPath: payload.scriptPath ?? previous?.scriptPath }
|
||||
: {}),
|
||||
...((payload.runId ?? previous?.runId) ? { runId: payload.runId ?? previous?.runId } : {}),
|
||||
...((payload.outputFile ?? previous?.outputFile)
|
||||
? { outputFile: payload.outputFile ?? previous?.outputFile }
|
||||
: {}),
|
||||
...(event.type === "task.completed" && event.payload.summary
|
||||
? { resultSummary: event.payload.summary }
|
||||
: previous?.resultSummary
|
||||
? { resultSummary: previous.resultSummary }
|
||||
: {}),
|
||||
...(event.type === "task.updated" && event.payload.errorMessage
|
||||
? { errorMessage: event.payload.errorMessage }
|
||||
: previous?.errorMessage
|
||||
? { errorMessage: previous.errorMessage }
|
||||
: {}),
|
||||
recentActivity,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
agents.set(payload.taskId, next);
|
||||
if (!previous) return true;
|
||||
const usageStepChanged =
|
||||
Math.floor((previous.usage?.totalTokens ?? 0) / AGENT_USAGE_MATERIAL_STEP) !==
|
||||
Math.floor((next.usage?.totalTokens ?? 0) / AGENT_USAGE_MATERIAL_STEP);
|
||||
return (
|
||||
previous.status !== next.status ||
|
||||
previous.name !== next.name ||
|
||||
previous.model !== next.model ||
|
||||
previous.phaseIndex !== next.phaseIndex ||
|
||||
previous.phaseTitle !== next.phaseTitle ||
|
||||
!workflowPhasesEqual(previous.phases, next.phases) ||
|
||||
previous.currentActivity !== next.currentActivity ||
|
||||
activityChanged ||
|
||||
usageStepChanged ||
|
||||
previous.endedAt !== next.endedAt ||
|
||||
previous.resultSummary !== next.resultSummary ||
|
||||
previous.errorMessage !== next.errorMessage ||
|
||||
previous.scriptPath !== next.scriptPath ||
|
||||
previous.runId !== next.runId ||
|
||||
previous.outputFile !== next.outputFile
|
||||
);
|
||||
}
|
||||
|
||||
export function pruneSettledAgents(agents: Map<string, ThreadAgentSnapshot>): void {
|
||||
const settled = Array.from(agents.values())
|
||||
.filter((agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status))
|
||||
.sort((left, right) => left.lastActivityAt.localeCompare(right.lastActivityAt));
|
||||
for (const agent of settled.slice(
|
||||
0,
|
||||
Math.max(0, settled.length - AGENT_SETTLED_RETENTION_LIMIT),
|
||||
)) {
|
||||
agents.delete(agent.agentId);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback when the in-memory description cache no longer has the task name
|
||||
// (server restart, session-exit sweep, TTL/capacity eviction): earlier
|
||||
@@ -310,6 +509,12 @@ export function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
taskTitle?: string,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
if (
|
||||
(isTaskAgentEvent(event) && event.payload.timelineBypass === true) ||
|
||||
event.type === "task.updated"
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const maybeSequence = (() => {
|
||||
const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number };
|
||||
return eventWithSequence.sessionSequence !== undefined
|
||||
@@ -693,6 +898,9 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const agentsByThread = new Map<ThreadId, Map<string, ThreadAgentSnapshot>>();
|
||||
const hydratedAgentThreads = new Set<ThreadId>();
|
||||
let agentSnapshotDispatchCount = 0;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
|
||||
@@ -1305,6 +1513,85 @@ const make = Effect.gen(function* () {
|
||||
return loadedThreadDetail;
|
||||
});
|
||||
|
||||
if (!hydratedAgentThreads.has(thread.id)) {
|
||||
const detail = yield* getLoadedThreadDetail();
|
||||
const latestSnapshot = detail?.activities.findLast(
|
||||
(activity) => activity.kind === THREAD_AGENTS_ACTIVITY_KIND,
|
||||
);
|
||||
const payload =
|
||||
latestSnapshot?.payload !== null && typeof latestSnapshot?.payload === "object"
|
||||
? (latestSnapshot.payload as { agents?: unknown })
|
||||
: undefined;
|
||||
const agents = new Map<string, ThreadAgentSnapshot>();
|
||||
if (Array.isArray(payload?.agents)) {
|
||||
for (const candidate of payload.agents) {
|
||||
if (
|
||||
candidate !== null &&
|
||||
typeof candidate === "object" &&
|
||||
typeof (candidate as { agentId?: unknown }).agentId === "string"
|
||||
) {
|
||||
const agent = candidate as ThreadAgentSnapshot;
|
||||
agents.set(agent.agentId, agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
agentsByThread.set(thread.id, agents);
|
||||
hydratedAgentThreads.add(thread.id);
|
||||
}
|
||||
|
||||
const threadAgents = agentsByThread.get(thread.id) ?? new Map<string, ThreadAgentSnapshot>();
|
||||
agentsByThread.set(thread.id, threadAgents);
|
||||
let agentRosterMaterial = false;
|
||||
if (isTaskAgentEvent(event)) {
|
||||
agentRosterMaterial = foldTaskAgentEvent(threadAgents, event);
|
||||
} else if (event.type === "session.exited") {
|
||||
for (const [agentId, agent] of threadAgents) {
|
||||
if (THREAD_AGENT_TERMINAL_STATUSES.has(agent.status)) continue;
|
||||
threadAgents.set(agentId, {
|
||||
...agent,
|
||||
status: "stopped",
|
||||
endedAt: event.createdAt,
|
||||
lastActivityAt: event.createdAt,
|
||||
errorMessage: "orphaned on session exit",
|
||||
updatedAt: event.createdAt,
|
||||
});
|
||||
agentRosterMaterial = true;
|
||||
}
|
||||
}
|
||||
if (agentRosterMaterial) {
|
||||
pruneSettledAgents(threadAgents);
|
||||
const roster = Array.from(threadAgents.values());
|
||||
const running = roster.filter((agent) => agent.status === "running").length;
|
||||
const settled = roster.filter(
|
||||
(agent) => agent.status === "idle" || THREAD_AGENT_TERMINAL_STATUSES.has(agent.status),
|
||||
).length;
|
||||
const count = running > 0 ? running : settled;
|
||||
const summary = `${count} ${count === 1 ? "agent" : "agents"} ${running > 0 ? "running" : "settled"}`;
|
||||
const snapshotUuid = yield* crypto.randomUUIDv4;
|
||||
const activity: OrchestrationThreadActivity = {
|
||||
id: EventId.make(`${event.eventId}:agent-snapshot:${snapshotUuid}`),
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: THREAD_AGENTS_ACTIVITY_KIND,
|
||||
summary,
|
||||
payload: { agents: roster },
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: yield* providerCommandId(event, "agent-snapshot-append"),
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
});
|
||||
agentSnapshotDispatchCount += 1;
|
||||
yield* Effect.logDebug("provider agent snapshot appended", {
|
||||
threadId: thread.id,
|
||||
agentCount: roster.length,
|
||||
dispatchCount: agentSnapshotDispatchCount,
|
||||
});
|
||||
}
|
||||
|
||||
const now = event.createdAt;
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
|
||||
@@ -1704,6 +1704,123 @@ describe("ClaudeAdapterLive", () => {
|
||||
"Code reviewer checked the migration edge cases.",
|
||||
);
|
||||
assert.equal(progressEvent.payload.description, "Running background teammate");
|
||||
assert.deepEqual(progressEvent.payload.usage, {
|
||||
totalTokens: 123,
|
||||
toolUses: 4,
|
||||
durationMs: 987,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("carries Claude task linkage, updates, and workflow progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => runtimeEvents.push(event)),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_started",
|
||||
task_id: "workflow-1",
|
||||
description: "Run checks",
|
||||
task_type: "local_workflow",
|
||||
subagent_type: "Workflow",
|
||||
tool_use_id: "tool-1",
|
||||
workflow_name: "Verification",
|
||||
prompt: "Check the repository",
|
||||
session_id: "session",
|
||||
uuid: "started",
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "workflow-1",
|
||||
description: "Run checks",
|
||||
subagent_type: "Workflow",
|
||||
tool_use_id: "tool-1",
|
||||
usage: { total_tokens: 12, tool_uses: 2, duration_ms: 30 },
|
||||
workflow_progress: [
|
||||
{ type: "workflow_phase", index: 0, title: "Inspect" },
|
||||
{
|
||||
type: "workflow_agent",
|
||||
label: "Reviewer",
|
||||
phaseIndex: 0,
|
||||
phaseTitle: "Inspect",
|
||||
agentId: "agent-1",
|
||||
model: "claude-sonnet",
|
||||
state: "start",
|
||||
attempt: 1,
|
||||
tokens: 7,
|
||||
toolCalls: 1,
|
||||
lastToolName: "Read",
|
||||
},
|
||||
],
|
||||
session_id: "session",
|
||||
uuid: "progress",
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "workflow-1",
|
||||
patch: {
|
||||
status: "paused",
|
||||
end_time: 1_700_000_000_000,
|
||||
is_backgrounded: true,
|
||||
error: "waiting",
|
||||
},
|
||||
session_id: "session",
|
||||
uuid: "updated",
|
||||
} as unknown as SDKMessage);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
|
||||
const started = runtimeEvents.find((event) => event.type === "task.started");
|
||||
assert.equal(started?.type, "task.started");
|
||||
if (started?.type === "task.started") {
|
||||
assert.equal(started.payload.name, "Run checks");
|
||||
assert.equal(started.payload.agentType, "Workflow");
|
||||
assert.equal(started.payload.toolUseId, "tool-1");
|
||||
assert.equal(started.payload.workflowName, "Verification");
|
||||
assert.equal(started.payload.prompt, "Check the repository");
|
||||
}
|
||||
const phasePatch = runtimeEvents.find(
|
||||
(event) => event.type === "task.updated" && event.payload.phases !== undefined,
|
||||
);
|
||||
assert.equal(phasePatch?.type, "task.updated");
|
||||
if (phasePatch?.type === "task.updated") {
|
||||
assert.deepEqual(phasePatch.payload.phases, [{ index: 0, title: "Inspect" }]);
|
||||
}
|
||||
const child = runtimeEvents.find(
|
||||
(event) => event.type === "task.started" && event.payload.taskId === "agent-1",
|
||||
);
|
||||
assert.equal(child?.type, "task.started");
|
||||
if (child?.type === "task.started") {
|
||||
assert.equal(child.payload.parentTaskId, "workflow-1");
|
||||
assert.equal(child.payload.timelineBypass, true);
|
||||
assert.equal(child.payload.taskType, "workflow_agent");
|
||||
}
|
||||
const statusPatch = runtimeEvents.find(
|
||||
(event) => event.type === "task.updated" && event.payload.status === "paused",
|
||||
);
|
||||
assert.equal(statusPatch?.type, "task.updated");
|
||||
if (statusPatch?.type === "task.updated") {
|
||||
assert.equal(statusPatch.payload.endTime, "2023-11-14T22:13:20.000Z");
|
||||
assert.equal(statusPatch.payload.isBackgrounded, true);
|
||||
assert.equal(statusPatch.payload.errorMessage, "waiting");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
|
||||
@@ -704,6 +704,32 @@ function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function readNonNegativeInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function epochMillisToIso(value: number): string {
|
||||
return DateTime.formatIso(DateTime.makeUnsafe(value));
|
||||
}
|
||||
|
||||
function normalizeRuntimeTaskUsage(value: unknown) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const usage = value as Record<string, unknown>;
|
||||
const totalTokens = readNonNegativeInteger(usage.total_tokens);
|
||||
if (totalTokens === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const toolUses = readNonNegativeInteger(usage.tool_uses);
|
||||
const durationMs = readNonNegativeInteger(usage.duration_ms);
|
||||
return {
|
||||
totalTokens,
|
||||
...(toolUses !== undefined ? { toolUses } : {}),
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readStringArray(value: unknown): Array<string> {
|
||||
return Array.isArray(value)
|
||||
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
|
||||
@@ -2388,6 +2414,33 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
|
||||
if (!toolResult.isError && tool.toolName === "Workflow" && toolUseResult) {
|
||||
const taskId = readString(toolUseResult.taskId);
|
||||
if (taskId) {
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "task.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make(taskId),
|
||||
...(readString(toolUseResult.scriptPath)
|
||||
? { scriptPath: readString(toolUseResult.scriptPath) }
|
||||
: {}),
|
||||
...(readString(toolUseResult.runId)
|
||||
? { runId: readString(toolUseResult.runId) }
|
||||
: {}),
|
||||
...(readString(toolUseResult.workflowName)
|
||||
? { workflowName: readString(toolUseResult.workflowName) }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const streamKind = toolResultStreamKind(tool.itemType);
|
||||
if (streamKind && toolResult.text.length > 0 && context.turnState) {
|
||||
const deltaStamp = yield* makeEventStamp();
|
||||
@@ -2676,18 +2729,33 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "task_started":
|
||||
case "task_started": {
|
||||
const record = message as unknown as Record<string, unknown>;
|
||||
const agentType = readString(record.subagent_type);
|
||||
const toolUseId = readString(record.tool_use_id);
|
||||
const workflowName = readString(record.workflow_name);
|
||||
const prompt = readString(record.prompt);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.started",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make(message.task_id),
|
||||
description: message.description,
|
||||
name: message.description,
|
||||
...(message.task_type ? { taskType: message.task_type } : {}),
|
||||
...(agentType ? { agentType } : {}),
|
||||
...(toolUseId ? { toolUseId } : {}),
|
||||
...(workflowName ? { workflowName } : {}),
|
||||
...(prompt ? { prompt } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "task_progress":
|
||||
}
|
||||
case "task_progress": {
|
||||
const record = message as unknown as Record<string, unknown>;
|
||||
const agentType = readString(record.subagent_type);
|
||||
const toolUseId = readString(record.tool_use_id);
|
||||
const usage = normalizeRuntimeTaskUsage(record.usage);
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
@@ -2703,17 +2771,142 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
taskId: RuntimeTaskId.make(message.task_id),
|
||||
description: message.description,
|
||||
...(message.summary ? { summary: message.summary } : {}),
|
||||
...(message.usage ? { usage: message.usage } : {}),
|
||||
...(usage ? { usage } : {}),
|
||||
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
|
||||
...(agentType ? { agentType } : {}),
|
||||
...(toolUseId ? { toolUseId } : {}),
|
||||
},
|
||||
});
|
||||
const workflowProgress = record.workflow_progress;
|
||||
if (Array.isArray(workflowProgress)) {
|
||||
const phases = workflowProgress.flatMap((entry) => {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return [];
|
||||
const item = entry as Record<string, unknown>;
|
||||
if (item.type !== "workflow_phase") return [];
|
||||
const index = readNonNegativeInteger(item.index);
|
||||
const title = readString(item.title);
|
||||
return index !== undefined && title ? [{ index, title }] : [];
|
||||
});
|
||||
if (phases.length > 0) {
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: stamp.eventId,
|
||||
createdAt: stamp.createdAt,
|
||||
type: "task.updated",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make(message.task_id),
|
||||
phases,
|
||||
timelineBypass: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
for (const entry of workflowProgress) {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
|
||||
const item = entry as Record<string, unknown>;
|
||||
if (item.type !== "workflow_agent") continue;
|
||||
const agentId = readString(item.agentId);
|
||||
const label = readString(item.label);
|
||||
if (!agentId || !label) continue;
|
||||
const state = readString(item.state);
|
||||
const childUsage = readNonNegativeInteger(item.tokens);
|
||||
const childToolUses = readNonNegativeInteger(item.toolCalls);
|
||||
const childPayload = {
|
||||
taskId: RuntimeTaskId.make(agentId),
|
||||
description: label,
|
||||
name: label,
|
||||
taskType: "workflow_agent",
|
||||
parentTaskId: RuntimeTaskId.make(message.task_id),
|
||||
timelineBypass: true as const,
|
||||
...(readString(item.model) ? { model: readString(item.model) } : {}),
|
||||
...(readNonNegativeInteger(item.phaseIndex) !== undefined
|
||||
? { phaseIndex: readNonNegativeInteger(item.phaseIndex) }
|
||||
: {}),
|
||||
...(readString(item.phaseTitle) ? { phaseTitle: readString(item.phaseTitle) } : {}),
|
||||
...(readNonNegativeInteger(item.attempt) !== undefined
|
||||
? { attempt: readNonNegativeInteger(item.attempt) }
|
||||
: {}),
|
||||
...(readString(item.lastToolName)
|
||||
? { lastToolName: readString(item.lastToolName) }
|
||||
: {}),
|
||||
...(childUsage !== undefined
|
||||
? {
|
||||
usage: {
|
||||
totalTokens: childUsage,
|
||||
...(childToolUses !== undefined ? { toolUses: childToolUses } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
const stamp = yield* makeEventStamp();
|
||||
if (state === "start") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: stamp.eventId,
|
||||
createdAt: stamp.createdAt,
|
||||
type: "task.started",
|
||||
payload: childPayload,
|
||||
});
|
||||
} else if (state === "done" || state === "error") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: stamp.eventId,
|
||||
createdAt: stamp.createdAt,
|
||||
type: "task.completed",
|
||||
payload: {
|
||||
...childPayload,
|
||||
status: state === "done" ? "completed" : "failed",
|
||||
...(readString(item.error) ? { summary: readString(item.error) } : {}),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: stamp.eventId,
|
||||
createdAt: stamp.createdAt,
|
||||
type: "task.progress",
|
||||
payload: childPayload,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "task_updated": {
|
||||
const record = message as unknown as Record<string, unknown>;
|
||||
// SDK shape: {task_id, patch: {status?, end_time?, is_backgrounded?, error?}}
|
||||
const patch =
|
||||
record.patch !== null && typeof record.patch === "object" && !Array.isArray(record.patch)
|
||||
? (record.patch as Record<string, unknown>)
|
||||
: {};
|
||||
const status = readString(patch.status);
|
||||
const endTime =
|
||||
typeof patch.end_time === "number" ? epochMillisToIso(patch.end_time) : undefined;
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.updated",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.make(String(record.task_id)),
|
||||
...(status === "pending" ||
|
||||
status === "running" ||
|
||||
status === "completed" ||
|
||||
status === "failed" ||
|
||||
status === "killed" ||
|
||||
status === "paused"
|
||||
? { status }
|
||||
: {}),
|
||||
...(endTime ? { endTime } : {}),
|
||||
...(typeof patch.is_backgrounded === "boolean"
|
||||
? { isBackgrounded: patch.is_backgrounded }
|
||||
: {}),
|
||||
...(readString(patch.error) ? { errorMessage: readString(patch.error) } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
// Task state patch (status/backgrounded/end_time). No runtime mapping
|
||||
// yet — the terminal task_notification reports the outcome — but it
|
||||
// must not surface as an unknown-subtype warning row.
|
||||
case "task_updated":
|
||||
return;
|
||||
case "task_notification":
|
||||
}
|
||||
case "task_notification": {
|
||||
const record = message as unknown as Record<string, unknown>;
|
||||
const usage = normalizeRuntimeTaskUsage(record.usage);
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
@@ -2729,10 +2922,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
taskId: RuntimeTaskId.make(message.task_id),
|
||||
status: message.status,
|
||||
...(message.summary ? { summary: message.summary } : {}),
|
||||
...(message.usage ? { usage: message.usage } : {}),
|
||||
...(usage ? { usage } : {}),
|
||||
...(readString(record.output_file)
|
||||
? { outputFile: readString(record.output_file) }
|
||||
: {}),
|
||||
...(readString(record.tool_use_id)
|
||||
? { toolUseId: readString(record.tool_use_id) }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "files_persisted":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
|
||||
Reference in new issue
Block a user