The best way to control Claude Code, Codex and more from any computer or phone
fix(server): Claude workflow members stream their thinking and tool calls into their threads (#20856)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 08:45 UTC
91f8c35dee93bc58b4a626ce6f62ea1dbd42eeb5
7 files changed
+1170
-515
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+527
-130
@@ -71,6 +71,7 @@ import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
71
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
72
73
import { attachmentRelativePath } from "../../attachmentStore.ts";
74
+import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";
75
import * as ServerConfig from "../../config.ts";
76
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
77
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
@@ -11395,7 +11396,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11396
yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
11397
yield* fileSystem.writeFileString(
11398
NodePath.join(transcriptDir, "agent-a1.jsonl"),
11398
- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n',
11399
+ `{"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`,
11400
);
11401
const harness = yield* makeWakeHarnessWithOptions({
11402
...options,
@@ -12368,7 +12369,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12369
(arrival) =>
12370
Effect.scoped(
12371
Effect.gen(function* () {
12371
- const crypto = yield* Crypto.Crypto;
12372
const digestStarted = yield* Deferred.make<void>();
12373
const releaseDigest = yield* Deferred.make<void>();
12374
const closeStarted = yield* Deferred.make<void>();
@@ -12406,7 +12406,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12406
yield* fileSystem.makeDirectory(liveTranscriptDir);
12407
yield* fileSystem.writeFileString(
12408
NodePath.join(liveTranscriptDir, "agent-a1.jsonl"),
12409
- '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Live member answer"}]}}\n',
12409
+ '{"type":"assistant","uuid":"wf-line-2","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"Live member answer"}]}}\n',
12410
);
12411
const liveTaskId = "task-workflow-live-while-waiting";
12412
const liveToolUseId = "toolu-workflow-live-while-waiting";
@@ -12512,18 +12512,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12512
}
12513
yield* start("attempt-workflow-waiting-next-user", 3, false);
12514
}).pipe(
12515
- Effect.provideService(Crypto.Crypto, {
12516
- ...crypto,
12517
- digest: (algorithm, data) =>
12518
- Effect.gen(function* () {
12519
- if (pauseDigest) {
12520
- pauseDigest = false;
12521
- yield* Deferred.succeed(digestStarted, undefined);
12522
- yield* Deferred.await(releaseDigest);
12523
- }
12524
- return yield* crypto.digest(algorithm, data);
12525
- }),
12526
- }),
12515
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
12516
+ Effect.gen(function* () {
12517
+ if (pauseDigest) {
12518
+ pauseDigest = false;
12519
+ yield* Deferred.succeed(digestStarted, undefined);
12520
+ yield* Deferred.await(releaseDigest);
12521
+ }
12522
+ }),
12523
+ ),
12524
);
12525
}).pipe(
12526
Effect.provide(
@@ -12539,7 +12536,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12536
Effect.scoped(
12537
Effect.gen(function* () {
12538
const clock = yield* Clock.Clock;
12542
- const crypto = yield* Crypto.Crypto;
12539
const progressRead = yield* Deferred.make<void>();
12540
const releaseProgress = yield* Deferred.make<void>();
12541
let pauseNextRead = false;
@@ -12655,18 +12651,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12651
return yield* clock.currentTimeMillis;
12652
}),
12653
}),
12658
- Effect.provideService(Crypto.Crypto, {
12659
- ...crypto,
12660
- digest: (algorithm, data) =>
12661
- Effect.gen(function* () {
12662
- if (boundary === "transcript" && pauseNextRead) {
12663
- pauseNextRead = false;
12664
- yield* Deferred.succeed(progressRead, undefined);
12665
- yield* Deferred.await(releaseProgress);
12666
- }
12667
- return yield* crypto.digest(algorithm, data);
12668
- }),
12669
- }),
12654
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
12655
+ Effect.gen(function* () {
12656
+ if (boundary === "transcript" && pauseNextRead) {
12657
+ pauseNextRead = false;
12658
+ yield* Deferred.succeed(progressRead, undefined);
12659
+ yield* Deferred.await(releaseProgress);
12660
+ }
12661
+ }),
12662
+ ),
12663
);
12664
}).pipe(
12665
Effect.provide(
@@ -12683,7 +12676,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12676
] as const)("orders %s arriving during workflow transcript replay", (arrival) =>
12677
Effect.scoped(
12678
Effect.gen(function* () {
12686
- const crypto = yield* Crypto.Crypto;
12679
const digestStarted = yield* Deferred.make<void>();
12680
const releaseDigest = yield* Deferred.make<void>();
12681
const liveFrameOffered = yield* Deferred.make<void>();
@@ -12887,18 +12879,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12879
);
12880
}
12881
}).pipe(
12890
- Effect.provideService(Crypto.Crypto, {
12891
- ...crypto,
12892
- digest: (algorithm, data) =>
12893
- Effect.gen(function* () {
12894
- if (pauseDigest) {
12895
- pauseDigest = false;
12896
- yield* Deferred.succeed(digestStarted, undefined);
12897
- yield* Deferred.await(releaseDigest);
12898
- }
12899
- return yield* crypto.digest(algorithm, data);
12900
- }),
12901
- }),
12882
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
12883
+ Effect.gen(function* () {
12884
+ if (pauseDigest) {
12885
+ pauseDigest = false;
12886
+ yield* Deferred.succeed(digestStarted, undefined);
12887
+ yield* Deferred.await(releaseDigest);
12888
+ }
12889
+ }),
12890
+ ),
12891
);
12892
}).pipe(
12893
Effect.provide(
@@ -12911,7 +12900,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12900
it.effect("preserves buffered workflow outcomes when interrupted during replay", () =>
12901
Effect.scoped(
12902
Effect.gen(function* () {
12914
- const crypto = yield* Crypto.Crypto;
12903
const digestStarted = yield* Deferred.make<void>();
12904
const releaseDigest = yield* Deferred.make<void>();
12905
let pauseDigest = false;
@@ -13011,18 +12999,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12999
assert.equal(second?.status, "completed");
13000
assert.equal(second?.result, "Workflow finished.");
13001
}).pipe(
13014
- Effect.provideService(Crypto.Crypto, {
13015
- ...crypto,
13016
- digest: (algorithm, data) =>
13017
- Effect.gen(function* () {
13018
- if (pauseDigest) {
13019
- pauseDigest = false;
13020
- yield* Deferred.succeed(digestStarted, undefined);
13021
- yield* Deferred.await(releaseDigest);
13022
- }
13023
- return yield* crypto.digest(algorithm, data);
13024
- }),
13025
- }),
13002
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
13003
+ Effect.gen(function* () {
13004
+ if (pauseDigest) {
13005
+ pauseDigest = false;
13006
+ yield* Deferred.succeed(digestStarted, undefined);
13007
+ yield* Deferred.await(releaseDigest);
13008
+ }
13009
+ }),
13010
+ ),
13011
);
13012
}).pipe(
13013
Effect.provide(
@@ -13483,7 +13468,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13468
);
13469
NodeFS.writeFileSync(
13470
NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),
13486
- '{"type":"assistant","message":{"role":"assistant","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',
13471
+ '{"type":"assistant","uuid":"wf-line-3","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',
13472
);
13473
yield* Queue.offer(
13474
harness.sdkMessages,
@@ -13594,7 +13579,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13579
const memberEventsBeforeRepeat = workflowMemberEvents(harness.events, 2).length;
13580
NodeFS.appendFileSync(
13581
NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13597
- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n',
13582
+ '{"type":"assistant","uuid":"wf-line-4","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 continued"}]}}\n',
13583
);
13584
yield* harness.offerAndWait(
13585
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }),
@@ -13605,19 +13590,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13590
);
13591
yield* awaitUntil(
13592
() =>
13608
- threadMessages(harness.events, firstThreadId).at(-1)?.message.text ===
13609
- "A1 from the transcript\n\nA1 continued",
13593
+ threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued",
13594
"continued workflow transcript answer",
13595
);
13596
assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat);
13597
assert.lengthOf(threadMessages(harness.events, secondThreadId), 2);
13614
- assert.equal(
13615
- threadMessages(harness.events, firstThreadId).at(-1)?.message.text,
13616
- "A1 from the transcript\n\nA1 continued",
13617
- );
13598
+ assert.deepEqual(currentAssistantAnswers(), ["A1 from the transcript", "A1 continued"]);
13599
NodeFS.writeFileSync(
13600
NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),
13620
- '{"type":"assistant","message":{"role":"assistant","id":"msg_a2","content":[{"type":"text","text":"A2 from the transcript"}]}}\n',
13601
+ '{"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',
13602
);
13603
yield* harness.offerAndWait(
13604
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }),
@@ -13637,8 +13618,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13618
NodeFS.writeFileSync(
13619
NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13620
[
13640
- '{"type":"assistant","message":{"role":"assistant","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}',
13641
- '{"type":"assistant","message":{"role":"assistant","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}',
13621
+ '{"type":"assistant","uuid":"wf-line-6","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_first","content":[{"type":"text","text":"First answer"}]}}',
13622
+ '{"type":"assistant","uuid":"wf-line-7","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_second","content":[{"type":"text","text":"Second answer"}]}}',
13623
].join("\n") + "\n",
13624
);
13625
yield* harness.offerAndWait(
@@ -13652,7 +13633,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13633
() => currentAssistantAnswers().join("\n\n").includes("Second answer"),
13634
"two-turn workflow member answer",
13635
);
13655
- assert.equal(currentAssistantAnswers().join("\n\n"), "First answer\n\nSecond answer");
13636
+ assert.deepEqual(currentAssistantAnswers().slice(-2), ["First answer", "Second answer"]);
13637
assert.notDeepEqual(
13638
workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt,
13639
previousStartedAt,
@@ -13669,9 +13650,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13650
() => workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status === "running",
13651
"retried workflow member running",
13652
);
13672
- assert.notInclude(currentAssistantAnswers().join("\n\n"), "First answer");
13673
- assert.notInclude(currentAssistantAnswers().join("\n\n"), "Second answer");
13674
- const answerEventsDuringRetry = threadMessages(harness.events, firstThreadId).length;
13653
yield* Queue.offer(
13654
harness.sdkMessages,
13655
workflowSnapshot({
@@ -13682,7 +13660,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13660
);
13661
NodeFS.writeFileSync(
13662
NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13685
- '{"type":"assistant","message":{"role":"assistant","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n',
13663
+ '{"type":"assistant","uuid":"wf-line-8","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_retry","content":[{"type":"text","text":"A1 retry answer"}]}}\n',
13664
);
13665
yield* Queue.offer(
13666
harness.sdkMessages,
@@ -13698,8 +13676,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13676
"A1 retry answer",
13677
"retried workflow member answer",
13678
);
13701
- assert.deepEqual(currentAssistantAnswers(), ["A1 retry answer"]);
13702
- assert.lengthOf(threadMessages(harness.events, firstThreadId), answerEventsDuringRetry + 1);
13679
+ assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer");
13680
NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"));
13681
yield* Queue.offer(
13682
harness.sdkMessages,
@@ -13710,11 +13687,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13687
}),
13688
);
13689
yield* awaitUntil(
13713
- () => currentAssistantAnswers().at(-1) === "Retry in progress.",
13714
- "retry progress answer",
13690
+ () =>
13691
+ workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]
13692
+ ?.attempt === 4,
13693
+ "fourth workflow member attempt",
13694
);
13716
- yield* Queue.offer(
13717
- harness.sdkMessages,
13695
+ const answersBeforeEmptyAttempt = currentAssistantAnswers();
13696
+ yield* harness.offerAndWait(
13697
workflowSnapshot({
13698
uuid: "00000000-0000-4000-8000-000000001023",
13699
state: "done",
@@ -13722,11 +13701,215 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13701
omitResult: true,
13702
}),
13703
);
13725
- yield* awaitUntil(
13726
- () => currentAssistantAnswers().at(-1) === "No answer from this workflow attempt.",
13727
- "empty retry answer",
13704
+ assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed");
13705
+ assert.deepEqual(
13706
+ currentAssistantAnswers(),
13707
+ answersBeforeEmptyAttempt,
13708
+ "an attempt with no transcript and no excerpt adds nothing",
13709
+ );
13710
+ }).pipe(
13711
+ Effect.provide(
13712
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13713
+ ),
13714
+ ),
13715
+ ),
13716
+ );
13717
+
13718
+ // Line shapes copied from a Claude CLI 2.1.301 workflow member transcript.
13719
+ const transcriptLine = (entry: Record<string, unknown>) =>
13720
+ `${JSON.stringify({ isSidechain: true, agentId: "a1", timestamp: "2026-10-17T05:08:07.524Z", ...entry })}\n`;
13721
+ const memberAssistantLine = (
13722
+ uuid: string,
13723
+ messageId: string,
13724
+ content: unknown,
13725
+ stopReason?: "tool_use" | "end_turn",
13726
+ ) =>
13727
+ transcriptLine({
13728
+ type: "assistant",
13729
+ uuid,
13730
+ message: {
13731
+ model: "claude-opus-5-5",
13732
+ id: messageId,
13733
+ type: "message",
13734
+ role: "assistant",
13735
+ content,
13736
+ ...(stopReason === undefined ? {} : { stop_reason: stopReason }),
13737
+ },
13738
+ });
13739
+ const memberToolResultLine = (uuid: string, toolUseId: string, output: string) =>
13740
+ transcriptLine({
13741
+ type: "user",
13742
+ uuid,
13743
+ message: {
13744
+ role: "user",
13745
+ content: [{ tool_use_id: toolUseId, type: "tool_result", content: output }],
13746
+ },
13747
+ });
13748
+ const memberTranscript = [
13749
+ transcriptLine({
13750
+ type: "user",
13751
+ uuid: "line-prompt",
13752
+ message: { role: "user", content: "Reply with exactly: A1" },
13753
+ }),
13754
+ transcriptLine({
13755
+ type: "attachment",
13756
+ uuid: "line-attachment",
13757
+ attachment: { type: "skill_listing", content: "- adhd" },
13758
+ }),
13759
+ transcriptLine({
13760
+ type: "user",
13761
+ uuid: "line-meta",
13762
+ isMeta: true,
13763
+ message: { role: "user", content: "<system-reminder>context</system-reminder>" },
13764
+ }),
13765
+ memberAssistantLine("line-thinking", "msg_a1", [
13766
+ { type: "thinking", thinking: "List the files first.", signature: "sig" },
13767
+ ]),
13768
+ memberAssistantLine("line-bash", "msg_a1", [
13769
+ { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } },
13770
+ ]),
13771
+ memberToolResultLine("line-ls-result", "toolu_a1_ls", "README.md"),
13772
+ memberAssistantLine("line-reply", "msg_a1_reply", [
13773
+ { type: "text", text: "A1 found README.md" },
13774
+ ]),
13775
+ ].join("");
13776
+ const memberThreadItems = (
13777
+ events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
13778
+ threadId: ThreadId | null | undefined,
13779
+ ) =>
13780
+ events.flatMap((event) =>
13781
+ event.type === "turn_item.updated" && event.turnItem.threadId === threadId
13782
+ ? [event.turnItem]
13783
+ : [],
13784
+ );
13785
+ const latestMemberThreadItems = (
13786
+ events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
13787
+ threadId: ThreadId | null | undefined,
13788
+ ) =>
13789
+ [
13790
+ ...new Map(memberThreadItems(events, threadId).map((item) => [item.id, item])).values(),
13791
+ ].toSorted((left, right) => left.ordinal - right.ordinal);
13792
+ const describeItem = (item: ReturnType<typeof memberThreadItems>[number]) =>
13793
+ item.type === "reasoning"
13794
+ ? `reasoning: ${item.text}`
13795
+ : item.type === "command_execution"
13796
+ ? `command ${item.status}: ${item.output ?? ""}`
13797
+ : item.type === "assistant_message" || item.type === "user_message"
13798
+ ? `${item.type}`
13799
+ : `${item.type} ${item.status}`;
13800
+
13801
+ it.effect("streams a running workflow member's conversation from its transcript", () =>
13802
+ Effect.scoped(
13803
+ Effect.gen(function* () {
13804
+ const reads: Array<{
13805
+ readonly startOffset: number;
13806
+ readonly endOffset: number;
13807
+ readonly lineCount: number;
13808
+ }> = [];
13809
+ yield* Effect.gen(function* () {
13810
+ const harness = yield* makeWorkflowHarness;
13811
+ const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl");
13812
+ NodeFS.writeFileSync(transcriptPath, memberTranscript);
13813
+ yield* harness.runtime.startTurn(
13814
+ makeClaudeTestTurnInput({
13815
+ threadId: harness.threadId,
13816
+ providerThread: harness.providerThread,
13817
+ now: yield* DateTime.now,
13818
+ attemptId: RunAttemptId.make("attempt-claude-workflow-live-stream"),
13819
+ text: "Run the alpha workflow.",
13820
+ attachments: [],
13821
+ }),
13822
+ );
13823
+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" });
13824
+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;
13825
+ const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" });
13826
+
13827
+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [
13828
+ "user_message",
13829
+ "reasoning: List the files first.",
13830
+ "command completed: README.md",
13831
+ "assistant_message",
13832
+ ]);
13833
+ assert.deepEqual(
13834
+ threadMessages(harness.events, threadId).map((event) => event.message.text),
13835
+ ["Reply with exactly: A1", "A1 found README.md"],
13836
+ );
13837
+ assert.deepEqual(reads.at(-1), {
13838
+ startOffset: 0,
13839
+ endOffset: Buffer.byteLength(memberTranscript),
13840
+ lineCount: 5,
13841
+ });
13842
+
13843
+ const itemsBefore = memberThreadItems(harness.events, threadId).length;
13844
+ const more = memberAssistantLine("line-more", "msg_a1_more", [
13845
+ {
13846
+ type: "tool_use",
13847
+ id: "toolu_a1_cat",
13848
+ name: "Bash",
13849
+ input: { command: "cat README.md" },
13850
+ },
13851
+ ]);
13852
+ const half = memberToolResultLine("line-cat-result", "toolu_a1_cat", "hello");
13853
+ NodeFS.appendFileSync(transcriptPath, more + half.slice(0, 40));
13854
+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361"));
13855
+ assert.deepEqual(reads.at(-1), {
13856
+ startOffset: Buffer.byteLength(memberTranscript),
13857
+ endOffset: Buffer.byteLength(memberTranscript + more),
13858
+ lineCount: 1,
13859
+ });
13860
+ assert.deepEqual(
13861
+ memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem),
13862
+ ["command running: "],
13863
+ "only the new line is projected; the half-written one waits",
13864
+ );
13865
+
13866
+ NodeFS.appendFileSync(transcriptPath, half.slice(40));
13867
+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362"));
13868
+ assert.deepEqual(reads.at(-1), {
13869
+ startOffset: Buffer.byteLength(memberTranscript + more),
13870
+ endOffset: Buffer.byteLength(memberTranscript + more + half),
13871
+ lineCount: 1,
13872
+ });
13873
+ assert.deepEqual(
13874
+ memberThreadItems(harness.events, threadId).slice(itemsBefore).map(describeItem),
13875
+ ["command running: ", "command completed: hello"],
13876
+ );
13877
+
13878
+ const itemsBeforeIdle = memberThreadItems(harness.events, threadId).length;
13879
+ yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363"));
13880
+ assert.equal(reads.at(-1)?.lineCount, 0);
13881
+ assert.lengthOf(memberThreadItems(harness.events, threadId), itemsBeforeIdle);
13882
+
13883
+ yield* harness.offerAndWait(
13884
+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }),
13885
+ );
13886
+ assert.equal(
13887
+ workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status,
13888
+ "completed",
13889
+ );
13890
+ assert.deepEqual(
13891
+ threadMessages(harness.events, threadId).map((event) => event.message.text),
13892
+ ["Reply with exactly: A1", "A1 found README.md"],
13893
+ "the settled member adds no second copy of its answer",
13894
+ );
13895
+ yield* Queue.offer(
13896
+ harness.sdkMessages,
13897
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }),
13898
+ );
13899
+ yield* Queue.take(harness.terminalReceipts);
13900
+ }).pipe(
13901
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) =>
13902
+ Effect.sync(() => {
13903
+ if (read.agentId === "a1") {
13904
+ reads.push({
13905
+ startOffset: read.startOffset,
13906
+ endOffset: read.endOffset,
13907
+ lineCount: read.lineCount,
13908
+ });
13909
+ }
13910
+ }),
13911
+ ),
13912
);
13729
- assert.deepEqual(currentAssistantAnswers(), ["No answer from this workflow attempt."]);
13913
}).pipe(
13914
Effect.provide(
13915
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -13735,76 +13918,97 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13918
),
13919
);
13920
13738
- it.effect("shows a running workflow member's answer so far from its transcript", () =>
13921
+ it.effect("interrupts the open tool calls of a workflow member that failed", () =>
13922
Effect.scoped(
13923
Effect.gen(function* () {
13924
const harness = yield* makeWorkflowHarness;
13742
- const now = yield* DateTime.now;
13925
+ NodeFS.writeFileSync(
13926
+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13927
+ memberAssistantLine("line-bash", "msg_a1", [
13928
+ { type: "tool_use", id: "toolu_a1_ls", name: "Bash", input: { command: "ls" } },
13929
+ ]),
13930
+ );
13931
yield* harness.runtime.startTurn(
13932
makeClaudeTestTurnInput({
13933
threadId: harness.threadId,
13934
providerThread: harness.providerThread,
13747
- now,
13748
- attemptId: RunAttemptId.make("attempt-claude-workflow-live-answer"),
13935
+ now: yield* DateTime.now,
13936
+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-fails"),
13937
text: "Run the alpha workflow.",
13938
attachments: [],
13939
}),
13940
);
13753
- yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001360" });
13754
- const firstThreadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;
13755
- const assistantEvents = () =>
13756
- threadMessages(harness.events, firstThreadId).filter(
13757
- (event) => event.message.role === "assistant",
13758
- );
13759
- const transcriptPath = NodePath.join(harness.transcriptDir, "agent-a1.jsonl");
13760
- const running = (uuid: string) => workflowSnapshot({ uuid, state: "start" });
13761
-
13762
- yield* awaitUntil(
13763
- () => assistantEvents().at(-1)?.message.text === "A1 from the transcript",
13764
- "running workflow member answer so far",
13941
+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001370" });
13942
+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;
13943
+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [
13944
+ "user_message",
13945
+ "command running: ",
13946
+ ]);
13947
+ yield* harness.offerAndWait(
13948
+ workflowNotification({ uuid: "00000000-0000-4000-8000-000000001371", status: "failed" }),
13949
);
13766
- assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "running");
13767
-
13768
- NodeFS.appendFileSync(
13769
- transcriptPath,
13770
- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1_more","content":[{"type":"text","text":"A1 keeps going"}]}}\n',
13950
+ assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "failed");
13951
+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [
13952
+ "user_message",
13953
+ "command interrupted: ",
13954
+ ]);
13955
+ yield* Queue.offer(
13956
+ harness.sdkMessages,
13957
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001372", result: "Done." }),
13958
);
13772
- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001361"));
13773
- assert.lengthOf(assistantEvents(), 1, "a frame inside the throttle window reads nothing");
13959
+ yield* Queue.take(harness.terminalReceipts);
13960
+ }).pipe(
13961
+ Effect.provide(
13962
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13963
+ ),
13964
+ ),
13965
+ ),
13966
+ );
13967
13775
- yield* TestClock.adjust("10 seconds");
13776
- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001362"));
13777
- assert.lengthOf(assistantEvents(), 2);
13778
- assert.equal(
13779
- assistantEvents().at(-1)?.message.text,
13780
- "A1 from the transcript\n\nA1 keeps going",
13968
+ it.effect("reads a settled workflow member's transcript to its end past the read cap", () =>
13969
+ Effect.scoped(
13970
+ Effect.gen(function* () {
13971
+ const harness = yield* makeWorkflowHarness;
13972
+ // About 1.3 MB of early replies: more than the launch frame's read
13973
+ // and the settled frame's read together, at 512 KB each.
13974
+ const filler = "x".repeat(16 * 1024);
13975
+ NodeFS.writeFileSync(
13976
+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13977
+ Array.from({ length: 80 }, (_, index) =>
13978
+ memberAssistantLine(`line-early-${index}`, `msg_early_${index}`, [
13979
+ { type: "text", text: `${index} ${filler}` },
13980
+ ]),
13981
+ ).join("") +
13982
+ memberAssistantLine("line-final", "msg_final", [
13983
+ { type: "text", text: "FINAL ANSWER" },
13984
+ ]),
13985
);
13782
-
13783
- yield* TestClock.adjust("10 seconds");
13784
- yield* harness.offerAndWait(running("00000000-0000-4000-8000-000000001363"));
13785
- assert.lengthOf(assistantEvents(), 2, "an unchanged transcript emits nothing");
13786
-
13787
- NodeFS.appendFileSync(
13788
- transcriptPath,
13789
- '{"type":"assistant","message":{"role":"assistant","id":"msg_a1_final","content":[{"type":"text","text":"A1 final"}]}}\n',
13986
+ yield* harness.runtime.startTurn(
13987
+ makeClaudeTestTurnInput({
13988
+ threadId: harness.threadId,
13989
+ providerThread: harness.providerThread,
13990
+ now: yield* DateTime.now,
13991
+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-long-transcript"),
13992
+ text: "Run the alpha workflow.",
13993
+ attachments: [],
13994
+ }),
13995
);
13996
+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001390" });
13997
+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;
13998
yield* harness.offerAndWait(
13792
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001364", state: "done" }),
13793
- );
13794
- assert.equal(workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, "completed");
13795
- assert.equal(
13796
- assistantEvents().at(-1)?.message.text,
13797
- "A1 from the transcript\n\nA1 keeps going\n\nA1 final",
13798
- );
13799
- assert.lengthOf(
13800
- new Set(assistantEvents().map((event) => event.message.id)),
13801
- 1,
13802
- "the settled answer replaces the running one in place",
13999
+ workflowNotification({
14000
+ uuid: "00000000-0000-4000-8000-000000001391",
14001
+ status: "completed",
14002
+ }),
14003
);
13804
-
14004
+ const texts = threadMessages(harness.events, threadId)
14005
+ .filter((event) => event.message.role === "assistant")
14006
+ .map((event) => event.message.text);
14007
+ assert.lengthOf(texts, 81);
14008
+ assert.equal(texts.at(-1), "FINAL ANSWER", "the answer past the first read is shown");
14009
yield* Queue.offer(
14010
harness.sdkMessages,
13807
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001365", result: "Done." }),
14011
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001392", result: "Done." }),
14012
);
14013
yield* Queue.take(harness.terminalReceipts);
14014
}).pipe(
@@ -13815,6 +14019,199 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14019
),
14020
);
14021
14022
+ it.effect.each([
14023
+ { before: "nothing" },
14024
+ { before: "text" },
14025
+ { before: "a line without a stop reason" },
14026
+ ] as const)(
14027
+ "waits for a settled workflow member's reply to reach its transcript ($before before it)",
14028
+ ({ before }) =>
14029
+ Effect.scoped(
14030
+ Effect.gen(function* () {
14031
+ // Claude Code flushes transcript lines every 100 ms, so a member's reply
14032
+ // can land after the frame that settles it (seen with CLI 2.1.301).
14033
+ let appendLateReply: (() => void) | undefined;
14034
+ const lateReplyWritten = yield* Deferred.make<void>();
14035
+ yield* Effect.gen(function* () {
14036
+ const harness = yield* makeWorkflowHarness;
14037
+ const transcriptPath = (agentId: string) =>
14038
+ NodePath.join(harness.transcriptDir, `agent-${agentId}.jsonl`);
14039
+ // A member often says what it is about to do before its first tool call.
14040
+ const toolCall = (agentId: string) =>
14041
+ memberAssistantLine(
14042
+ `line-${agentId}-bash`,
14043
+ `msg_${agentId}`,
14044
+ [
14045
+ ...(before === "text"
14046
+ ? [{ type: "text", text: `${agentId} lists the files.` }]
14047
+ : []),
14048
+ {
14049
+ type: "tool_use",
14050
+ id: `toolu_${agentId}`,
14051
+ name: "Bash",
14052
+ input: { command: "ls" },
14053
+ },
14054
+ ],
14055
+ "tool_use",
14056
+ ) +
14057
+ memberToolResultLine(`line-${agentId}-result`, `toolu_${agentId}`, "README.md") +
14058
+ // A line from a writer that leaves the field out entirely.
14059
+ (before === "a line without a stop reason"
14060
+ ? memberAssistantLine(`line-${agentId}-thinking`, `msg_${agentId}_reply`, [
14061
+ { type: "thinking", thinking: "Summarize the file.", signature: "sig" },
14062
+ ])
14063
+ : "");
14064
+ const early = (agentId: string) =>
14065
+ before === "text" ? [`${agentId} lists the files.`] : [];
14066
+ const reply = (agentId: string) =>
14067
+ memberAssistantLine(
14068
+ `line-${agentId}-reply`,
14069
+ `msg_${agentId}_reply`,
14070
+ [{ type: "text", text: `${agentId} found README.md` }],
14071
+ "end_turn",
14072
+ );
14073
+ NodeFS.writeFileSync(transcriptPath("a1"), toolCall("a1"));
14074
+ NodeFS.writeFileSync(transcriptPath("a2"), toolCall("a2"));
14075
+ yield* harness.runtime.startTurn(
14076
+ makeClaudeTestTurnInput({
14077
+ threadId: harness.threadId,
14078
+ providerThread: harness.providerThread,
14079
+ now: yield* DateTime.now,
14080
+ attemptId: RunAttemptId.make("attempt-claude-workflow-member-late-flush"),
14081
+ text: "Run the alpha workflow.",
14082
+ attachments: [],
14083
+ }),
14084
+ );
14085
+ yield* launchWorkflow({
14086
+ harness,
14087
+ snapshotUuid: "00000000-0000-4000-8000-000000001395",
14088
+ });
14089
+ const texts = (index: number) =>
14090
+ threadMessages(
14091
+ harness.events,
14092
+ workflowMemberEvents(harness.events, index)[0]?.subagent.childThreadId,
14093
+ ).map((event) => event.message.text);
14094
+
14095
+ // The first member settles while the workflow runs on.
14096
+ yield* harness.offerAndWait(
14097
+ workflowSnapshot({
14098
+ uuid: "00000000-0000-4000-8000-000000001396",
14099
+ state: "done",
14100
+ secondState: "start",
14101
+ }),
14102
+ );
14103
+ assert.equal(
14104
+ workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status,
14105
+ "completed",
14106
+ );
14107
+ assert.deepEqual(
14108
+ texts(1),
14109
+ ["Reply with exactly: A1", ...early("a1")],
14110
+ "no excerpt before the reply",
14111
+ );
14112
+ NodeFS.appendFileSync(transcriptPath("a1"), reply("a1"));
14113
+ yield* harness.offerAndWait(
14114
+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001397", state: "done" }),
14115
+ );
14116
+ assert.deepEqual(texts(1), [
14117
+ "Reply with exactly: A1",
14118
+ ...early("a1"),
14119
+ "a1 found README.md",
14120
+ ]);
14121
+ assert.deepEqual(texts(2), ["Reply with exactly: A2", ...early("a2")]);
14122
+
14123
+ // The workflow ends right after the second member, before its reply lands.
14124
+ appendLateReply = () => NodeFS.appendFileSync(transcriptPath("a2"), reply("a2"));
14125
+ const notified = yield* harness
14126
+ .offerAndWait(
14127
+ workflowNotification({
14128
+ uuid: "00000000-0000-4000-8000-000000001398",
14129
+ status: "completed",
14130
+ }),
14131
+ )
14132
+ .pipe(Effect.forkScoped);
14133
+ yield* Deferred.await(lateReplyWritten);
14134
+ for (let tick = 0; tick < 20 && texts(2).at(-1) !== "a2 found README.md"; tick += 1) {
14135
+ yield* TestClock.adjust("100 millis");
14136
+ }
14137
+ yield* Fiber.join(notified);
14138
+ assert.deepEqual(texts(2), [
14139
+ "Reply with exactly: A2",
14140
+ ...early("a2"),
14141
+ "a2 found README.md",
14142
+ ]);
14143
+ yield* Queue.offer(
14144
+ harness.sdkMessages,
14145
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001399", result: "Done." }),
14146
+ );
14147
+ yield* Queue.take(harness.terminalReceipts);
14148
+ }).pipe(
14149
+ Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => {
14150
+ // Lands just after the read that would have settled the member.
14151
+ if (read.agentId !== "a2" || appendLateReply === undefined) return Effect.void;
14152
+ const append = appendLateReply;
14153
+ appendLateReply = undefined;
14154
+ append();
14155
+ return Deferred.succeed(lateReplyWritten, undefined).pipe(Effect.asVoid);
14156
+ }),
14157
+ );
14158
+ }).pipe(
14159
+ Effect.provide(
14160
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14161
+ ),
14162
+ ),
14163
+ ),
14164
+ );
14165
+
14166
+ it.effect("re-reads a workflow member's transcript after a restart without new items", () =>
14167
+ Effect.scoped(
14168
+ Effect.gen(function* () {
14169
+ const runOnce = Effect.fnUntraced(function* (attemptId: string) {
14170
+ const harness = yield* makeWorkflowHarness;
14171
+ NodeFS.writeFileSync(
14172
+ NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
14173
+ memberTranscript,
14174
+ );
14175
+ yield* harness.runtime.startTurn(
14176
+ makeClaudeTestTurnInput({
14177
+ threadId: harness.threadId,
14178
+ providerThread: harness.providerThread,
14179
+ now: yield* DateTime.now,
14180
+ attemptId: RunAttemptId.make(attemptId),
14181
+ text: "Run the alpha workflow.",
14182
+ attachments: [],
14183
+ }),
14184
+ );
14185
+ yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001380" });
14186
+ const threadId = workflowMemberEvents(harness.events, 1)[0]?.subagent.childThreadId;
14187
+ yield* Queue.offer(
14188
+ harness.sdkMessages,
14189
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001381", result: "Done." }),
14190
+ );
14191
+ yield* Queue.take(harness.terminalReceipts);
14192
+ assert.deepEqual(latestMemberThreadItems(harness.events, threadId).map(describeItem), [
14193
+ "user_message",
14194
+ "reasoning: List the files first.",
14195
+ "command completed: README.md",
14196
+ "assistant_message",
14197
+ ]);
14198
+ return new Set(memberThreadItems(harness.events, threadId).map((item) => item.id));
14199
+ });
14200
+ const before = yield* runOnce("attempt-claude-workflow-before-restart");
14201
+ const after = yield* runOnce("attempt-claude-workflow-after-restart");
14202
+ assert.isAtLeast(before.size, 4);
14203
+ assert.deepEqual(
14204
+ [...after].filter((id) => !before.has(id)),
14205
+ [],
14206
+ );
14207
+ }).pipe(
14208
+ Effect.provide(
14209
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14210
+ ),
14211
+ ),
14212
+ ),
14213
+ );
14214
+
14215
it.effect.each([
14216
{ backgrounding: "succeeds" },
14217
{ backgrounding: "fails" },
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+428
-176
@@ -6,7 +6,11 @@ import {
6
formatSearchToolLabel,
7
} from "@t3tools/shared/toolActivity";
8
import { field, text } from "../unknownField.ts";
9
-import { readWorkflowAgentAnswers } from "../workflowAgentAnswers.ts";
9
+import {
10
+ initialWorkflowAgentTranscriptCursor,
11
+ readWorkflowAgentTranscript,
12
+ type WorkflowAgentTranscriptCursor,
13
+} from "../workflowAgentTranscript.ts";
14
import {
15
CLAUDE_WORKFLOW_TASK_TYPE,
16
hasClaudeWorkflowSnapshot,
@@ -91,7 +95,6 @@ import {
95
import * as Cause from "effect/Cause";
96
import * as Context from "effect/Context";
97
import * as Crypto from "effect/Crypto";
94
-import * as Hex from "effect/encoding/Hex";
98
import * as DateTime from "effect/DateTime";
99
import * as Deferred from "effect/Deferred";
100
import * as Effect from "effect/Effect";
@@ -232,6 +235,10 @@ const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
235
// The SDK puts no deadline on control requests. The CLI answers
236
// mcp_set_servers once each server connected or hit its own 30 s timeout.
237
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
238
+// Claude Code flushes transcript writes every 100 ms, so a workflow member's
239
+// reply can land after the progress frame that settles it. Its transcript
240
+// stays the source of its answer this long after it settles.
241
+const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
242
243
/**
244
* 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:
1675
} satisfies SDKUserMessage;
1676
});
1677
1671
-const sha256Hex = Effect.fnUntraced(function* (crypto: Crypto.Crypto, value: string) {
1672
- return Hex.encode(
1673
- yield* crypto.digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.orDie),
1674
- );
1675
-});
1676
-
1678
export function isClaudePromptUuid(value: string): value is NonNullable<SDKUserMessage["uuid"]> {
1679
return /^[^-]+-[^-]+-[^-]+-[^-]+-[^-]+$/.test(value);
1680
}
@@ -3064,6 +3065,39 @@ interface ActiveClaudeToolCall {
3065
readonly presentation?: ClaudeToolPresentation;
3066
}
3067
3068
+/** Where a subagent's conversation items land: its child thread and root node. */
3069
+interface ClaudeSubagentProjectionTarget {
3070
+ readonly childThreadId: ThreadId;
3071
+ readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
3072
+ readonly nextOrdinal: () => number;
3073
+ readonly toolCalls: Map<string, ActiveClaudeToolCall>;
3074
+}
3075
+
3076
+/**
3077
+ * Whether a transcript line ends the assistant's turn. Claude Code writes each
3078
+ * block of a message as its own line, `stop_reason: null` on all but the last,
3079
+ * and text before a tool call (`tool_use`) is not the reply. A line without the
3080
+ * field (no CLI writes one) keeps the turn open: waiting costs at most the flush
3081
+ * window, while ending the turn early can lose the reply.
3082
+ */
3083
+function isClaudeTranscriptTurnEnd(entry: unknown): boolean {
3084
+ if (field(entry, "type") !== "assistant") return false;
3085
+ const stopReason = field(field(entry, "message"), "stop_reason");
3086
+ return typeof stopReason === "string" && stopReason !== "tool_use";
3087
+}
3088
+
3089
+function isClaudeTranscriptConversationLine(
3090
+ entry: unknown,
3091
+): entry is SDKAssistantMessage | SDKUserMessage {
3092
+ const type = field(entry, "type");
3093
+ const content = field(field(entry, "message"), "content");
3094
+ return (
3095
+ typeof field(entry, "uuid") === "string" &&
3096
+ ((type === "assistant" && Array.isArray(content)) ||
3097
+ (type === "user" && (Array.isArray(content) || typeof content === "string")))
3098
+ );
3099
+}
3100
+
3101
interface PendingClaudeSubagentLaunch {
3102
readonly model?: string;
3103
readonly effort?: string;
@@ -3092,9 +3126,6 @@ function claudeSubagentModelSelection(
3126
3127
const PENDING_CLAUDE_SUBAGENT_CAP = 64;
3128
const PENDING_CLAUDE_SUBAGENT_FRAME_CAP = 256;
3095
-// Workflow progress frames arrive about every 12 seconds; a running member's
3096
-// transcript is re-read at most this often to show its answer so far.
3097
-const WORKFLOW_MEMBER_LIVE_TRANSCRIPT_READ_INTERVAL_MS = 10_000;
3129
3130
function rememberPendingClaudeSubagentLaunch(
3131
pending: Map<string, PendingClaudeSubagentLaunch>,
@@ -3423,10 +3454,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3454
{
3455
readonly status: OrchestrationV2Subagent["status"];
3456
readonly attempt: number;
3426
- readonly transcriptAnswerDigest: string | undefined;
3457
readonly transcriptReadAttempts: number;
3428
- readonly liveTranscriptReadAt: DateTime.Utc | null;
3458
readonly finalTranscriptRead: boolean;
3459
+ // Where the next read of the member's transcript starts; every
3460
+ // line before it is already projected into the member's thread.
3461
+ readonly agentId: string | undefined;
3462
+ readonly transcriptCursor: WorkflowAgentTranscriptCursor;
3463
+ readonly nextItemOrdinal: number;
3464
+ readonly toolCalls: Map<string, ActiveClaudeToolCall>;
3465
+ readonly textShown: boolean;
3466
+ // The transcript reached the end of the member's last turn.
3467
+ readonly turnEnded: boolean;
3468
+ readonly resultShown: boolean;
3469
readonly result: string | undefined;
3470
readonly label: string;
3471
readonly prompt: string;
@@ -4131,7 +4170,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4170
});
4171
4172
const buildToolCallArtifacts = (input: {
4134
- readonly context: ActiveClaudeTurnContext;
4173
+ // Only a call in a run (runId set) needs its provider turn.
4174
+ readonly context: ActiveClaudeTurnContext | null;
4175
readonly nativeItemId: string;
4176
readonly toolName: string;
4177
readonly classification: ClaudeToolClassification;
@@ -4174,8 +4214,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4214
kind: "tool_call",
4215
status: input.status,
4216
countsForRun: false,
4177
- providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,
4178
- providerTurnId: input.runId === null ? null : input.context.providerTurnId,
4217
+ providerThreadId:
4218
+ input.runId === null ? null : (input.context?.input.providerThread.id ?? null),
4219
+ providerTurnId: input.runId === null ? null : (input.context?.providerTurnId ?? null),
4220
nativeItemRef,
4221
runtimeRequestId: null,
4222
checkpointScopeId: null,
@@ -4204,8 +4245,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4245
threadId: input.threadId,
4246
runId: input.runId,
4247
nodeId,
4207
- providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,
4208
- providerTurnId: input.runId === null ? null : input.context.providerTurnId,
4248
+ providerThreadId:
4249
+ input.runId === null ? null : (input.context?.input.providerThread.id ?? null),
4250
+ providerTurnId: input.runId === null ? null : (input.context?.providerTurnId ?? null),
4251
nativeItemRef,
4252
parentItemId: null,
4253
ordinal: input.ordinal,
@@ -4529,18 +4571,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4571
(input.coordinator.task.status === "running"
4572
? (restarted ? 0 : (previous?.transcriptReadAttempts ?? 0)) < 3
4573
: restarted || previous?.finalTranscriptRead !== true);
4532
- // A running member streams nothing, so its transcript is the only
4533
- // way to show its answer so far. A restart shows "Retry in
4534
- // progress." and starts a fresh throttle window before the next read.
4535
- const liveTranscriptReadAt = previous?.liveTranscriptReadAt ?? null;
4574
+ // The CLI forwards nothing a member says, so every frame while it
4575
+ // runs reads what its transcript gained since the last one.
4576
const readLiveTranscript =
4537
- status === "running" &&
4538
- !restarted &&
4539
- transcriptDir !== undefined &&
4540
- agentId !== undefined &&
4541
- (liveTranscriptReadAt === null ||
4542
- DateTime.toEpochMillis(now) - DateTime.toEpochMillis(liveTranscriptReadAt) >=
4543
- WORKFLOW_MEMBER_LIVE_TRANSCRIPT_READ_INTERVAL_MS);
4577
+ status === "running" && transcriptDir !== undefined && agentId !== undefined;
4578
if (!changed && !readTranscript && !readLiveTranscript) continue;
4579
4580
const nodeId = idAllocator.derive.nodeFromProviderItem({
@@ -4587,17 +4621,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4621
now,
4622
});
4623
}
4590
- if (restarted && !settled) {
4591
- yield* emitSubagentConversationMessage({
4592
- nativeItemId: `${memberKey}:answer:200`,
4593
- threadId: childThreadId,
4594
- rootNodeId: childRootNodeId,
4595
- role: "assistant",
4596
- text: "Retry in progress.",
4597
- ordinal: 200,
4598
- now,
4599
- });
4600
- }
4624
4625
const task = {
4626
id: nodeId,
@@ -4665,55 +4688,125 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4688
});
4689
}
4690
4668
- let transcriptAnswerDigest = restarted ? undefined : previous?.transcriptAnswerDigest;
4669
- let transcript: ReadonlyArray<string> = [];
4670
- if (settled || readLiveTranscript) {
4671
- transcript =
4672
- readTranscript || readLiveTranscript
4673
- ? yield* readWorkflowAgentAnswers({
4674
- transcriptDir,
4675
- agentId,
4676
- ...(adapterOptions.environment.CLAUDE_CONFIG_DIR === undefined
4677
- ? {}
4678
- : {
4679
- configDir: path.resolve(
4680
- session.cwd,
4681
- adapterOptions.environment.CLAUDE_CONFIG_DIR,
4682
- ),
4683
- }),
4684
- }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))
4685
- : [];
4686
- const transcriptAnswer = transcript.length > 0 ? transcript.join("\n\n") : undefined;
4687
- const answerDigest =
4688
- transcriptAnswer === undefined
4689
- ? undefined
4690
- : yield* sha256Hex(crypto, transcriptAnswer);
4691
- if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
4692
- return;
4693
- const previousDigest = transcriptAnswerDigest;
4694
- if (answerDigest !== undefined) transcriptAnswerDigest = answerDigest;
4695
- const answer =
4696
- transcriptAnswer ??
4697
- (!settled
4698
- ? undefined
4699
- : member.result !== undefined && changed && previousDigest === undefined
4700
- ? `Partial answer from workflow progress:\n\n${member.result}`
4701
- : attempt > 1 && changed && previousDigest === undefined
4702
- ? "No answer from this workflow attempt."
4703
- : undefined);
4691
+ const toolCalls = previous?.toolCalls ?? new Map<string, ActiveClaudeToolCall>();
4692
+ let nextItemOrdinal = previous?.nextItemOrdinal ?? 100;
4693
+ const target: ClaudeSubagentProjectionTarget = {
4694
+ childThreadId,
4695
+ childRootNodeId,
4696
+ nextOrdinal: () => ++nextItemOrdinal,
4697
+ toolCalls,
4698
+ };
4699
+ const endOpenToolCalls = Effect.fnUntraced(function* () {
4700
+ if (toolCalls.size === 0) return;
4701
+ yield* endToolCalls({
4702
+ context: null,
4703
+ toolCalls: [...toolCalls.values()],
4704
+ status: "interrupted",
4705
+ completedAt: now,
4706
+ });
4707
+ toolCalls.clear();
4708
+ });
4709
+ if (restarted) yield* endOpenToolCalls();
4710
+ // A retry may rewrite the transcript in place, past the old cursor;
4711
+ // re-reading from 0 re-emits only items already shown.
4712
+ let transcriptCursor =
4713
+ previous === undefined || restarted || previous.agentId !== agentId
4714
+ ? initialWorkflowAgentTranscriptCursor
4715
+ : previous.transcriptCursor;
4716
+ let textShown = !restarted && previous?.textShown === true;
4717
+ let resultShown = !restarted && previous?.resultShown === true;
4718
+ let turnEnded = !restarted && previous?.turnEnded === true;
4719
+ let transcriptRead = false;
4720
+ let lastReadAt = now;
4721
+ // Text before a tool call is not the reply, so wait for the turn's end.
4722
+ const awaitingReply = () => settled && transcriptRead && !turnEnded && !resultShown;
4723
+ // Milliseconds until a read started at `at` sees every line the
4724
+ // member wrote before it settled.
4725
+ const flushWindowLeft = (at: DateTime.Utc) =>
4726
+ completedAt === null
4727
+ ? 0
4728
+ : WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS -
4729
+ (DateTime.toEpochMillis(at) - DateTime.toEpochMillis(completedAt));
4730
+ // Each read is capped, so keep reading until the transcript has no
4731
+ // more complete lines; a settled member's answer may be past the cap.
4732
+ let transcriptDrained = true;
4733
+ if (
4734
+ (readTranscript || readLiveTranscript) &&
4735
+ transcriptDir !== undefined &&
4736
+ agentId !== undefined
4737
+ ) {
4738
+ const readNext = (cursor: WorkflowAgentTranscriptCursor) =>
4739
+ readWorkflowAgentTranscript({
4740
+ transcriptDir,
4741
+ agentId,
4742
+ cursor,
4743
+ ...(adapterOptions.environment.CLAUDE_CONFIG_DIR === undefined
4744
+ ? {}
4745
+ : {
4746
+ configDir: path.resolve(
4747
+ session.cwd,
4748
+ adapterOptions.environment.CLAUDE_CONFIG_DIR,
4749
+ ),
4750
+ }),
4751
+ }).pipe(Effect.option);
4752
+ // False once the coordinator was replaced mid-read.
4753
+ const drain = Effect.fnUntraced(function* () {
4754
+ lastReadAt = yield* DateTime.now;
4755
+ transcriptDrained = false;
4756
+ while (!transcriptDrained) {
4757
+ const read = yield* readNext(transcriptCursor);
4758
+ if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
4759
+ return false;
4760
+ if (Option.isNone(read)) break;
4761
+ transcriptRead = true;
4762
+ const advanced = read.value.cursor.offset !== transcriptCursor.offset;
4763
+ transcriptCursor = read.value.cursor;
4764
+ for (const line of read.value.lines) {
4765
+ if (yield* projectSubagentTranscriptLine(target, line)) textShown = true;
4766
+ // A later line (a retry, or a resumed member) reopens the turn.
4767
+ turnEnded = isClaudeTranscriptTurnEnd(line);
4768
+ }
4769
+ // A line longer than the cap can't advance; stop rather than spin.
4770
+ transcriptDrained = !read.value.truncated || !advanced;
4771
+ }
4772
+ return true;
4773
+ });
4774
+ if (!(yield* drain())) return;
4775
+ // The coordinator sends nothing after its last frame, so wait out
4776
+ // the flush window here rather than settle on the excerpt.
4777
+ const waitLeft = flushWindowLeft(lastReadAt);
4778
+ if (
4779
+ input.coordinator.task.status !== "running" &&
4780
+ awaitingReply() &&
4781
+ member.result !== undefined &&
4782
+ waitLeft > 0
4783
+ ) {
4784
+ yield* Effect.sleep(waitLeft);
4785
+ if (!(yield* drain())) return;
4786
+ }
4787
+ }
4788
+ if (settled) {
4789
+ // As for an ordinary subagent, a call still open once the member
4790
+ // settles will never get its result.
4791
+ yield* endOpenToolCalls();
4792
+ // Only the progress excerpt is left when the transcript says
4793
+ // nothing, read after its last writes had time to land.
4794
if (
4705
- answer !== undefined &&
4706
- (transcriptAnswer === undefined || restarted || answerDigest !== previousDigest)
4795
+ !textShown &&
4796
+ !resultShown &&
4797
+ member.result !== undefined &&
4798
+ (!transcriptRead || flushWindowLeft(lastReadAt) <= 0)
4799
) {
4800
yield* emitSubagentConversationMessage({
4709
- nativeItemId: `${memberKey}:answer:200`,
4801
+ nativeItemId: `${memberKey}:result:${attempt}`,
4802
threadId: childThreadId,
4803
rootNodeId: childRootNodeId,
4804
role: "assistant",
4713
- text: answer,
4714
- ordinal: 200,
4805
+ text: `Partial answer from workflow progress:\n\n${member.result}`,
4806
+ ordinal: target.nextOrdinal(),
4807
now,
4808
});
4809
+ resultShown = true;
4810
}
4811
}
4812
@@ -4721,20 +4814,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4814
new Map(current).set(memberKey, {
4815
status,
4816
attempt,
4817
+ agentId,
4818
result: member.result,
4819
label: member.label,
4820
prompt,
4821
model,
4728
- transcriptAnswerDigest,
4822
transcriptReadAttempts:
4823
(restarted ? 0 : (previous?.transcriptReadAttempts ?? 0)) +
4824
(readTranscript ? 1 : 0),
4732
- liveTranscriptReadAt: readLiveTranscript || restarted ? now : liveTranscriptReadAt,
4825
finalTranscriptRead:
4826
(!restarted && previous?.finalTranscriptRead === true) ||
4827
(readTranscript &&
4736
- transcript.length > 0 &&
4828
+ transcriptRead &&
4829
+ transcriptDrained &&
4830
+ textShown &&
4831
input.coordinator.task.status !== "running"),
4832
+ transcriptCursor,
4833
+ nextItemOrdinal,
4834
+ toolCalls,
4835
+ textShown,
4836
+ turnEnded,
4837
+ resultShown,
4838
createdAt,
4839
startedAt,
4840
completedAt,
@@ -5379,56 +5479,259 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5479
);
5480
return presented;
5481
}
5382
- const startedAt = yield* DateTime.now;
5383
- const classification = classifyClaudeNativeTool(input.toolName);
5482
const subagent =
5483
input.parentToolUseId === null
5484
? undefined
5485
: yield* resolveSubagentByToolUseId(input.context, input.parentToolUseId);
5388
- const threadId = subagent?.childThreadId ?? input.context.input.threadId;
5389
- const runId = subagent === undefined ? input.context.input.runId : null;
5390
- const rootNodeId = subagent?.childRootNodeId ?? input.context.input.rootNodeId;
5391
- const parentNodeId = rootNodeId;
5392
- const ordinal =
5393
- subagent === undefined
5394
- ? yield* resolveItemOrdinal(input.context, input.nativeItemId)
5395
- : ++subagent.nextChildItemOrdinal;
5486
+ const call = {
5487
+ nativeItemId: input.nativeItemId,
5488
+ toolName: input.toolName,
5489
+ toolInput: input.toolInput,
5490
+ presentation: input.presentation,
5491
+ startedAt: yield* DateTime.now,
5492
+ };
5493
+ if (subagent !== undefined) {
5494
+ return yield* startSubagentToolCall(subagentProjectionTarget(subagent), call);
5495
+ }
5496
+ return yield* startToolCall({
5497
+ ...call,
5498
+ context: input.context,
5499
+ threadId: input.context.input.threadId,
5500
+ runId: input.context.input.runId,
5501
+ rootNodeId: input.context.input.rootNodeId,
5502
+ ordinal: yield* resolveItemOrdinal(input.context, input.nativeItemId),
5503
+ registry: input.context.toolCalls,
5504
+ });
5505
+ });
5506
+
5507
+ const startToolCall = Effect.fnUntraced(function* (input: {
5508
+ readonly context: ActiveClaudeTurnContext | null;
5509
+ readonly nativeItemId: string;
5510
+ readonly toolName: string;
5511
+ readonly toolInput: ClaudeNativeToolInput;
5512
+ readonly presentation: ClaudeToolPresentation | undefined;
5513
+ readonly threadId: ThreadId;
5514
+ readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null;
5515
+ readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
5516
+ readonly ordinal: number;
5517
+ readonly startedAt: DateTime.Utc;
5518
+ readonly registry: Map<string, ActiveClaudeToolCall>;
5519
+ }) {
5520
const toolCall: ActiveClaudeToolCall = {
5521
nativeItemId: input.nativeItemId,
5522
toolName: input.toolName,
5399
- classification,
5523
+ classification: classifyClaudeNativeTool(input.toolName),
5524
input: input.toolInput,
5401
- threadId,
5402
- runId,
5403
- rootNodeId,
5404
- parentNodeId,
5405
- ordinal,
5406
- startedAt,
5525
+ threadId: input.threadId,
5526
+ runId: input.runId,
5527
+ rootNodeId: input.rootNodeId,
5528
+ parentNodeId: input.rootNodeId,
5529
+ ordinal: input.ordinal,
5530
+ startedAt: input.startedAt,
5531
...(input.presentation === undefined ? {} : { presentation: input.presentation }),
5532
};
5409
- toolCallsFor(input.context, toolCall).set(input.nativeItemId, toolCall);
5533
+ input.registry.set(input.nativeItemId, toolCall);
5534
yield* emitToolCallArtifacts(
5535
buildToolCallArtifacts({
5536
context: input.context,
5413
- nativeItemId: input.nativeItemId,
5414
- toolName: input.toolName,
5415
- classification,
5416
- toolInput: input.toolInput,
5417
- threadId,
5418
- runId,
5419
- rootNodeId,
5420
- parentNodeId,
5421
- ordinal,
5537
+ nativeItemId: toolCall.nativeItemId,
5538
+ toolName: toolCall.toolName,
5539
+ classification: toolCall.classification,
5540
+ toolInput: toolCall.input,
5541
+ threadId: toolCall.threadId,
5542
+ runId: toolCall.runId,
5543
+ rootNodeId: toolCall.rootNodeId,
5544
+ parentNodeId: toolCall.parentNodeId,
5545
+ ordinal: toolCall.ordinal,
5546
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
5547
status: "running",
5424
- startedAt,
5425
- updatedAt: startedAt,
5548
+ startedAt: toolCall.startedAt,
5549
+ updatedAt: toolCall.startedAt,
5550
presentation: input.presentation,
5551
}),
5552
);
5553
return toolCall;
5554
});
5555
5556
+ const subagentProjectionTarget = (
5557
+ subagent: ActiveClaudeSubagent,
5558
+ ): ClaudeSubagentProjectionTarget => ({
5559
+ childThreadId: subagent.childThreadId,
5560
+ childRootNodeId: subagent.childRootNodeId,
5561
+ nextOrdinal: () => ++subagent.nextChildItemOrdinal,
5562
+ toolCalls: subagentToolCalls,
5563
+ });
5564
+
5565
+ const startSubagentToolCall = (
5566
+ target: ClaudeSubagentProjectionTarget,
5567
+ call: {
5568
+ readonly nativeItemId: string;
5569
+ readonly toolName: string;
5570
+ readonly toolInput: ClaudeNativeToolInput;
5571
+ readonly presentation: ClaudeToolPresentation | undefined;
5572
+ readonly startedAt: DateTime.Utc;
5573
+ },
5574
+ ) =>
5575
+ startToolCall({
5576
+ ...call,
5577
+ context: null,
5578
+ threadId: target.childThreadId,
5579
+ runId: null,
5580
+ rootNodeId: target.childRootNodeId,
5581
+ ordinal: target.nextOrdinal(),
5582
+ registry: target.toolCalls,
5583
+ });
5584
+
5585
+ const settleToolCall = Effect.fnUntraced(function* (input: {
5586
+ readonly context: ActiveClaudeTurnContext | null;
5587
+ readonly toolCall: ActiveClaudeToolCall;
5588
+ readonly registry: Map<string, ActiveClaudeToolCall>;
5589
+ readonly message: SDKMessage;
5590
+ readonly toolResult: ClaudeToolResultContentBlock;
5591
+ readonly output: ClaudeNativeToolOutput;
5592
+ readonly completedAt: DateTime.Utc;
5593
+ }) {
5594
+ const { toolCall } = input;
5595
+ const toolNonExecutionKind = claudeToolNonExecutionKind(
5596
+ input.message,
5597
+ input.toolResult.tool_use_id,
5598
+ );
5599
+ yield* stopTaskOutputTail(toolCall.nativeItemId);
5600
+ yield* emitToolCallArtifacts(
5601
+ buildToolCallArtifacts({
5602
+ context: input.context,
5603
+ nativeItemId: toolCall.nativeItemId,
5604
+ toolName: toolCall.toolName,
5605
+ classification: toolCall.classification,
5606
+ toolInput: toolCall.input,
5607
+ threadId: toolCall.threadId,
5608
+ runId: toolCall.runId,
5609
+ rootNodeId: toolCall.rootNodeId,
5610
+ parentNodeId: toolCall.parentNodeId,
5611
+ ordinal: toolCall.ordinal,
5612
+ output: input.output,
5613
+ status:
5614
+ toolNonExecutionKind === "cancelled"
5615
+ ? "cancelled"
5616
+ : isClaudeToolResultError(input.toolResult)
5617
+ ? "failed"
5618
+ : "completed",
5619
+ ...(toolNonExecutionKind === undefined ? {} : { toolNonExecutionKind }),
5620
+ startedAt: toolCall.startedAt,
5621
+ updatedAt: input.completedAt,
5622
+ presentation: toolCall.presentation,
5623
+ }),
5624
+ );
5625
+ input.registry.delete(toolCall.nativeItemId);
5626
+ });
5627
+
5628
+ const emitSubagentThinking = Effect.fnUntraced(function* (
5629
+ target: ClaudeSubagentProjectionTarget,
5630
+ message: SDKAssistantMessage,
5631
+ at: DateTime.Utc,
5632
+ ) {
5633
+ const thinking = message.message.content.flatMap((block) =>
5634
+ block.type === "thinking" && block.thinking.trim().length > 0 ? [block.thinking] : [],
5635
+ );
5636
+ for (const [index, text] of thinking.entries()) {
5637
+ const nativeItemId = `${message.uuid}:thinking:${index}`;
5638
+ yield* emitProviderEvent({
5639
+ type: "turn_item.updated",
5640
+ driver: CLAUDE_PROVIDER,
5641
+ turnItem: {
5642
+ id: idAllocator.derive.turnItemFromProviderItem({
5643
+ driver: CLAUDE_PROVIDER,
5644
+ nativeItemId,
5645
+ }),
5646
+ threadId: target.childThreadId,
5647
+ runId: null,
5648
+ nodeId: target.childRootNodeId,
5649
+ providerThreadId: null,
5650
+ providerTurnId: null,
5651
+ nativeItemRef: {
5652
+ driver: CLAUDE_PROVIDER,
5653
+ nativeId: nativeItemId,
5654
+ strength: "strong",
5655
+ },
5656
+ parentItemId: null,
5657
+ ordinal: target.nextOrdinal(),
5658
+ type: "reasoning",
5659
+ title: "Thinking",
5660
+ text,
5661
+ streaming: false,
5662
+ status: "completed",
5663
+ startedAt: at,
5664
+ completedAt: at,
5665
+ updatedAt: at,
5666
+ },
5667
+ });
5668
+ }
5669
+ });
5670
+
5671
+ /**
5672
+ * Projects one transcript line of a subagent whose messages the CLI
5673
+ * does not forward (a workflow member) the way a forwarded frame with
5674
+ * its parent_tool_use_id is projected. Returns whether it carried text.
5675
+ */
5676
+ const projectSubagentTranscriptLine = Effect.fnUntraced(function* (
5677
+ target: ClaudeSubagentProjectionTarget,
5678
+ line: unknown,
5679
+ ) {
5680
+ if (!isClaudeTranscriptConversationLine(line)) return false;
5681
+ const at =
5682
+ Option.getOrUndefined(DateTime.make(text(field(line, "timestamp")) ?? "")) ??
5683
+ (yield* DateTime.now);
5684
+ const presentations = claudeToolPresentationsFromAssistantMessage(line);
5685
+ for (const toolUse of claudeToolUseBlocksFromAssistantMessage(line)) {
5686
+ if (target.toolCalls.has(toolUse.id)) continue;
5687
+ yield* startSubagentToolCall(target, {
5688
+ nativeItemId: toolUse.id,
5689
+ toolName: toolUse.name,
5690
+ toolInput: claudeNativeToolInputFromUnknown(toolUse.input),
5691
+ presentation:
5692
+ presentations.get(toolUse.id) ??
5693
+ mcpToolPresentation({
5694
+ toolName: toolUse.name.replace(/^mcp__claude_ai_/u, "mcp__"),
5695
+ }),
5696
+ startedAt: at,
5697
+ });
5698
+ }
5699
+ for (const { toolResult, output } of claudeToolResultEntriesFromMessage(line)) {
5700
+ const toolCall =
5701
+ target.toolCalls.get(toolResult.tool_use_id) ??
5702
+ (yield* startSubagentToolCall(target, {
5703
+ nativeItemId: toolResult.tool_use_id,
5704
+ toolName: toolNameFromClaudeToolResult(toolResult),
5705
+ toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,
5706
+ presentation: undefined,
5707
+ startedAt: at,
5708
+ }));
5709
+ yield* settleToolCall({
5710
+ context: null,
5711
+ toolCall,
5712
+ registry: target.toolCalls,
5713
+ message: line,
5714
+ toolResult,
5715
+ output,
5716
+ completedAt: at,
5717
+ });
5718
+ }
5719
+ if (line.type !== "assistant") return false;
5720
+ yield* emitSubagentThinking(target, line, at);
5721
+ const assistantText = textFromClaudeContent(line.message.content);
5722
+ if (assistantText.length === 0) return false;
5723
+ yield* emitSubagentConversationMessage({
5724
+ nativeItemId: line.uuid,
5725
+ threadId: target.childThreadId,
5726
+ rootNodeId: target.childRootNodeId,
5727
+ role: "assistant",
5728
+ text: assistantText,
5729
+ ordinal: target.nextOrdinal(),
5730
+ now: at,
5731
+ });
5732
+ return true;
5733
+ });
5734
+
5735
const buildApprovalRequestArtifacts = Effect.fnUntraced(function* (input: {
5736
readonly context: ActiveClaudeTurnContext;
5737
readonly nativeItemId: string;
@@ -5585,7 +5888,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5888
});
5889
5890
const endToolCalls = Effect.fnUntraced(function* (input: {
5588
- readonly context: ActiveClaudeTurnContext;
5891
+ readonly context: ActiveClaudeTurnContext | null;
5892
readonly toolCalls: ReadonlyArray<ActiveClaudeToolCall>;
5893
readonly status: Extract<
5894
OrchestrationV2ProviderTurn["status"],
@@ -7266,37 +7569,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7569
toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,
7570
parentToolUseId,
7571
}));
7269
- const completedAt = yield* DateTime.now;
7270
- const toolNonExecutionKind = claudeToolNonExecutionKind(
7271
- message,
7272
- toolResult.tool_use_id,
7273
- );
7274
- const artifacts = buildToolCallArtifacts({
7572
+ yield* settleToolCall({
7573
context,
7276
- nativeItemId: toolCall.nativeItemId,
7277
- toolName: toolCall.toolName,
7278
- classification: toolCall.classification,
7279
- toolInput: toolCall.input,
7280
- threadId: toolCall.threadId,
7281
- runId: toolCall.runId,
7282
- rootNodeId: toolCall.rootNodeId,
7283
- parentNodeId: toolCall.parentNodeId,
7284
- ordinal: toolCall.ordinal,
7574
+ toolCall,
7575
+ registry: toolCallsFor(context, toolCall),
7576
+ message,
7577
+ toolResult,
7578
output,
7286
- status:
7287
- toolNonExecutionKind === "cancelled"
7288
- ? "cancelled"
7289
- : isClaudeToolResultError(toolResult)
7290
- ? "failed"
7291
- : "completed",
7292
- ...(toolNonExecutionKind === undefined ? {} : { toolNonExecutionKind }),
7293
- startedAt: toolCall.startedAt,
7294
- updatedAt: completedAt,
7295
- presentation: toolCall.presentation,
7579
+ completedAt: yield* DateTime.now,
7580
});
7297
- yield* stopTaskOutputTail(toolCall.nativeItemId);
7298
- yield* emitToolCallArtifacts(artifacts);
7299
- toolCallsFor(context, toolCall).delete(toolCall.nativeItemId);
7581
if (parentToolUseId === null && !isClaudeToolResultError(toolResult)) {
7582
const taskLists = yield* Ref.get(taskListsByNativeThread);
7583
const taskList = applyClaudeTaskTool(
@@ -7330,40 +7611,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7611
? undefined
7612
: yield* resolveSubagentByToolUseId(context, assistantParentToolUseId);
7613
if (subagent !== undefined) {
7333
- const now = yield* DateTime.now;
7334
- for (const [index, text] of thinking.entries()) {
7335
- const nativeItemId = `${message.uuid}:thinking:${index}`;
7336
- yield* emitProviderEvent({
7337
- type: "turn_item.updated",
7338
- driver: CLAUDE_PROVIDER,
7339
- turnItem: {
7340
- id: idAllocator.derive.turnItemFromProviderItem({
7341
- driver: CLAUDE_PROVIDER,
7342
- nativeItemId,
7343
- }),
7344
- threadId: subagent.childThreadId,
7345
- runId: null,
7346
- nodeId: subagent.childRootNodeId,
7347
- providerThreadId: null,
7348
- providerTurnId: null,
7349
- nativeItemRef: {
7350
- driver: CLAUDE_PROVIDER,
7351
- nativeId: nativeItemId,
7352
- strength: "strong",
7353
- },
7354
- parentItemId: null,
7355
- ordinal: ++subagent.nextChildItemOrdinal,
7356
- type: "reasoning",
7357
- title: "Thinking",
7358
- text,
7359
- streaming: false,
7360
- status: "completed",
7361
- startedAt: now,
7362
- completedAt: now,
7363
- updatedAt: now,
7364
- },
7365
- });
7366
- }
7614
+ yield* emitSubagentThinking(
7615
+ subagentProjectionTarget(subagent),
7616
+ message,
7617
+ yield* DateTime.now,
7618
+ );
7619
}
7620
}
7621
const assistantText = assistantTextFromSdkMessage(message);
apps/server/src/orchestration-v2/workflowAgentAnswers.test.ts
deleted
-117
@@ -1,117 +0,0 @@
1
-// @effect-diagnostics nodeBuiltinImport:off
2
-import * as NodeFS from "node:fs";
3
-import * as NodeOS from "node:os";
4
-import * as NodePath from "node:path";
5
-import { it as effectIt } from "@effect/vitest";
6
-import * as Effect from "effect/Effect";
7
-import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
8
-
9
-import { parseWorkflowAgentAnswers, readWorkflowAgentAnswers } from "./workflowAgentAnswers.ts";
10
-
11
-const line = (value: unknown) => `${JSON.stringify(value)}\n`;
12
-
13
-const assistant = (id: string, content: ReadonlyArray<unknown>) =>
14
- line({ type: "assistant", message: { role: "assistant", id, content } });
15
-
16
-describe("parseWorkflowAgentAnswers", () => {
17
- it("returns one entry per assistant turn", () => {
18
- expect(
19
- parseWorkflowAgentAnswers(
20
- assistant("a", [{ type: "text", text: "first" }]) +
21
- assistant("b", [{ type: "text", text: "second" }]),
22
- ),
23
- ).toEqual(["first", "second"]);
24
- });
25
-
26
- it("joins the lines of one split assistant message into a single turn", () => {
27
- expect(
28
- parseWorkflowAgentAnswers(
29
- assistant("a", [{ type: "thinking", thinking: "weighing it up" }]) +
30
- assistant("a", [{ type: "text", text: "the answer" }]) +
31
- assistant("a", [{ type: "text", text: "and more" }]),
32
- ),
33
- ).toEqual(["the answer\n\nand more"]);
34
- });
35
-
36
- it("ignores harness bookkeeping and the member's own prompt", () => {
37
- expect(
38
- parseWorkflowAgentAnswers(
39
- line({ type: "attachment", attachment: { type: "skill_listing", content: "- adhd" } }) +
40
- line({ type: "user", message: { role: "user", content: "the prompt" } }) +
41
- line({
42
- type: "assistant",
43
- isMeta: true,
44
- message: { role: "assistant", id: "m", content: [{ type: "text", text: "injected" }] },
45
- }) +
46
- assistant("a", [{ type: "text", text: "real answer" }]),
47
- ),
48
- ).toEqual(["real answer"]);
49
- });
50
-
51
- it("skips a turn that produced no text", () => {
52
- expect(
53
- parseWorkflowAgentAnswers(
54
- assistant("a", [{ type: "tool_use", id: "t", name: "Bash", input: {} }]),
55
- ),
56
- ).toEqual([]);
57
- });
58
-
59
- it("preserves answer indentation and ignores blank text", () => {
60
- expect(
61
- parseWorkflowAgentAnswers(
62
- assistant("a", [{ type: "text", text: " indented code" }]) +
63
- assistant("b", [{ type: "text", text: " " }]),
64
- ),
65
- ).toEqual([" indented code"]);
66
- });
67
-
68
- it("survives a trailing line the byte cap cut in half", () => {
69
- expect(
70
- parseWorkflowAgentAnswers(
71
- assistant("a", [{ type: "text", text: "complete" }]) + '{"type":"assistant","mess',
72
- ),
73
- ).toEqual(["complete"]);
74
- });
75
-});
76
-
77
-let configDir: string;
78
-let transcriptDir: string;
79
-beforeAll(() => {
80
- configDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "wf-config-"));
81
- transcriptDir = NodePath.join(configDir, "projects", "test");
82
- NodeFS.mkdirSync(transcriptDir, { recursive: true });
83
-});
84
-
85
-afterAll(() => {
86
- NodeFS.rmSync(configDir, { recursive: true, force: true });
87
-});
88
-
89
-describe("readWorkflowAgentAnswers", () => {
90
- effectIt.effect("reads final answers from both small and capped transcripts", () =>
91
- Effect.gen(function* () {
92
- const turn = assistant("a", [{ type: "text", text: "the answer" }]);
93
- const filler = line({ type: "user", message: { role: "user", content: "x".repeat(4096) } });
94
- const write = (agentId: string, contents: string) =>
95
- NodeFS.writeFileSync(NodePath.join(transcriptDir, `agent-${agentId}.jsonl`), contents);
96
- const read = (agentId: string) =>
97
- readWorkflowAgentAnswers({ transcriptDir, agentId, configDir });
98
- write("small", turn);
99
- const edgeAnswer = "x".repeat(
100
- 512 * 1024 + 1 - Buffer.byteLength(assistant("edge", [{ type: "text", text: "" }])),
101
- );
102
- write("edge", assistant("edge", [{ type: "text", text: edgeAnswer }]));
103
- write(
104
- "boundary",
105
- filler.repeat(160) + turn + " ".repeat(512 * 1024 - Buffer.byteLength(turn)),
106
- );
107
- write(
108
- "huge",
109
- turn + filler.repeat(160) + assistant("final", [{ type: "text", text: "final answer" }]),
110
- );
111
- expect(yield* read("small")).toEqual(["the answer"]);
112
- expect(yield* read("edge")).toEqual([edgeAnswer]);
113
- expect(yield* read("huge")).toEqual(["final answer"]);
114
- expect(yield* read("boundary")).toEqual(["the answer"]);
115
- }),
116
- );
117
-});
apps/server/src/orchestration-v2/workflowAgentAnswers.ts
deleted
-91
@@ -1,91 +0,0 @@
1
-// @effect-diagnostics nodeBuiltinImport:off
2
-/**
3
- * A member agent never becomes a provider task and emits nothing on the event
4
- * stream, so the transcript the harness writes is the only full record of its
5
- * turn — the progress snapshot carries a capped excerpt. The path is derived
6
- * here from the run's transcript directory and the member's provider id rather
7
- * than accepted from the caller, and the read itself is contained by
8
- * readContainedWorkflowFile.
9
- */
10
-import * as NodePath from "node:path";
11
-
12
-import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
13
-import * as Effect from "effect/Effect";
14
-
15
-import { field, text } from "./unknownField.ts";
16
-import { readContainedWorkflowFile } from "./workflowFileRead.ts";
17
-
18
-const TRANSCRIPT_BYTE_CAP = 512 * 1024;
19
-
20
-const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
21
-
22
-/**
23
- * Two shapes have to be handled: `attachment` lines and `isMeta` user lines are
24
- * harness bookkeeping (hook output, skill listings, injected context) and are
25
- * never conversation, and one assistant API message is split across several
26
- * lines sharing a `message.id`, so those are joined into a single turn rather
27
- * than read as separate ones.
28
- */
29
-export function parseWorkflowAgentAnswers(contents: string): ReadonlyArray<string> {
30
- const turns: string[] = [];
31
- const turnIndexById = new Map<string, number>();
32
-
33
- for (const line of contents.split("\n")) {
34
- if (line.trim().length === 0) continue;
35
- let entry: unknown;
36
- try {
37
- entry = JSON.parse(line);
38
- } catch {
39
- // A capped read can cut the final line mid-object; drop it and keep the rest.
40
- continue;
41
- }
42
- if (text(field(entry, "type")) !== "assistant") continue;
43
- if (field(entry, "isMeta") === true) continue;
44
-
45
- const message = field(entry, "message");
46
- const content = field(message, "content");
47
- if (!Array.isArray(content)) continue;
48
- const body = content
49
- .filter((block) => text(field(block, "type")) === "text")
50
- .map((block) => field(block, "text"))
51
- .filter((value): value is string => typeof value === "string" && value.trim().length > 0)
52
- .join("\n\n");
53
- if (body.length === 0) continue;
54
-
55
- const messageId = text(field(message, "id"));
56
- const existing = messageId === undefined ? undefined : turnIndexById.get(messageId);
57
- if (existing !== undefined) {
58
- turns[existing] = `${turns[existing]}\n\n${body}`;
59
- continue;
60
- }
61
- if (messageId !== undefined) turnIndexById.set(messageId, turns.length);
62
- turns.push(body);
63
- }
64
-
65
- return turns;
66
-}
67
-
68
-export const readWorkflowAgentAnswers = Effect.fn("orchestration.readWorkflowAgentAnswers")(
69
- function* (input: {
70
- readonly transcriptDir: string;
71
- readonly agentId: string;
72
- readonly configDir?: string;
73
- }) {
74
- if (!AGENT_ID_PATTERN.test(input.agentId)) {
75
- return yield* new OrchestrationWorkflowFileError({
76
- reason: "invalid-path",
77
- path: input.agentId,
78
- });
79
- }
80
- const file = yield* readContainedWorkflowFile({
81
- path: NodePath.join(input.transcriptDir, `agent-${input.agentId}.jsonl`),
82
- extension: ".jsonl",
83
- byteCap: TRANSCRIPT_BYTE_CAP,
84
- tail: true,
85
- ...(input.configDir === undefined ? {} : { configDir: input.configDir }),
86
- });
87
- return parseWorkflowAgentAnswers(
88
- file.truncated ? file.contents.slice(file.contents.indexOf("\n") + 1) : file.contents,
89
- );
90
- },
91
-);
apps/server/src/orchestration-v2/workflowAgentTranscript.test.ts
new
+65
@@ -0,0 +1,65 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+import * as NodeFS from "node:fs";
3
+import * as NodePath from "node:path";
4
+import * as NodeServices from "@effect/platform-node/NodeServices";
5
+import { it } from "@effect/vitest";
6
+import * as Effect from "effect/Effect";
7
+import * as FileSystem from "effect/FileSystem";
8
+import { assert } from "vite-plus/test";
9
+
10
+import {
11
+ initialWorkflowAgentTranscriptCursor,
12
+ readWorkflowAgentTranscript,
13
+} from "./workflowAgentTranscript.ts";
14
+
15
+const line = (value: unknown) => `${JSON.stringify(value)}\n`;
16
+const assistant = (uuid: string, text: string) =>
17
+ line({
18
+ type: "assistant",
19
+ uuid,
20
+ message: { role: "assistant", id: uuid, content: [{ type: "text", text }] },
21
+ });
22
+const uuids = (lines: ReadonlyArray<unknown>) =>
23
+ lines.map((entry) => (entry as { readonly uuid: string }).uuid);
24
+
25
+it.layer(NodeServices.layer)("readWorkflowAgentTranscript", (it) => {
26
+ it.effect("reads complete lines from its cursor and starts over on a new file", () =>
27
+ Effect.gen(function* () {
28
+ const fileSystem = yield* FileSystem.FileSystem;
29
+ const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "wf-transcript-" });
30
+ const transcriptDir = NodePath.join(configDir, "projects", "test");
31
+ yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
32
+ const file = NodePath.join(transcriptDir, "agent-a1.jsonl");
33
+ const read = (cursor = initialWorkflowAgentTranscriptCursor) =>
34
+ readWorkflowAgentTranscript({ transcriptDir, agentId: "a1", cursor, configDir });
35
+
36
+ const bookkeeping =
37
+ line({ type: "attachment", uuid: "att", attachment: { type: "skill_listing" } }) +
38
+ line({ type: "user", uuid: "meta", isMeta: true, message: { content: "context" } });
39
+ const second = assistant("b", "second");
40
+ NodeFS.writeFileSync(file, bookkeeping + assistant("a", "first") + second.slice(0, 20));
41
+ const first = yield* read();
42
+ assert.deepEqual(uuids(first.lines), ["a"]);
43
+ assert.equal(
44
+ first.cursor.offset,
45
+ Buffer.byteLength(bookkeeping + assistant("a", "first")),
46
+ "a half-written line is left for the next read",
47
+ );
48
+
49
+ NodeFS.appendFileSync(file, second.slice(20));
50
+ const next = yield* read(first.cursor);
51
+ assert.deepEqual(uuids(next.lines), ["b"]);
52
+ assert.equal(next.cursor.offset, NodeFS.statSync(file).size);
53
+
54
+ NodeFS.rmSync(file);
55
+ NodeFS.writeFileSync(file, assistant("c", "replaced"));
56
+ const replaced = yield* read(next.cursor);
57
+ assert.deepEqual(uuids(replaced.lines), ["c"], "a new inode reads from 0");
58
+
59
+ NodeFS.writeFileSync(file, assistant("d", "x"));
60
+ assert.equal(NodeFS.statSync(file).ino, replaced.cursor.identity?.ino);
61
+ const shrunk = yield* read(replaced.cursor);
62
+ assert.deepEqual(uuids(shrunk.lines), ["d"], "a shrunk file reads from 0");
63
+ }).pipe(Effect.scoped),
64
+ );
65
+});
apps/server/src/orchestration-v2/workflowAgentTranscript.ts
new
+99
@@ -0,0 +1,99 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+/**
3
+ * A workflow member never becomes a provider task and the CLI forwards none of
4
+ * its messages, so the transcript the harness writes is the only record of its
5
+ * conversation. The path is derived here from the run's transcript directory
6
+ * and the member's provider id rather than accepted from the caller, and the
7
+ * read itself is contained by readContainedWorkflowFile.
8
+ */
9
+import * as NodePath from "node:path";
10
+
11
+import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
12
+import * as Context from "effect/Context";
13
+import * as Effect from "effect/Effect";
14
+import * as Option from "effect/Option";
15
+import * as Schema from "effect/Schema";
16
+
17
+import { field, text } from "./unknownField.ts";
18
+import { readContainedWorkflowFile, type WorkflowFileIdentity } from "./workflowFileRead.ts";
19
+
20
+const TRANSCRIPT_READ_BYTE_CAP = 512 * 1024;
21
+
22
+const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
23
+
24
+const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
25
+
26
+export interface WorkflowAgentTranscriptCursor {
27
+ readonly offset: number;
28
+ readonly identity: WorkflowFileIdentity | null;
29
+}
30
+
31
+export const initialWorkflowAgentTranscriptCursor: WorkflowAgentTranscriptCursor = {
32
+ offset: 0,
33
+ identity: null,
34
+};
35
+
36
+/** Sees every transcript read: where it started and ended, and how many lines it kept. */
37
+export const WorkflowAgentTranscriptReadObserver = Context.Reference<
38
+ (read: {
39
+ readonly agentId: string;
40
+ readonly startOffset: number;
41
+ readonly endOffset: number;
42
+ readonly lineCount: number;
43
+ }) => Effect.Effect<void>
44
+>("t3/orchestration/WorkflowAgentTranscriptReadObserver", {
45
+ defaultValue: () => () => Effect.void,
46
+});
47
+
48
+/**
49
+ * Conversation lines only: `attachment` lines and `isMeta` user lines are
50
+ * harness bookkeeping (hook output, skill listings, injected context), and a
51
+ * line without a uuid cannot be projected idempotently.
52
+ */
53
+function parseWorkflowAgentTranscriptLines(contents: string): ReadonlyArray<unknown> {
54
+ return contents.split("\n").flatMap((line) => {
55
+ if (line.trim().length === 0) return [];
56
+ const entry = Option.getOrUndefined(decodeJsonLine(line));
57
+ const type = text(field(entry, "type"));
58
+ if (type !== "assistant" && type !== "user") return [];
59
+ if (field(entry, "isMeta") === true || text(field(entry, "uuid")) === undefined) return [];
60
+ return [entry];
61
+ });
62
+}
63
+
64
+/** Reads the complete lines written since `cursor`, and the cursor after them. */
65
+export const readWorkflowAgentTranscript = Effect.fn("orchestration.readWorkflowAgentTranscript")(
66
+ function* (input: {
67
+ readonly transcriptDir: string;
68
+ readonly agentId: string;
69
+ readonly cursor: WorkflowAgentTranscriptCursor;
70
+ readonly configDir?: string;
71
+ }) {
72
+ if (!AGENT_ID_PATTERN.test(input.agentId)) {
73
+ return yield* new OrchestrationWorkflowFileError({
74
+ reason: "invalid-path",
75
+ path: input.agentId,
76
+ });
77
+ }
78
+ const file = yield* readContainedWorkflowFile({
79
+ path: NodePath.join(input.transcriptDir, `agent-${input.agentId}.jsonl`),
80
+ extension: ".jsonl",
81
+ byteCap: TRANSCRIPT_READ_BYTE_CAP,
82
+ fromOffset: input.cursor,
83
+ ...(input.configDir === undefined ? {} : { configDir: input.configDir }),
84
+ });
85
+ const lines = parseWorkflowAgentTranscriptLines(file.contents);
86
+ yield* (yield* WorkflowAgentTranscriptReadObserver)({
87
+ agentId: input.agentId,
88
+ startOffset: file.startOffset,
89
+ endOffset: file.endOffset,
90
+ lineCount: lines.length,
91
+ });
92
+ return {
93
+ lines,
94
+ cursor: { offset: file.endOffset, identity: file.identity },
95
+ // More complete lines may follow past the per-read cap.
96
+ truncated: file.truncated,
97
+ };
98
+ },
99
+);
apps/server/src/orchestration-v2/workflowFileRead.ts
+51
-1
@@ -7,6 +7,11 @@ import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
7
import * as Effect from "effect/Effect";
8
import * as HostProcess from "@t3tools/shared/HostProcess";
9
10
+export interface WorkflowFileIdentity {
11
+ readonly dev: number;
12
+ readonly ino: number;
13
+}
14
+
15
function workflowFilesRoot(home: string, configDir?: string): string {
16
return NodePath.join(configDir?.trim() || NodePath.join(home, ".claude"), "projects");
17
}
@@ -18,6 +23,14 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedW
23
readonly byteCap: number;
24
readonly tail?: boolean;
25
readonly configDir?: string;
26
+ /**
27
+ * Read only complete lines from this byte offset of the file `identity`
28
+ * names. A different file (shrunk or another inode) is read from 0.
29
+ */
30
+ readonly fromOffset?: {
31
+ readonly offset: number;
32
+ readonly identity: WorkflowFileIdentity | null;
33
+ };
34
}) {
35
if (!NodePath.isAbsolute(input.path) || NodePath.extname(input.path) !== input.extension) {
36
return yield* new OrchestrationWorkflowFileError({
@@ -72,6 +85,33 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedW
85
if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {
86
return { failure: "changed-during-read" as const };
87
}
88
+ const identity = { dev: stat.dev, ino: stat.ino };
89
+ if (input.fromOffset !== undefined) {
90
+ const previous = input.fromOffset.identity;
91
+ const start =
92
+ previous !== null &&
93
+ previous.dev === identity.dev &&
94
+ previous.ino === identity.ino &&
95
+ input.fromOffset.offset <= stat.size
96
+ ? input.fromOffset.offset
97
+ : 0;
98
+ const buffer = Buffer.alloc(Math.min(stat.size - start, input.byteCap));
99
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
100
+ const read = buffer.subarray(0, bytesRead);
101
+ // A writer may be mid-line; leave it for the next read. A single
102
+ // line over the cap is skipped so the cursor can't stall on it.
103
+ const lineEnd = read.lastIndexOf(0x0a) + 1;
104
+ const consumed = lineEnd === 0 && bytesRead === input.byteCap ? bytesRead : lineEnd;
105
+ return {
106
+ contents: read.subarray(0, lineEnd).toString("utf8"),
107
+ // Only the cap can leave complete lines unread; a half-written
108
+ // last line is not truncation.
109
+ truncated: stat.size - start > input.byteCap,
110
+ startOffset: start,
111
+ endOffset: start + consumed,
112
+ identity,
113
+ };
114
+ }
115
const buffer = Buffer.alloc(Math.min(stat.size, input.byteCap + (input.tail ? 1 : 0)));
116
const truncated = stat.size > buffer.length;
117
const offset = input.tail ? stat.size - buffer.length : 0;
@@ -79,6 +119,9 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedW
119
return {
120
contents: buffer.subarray(0, bytesRead).toString("utf8"),
121
truncated,
122
+ startOffset: offset,
123
+ endOffset: offset + bytesRead,
124
+ identity,
125
};
126
} finally {
127
await handle.close();
@@ -91,6 +134,13 @@ export const readContainedWorkflowFile = Effect.fn("orchestration.readContainedW
134
return yield* new OrchestrationWorkflowFileError({ reason: read.failure, path: resolved });
135
}
136
94
- return { path: resolved, contents: read.contents, truncated: read.truncated };
137
+ return {
138
+ path: resolved,
139
+ contents: read.contents,
140
+ truncated: read.truncated,
141
+ startOffset: read.startOffset,
142
+ endOffset: read.endOffset,
143
+ identity: read.identity,
144
+ };
145
},
146
);