TypeScript
fix(server): Claude workflow members stream their thinking and tool calls into their threads (#20856)
Julius Marminge91f8c35dee93
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 2c0d13aa0b3..411ebc1dff8 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -71,6 +71,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";import { SpawnExecutableResolution } from "@t3tools/shared/shell";import { attachmentRelativePath } from "../../attachmentStore.ts";+import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";import * as ServerConfig from "../../config.ts";import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";@@ -11395,7 +11396,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });yield* fileSystem.writeFileString(NodePath.join(transcriptDir, "agent-a1.jsonl"),- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n',+ `{"type":"assistant","uuid":"wf-line-1-${options?.nativeSessionId ?? "default"}","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n`,);const harness = yield* makeWakeHarnessWithOptions({...options,@@ -12368,7 +12369,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {(arrival) =>Effect.scoped(Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;const digestStarted = yield* Deferred.make<void>();const releaseDigest = yield* Deferred.make<void>();const closeStarted = yield* Deferred.make<void>();@@ -12406,7 +12406,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {yield* fileSystem.makeDirectory(liveTranscriptDir);yield* fileSystem.writeFileString(NodePath.join(liveTranscriptDir, "agent-a1.jsonl"),- '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Live member answer"}]}}\n',+ '{"type":"assistant","uuid":"wf-line-2","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"Live member answer"}]}}\n',);const liveTaskId = "task-workflow-live-while-waiting";const liveToolUseId = "toolu-workflow-live-while-waiting";@@ -12512,18 +12512,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {}yield* start("attempt-workflow-waiting-next-user", 3, false);}).pipe(- Effect.provideService(Crypto.Crypto, {- ...crypto,- digest: (algorithm, data) =>- Effect.gen(function* () {- if (pauseDigest) {- pauseDigest = false;- yield* Deferred.succeed(digestStarted, undefined);- yield* Deferred.await(releaseDigest);- }- return yield* crypto.digest(algorithm, data);- }),- }),+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>+ Effect.gen(function* () {+ if (pauseDigest) {+ pauseDigest = false;+ yield* Deferred.succeed(digestStarted, undefined);+ yield* Deferred.await(releaseDigest);+ }+ }),+ ),);}).pipe(Effect.provide(@@ -12539,7 +12536,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {Effect.scoped(Effect.gen(function* () {const clock = yield* Clock.Clock;- const crypto = yield* Crypto.Crypto;const progressRead = yield* Deferred.make<void>();const releaseProgress = yield* Deferred.make<void>();let pauseNextRead = false;@@ -12655,18 +12651,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {return yield* clock.currentTimeMillis;}),}),- Effect.provideService(Crypto.Crypto, {- ...crypto,- digest: (algorithm, data) =>- Effect.gen(function* () {- if (boundary === "transcript" && pauseNextRead) {- pauseNextRead = false;- yield* Deferred.succeed(progressRead, undefined);- yield* Deferred.await(releaseProgress);- }- return yield* crypto.digest(algorithm, data);- }),- }),+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>+ Effect.gen(function* () {+ if (boundary === "transcript" && pauseNextRead) {+ pauseNextRead = false;+ yield* Deferred.succeed(progressRead, undefined);+ yield* Deferred.await(releaseProgress);+ }+ }),+ ),);}).pipe(Effect.provide(@@ -12683,7 +12676,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {] as const)("orders %s arriving during workflow transcript replay", (arrival) =>Effect.scoped(Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;const digestStarted = yield* Deferred.make<void>();const releaseDigest = yield* Deferred.make<void>();const liveFrameOffered = yield* Deferred.make<void>();@@ -12887,18 +12879,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {);}}).pipe(- Effect.provideService(Crypto.Crypto, {- ...crypto,- digest: (algorithm, data) =>- Effect.gen(function* () {- if (pauseDigest) {- pauseDigest = false;- yield* Deferred.succeed(digestStarted, undefined);- yield* Deferred.await(releaseDigest);- }- return yield* crypto.digest(algorithm, data);- }),- }),+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>+ Effect.gen(function* () {+ if (pauseDigest) {+ pauseDigest = false;+ yield* Deferred.succeed(digestStarted, undefined);+ yield* Deferred.await(releaseDigest);+ }+ }),+ ),);}).pipe(Effect.provide(@@ -12911,7 +12900,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {it.effect("preserves buffered workflow outcomes when interrupted during replay", () =>Effect.scoped(Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;const digestStarted = yield* Deferred.make<void>();const releaseDigest = yield* Deferred.make<void>();let pauseDigest = false;@@ -13011,18 +12999,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {assert.equal(second?.status, "completed");assert.equal(second?.result, "Workflow finished.");}).pipe(- Effect.provideService(Crypto.Crypto, {- ...crypto,- digest: (algorithm, data) =>- Effect.gen(function* () {- if (pauseDigest) {- pauseDigest = false;- yield* Deferred.succeed(digestStarted, undefined);- yield* Deferred.await(releaseDigest);- }- return yield* crypto.digest(algorithm, data);- }),- }),+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>+ Effect.gen(function* () {+ if (pauseDigest) {+ pauseDigest = false;+ yield* Deferred.succeed(digestStarted, undefined);+ yield* Deferred.await(releaseDigest);+ }+ }),+ ),);}).pipe(Effect.provide(@@ -13483,7 +13468,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {);NodeFS.writeFileSync(NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),- '{"type":"assistant","message":{"role":"assistant","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',+ '{"type":"assistant","uuid":"wf-line-3","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',);yield* Queue.offer(harness.sdkMessages,@@ -13594,7 +13579,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {const memberEventsBeforeRepeat = workflowMemberEvents(harness.events, 2).length;NodeFS.appendFileSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n',+ '{"type":"assistant","uuid":"wf-line-4","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n',);yield* harness.offerAndWait(workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }),@@ -13605,19 +13590,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {);yield* awaitUntil(() =>- threadMessages(harness.events, firstThreadId).at(-1)?.message.text ===- "A1 from the transcript\n\nA1 continued",+ threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued","continued workflow transcript answer",);assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat);assert.lengthOf(threadMessages(harness.events, secondThreadId), 2);- assert.equal(- threadMessages(harness.events, firstThreadId).at(-1)?.message.text,- "A1 from the transcript\n\nA1 continued",- );+ assert.deepEqual(currentAssistantAnswers(), ["A1 from the transcript", "A1 continued"]);NodeFS.writeFileSync(NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),- '{"type":"assistant","message":{"role":"assistant","id":"msg_a2","content":[{"type":"text","text":"A2 from the transcript"}]}}\n',+ '{"type":"assistant","uuid":"wf-line-5","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a2","content":[{"type":"text","text":"A2 from the transcript"}]}}\n',);yield* harness.offerAndWait(workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }),@@ -13637,8 +13618,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {NodeFS.writeFileSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),[- '{"type":"assistant","message":{"role":"assistant","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}',- '{"type":"assistant","message":{"role":"assistant","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}',+ '{"type":"assistant","uuid":"wf-line-6","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}',+ '{"type":"assistant","uuid":"wf-line-7","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}',].join("\n") + "\n",);yield* harness.offerAndWait(@@ -13652,7 +13633,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {() => currentAssistantAnswers().join("\n\n").includes("Second answer"),"two-turn workflow member answer",);- assert.equal(currentAssistantAnswers().join("\n\n"), "First answer\n\nSecond answer");+ assert.deepEqual(currentAssistantAnswers().slice(-2), ["First answer", "Second answer"]);assert.notDeepEqual(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt,previousStartedAt,@@ -13669,9 +13650,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {() => workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status === "running","retried workflow member running",);- assert.notInclude(currentAssistantAnswers().join("\n\n"), "First answer");- assert.notInclude(currentAssistantAnswers().join("\n\n"), "Second answer");- const answerEventsDuringRetry = threadMessages(harness.events, firstThreadId).length;yield* Queue.offer(harness.sdkMessages,workflowSnapshot({@@ -13682,7 +13660,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {);NodeFS.writeFileSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),- '{"type":"assistant","message":{"role":"assistant","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n',+ '{"type":"assistant","uuid":"wf-line-8","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n',);yield* Queue.offer(harness.sdkMessages,@@ -13698,8 +13676,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {"A1 retry answer","retried workflow member answer",);- assert.deepEqual(currentAssistantAnswers(), ["A1 retry answer"]);- assert.lengthOf(threadMessages(harness.events, firstThreadId), answerEventsDuringRetry + 1);+ assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer");NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"));yield* Queue.offer(harness.sdkMessages,@@ -13710,11 +13687,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {}),);yield* awaitUntil(- () => currentAssistantAnswers().at(-1) === "Retry in progress.",- "retry progress answer",+ () =>+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]+ ?.attempt === 4,+ "fourth workflow member attempt",);- yield* Queue.offer(- harness.sdkMessages,+ const answersBeforeEmptyAttempt = currentAssistantAnswers();+ yield* harness.offerAndWait(workflowSnapshot({uuid: "00000000-0000-4000-8000-000000001023",state: "done",@@ -13722,11 +13701,215 @@ describe("ClaudeAdapterV2 background wake turns", () => {omitResult: true,}),);- yield* awaitUntil(- () => currentAssistantAnswers().at(-1) === "No answer from this workflow attempt.",- "empty retry answer",+ assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed");+ assert.deepEqual(+ currentAssistantAnswers(),+ answersBeforeEmptyAttempt,+ "an attempt with no transcript and no excerpt adds nothing",+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );++ // Line shapes copied from a Claude CLI 2.1.301 workflow member transcript.+ const transcriptLine = (entry: Record<string, unknown>) =>+ `${JSON.stringify({ isSidechain: true, agentId: "a1", timestamp: "2026-10-17T05:08:07.524Z", ...entry })}\n`;+ const memberAssistantLine = (+ uuid: string,+ messageId: string,+ content: unknown,+ stopReason?: "tool_use" | "end_turn",+ ) =>+ transcriptLine({+ type: "assistant",+ uuid,+ message: {+ model: "claude-opus-5-5",+ id: messageId,+ type: "message",+ role: "assistant",+ content,+ ...(stopReason === undefined ? {} : { stop_reason: stopReason }),+ },+ });+ const memberToolResultLine = (uuid: string, toolUseId: string, output: string) =>+ transcriptLine({+ type: "user",+ uuid,+ message: {+ role: "user",+ content: [{ tool_use_id: toolUseId, type: "tool_result", content: output }],+ },+ });+ const memberTranscript = [+ transcriptLine({+ type: "user",+ uuid: "line-prompt",+ message: { role: "user", content: "Reply with exactly: A1" },+ }),+ transcriptLine({+ type: "attachment",+ uuid: "line-attachment",+ attachment: { type: "skill_listing", content: "- adhd" },+ }),+ transcriptLine({+ type: "user",+ uuid: "line-meta",+ isMeta: true,+ message: { role: "user", content: "<system-reminder>context</system-reminder>" },+ }),+ memberAssistantLine("line-thinking", "msg_a1", [+ { type: "thinking", thinking: "List the files first.", signature: "sig" },+ ]),+ memberAssistantLine("line-bash", "msg_a1", [+ { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } },+ ]),+ memberToolResultLine("line-ls-result", "toolu_a1_ls", "README.md"),+ memberAssistantLine("line-reply", "msg_a1_reply", [+ { type: "text", text: "A1 found README.md" },+ ]),+ ].join("");+ const memberThreadItems = (+ events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,+ threadId: ThreadId | null | undefined,+ ) =>+ events.flatMap((event) =>+ event.type === "turn_item.updated" && event.turnItem.threadId === threadId+ ? [event.turnItem]+ : [],+ );+ const latestMemberThreadItems = (+ events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,+ threadId: ThreadId | null | undefined,+ ) =>+ [+ ...new Map(memberThreadItems(events, threadId).map((item) => [item.id, item])).values(),+ ].toSorted((left, right) => left.ordinal - right.ordinal);+ const describeItem = (item: ReturnType<typeof memberThreadItems>[number]) =>+ item.type === "reasoning"+ ? `reasoning: ${item.text}`+ : item.type === "command_execution"+ ? `command ${item.status}: ${item.output ?? ""}`+ : item.type === "assistant_message" || item.type === "user_message"+ ? `${item.type}`+ : `${item.type} ${item.status}`;++ it.effect("streams a running workflow member's conversation from its transcript", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const reads: Array<{+ readonly startOffset: number;+ readonly endOffset: number;+ readonly lineCount: number;+ }> = [];+ yield* Effect.gen(function* () {+ const harness = yield* makeWorkflowHarness;+ const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl");+ NodeFS.writeFileSync(transcriptPath, memberTranscript);+ yield* harness.runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-claude-workflow-live-stream"),+ text: "Run the alpha workflow.",+ attachments: [],+ }),+ );+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" });+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;+ const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" });++ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [+ "user_message",+ "reasoning: List the files first.",+ "command completed: README.md",+ "assistant_message",+ ]);+ assert.deepEqual(+ threadMessages(harness.events, threadId).map((event) => event.message.text),+ ["Reply with exactly: A1", "A1 found README.md"],+ );+ assert.deepEqual(reads.at(-1), {+ startOffset: 0,+ endOffset: Buffer.byteLength(memberTranscript),+ lineCount: 5,+ });++ const itemsBefore = memberThreadItems(harness.events, threadId).length;+ const more = memberAssistantLine("line-more", "msg_a1_more", [+ {+ type: "tool_use",+ id: "toolu_a1_cat",+ name: "Bash",+ input: { command: "cat README.md" },+ },+ ]);+ const half = memberToolResultLine("line-cat-result", "toolu_a1_cat", "hello");+ NodeFS.appendFileSync(transcriptPath, more + half.slice(0, 40));+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361"));+ assert.deepEqual(reads.at(-1), {+ startOffset: Buffer.byteLength(memberTranscript),+ endOffset: Buffer.byteLength(memberTranscript + more),+ lineCount: 1,+ });+ assert.deepEqual(+ memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem),+ ["command running: "],+ "only the new line is projected; the half-written one waits",+ );++ NodeFS.appendFileSync(transcriptPath, half.slice(40));+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362"));+ assert.deepEqual(reads.at(-1), {+ startOffset: Buffer.byteLength(memberTranscript + more),+ endOffset: Buffer.byteLength(memberTranscript + more + half),+ lineCount: 1,+ });+ assert.deepEqual(+ memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem),+ ["command running: ", "command completed: hello"],+ );++ const itemsBeforeIdle = memberThreadItems(harness.events, threadId).length;+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363"));+ assert.equal(reads.at(-1)?.lineCount, 0);+ assert.lengthOf(memberThreadItems(harness.events, threadId), itemsBeforeIdle);++ yield* harness.offerAndWait(+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }),+ );+ assert.equal(+ workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status,+ "completed",+ );+ assert.deepEqual(+ threadMessages(harness.events, threadId).map((event) => event.message.text),+ ["Reply with exactly: A1", "A1 found README.md"],+ "the settled member adds no second copy of its answer",+ );+ yield* Queue.offer(+ harness.sdkMessages,+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }),+ );+ yield* Queue.take(harness.terminalReceipts);+ }).pipe(+ Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) =>+ Effect.sync(() => {+ if (read.agentId === "a1") {+ reads.push({+ startOffset: read.startOffset,+ endOffset: read.endOffset,+ lineCount: read.lineCount,+ });+ }+ }),+ ),);- assert.deepEqual(currentAssistantAnswers(), ["No answer from this workflow attempt."]);}).pipe(Effect.provide(Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),@@ -13735,76 +13918,97 @@ describe("ClaudeAdapterV2 background wake turns", () => {),);- it.effect("shows a running workflow member's answer so far from its transcript", () =>+ it.effect("interrupts the open tool calls of a workflow member that failed", () =>Effect.scoped(Effect.gen(function* () {const harness = yield* makeWorkflowHarness;- const now = yield* DateTime.now;+ NodeFS.writeFileSync(+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),+ memberAssistantLine("line-bash", "msg_a1", [+ { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } },+ ]),+ );yield* harness.runtime.startTurn(makeClaudeTestTurnInput({threadId: harness.threadId,providerThread: harness.providerThread,- now,- attemptId: RunAttemptId.make("attempt-claude-workflow-live-answer"),+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-fails"),text: "Run the alpha workflow.",attachments: [],}),);- yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" });- const firstThreadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;- const assistantEvents = () =>- threadMessages(harness.events, firstThreadId).filter(- (event) => event.message.role === "assistant",- );- const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl");- const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" });-- yield* awaitUntil(- () => assistantEvents().at(-1)?.message.text === "A1 from the transcript",- "running workflow member answer so far",+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001370" });+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [+ "user_message",+ "command running: ",+ ]);+ yield* harness.offerAndWait(+ workflowNotification({ uuid: "00000000-0000-4000-8000-000000001371", status: "failed" }),);- assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running");-- NodeFS.appendFileSync(- transcriptPath,- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1_more","content":[{"type":"text","text":"A1 keeps going"}]}}\n',+ assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "failed");+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [+ "user_message",+ "command interrupted: ",+ ]);+ yield* Queue.offer(+ harness.sdkMessages,+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001372", result: "Done." }),);- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361"));- assert.lengthOf(assistantEvents(), 1, "a frame inside the throttle window reads nothing");+ yield* Queue.take(harness.terminalReceipts);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );- yield* TestClock.adjust("10 seconds");- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362"));- assert.lengthOf(assistantEvents(), 2);- assert.equal(- assistantEvents().at(-1)?.message.text,- "A1 from the transcript\n\nA1 keeps going",+ it.effect("reads a settled workflow member's transcript to its end past the read cap", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const harness = yield* makeWorkflowHarness;+ // About 1.3 MB of early replies: more than the launch frame's read+ // and the settled frame's read together, at 512 KB each.+ const filler = "x".repeat(16 * 1024);+ NodeFS.writeFileSync(+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),+ Array.from({ length: 80 }, (_, index) =>+ memberAssistantLine(`line-early-${index}`, `msg_early_${index}`, [+ { type: "text", text: `${index} ${filler}` },+ ]),+ ).join("") ++ memberAssistantLine("line-final", "msg_final", [+ { type: "text", text: "FINAL ANSWER" },+ ]),);-- yield* TestClock.adjust("10 seconds");- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363"));- assert.lengthOf(assistantEvents(), 2, "an unchanged transcript emits nothing");-- NodeFS.appendFileSync(- transcriptPath,- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1_final","content":[{"type":"text","text":"A1 final"}]}}\n',+ yield* harness.runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-long-transcript"),+ text: "Run the alpha workflow.",+ attachments: [],+ }),);+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001390" });+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;yield* harness.offerAndWait(- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }),- );- assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed");- assert.equal(- assistantEvents().at(-1)?.message.text,- "A1 from the transcript\n\nA1 keeps going\n\nA1 final",- );- assert.lengthOf(- new Set(assistantEvents().map((event) => event.message.id)),- 1,- "the settled answer replaces the running one in place",+ workflowNotification({+ uuid: "00000000-0000-4000-8000-000000001391",+ status: "completed",+ }),);-+ const texts = threadMessages(harness.events, threadId)+ .filter((event) => event.message.role === "assistant")+ .map((event) => event.message.text);+ assert.lengthOf(texts, 81);+ assert.equal(texts.at(-1), "FINAL ANSWER", "the answer past the first read is shown");yield* Queue.offer(harness.sdkMessages,- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }),+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001392", result: "Done." }),);yield* Queue.take(harness.terminalReceipts);}).pipe(@@ -13815,6 +14019,199 @@ describe("ClaudeAdapterV2 background wake turns", () => {),);+ it.effect.each([+ { before: "nothing" },+ { before: "text" },+ { before: "a line without a stop reason" },+ ] as const)(+ "waits for a settled workflow member's reply to reach its transcript ($before before it)",+ ({ before }) =>+ Effect.scoped(+ Effect.gen(function* () {+ // Claude Code flushes transcript lines every 100 ms, so a member's reply+ // can land after the frame that settles it (seen with CLI 2.1.301).+ let appendLateReply: (() => void) | undefined;+ const lateReplyWritten = yield* Deferred.make<void>();+ yield* Effect.gen(function* () {+ const harness = yield* makeWorkflowHarness;+ const transcriptPath = (agentId: string) =>+ NodePath.join(harness.transcriptDir, `agent-${agentId}.jsonl`);+ // A member often says what it is about to do before its first tool call.+ const toolCall = (agentId: string) =>+ memberAssistantLine(+ `line-${agentId}-bash`,+ `msg_${agentId}`,+ [+ ...(before === "text"+ ? [{ type: "text", text: `${agentId} lists the files.` }]+ : []),+ {+ type: "tool_use",+ id: `toolu_${agentId}`,+ name: "Bash",+ input: { command: "ls" },+ },+ ],+ "tool_use",+ ) ++ memberToolResultLine(`line-${agentId}-result`, `toolu_${agentId}`, "README.md") ++ // A line from a writer that leaves the field out entirely.+ (before === "a line without a stop reason"+ ? memberAssistantLine(`line-${agentId}-thinking`, `msg_${agentId}_reply`, [+ { type: "thinking", thinking: "Summarize the file.", signature: "sig" },+ ])+ : "");+ const early = (agentId: string) =>+ before === "text" ? [`${agentId} lists the files.`] : [];+ const reply = (agentId: string) =>+ memberAssistantLine(+ `line-${agentId}-reply`,+ `msg_${agentId}_reply`,+ [{ type: "text", text: `${agentId} found README.md` }],+ "end_turn",+ );+ NodeFS.writeFileSync(transcriptPath("a1"), toolCall("a1"));+ NodeFS.writeFileSync(transcriptPath("a2"), toolCall("a2"));+ yield* harness.runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-late-flush"),+ text: "Run the alpha workflow.",+ attachments: [],+ }),+ );+ yield* launchWorkflow({+ harness,+ snapshotUuid: "00000000-0000-4000-8000-000000001395",+ });+ const texts = (index: number) =>+ threadMessages(+ harness.events,+ workflowMemberEvents(harness.events, index)[0]?.subagent.childThreadId,+ ).map((event) => event.message.text);++ // The first member settles while the workflow runs on.+ yield* harness.offerAndWait(+ workflowSnapshot({+ uuid: "00000000-0000-4000-8000-000000001396",+ state: "done",+ secondState: "start",+ }),+ );+ assert.equal(+ workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status,+ "completed",+ );+ assert.deepEqual(+ texts(1),+ ["Reply with exactly: A1", ...early("a1")],+ "no excerpt before the reply",+ );+ NodeFS.appendFileSync(transcriptPath("a1"), reply("a1"));+ yield* harness.offerAndWait(+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001397", state: "done" }),+ );+ assert.deepEqual(texts(1), [+ "Reply with exactly: A1",+ ...early("a1"),+ "a1 found README.md",+ ]);+ assert.deepEqual(texts(2), ["Reply with exactly: A2", ...early("a2")]);++ // The workflow ends right after the second member, before its reply lands.+ appendLateReply = () => NodeFS.appendFileSync(transcriptPath("a2"), reply("a2"));+ const notified = yield* harness+ .offerAndWait(+ workflowNotification({+ uuid: "00000000-0000-4000-8000-000000001398",+ status: "completed",+ }),+ )+ .pipe(Effect.forkScoped);+ yield* Deferred.await(lateReplyWritten);+ for (let tick = 0; tick < 20 && texts(2).at(-1) !== "a2 found README.md"; tick += 1) {+ yield* TestClock.adjust("100 millis");+ }+ yield* Fiber.join(notified);+ assert.deepEqual(texts(2), [+ "Reply with exactly: A2",+ ...early("a2"),+ "a2 found README.md",+ ]);+ yield* Queue.offer(+ harness.sdkMessages,+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001399", result: "Done." }),+ );+ yield* Queue.take(harness.terminalReceipts);+ }).pipe(+ Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => {+ // Lands just after the read that would have settled the member.+ if (read.agentId !== "a2" || appendLateReply === undefined) return Effect.void;+ const append = appendLateReply;+ appendLateReply = undefined;+ append();+ return Deferred.succeed(lateReplyWritten, undefined).pipe(Effect.asVoid);+ }),+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );++ it.effect("re-reads a workflow member's transcript after a restart without new items", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const runOnce = Effect.fnUntraced(function* (attemptId: string) {+ const harness = yield* makeWorkflowHarness;+ NodeFS.writeFileSync(+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),+ memberTranscript,+ );+ yield* harness.runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make(attemptId),+ text: "Run the alpha workflow.",+ attachments: [],+ }),+ );+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001380" });+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;+ yield* Queue.offer(+ harness.sdkMessages,+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001381", result: "Done." }),+ );+ yield* Queue.take(harness.terminalReceipts);+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [+ "user_message",+ "reasoning: List the files first.",+ "command completed: README.md",+ "assistant_message",+ ]);+ return new Set(memberThreadItems(harness.events, threadId).map((item) => item.id));+ });+ const before = yield* runOnce("attempt-claude-workflow-before-restart");+ const after = yield* runOnce("attempt-claude-workflow-after-restart");+ assert.isAtLeast(before.size, 4);+ assert.deepEqual(+ [...after].filter((id) => !before.has(id)),+ [],+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );+it.effect.each([{ backgrounding: "succeeds" },{ backgrounding: "fails" },diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 0a289a52266..d3977ee9e85 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -6,7 +6,11 @@ import {formatSearchToolLabel,} from "@t3tools/shared/toolActivity";import { field, text } from "../unknownField.ts";-import { readWorkflowAgentAnswers } from "../workflowAgentAnswers.ts";+import {+ initialWorkflowAgentTranscriptCursor,+ readWorkflowAgentTranscript,+ type WorkflowAgentTranscriptCursor,+} from "../workflowAgentTranscript.ts";import {CLAUDE_WORKFLOW_TASK_TYPE,hasClaudeWorkflowSnapshot,@@ -91,7 +95,6 @@ import {import * as Cause from "effect/Cause";import * as Context from "effect/Context";import * as Crypto from "effect/Crypto";-import * as Hex from "effect/encoding/Hex";import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -232,6 +235,10 @@ const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];// The SDK puts no deadline on control requests. The CLI answers// mcp_set_servers once each server connected or hit its own 30 s timeout.const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";+// Claude Code flushes transcript writes every 100 ms, so a workflow member's+// reply can land after the progress frame that settles it. Its transcript+// stays the source of its answer this long after it settles.+const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;/*** When the CLI exits it stops the MCP servers it started, but not their children: a plugin's@@ -1668,12 +1675,6 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:} satisfies SDKUserMessage;});-const sha256Hex = Effect.fnUntraced(function* (crypto: Crypto.Crypto, value: string) {- return Hex.encode(- yield* crypto.digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.orDie),- );-});-export function isClaudePromptUuid(value: string): value is NonNullable<SDKUserMessage["uuid"]> {return /^[^-]+-[^-]+-[^-]+-[^-]+-[^-]+$/.test(value);}@@ -3064,6 +3065,39 @@ interface ActiveClaudeToolCall {readonly presentation?: ClaudeToolPresentation;}+/** Where a subagent's conversation items land: its child thread and root node. */+interface ClaudeSubagentProjectionTarget {+ readonly childThreadId: ThreadId;+ readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];+ readonly nextOrdinal: () => number;+ readonly toolCalls: Map<string, ActiveClaudeToolCall>;+}++/**+ * Whether a transcript line ends the assistant's turn. Claude Code writes each+ * block of a message as its own line, `stop_reason: null` on all but the last,+ * and text before a tool call (`tool_use`) is not the reply. A line without the+ * field (no CLI writes one) keeps the turn open: waiting costs at most the flush+ * window, while ending the turn early can lose the reply.+ */+function isClaudeTranscriptTurnEnd(entry: unknown): boolean {+ if (field(entry, "type") !== "assistant") return false;+ const stopReason = field(field(entry, "message"), "stop_reason");+ return typeof stopReason === "string" && stopReason !== "tool_use";+}++function isClaudeTranscriptConversationLine(+ entry: unknown,+): entry is SDKAssistantMessage | SDKUserMessage {+ const type = field(entry, "type");+ const content = field(field(entry, "message"), "content");+ return (+ typeof field(entry, "uuid") === "string" &&+ ((type === "assistant" && Array.isArray(content)) ||+ (type === "user" && (Array.isArray(content) || typeof content === "string")))+ );+}+interface PendingClaudeSubagentLaunch {readonly model?: string;readonly effort?: string;@@ -3092,9 +3126,6 @@ function claudeSubagentModelSelection(const PENDING_CLAUDE_SUBAGENT_CAP = 64;const PENDING_CLAUDE_SUBAGENT_FRAME_CAP = 256;-// Workflow progress frames arrive about every 12 seconds; a running member's-// transcript is re-read at most this often to show its answer so far.-const WORKFLOW_MEMBER_LIVE_TRANSCRIPT_READ_INTERVAL_MS = 10_000;function rememberPendingClaudeSubagentLaunch(pending: Map<string, PendingClaudeSubagentLaunch>,@@ -3423,10 +3454,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ({readonly status: OrchestrationV2Subagent["status"];readonly attempt: number;- readonly transcriptAnswerDigest: string | undefined;readonly transcriptReadAttempts: number;- readonly liveTranscriptReadAt: DateTime.Utc | null;readonly finalTranscriptRead: boolean;+ // Where the next read of the member's transcript starts; every+ // line before it is already projected into the member's thread.+ readonly agentId: string | undefined;+ readonly transcriptCursor: WorkflowAgentTranscriptCursor;+ readonly nextItemOrdinal: number;+ readonly toolCalls: Map<string, ActiveClaudeToolCall>;+ readonly textShown: boolean;+ // The transcript reached the end of the member's last turn.+ readonly turnEnded: boolean;+ readonly resultShown: boolean;readonly result: string | undefined;readonly label: string;readonly prompt: string;@@ -4131,7 +4170,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});const buildToolCallArtifacts = (input: {- readonly context: ActiveClaudeTurnContext;+ // Only a call in a run (runId set) needs its provider turn.+ readonly context: ActiveClaudeTurnContext | null;readonly nativeItemId: string;readonly toolName: string;readonly classification: ClaudeToolClassification;@@ -4174,8 +4214,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (kind: "tool_call",status: input.status,countsForRun: false,- providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,- providerTurnId: input.runId === null ? null : input.context.providerTurnId,+ providerThreadId:+ input.runId === null ? null : (input.context?.input.providerThread.id ?? null),+ providerTurnId: input.runId === null ? null : (input.context?.providerTurnId ?? null),nativeItemRef,runtimeRequestId: null,checkpointScopeId: null,@@ -4204,8 +4245,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (threadId: input.threadId,runId: input.runId,nodeId,- providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,- providerTurnId: input.runId === null ? null : input.context.providerTurnId,+ providerThreadId:+ input.runId === null ? null : (input.context?.input.providerThread.id ?? null),+ providerTurnId: input.runId === null ? null : (input.context?.providerTurnId ?? null),nativeItemRef,parentItemId: null,ordinal: input.ordinal,@@ -4529,18 +4571,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ((input.coordinator.task.status === "running"? (restarted ? 0 : (previous?.transcriptReadAttempts ?? 0)) < 3: restarted || previous?.finalTranscriptRead !== true);- // A running member streams nothing, so its transcript is the only- // way to show its answer so far. A restart shows "Retry in- // progress." and starts a fresh throttle window before the next read.- const liveTranscriptReadAt = previous?.liveTranscriptReadAt ?? null;+ // The CLI forwards nothing a member says, so every frame while it+ // runs reads what its transcript gained since the last one.const readLiveTranscript =- status === "running" &&- !restarted &&- transcriptDir !== undefined &&- agentId !== undefined &&- (liveTranscriptReadAt === null ||- DateTime.toEpochMillis(now) - DateTime.toEpochMillis(liveTranscriptReadAt) >=- WORKFLOW_MEMBER_LIVE_TRANSCRIPT_READ_INTERVAL_MS);+ status === "running" && transcriptDir !== undefined && agentId !== undefined;if (!changed && !readTranscript && !readLiveTranscript) continue;const nodeId = idAllocator.derive.nodeFromProviderItem({@@ -4587,17 +4621,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (now,});}- if (restarted && !settled) {- yield* emitSubagentConversationMessage({- nativeItemId: `${memberKey}:answer:200`,- threadId: childThreadId,- rootNodeId: childRootNodeId,- role: "assistant",- text: "Retry in progress.",- ordinal: 200,- now,- });- }const task = {id: nodeId,@@ -4665,55 +4688,125 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});}- let transcriptAnswerDigest = restarted ? undefined : previous?.transcriptAnswerDigest;- let transcript: ReadonlyArray<string> = [];- if (settled || readLiveTranscript) {- transcript =- readTranscript || readLiveTranscript- ? yield* readWorkflowAgentAnswers({- transcriptDir,- agentId,- ...(adapterOptions.environment.CLAUDE_CONFIG_DIR === undefined- ? {}- : {- configDir: path.resolve(- session.cwd,- adapterOptions.environment.CLAUDE_CONFIG_DIR,- ),- }),- }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))- : [];- const transcriptAnswer = transcript.length > 0 ? transcript.join("\n\n") : undefined;- const answerDigest =- transcriptAnswer === undefined- ? undefined- : yield* sha256Hex(crypto, transcriptAnswer);- if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)- return;- const previousDigest = transcriptAnswerDigest;- if (answerDigest !== undefined) transcriptAnswerDigest = answerDigest;- const answer =- transcriptAnswer ??- (!settled- ? undefined- : member.result !== undefined && changed && previousDigest === undefined- ? `Partial answer from workflow progress:\n\n${member.result}`- : attempt > 1 && changed && previousDigest === undefined- ? "No answer from this workflow attempt."- : undefined);+ const toolCalls = previous?.toolCalls ?? new Map<string, ActiveClaudeToolCall>();+ let nextItemOrdinal = previous?.nextItemOrdinal ?? 100;+ const target: ClaudeSubagentProjectionTarget = {+ childThreadId,+ childRootNodeId,+ nextOrdinal: () => ++nextItemOrdinal,+ toolCalls,+ };+ const endOpenToolCalls = Effect.fnUntraced(function* () {+ if (toolCalls.size === 0) return;+ yield* endToolCalls({+ context: null,+ toolCalls: [...toolCalls.values()],+ status: "interrupted",+ completedAt: now,+ });+ toolCalls.clear();+ });+ if (restarted) yield* endOpenToolCalls();+ // A retry may rewrite the transcript in place, past the old cursor;+ // re-reading from 0 re-emits only items already shown.+ let transcriptCursor =+ previous === undefined || restarted || previous.agentId !== agentId+ ? initialWorkflowAgentTranscriptCursor+ : previous.transcriptCursor;+ let textShown = !restarted && previous?.textShown === true;+ let resultShown = !restarted && previous?.resultShown === true;+ let turnEnded = !restarted && previous?.turnEnded === true;+ let transcriptRead = false;+ let lastReadAt = now;+ // Text before a tool call is not the reply, so wait for the turn's end.+ const awaitingReply = () => settled && transcriptRead && !turnEnded && !resultShown;+ // Milliseconds until a read started at `at` sees every line the+ // member wrote before it settled.+ const flushWindowLeft = (at: DateTime.Utc) =>+ completedAt === null+ ? 0+ : WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS -+ (DateTime.toEpochMillis(at) - DateTime.toEpochMillis(completedAt));+ // Each read is capped, so keep reading until the transcript has no+ // more complete lines; a settled member's answer may be past the cap.+ let transcriptDrained = true;+ if (+ (readTranscript || readLiveTranscript) &&+ transcriptDir !== undefined &&+ agentId !== undefined+ ) {+ const readNext = (cursor: WorkflowAgentTranscriptCursor) =>+ readWorkflowAgentTranscript({+ transcriptDir,+ agentId,+ cursor,+ ...(adapterOptions.environment.CLAUDE_CONFIG_DIR === undefined+ ? {}+ : {+ configDir: path.resolve(+ session.cwd,+ adapterOptions.environment.CLAUDE_CONFIG_DIR,+ ),+ }),+ }).pipe(Effect.option);+ // False once the coordinator was replaced mid-read.+ const drain = Effect.fnUntraced(function* () {+ lastReadAt = yield* DateTime.now;+ transcriptDrained = false;+ while (!transcriptDrained) {+ const read = yield* readNext(transcriptCursor);+ if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)+ return false;+ if (Option.isNone(read)) break;+ transcriptRead = true;+ const advanced = read.value.cursor.offset !== transcriptCursor.offset;+ transcriptCursor = read.value.cursor;+ for (const line of read.value.lines) {+ if (yield* projectSubagentTranscriptLine(target, line)) textShown = true;+ // A later line (a retry, or a resumed member) reopens the turn.+ turnEnded = isClaudeTranscriptTurnEnd(line);+ }+ // A line longer than the cap can't advance; stop rather than spin.+ transcriptDrained = !read.value.truncated || !advanced;+ }+ return true;+ });+ if (!(yield* drain())) return;+ // The coordinator sends nothing after its last frame, so wait out+ // the flush window here rather than settle on the excerpt.+ const waitLeft = flushWindowLeft(lastReadAt);+ if (+ input.coordinator.task.status !== "running" &&+ awaitingReply() &&+ member.result !== undefined &&+ waitLeft > 0+ ) {+ yield* Effect.sleep(waitLeft);+ if (!(yield* drain())) return;+ }+ }+ if (settled) {+ // As for an ordinary subagent, a call still open once the member+ // settles will never get its result.+ yield* endOpenToolCalls();+ // Only the progress excerpt is left when the transcript says+ // nothing, read after its last writes had time to land.if (- answer !== undefined &&- (transcriptAnswer === undefined || restarted || answerDigest !== previousDigest)+ !textShown &&+ !resultShown &&+ member.result !== undefined &&+ (!transcriptRead || flushWindowLeft(lastReadAt) <= 0)) {yield* emitSubagentConversationMessage({- nativeItemId: `${memberKey}:answer:200`,+ nativeItemId: `${memberKey}:result:${attempt}`,threadId: childThreadId,rootNodeId: childRootNodeId,role: "assistant",- text: answer,- ordinal: 200,+ text: `Partial answer from workflow progress:\n\n${member.result}`,+ ordinal: target.nextOrdinal(),now,});+ resultShown = true;}}@@ -4721,20 +4814,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (new Map(current).set(memberKey, {status,attempt,+ agentId,result: member.result,label: member.label,prompt,model,- transcriptAnswerDigest,transcriptReadAttempts:(restarted ? 0 : (previous?.transcriptReadAttempts ?? 0)) +(readTranscript ? 1 : 0),- liveTranscriptReadAt: readLiveTranscript || restarted ? now : liveTranscriptReadAt,finalTranscriptRead:(!restarted && previous?.finalTranscriptRead === true) ||(readTranscript &&- transcript.length > 0 &&+ transcriptRead &&+ transcriptDrained &&+ textShown &&input.coordinator.task.status !== "running"),+ transcriptCursor,+ nextItemOrdinal,+ toolCalls,+ textShown,+ turnEnded,+ resultShown,createdAt,startedAt,completedAt,@@ -5379,56 +5479,259 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ();return presented;}- const startedAt = yield* DateTime.now;- const classification = classifyClaudeNativeTool(input.toolName);const subagent =input.parentToolUseId === null? undefined: yield* resolveSubagentByToolUseId(input.context, input.parentToolUseId);- const threadId = subagent?.childThreadId ?? input.context.input.threadId;- const runId = subagent === undefined ? input.context.input.runId : null;- const rootNodeId = subagent?.childRootNodeId ?? input.context.input.rootNodeId;- const parentNodeId = rootNodeId;- const ordinal =- subagent === undefined- ? yield* resolveItemOrdinal(input.context, input.nativeItemId)- : ++subagent.nextChildItemOrdinal;+ const call = {+ nativeItemId: input.nativeItemId,+ toolName: input.toolName,+ toolInput: input.toolInput,+ presentation: input.presentation,+ startedAt: yield* DateTime.now,+ };+ if (subagent !== undefined) {+ return yield* startSubagentToolCall(subagentProjectionTarget(subagent), call);+ }+ return yield* startToolCall({+ ...call,+ context: input.context,+ threadId: input.context.input.threadId,+ runId: input.context.input.runId,+ rootNodeId: input.context.input.rootNodeId,+ ordinal: yield* resolveItemOrdinal(input.context, input.nativeItemId),+ registry: input.context.toolCalls,+ });+ });++ const startToolCall = Effect.fnUntraced(function* (input: {+ readonly context: ActiveClaudeTurnContext | null;+ readonly nativeItemId: string;+ readonly toolName: string;+ readonly toolInput: ClaudeNativeToolInput;+ readonly presentation: ClaudeToolPresentation | undefined;+ readonly threadId: ThreadId;+ readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null;+ readonly rootNodeId: OrchestrationV2ExecutionNode["id"];+ readonly ordinal: number;+ readonly startedAt: DateTime.Utc;+ readonly registry: Map<string, ActiveClaudeToolCall>;+ }) {const toolCall: ActiveClaudeToolCall = {nativeItemId: input.nativeItemId,toolName: input.toolName,- classification,+ classification: classifyClaudeNativeTool(input.toolName),input: input.toolInput,- threadId,- runId,- rootNodeId,- parentNodeId,- ordinal,- startedAt,+ threadId: input.threadId,+ runId: input.runId,+ rootNodeId: input.rootNodeId,+ parentNodeId: input.rootNodeId,+ ordinal: input.ordinal,+ startedAt: input.startedAt,...(input.presentation === undefined ? {} : { presentation: input.presentation }),};- toolCallsFor(input.context, toolCall).set(input.nativeItemId, toolCall);+ input.registry.set(input.nativeItemId, toolCall);yield* emitToolCallArtifacts(buildToolCallArtifacts({context: input.context,- nativeItemId: input.nativeItemId,- toolName: input.toolName,- classification,- toolInput: input.toolInput,- threadId,- runId,- rootNodeId,- parentNodeId,- ordinal,+ nativeItemId: toolCall.nativeItemId,+ toolName: toolCall.toolName,+ classification: toolCall.classification,+ toolInput: toolCall.input,+ threadId: toolCall.threadId,+ runId: toolCall.runId,+ rootNodeId: toolCall.rootNodeId,+ parentNodeId: toolCall.parentNodeId,+ ordinal: toolCall.ordinal,output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,status: "running",- startedAt,- updatedAt: startedAt,+ startedAt: toolCall.startedAt,+ updatedAt: toolCall.startedAt,presentation: input.presentation,}),);return toolCall;});+ const subagentProjectionTarget = (+ subagent: ActiveClaudeSubagent,+ ): ClaudeSubagentProjectionTarget => ({+ childThreadId: subagent.childThreadId,+ childRootNodeId: subagent.childRootNodeId,+ nextOrdinal: () => ++subagent.nextChildItemOrdinal,+ toolCalls: subagentToolCalls,+ });++ const startSubagentToolCall = (+ target: ClaudeSubagentProjectionTarget,+ call: {+ readonly nativeItemId: string;+ readonly toolName: string;+ readonly toolInput: ClaudeNativeToolInput;+ readonly presentation: ClaudeToolPresentation | undefined;+ readonly startedAt: DateTime.Utc;+ },+ ) =>+ startToolCall({+ ...call,+ context: null,+ threadId: target.childThreadId,+ runId: null,+ rootNodeId: target.childRootNodeId,+ ordinal: target.nextOrdinal(),+ registry: target.toolCalls,+ });++ const settleToolCall = Effect.fnUntraced(function* (input: {+ readonly context: ActiveClaudeTurnContext | null;+ readonly toolCall: ActiveClaudeToolCall;+ readonly registry: Map<string, ActiveClaudeToolCall>;+ readonly message: SDKMessage;+ readonly toolResult: ClaudeToolResultContentBlock;+ readonly output: ClaudeNativeToolOutput;+ readonly completedAt: DateTime.Utc;+ }) {+ const { toolCall } = input;+ const toolNonExecutionKind = claudeToolNonExecutionKind(+ input.message,+ input.toolResult.tool_use_id,+ );+ yield* stopTaskOutputTail(toolCall.nativeItemId);+ yield* emitToolCallArtifacts(+ buildToolCallArtifacts({+ context: input.context,+ nativeItemId: toolCall.nativeItemId,+ toolName: toolCall.toolName,+ classification: toolCall.classification,+ toolInput: toolCall.input,+ threadId: toolCall.threadId,+ runId: toolCall.runId,+ rootNodeId: toolCall.rootNodeId,+ parentNodeId: toolCall.parentNodeId,+ ordinal: toolCall.ordinal,+ output: input.output,+ status:+ toolNonExecutionKind === "cancelled"+ ? "cancelled"+ : isClaudeToolResultError(input.toolResult)+ ? "failed"+ : "completed",+ ...(toolNonExecutionKind === undefined ? {} : { toolNonExecutionKind }),+ startedAt: toolCall.startedAt,+ updatedAt: input.completedAt,+ presentation: toolCall.presentation,+ }),+ );+ input.registry.delete(toolCall.nativeItemId);+ });++ const emitSubagentThinking = Effect.fnUntraced(function* (+ target: ClaudeSubagentProjectionTarget,+ message: SDKAssistantMessage,+ at: DateTime.Utc,+ ) {+ const thinking = message.message.content.flatMap((block) =>+ block.type === "thinking" && block.thinking.trim().length > 0 ? [block.thinking] : [],+ );+ for (const [index, text] of thinking.entries()) {+ const nativeItemId = `${message.uuid}:thinking:${index}`;+ yield* emitProviderEvent({+ type: "turn_item.updated",+ driver: CLAUDE_PROVIDER,+ turnItem: {+ id: idAllocator.derive.turnItemFromProviderItem({+ driver: CLAUDE_PROVIDER,+ nativeItemId,+ }),+ threadId: target.childThreadId,+ runId: null,+ nodeId: target.childRootNodeId,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: {+ driver: CLAUDE_PROVIDER,+ nativeId: nativeItemId,+ strength: "strong",+ },+ parentItemId: null,+ ordinal: target.nextOrdinal(),+ type: "reasoning",+ title: "Thinking",+ text,+ streaming: false,+ status: "completed",+ startedAt: at,+ completedAt: at,+ updatedAt: at,+ },+ });+ }+ });++ /**+ * Projects one transcript line of a subagent whose messages the CLI+ * does not forward (a workflow member) the way a forwarded frame with+ * its parent_tool_use_id is projected. Returns whether it carried text.+ */+ const projectSubagentTranscriptLine = Effect.fnUntraced(function* (+ target: ClaudeSubagentProjectionTarget,+ line: unknown,+ ) {+ if (!isClaudeTranscriptConversationLine(line)) return false;+ const at =+ Option.getOrUndefined(DateTime.make(text(field(line, "timestamp")) ?? "")) ??+ (yield* DateTime.now);+ const presentations = claudeToolPresentationsFromAssistantMessage(line);+ for (const toolUse of claudeToolUseBlocksFromAssistantMessage(line)) {+ if (target.toolCalls.has(toolUse.id)) continue;+ yield* startSubagentToolCall(target, {+ nativeItemId: toolUse.id,+ toolName: toolUse.name,+ toolInput: claudeNativeToolInputFromUnknown(toolUse.input),+ presentation:+ presentations.get(toolUse.id) ??+ mcpToolPresentation({+ toolName: toolUse.name.replace(/^mcp__claude_ai_/u, "mcp__"),+ }),+ startedAt: at,+ });+ }+ for (const { toolResult, output } of claudeToolResultEntriesFromMessage(line)) {+ const toolCall =+ target.toolCalls.get(toolResult.tool_use_id) ??+ (yield* startSubagentToolCall(target, {+ nativeItemId: toolResult.tool_use_id,+ toolName: toolNameFromClaudeToolResult(toolResult),+ toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,+ presentation: undefined,+ startedAt: at,+ }));+ yield* settleToolCall({+ context: null,+ toolCall,+ registry: target.toolCalls,+ message: line,+ toolResult,+ output,+ completedAt: at,+ });+ }+ if (line.type !== "assistant") return false;+ yield* emitSubagentThinking(target, line, at);+ const assistantText = textFromClaudeContent(line.message.content);+ if (assistantText.length === 0) return false;+ yield* emitSubagentConversationMessage({+ nativeItemId: line.uuid,+ threadId: target.childThreadId,+ rootNodeId: target.childRootNodeId,+ role: "assistant",+ text: assistantText,+ ordinal: target.nextOrdinal(),+ now: at,+ });+ return true;+ });+const buildApprovalRequestArtifacts = Effect.fnUntraced(function* (input: {readonly context: ActiveClaudeTurnContext;readonly nativeItemId: string;@@ -5585,7 +5888,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});const endToolCalls = Effect.fnUntraced(function* (input: {- readonly context: ActiveClaudeTurnContext;+ readonly context: ActiveClaudeTurnContext | null;readonly toolCalls: ReadonlyArray<ActiveClaudeToolCall>;readonly status: Extract<OrchestrationV2ProviderTurn["status"],@@ -7266,37 +7569,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,parentToolUseId,}));- const completedAt = yield* DateTime.now;- const toolNonExecutionKind = claudeToolNonExecutionKind(- message,- toolResult.tool_use_id,- );- const artifacts = buildToolCallArtifacts({+ yield* settleToolCall({context,- nativeItemId: toolCall.nativeItemId,- toolName: toolCall.toolName,- classification: toolCall.classification,- toolInput: toolCall.input,- threadId: toolCall.threadId,- runId: toolCall.runId,- rootNodeId: toolCall.rootNodeId,- parentNodeId: toolCall.parentNodeId,- ordinal: toolCall.ordinal,+ toolCall,+ registry: toolCallsFor(context, toolCall),+ message,+ toolResult,output,- status:- toolNonExecutionKind === "cancelled"- ? "cancelled"- : isClaudeToolResultError(toolResult)- ? "failed"- : "completed",- ...(toolNonExecutionKind === undefined ? {} : { toolNonExecutionKind }),- startedAt: toolCall.startedAt,- updatedAt: completedAt,- presentation: toolCall.presentation,+ completedAt: yield* DateTime.now,});- yield* stopTaskOutputTail(toolCall.nativeItemId);- yield* emitToolCallArtifacts(artifacts);- toolCallsFor(context, toolCall).delete(toolCall.nativeItemId);if (parentToolUseId === null && !isClaudeToolResultError(toolResult)) {const taskLists = yield* Ref.get(taskListsByNativeThread);const taskList = applyClaudeTaskTool(@@ -7330,40 +7611,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (? undefined: yield* resolveSubagentByToolUseId(context, assistantParentToolUseId);if (subagent !== undefined) {- const now = yield* DateTime.now;- for (const [index, text] of thinking.entries()) {- const nativeItemId = `${message.uuid}:thinking:${index}`;- yield* emitProviderEvent({- type: "turn_item.updated",- driver: CLAUDE_PROVIDER,- turnItem: {- id: idAllocator.derive.turnItemFromProviderItem({- driver: CLAUDE_PROVIDER,- nativeItemId,- }),- threadId: subagent.childThreadId,- runId: null,- nodeId: subagent.childRootNodeId,- providerThreadId: null,- providerTurnId: null,- nativeItemRef: {- driver: CLAUDE_PROVIDER,- nativeId: nativeItemId,- strength: "strong",- },- parentItemId: null,- ordinal: ++subagent.nextChildItemOrdinal,- type: "reasoning",- title: "Thinking",- text,- streaming: false,- status: "completed",- startedAt: now,- completedAt: now,- updatedAt: now,- },- });- }+ yield* emitSubagentThinking(+ subagentProjectionTarget(subagent),+ message,+ yield* DateTime.now,+ );}}const assistantText = assistantTextFromSdkMessage(message);diff --git a/apps/server/src/orchestration-v2/workflowAgentAnswers.test.ts b/apps/server/src/orchestration-v2/workflowAgentAnswers.test.tsdeleted file mode 100644index 47c03c76e49..00000000000--- a/apps/server/src/orchestration-v2/workflowAgentAnswers.test.ts+++ /dev/null@@ -1,117 +0,0 @@-// @effect-diagnostics nodeBuiltinImport:off-import * as NodeFS from "node:fs";-import * as NodeOS from "node:os";-import * as NodePath from "node:path";-import { it as effectIt } from "@effect/vitest";-import * as Effect from "effect/Effect";-import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";--import { parseWorkflowAgentAnswers, readWorkflowAgentAnswers } from "./workflowAgentAnswers.ts";--const line = (value: unknown) => `${JSON.stringify(value)}\n`;--const assistant = (id: string, content: ReadonlyArray<unknown>) =>- line({ type: "assistant", message: { role: "assistant", id, content } });--describe("parseWorkflowAgentAnswers", () => {- it("returns one entry per assistant turn", () => {- expect(- parseWorkflowAgentAnswers(- assistant("a", [{ type: "text", text: "first" }]) +- assistant("b", [{ type: "text", text: "second" }]),- ),- ).toEqual(["first", "second"]);- });-- it("joins the lines of one split assistant message into a single turn", () => {- expect(- parseWorkflowAgentAnswers(- assistant("a", [{ type: "thinking", thinking: "weighing it up" }]) +- assistant("a", [{ type: "text", text: "the answer" }]) +- assistant("a", [{ type: "text", text: "and more" }]),- ),- ).toEqual(["the answer\n\nand more"]);- });-- it("ignores harness bookkeeping and the member's own prompt", () => {- expect(- parseWorkflowAgentAnswers(- line({ type: "attachment", attachment: { type: "skill_listing", content: "- adhd" } }) +- line({ type: "user", message: { role: "user", content: "the prompt" } }) +- line({- type: "assistant",- isMeta: true,- message: { role: "assistant", id: "m", content: [{ type: "text", text: "injected" }] },- }) +- assistant("a", [{ type: "text", text: "real answer" }]),- ),- ).toEqual(["real answer"]);- });-- it("skips a turn that produced no text", () => {- expect(- parseWorkflowAgentAnswers(- assistant("a", [{ type: "tool_use", id: "t", name: "Bash", input: {} }]),- ),- ).toEqual([]);- });-- it("preserves answer indentation and ignores blank text", () => {- expect(- parseWorkflowAgentAnswers(- assistant("a", [{ type: "text", text: " indented code" }]) +- assistant("b", [{ type: "text", text: " " }]),- ),- ).toEqual([" indented code"]);- });-- it("survives a trailing line the byte cap cut in half", () => {- expect(- parseWorkflowAgentAnswers(- assistant("a", [{ type: "text", text: "complete" }]) + '{"type":"assistant","mess',- ),- ).toEqual(["complete"]);- });-});--let configDir: string;-let transcriptDir: string;-beforeAll(() => {- configDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "wf-config-"));- transcriptDir = NodePath.join(configDir, "projects", "test");- NodeFS.mkdirSync(transcriptDir, { recursive: true });-});--afterAll(() => {- NodeFS.rmSync(configDir, { recursive: true, force: true });-});--describe("readWorkflowAgentAnswers", () => {- effectIt.effect("reads final answers from both small and capped transcripts", () =>- Effect.gen(function* () {- const turn = assistant("a", [{ type: "text", text: "the answer" }]);- const filler = line({ type: "user", message: { role: "user", content: "x".repeat(4096) } });- const write = (agentId: string, contents: string) =>- NodeFS.writeFileSync(NodePath.join(transcriptDir, `agent-${agentId}.jsonl`), contents);- const read = (agentId: string) =>- readWorkflowAgentAnswers({ transcriptDir, agentId, configDir });- write("small", turn);- const edgeAnswer = "x".repeat(- 512 * 1024 + 1 - Buffer.byteLength(assistant("edge", [{ type: "text", text: "" }])),- );- write("edge", assistant("edge", [{ type: "text", text: edgeAnswer }]));- write(- "boundary",- filler.repeat(160) + turn + " ".repeat(512 * 1024 - Buffer.byteLength(turn)),- );- write(- "huge",- turn + filler.repeat(160) + assistant("final", [{ type: "text", text: "final answer" }]),- );- expect(yield* read("small")).toEqual(["the answer"]);- expect(yield* read("edge")).toEqual([edgeAnswer]);- expect(yield* read("huge")).toEqual(["final answer"]);- expect(yield* read("boundary")).toEqual(["the answer"]);- }),- );-});diff --git a/apps/server/src/orchestration-v2/workflowAgentAnswers.ts b/apps/server/src/orchestration-v2/workflowAgentAnswers.tsdeleted file mode 100644index 7e1f9e651f5..00000000000--- a/apps/server/src/orchestration-v2/workflowAgentAnswers.ts+++ /dev/null@@ -1,91 +0,0 @@-// @effect-diagnostics nodeBuiltinImport:off-/**- * A member agent never becomes a provider task and emits nothing on the event- * stream, so the transcript the harness writes is the only full record of its- * turn — the progress snapshot carries a capped excerpt. The path is derived- * here from the run's transcript directory and the member's provider id rather- * than accepted from the caller, and the read itself is contained by- * readContainedWorkflowFile.- */-import * as NodePath from "node:path";--import { OrchestrationWorkflowFileError } from "@t3tools/contracts";-import * as Effect from "effect/Effect";--import { field, text } from "./unknownField.ts";-import { readContainedWorkflowFile } from "./workflowFileRead.ts";--const TRANSCRIPT_BYTE_CAP = 512 * 1024;--const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;--/**- * Two shapes have to be handled: `attachment` lines and `isMeta` user lines are- * harness bookkeeping (hook output, skill listings, injected context) and are- * never conversation, and one assistant API message is split across several- * lines sharing a `message.id`, so those are joined into a single turn rather- * than read as separate ones.- */-export function parseWorkflowAgentAnswers(contents: string): ReadonlyArray<string> {- const turns: string[] = [];- const turnIndexById = new Map<string, number>();-- for (const line of contents.split("\n")) {- if (line.trim().length === 0) continue;- let entry: unknown;- try {- entry = JSON.parse(line);- } catch {- // A capped read can cut the final line mid-object; drop it and keep the rest.- continue;- }- if (text(field(entry, "type")) !== "assistant") continue;- if (field(entry, "isMeta") === true) continue;-- const message = field(entry, "message");- const content = field(message, "content");- if (!Array.isArray(content)) continue;- const body = content- .filter((block) => text(field(block, "type")) === "text")- .map((block) => field(block, "text"))- .filter((value): value is string => typeof value === "string" && value.trim().length > 0)- .join("\n\n");- if (body.length === 0) continue;-- const messageId = text(field(message, "id"));- const existing = messageId === undefined ? undefined : turnIndexById.get(messageId);- if (existing !== undefined) {- turns[existing] = `${turns[existing]}\n\n${body}`;- continue;- }- if (messageId !== undefined) turnIndexById.set(messageId, turns.length);- turns.push(body);- }-- return turns;-}--export const readWorkflowAgentAnswers = Effect.fn("orchestration.readWorkflowAgentAnswers")(- function* (input: {- readonly transcriptDir: string;- readonly agentId: string;- readonly configDir?: string;- }) {- if (!AGENT_ID_PATTERN.test(input.agentId)) {- return yield* new OrchestrationWorkflowFileError({- reason: "invalid-path",- path: input.agentId,- });- }- const file = yield* readContainedWorkflowFile({- path: NodePath.join(input.transcriptDir, `agent-${input.agentId}.jsonl`),- extension: ".jsonl",- byteCap: TRANSCRIPT_BYTE_CAP,- tail: true,- ...(input.configDir === undefined ? {} : { configDir: input.configDir }),- });- return parseWorkflowAgentAnswers(- file.truncated ? file.contents.slice(file.contents.indexOf("\n") + 1) : file.contents,- );- },-);diff --git a/apps/server/src/orchestration-v2/workflowAgentTranscript.test.ts b/apps/server/src/orchestration-v2/workflowAgentTranscript.test.tsnew file mode 100644index 00000000000..e6fd24582c3--- /dev/null+++ b/apps/server/src/orchestration-v2/workflowAgentTranscript.test.ts@@ -0,0 +1,65 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodePath from "node:path";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import { assert } from "vite-plus/test";++import {+ initialWorkflowAgentTranscriptCursor,+ readWorkflowAgentTranscript,+} from "./workflowAgentTranscript.ts";++const line = (value: unknown) => `${JSON.stringify(value)}\n`;+const assistant = (uuid: string, text: string) =>+ line({+ type: "assistant",+ uuid,+ message: { role: "assistant", id: uuid, content: [{ type: "text", text }] },+ });+const uuids = (lines: ReadonlyArray<unknown>) =>+ lines.map((entry) => (entry as { readonly uuid: string }).uuid);++it.layer(NodeServices.layer)("readWorkflowAgentTranscript", (it) => {+ it.effect("reads complete lines from its cursor and starts over on a new file", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "wf-transcript-" });+ const transcriptDir = NodePath.join(configDir, "projects", "test");+ yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });+ const file = NodePath.join(transcriptDir, "agent-a1.jsonl");+ const read = (cursor = initialWorkflowAgentTranscriptCursor) =>+ readWorkflowAgentTranscript({ transcriptDir, agentId: "a1", cursor, configDir });++ const bookkeeping =+ line({ type: "attachment", uuid: "att", attachment: { type: "skill_listing" } }) ++ line({ type: "user", uuid: "meta", isMeta: true, message: { content: "context" } });+ const second = assistant("b", "second");+ NodeFS.writeFileSync(file, bookkeeping + assistant("a", "first") + second.slice(0, 20));+ const first = yield* read();+ assert.deepEqual(uuids(first.lines), ["a"]);+ assert.equal(+ first.cursor.offset,+ Buffer.byteLength(bookkeeping + assistant("a", "first")),+ "a half-written line is left for the next read",+ );++ NodeFS.appendFileSync(file, second.slice(20));+ const next = yield* read(first.cursor);+ assert.deepEqual(uuids(next.lines), ["b"]);+ assert.equal(next.cursor.offset, NodeFS.statSync(file).size);++ NodeFS.rmSync(file);+ NodeFS.writeFileSync(file, assistant("c", "replaced"));+ const replaced = yield* read(next.cursor);+ assert.deepEqual(uuids(replaced.lines), ["c"], "a new inode reads from 0");++ NodeFS.writeFileSync(file, assistant("d", "x"));+ assert.equal(NodeFS.statSync(file).ino, replaced.cursor.identity?.ino);+ const shrunk = yield* read(replaced.cursor);+ assert.deepEqual(uuids(shrunk.lines), ["d"], "a shrunk file reads from 0");+ }).pipe(Effect.scoped),+ );+});diff --git a/apps/server/src/orchestration-v2/workflowAgentTranscript.ts b/apps/server/src/orchestration-v2/workflowAgentTranscript.tsnew file mode 100644index 00000000000..35ddea0a2df--- /dev/null+++ b/apps/server/src/orchestration-v2/workflowAgentTranscript.ts@@ -0,0 +1,99 @@+// @effect-diagnostics nodeBuiltinImport:off+/**+ * A workflow member never becomes a provider task and the CLI forwards none of+ * its messages, so the transcript the harness writes is the only record of its+ * conversation. The path is derived here from the run's transcript directory+ * and the member's provider id rather than accepted from the caller, and the+ * read itself is contained by readContainedWorkflowFile.+ */+import * as NodePath from "node:path";++import { OrchestrationWorkflowFileError } from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";++import { field, text } from "./unknownField.ts";+import { readContainedWorkflowFile, type WorkflowFileIdentity } from "./workflowFileRead.ts";++const TRANSCRIPT_READ_BYTE_CAP = 512 * 1024;++const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;++const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));++export interface WorkflowAgentTranscriptCursor {+ readonly offset: number;+ readonly identity: WorkflowFileIdentity | null;+}++export const initialWorkflowAgentTranscriptCursor: WorkflowAgentTranscriptCursor = {+ offset: 0,+ identity: null,+};++/** Sees every transcript read: where it started and ended, and how many lines it kept. */+export const WorkflowAgentTranscriptReadObserver = Context.Reference<+ (read: {+ readonly agentId: string;+ readonly startOffset: number;+ readonly endOffset: number;+ readonly lineCount: number;+ }) => Effect.Effect<void>+>("t3/orchestration/WorkflowAgentTranscriptReadObserver", {+ defaultValue: () => () => Effect.void,+});++/**+ * Conversation lines only: `attachment` lines and `isMeta` user lines are+ * harness bookkeeping (hook output, skill listings, injected context), and a+ * line without a uuid cannot be projected idempotently.+ */+function parseWorkflowAgentTranscriptLines(contents: string): ReadonlyArray<unknown> {+ return contents.split("\n").flatMap((line) => {+ if (line.trim().length === 0) return [];+ const entry = Option.getOrUndefined(decodeJsonLine(line));+ const type = text(field(entry, "type"));+ if (type !== "assistant" && type !== "user") return [];+ if (field(entry, "isMeta") === true || text(field(entry, "uuid")) === undefined) return [];+ return [entry];+ });+}++/** Reads the complete lines written since `cursor`, and the cursor after them. */+export const readWorkflowAgentTranscript = Effect.fn("orchestration.readWorkflowAgentTranscript")(+ function* (input: {+ readonly transcriptDir: string;+ readonly agentId: string;+ readonly cursor: WorkflowAgentTranscriptCursor;+ readonly configDir?: string;+ }) {+ if (!AGENT_ID_PATTERN.test(input.agentId)) {+ return yield* new OrchestrationWorkflowFileError({+ reason: "invalid-path",+ path: input.agentId,+ });+ }+ const file = yield* readContainedWorkflowFile({+ path: NodePath.join(input.transcriptDir, `agent-${input.agentId}.jsonl`),+ extension: ".jsonl",+ byteCap: TRANSCRIPT_READ_BYTE_CAP,+ fromOffset: input.cursor,+ ...(input.configDir === undefined ? {} : { configDir: input.configDir }),+ });+ const lines = parseWorkflowAgentTranscriptLines(file.contents);+ yield* (yield* WorkflowAgentTranscriptReadObserver)({+ agentId: input.agentId,+ startOffset: file.startOffset,+ endOffset: file.endOffset,+ lineCount: lines.length,+ });+ return {+ lines,+ cursor: { offset: file.endOffset, identity: file.identity },+ // More complete lines may follow past the per-read cap.+ truncated: file.truncated,+ };+ },+);diff --git a/apps/server/src/orchestration-v2/workflowFileRead.ts b/apps/server/src/orchestration-v2/workflowFileRead.tsindex f9938f388a9..81486b631f7 100644--- a/apps/server/src/orchestration-v2/workflowFileRead.ts+++ b/apps/server/src/orchestration-v2/workflowFileRead.ts@@ -7,6 +7,11 @@ import { OrchestrationWorkflowFileError } from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as HostProcess from "@t3tools/shared/HostProcess";+export interface WorkflowFileIdentity {+ readonly dev: number;+ readonly ino: number;+}+function workflowFilesRoot(home: string, configDir?: string): string {return NodePath.join(configDir?.trim() || NodePath.join(home, ".claude"), "projects");}@@ -18,6 +23,14 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedWreadonly byteCap: number;readonly tail?: boolean;readonly configDir?: string;+ /**+ * Read only complete lines from this byte offset of the file `identity`+ * names. A different file (shrunk or another inode) is read from 0.+ */+ readonly fromOffset?: {+ readonly offset: number;+ readonly identity: WorkflowFileIdentity | null;+ };}) {if (!NodePath.isAbsolute(input.path) || NodePath.extname(input.path) !== input.extension) {return yield* new OrchestrationWorkflowFileError({@@ -72,6 +85,33 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedWif (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {return { failure: "changed-during-read" as const };}+ const identity = { dev: stat.dev, ino: stat.ino };+ if (input.fromOffset !== undefined) {+ const previous = input.fromOffset.identity;+ const start =+ previous !== null &&+ previous.dev === identity.dev &&+ previous.ino === identity.ino &&+ input.fromOffset.offset <= stat.size+ ? input.fromOffset.offset+ : 0;+ const buffer = Buffer.alloc(Math.min(stat.size - start, input.byteCap));+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);+ const read = buffer.subarray(0, bytesRead);+ // A writer may be mid-line; leave it for the next read. A single+ // line over the cap is skipped so the cursor can't stall on it.+ const lineEnd = read.lastIndexOf(0x0a) + 1;+ const consumed = lineEnd === 0 && bytesRead === input.byteCap ? bytesRead : lineEnd;+ return {+ contents: read.subarray(0, lineEnd).toString("utf8"),+ // Only the cap can leave complete lines unread; a half-written+ // last line is not truncation.+ truncated: stat.size - start > input.byteCap,+ startOffset: start,+ endOffset: start + consumed,+ identity,+ };+ }const buffer = Buffer.alloc(Math.min(stat.size, input.byteCap + (input.tail ? 1 : 0)));const truncated = stat.size > buffer.length;const offset = input.tail ? stat.size - buffer.length : 0;@@ -79,6 +119,9 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedWreturn {contents: buffer.subarray(0, bytesRead).toString("utf8"),truncated,+ startOffset: offset,+ endOffset: offset + bytesRead,+ identity,};} finally {await handle.close();@@ -91,6 +134,13 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedWreturn yield* new OrchestrationWorkflowFileError({ reason: read.failure, path: resolved });}- return { path: resolved, contents: read.contents, truncated: read.truncated };+ return {+ path: resolved,+ contents: read.contents,+ truncated: read.truncated,+ startOffset: read.startOffset,+ endOffset: read.endOffset,+ identity: read.identity,+ };},);