The best way to control Claude Code, Codex and more from any computer or phone
fix: command output streams live while it runs (#15094)
Co-authored-by: scratchyone <11479077+scratchyone@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Co-authored-by: maria-rcks <maria@kuuro.net>
scratchyone committed
Oct 15, 2026 at 17:14 UTC
a5d97921f6a2a310f55c481763248a313ed3dc17
48 files changed
+3287
-41
apps/mobile/src/features/threads/thread-command-output.tsx
new
+99
@@ -0,0 +1,99 @@
1
+import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2
+import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";
3
+import type React from "react";
4
+import { useMemo, useRef } from "react";
5
+import { ScrollView, View } from "react-native";
6
+
7
+import { AppText as Text } from "../../components/AppText";
8
+import { useServerConfigs } from "../../state/entities";
9
+import { orchestrationEnvironment } from "../../state/orchestration";
10
+import { useEnvironmentQuery } from "../../state/query";
11
+
12
+// Within this many points of the end still counts as following the output.
13
+const FOLLOW_SLACK = 8;
14
+
15
+/** True when the environment streams command output; older servers only return final output. */
16
+export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean {
17
+ return (
18
+ useServerConfigs().get(environmentId)?.environment.capabilities.commandOutputStreaming === true
19
+ );
20
+}
21
+
22
+/**
23
+ * Output of one expanded command row: streams while the command runs, then
24
+ * shows its final output. Mount it only when `useCommandOutputStreaming` holds.
25
+ * It subscribes only while mounted, so collapsed rows and other threads receive nothing.
26
+ */
27
+export function ThreadCommandOutput(props: {
28
+ readonly environmentId: EnvironmentId;
29
+ readonly threadId: ThreadId;
30
+ readonly itemId: TurnItemId;
31
+ readonly themeAppearance: "light" | "dark";
32
+}) {
33
+ const { data, error } = useEnvironmentQuery(
34
+ orchestrationEnvironment.v2.commandOutput({
35
+ environmentId: props.environmentId,
36
+ input: { threadId: props.threadId, itemId: props.itemId },
37
+ }),
38
+ );
39
+ const scrollRef = useRef<React.ComponentRef<typeof ScrollView>>(null);
40
+ // Follow new output until the reader scrolls up; scrolling back down resumes.
41
+ const followRef = useRef(true);
42
+ const text = data?.output.text ?? "";
43
+ const spans = useMemo(
44
+ () => terminalOutputSpans(text, TERMINAL_PALETTES[props.themeAppearance]),
45
+ [text, props.themeAppearance],
46
+ );
47
+ if (text.length === 0) {
48
+ const message = error
49
+ ? `Couldn't load output: ${error}`
50
+ : data === null
51
+ ? "Loading output…"
52
+ : data.running
53
+ ? null
54
+ : "No output.";
55
+ return message === null ? null : (
56
+ <Text className="pt-1.5 font-mono text-2xs leading-normal text-foreground-muted">
57
+ {message}
58
+ </Text>
59
+ );
60
+ }
61
+ return (
62
+ <View className="pt-1.5">
63
+ {data?.output.truncated ? (
64
+ <Text className="pb-0.5 text-3xs text-foreground-subtle">Earlier output not shown</Text>
65
+ ) : null}
66
+ <ScrollView
67
+ ref={scrollRef}
68
+ nestedScrollEnabled
69
+ directionalLockEnabled
70
+ showsVerticalScrollIndicator
71
+ className="max-h-60"
72
+ contentContainerStyle={{ paddingRight: 8 }}
73
+ scrollEventThrottle={100}
74
+ onScroll={(event) => {
75
+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
76
+ followRef.current =
77
+ contentSize.height - contentOffset.y - layoutMeasurement.height <= FOLLOW_SLACK;
78
+ }}
79
+ onContentSizeChange={() => {
80
+ if (followRef.current) scrollRef.current?.scrollToEnd({ animated: false });
81
+ }}
82
+ >
83
+ <Text selectable className="font-mono text-2xs leading-normal text-foreground-muted">
84
+ {spans.map((span, index) =>
85
+ span.style === null ? (
86
+ span.text
87
+ ) : (
88
+ // Spans are rebuilt from scratch on every update and never reorder.
89
+ // oxlint-disable-next-line react/no-array-index-key
90
+ <Text key={index} style={span.style}>
91
+ {span.text}
92
+ </Text>
93
+ ),
94
+ )}
95
+ </Text>
96
+ </ScrollView>
97
+ </View>
98
+ );
99
+}
apps/mobile/src/features/threads/thread-work-log.tsx
+39
-20
@@ -8,6 +8,7 @@ import {
8
WorkLogPressable,
9
} from "./work-log-layout";
10
import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
11
+import { ThreadCommandOutput, useCommandOutputStreaming } from "./thread-command-output";
12
import {
13
getQuestionAnswerPreview,
14
hasQuestionAnswer,
@@ -901,8 +902,12 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
902
) {
903
const { row, expanded } = props;
904
const navigation = useNavigation();
905
+ // Command rows stream their output, including the final output, from the server.
906
+ const streamsOutput =
907
+ useCommandOutputStreaming(props.environmentId) &&
908
+ row.projectedItem.item.type === "command_execution";
909
const fetchedDetail = useTurnItemDetail(
905
- expanded && row.fetchesDetail
910
+ expanded && row.fetchesDetail && !streamsOutput
911
? { environmentId: props.environmentId, row: row.projectedItem }
912
: null,
913
);
@@ -1014,20 +1019,27 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
1019
: null;
1020
const outputImages = expanded && fetchedItem ? turnItemOutputImages(fetchedItem) : [];
1021
const viewedImagePath = workEntryViewedImagePath(row.workEntry);
1017
- const fetchedOutput = !expanded
1018
- ? null
1019
- : shownItem.type === "file_search" || shownItem.type === "web_search"
1020
- ? turnItemOutputText(shownItem)
1021
- : fetchedItem
1022
- ? (turnItemOutputText(fetchedItem) ??
1023
- (outputImages.length > 0 || viewedImagePath ? null : "No output."))
1024
- : fetchedDetail.error
1025
- ? `Couldn't load output: ${fetchedDetail.error}`
1026
- : row.fetchesDetail
1027
- ? fetchedDetail.data
1028
- ? "Output is no longer available."
1029
- : "Loading output…"
1030
- : null;
1022
+ const fetchedOutput =
1023
+ !expanded || streamsOutput
1024
+ ? null
1025
+ : shownItem.type === "file_search" || shownItem.type === "web_search"
1026
+ ? turnItemOutputText(shownItem)
1027
+ : fetchedItem
1028
+ ? (turnItemOutputText(fetchedItem) ??
1029
+ (outputImages.length > 0 || viewedImagePath ? null : "No output."))
1030
+ : fetchedDetail.error
1031
+ ? `Couldn't load output: ${fetchedDetail.error}`
1032
+ : row.fetchesDetail
1033
+ ? fetchedDetail.data
1034
+ ? "Output is no longer available."
1035
+ : "Loading output…"
1036
+ : null;
1037
+ const exitLine =
1038
+ failedExitCode === null ? null : (
1039
+ <Text className="mt-1.5 font-mono text-2xs leading-normal text-danger-foreground">
1040
+ exit {failedExitCode}
1041
+ </Text>
1042
+ );
1043
const toolPresentation = resolveWorkEntryToolPresentation(row.workEntry);
1044
const previewText = workEntryRowLabel(row.workEntry);
1045
const answerPreview = row.workEntry.questionAnswer
@@ -1274,12 +1286,19 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
1286
{fetchedOutput}
1287
</Text>
1288
) : null}
1277
- {failedExitCode !== null ? (
1278
- <Text className="mt-1.5 font-mono text-2xs leading-normal text-danger-foreground">
1279
- exit {failedExitCode}
1280
- </Text>
1281
- ) : null}
1289
+ {streamsOutput ? null : exitLine}
1290
</ScrollView>
1291
+ {streamsOutput ? (
1292
+ <>
1293
+ <ThreadCommandOutput
1294
+ environmentId={props.environmentId}
1295
+ threadId={row.projectedItem.sourceThreadId}
1296
+ itemId={row.projectedItem.sourceItemId}
1297
+ themeAppearance={props.themeAppearance}
1298
+ />
1299
+ {exitLine}
1300
+ </>
1301
+ ) : null}
1302
</Animated.View>
1303
) : null}
1304
</Animated.View>
apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts
+7
@@ -52,6 +52,7 @@ import {
52
TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
53
TOOL_CALL_WRITE_PROMPT,
54
TURN_INTERRUPT_MID_TOOL_PROMPT,
55
+ COMMAND_OUTPUT_STREAMING_PROMPT,
56
TURN_INTERRUPT_PROMPT,
57
TURN_INTERRUPT_RECOVERY_PROMPT,
58
WORKSPACE_NEVER_POLICY,
@@ -115,6 +116,12 @@ const CLAUDE_RECORDINGS = {
116
queryMode: "active_steering",
117
enableTools: true,
118
},
119
+ command_output_streaming: {
120
+ prompts: [COMMAND_OUTPUT_STREAMING_PROMPT],
121
+ defaultTranscriptFile: "fixtures/command_output_streaming/claude_transcript.ndjson",
122
+ queryMode: "streaming",
123
+ enableTools: true,
124
+ },
125
turn_interrupt_mid_tool: {
126
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],
127
defaultTranscriptFile: "fixtures/turn_interrupt_mid_tool/claude_transcript.ndjson",
apps/server/scripts/record-codex-app-server-replay-fixture.ts
+25
@@ -58,6 +58,7 @@ import {
58
TODO_LIST_PROMPT,
59
TOOL_CALL_WRITE_PROMPT,
60
TURN_INTERRUPT_MID_TOOL_PROMPT,
61
+ COMMAND_OUTPUT_STREAMING_PROMPT,
62
TURN_INTERRUPT_PROMPT,
63
WEB_SEARCH_PROMPT,
64
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
@@ -98,6 +99,7 @@ const SCENARIO_NAMES = [
99
"message_steering",
100
"turn_interrupt",
101
"turn_interrupt_mid_tool",
102
+ "command_output_streaming",
103
"thread_rollback",
104
"thread_rollback_after_restart",
105
"thread_rollback_to_stopped_turn",
@@ -768,6 +770,29 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
770
},
771
],
772
},
773
+ {
774
+ name: "command_output_streaming",
775
+ fileName: "command_output_streaming.ndjson",
776
+ description: "One command prints over several seconds, so Codex streams its output deltas.",
777
+ runs: [
778
+ {
779
+ name: "command-output-streaming",
780
+ description: "Run a foreground command that prints a line a second.",
781
+ prompt: COMMAND_OUTPUT_STREAMING_PROMPT,
782
+ turnDefaults: {
783
+ approvalPolicy: "never",
784
+ sandboxPolicy: workspaceWriteSandbox(),
785
+ },
786
+ steps: [
787
+ {
788
+ type: "turn",
789
+ label: "command-output-streaming",
790
+ prompt: COMMAND_OUTPUT_STREAMING_PROMPT,
791
+ },
792
+ ],
793
+ },
794
+ ],
795
+ },
796
{
797
name: "thread_rollback",
798
fileName: "thread_rollback.ndjson",
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -59,6 +59,7 @@ export const RPC_REQUIRED_SCOPES = {
59
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope,
60
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
61
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
62
+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope,
63
[WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
64
[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
65
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -248,6 +248,7 @@ export const make = Effect.gen(function* () {
248
threadActiveReorder: true,
249
threadAutoSettleOptOut: true,
250
threadTitleRegeneration: true,
251
+ commandOutputStreaming: true,
252
threadVisitedTracking: true,
253
threadPullRequests: true,
254
threadPullRequestWatch: true,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -30,6 +30,7 @@ const RPC_AGGREGATES = {
30
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration",
31
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2",
32
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2",
33
+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2",
34
[WS_METHODS.projectsMutate]: "orchestration",
35
[WS_METHODS.serverProbe]: "server",
36
[WS_METHODS.serverGetConfig]: "server",
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+66
-8
@@ -21,7 +21,9 @@ import * as Crypto from "effect/Crypto";
21
import * as Duration from "effect/Duration";
22
import * as Effect from "effect/Effect";
23
import * as Exit from "effect/Exit";
24
+import * as FileSystem from "effect/FileSystem";
25
import * as Layer from "effect/Layer";
26
+import * as Path from "effect/Path";
27
import * as Schema from "effect/Schema";
28
import * as Stream from "effect/Stream";
29
@@ -31,6 +33,7 @@ import {
33
resolveClaudeSdkExecutablePath,
34
} from "../../provider/Drivers/ClaudeExecutable.ts";
35
import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts";
36
+import { claudeTaskOutputRoot } from "./ClaudeTaskOutputTail.ts";
37
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38
import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";
39
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
@@ -998,6 +1001,52 @@ function layerClaudeAgentSdkReplay(
1001
);
1002
}
1003
1004
+/**
1005
+ * While a foreground Bash call runs, Claude Code writes its output to a task
1006
+ * file the adapter tails. A replay has no Claude Code process, so it writes the
1007
+ * file each recorded `task_started` names, holding that call's recorded output,
1008
+ * under a scenario-owned `CLAUDE_CODE_TMPDIR`.
1009
+ */
1010
+const writeReplayTaskOutputFiles = Effect.fn("ClaudeReplay.writeTaskOutputFiles")(function* (
1011
+ transcript: ClaudeAgentSdkReplayTranscript,
1012
+) {
1013
+ const fileSystem = yield* FileSystem.FileSystem;
1014
+ const path = yield* Path.Path;
1015
+ const tmpRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-replay-tasks-" });
1016
+ const frames = transcript.entries.flatMap((entry) =>
1017
+ entry.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null
1018
+ ? [entry.frame as Record<string, unknown>]
1019
+ : [],
1020
+ );
1021
+ const outputByToolUseId = new Map<string, string>();
1022
+ for (const frame of frames) {
1023
+ const result = frame.tool_use_result as Record<string, unknown> | undefined;
1024
+ const content = (frame.message as { readonly content?: unknown } | undefined)?.content;
1025
+ if (typeof result?.stdout !== "string" || !Array.isArray(content)) continue;
1026
+ const toolResult = content.find(
1027
+ (block): block is { readonly tool_use_id: string } =>
1028
+ block?.type === "tool_result" && typeof block.tool_use_id === "string",
1029
+ );
1030
+ if (toolResult === undefined) continue;
1031
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
1032
+ outputByToolUseId.set(toolResult.tool_use_id, `${result.stdout}${stderr}`);
1033
+ }
1034
+ const root = claudeTaskOutputRoot({ CLAUDE_CODE_TMPDIR: tmpRoot }, path);
1035
+ for (const frame of frames) {
1036
+ if (frame.type !== "system" || frame.subtype !== "task_started") continue;
1037
+ if (frame.task_type !== "local_bash" || frame.is_backgrounded !== false) continue;
1038
+ const output =
1039
+ typeof frame.tool_use_id === "string" ? outputByToolUseId.get(frame.tool_use_id) : undefined;
1040
+ if (root === undefined || output === undefined || typeof frame.session_id !== "string") {
1041
+ continue;
1042
+ }
1043
+ const tasks = path.join(root, "replay-project", frame.session_id, "tasks");
1044
+ yield* fileSystem.makeDirectory(tasks, { recursive: true });
1045
+ yield* fileSystem.writeFileString(path.join(tasks, `${String(frame.task_id)}.output`), output);
1046
+ }
1047
+ return tmpRoot;
1048
+});
1049
+
1050
function layerClaudeProviderAdapterRegistryReplay(
1051
transcript: ClaudeAgentSdkReplayTranscript,
1052
options: {
@@ -1009,14 +1058,23 @@ function layerClaudeProviderAdapterRegistryReplay(
1058
ServerConfig.ServerConfig,
1059
makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
1060
).pipe(Layer.provide(NodeServices.layer));
1012
- return ProviderAdapterRegistry.layerFromDrivers({
1013
- drivers: [ClaudeAdapterV2.ClaudeAdapterV2Driver],
1014
- configMap: {
1015
- [ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID]: {
1016
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1017
- },
1018
- },
1019
- }).pipe(
1061
+ return Layer.unwrap(
1062
+ writeReplayTaskOutputFiles(transcript).pipe(
1063
+ Effect.orDie,
1064
+ Effect.map((tmpRoot) =>
1065
+ ProviderAdapterRegistry.layerFromDrivers({
1066
+ drivers: [ClaudeAdapterV2.ClaudeAdapterV2Driver],
1067
+ configMap: {
1068
+ [ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID]: {
1069
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1070
+ environment: [{ name: "CLAUDE_CODE_TMPDIR", value: tmpRoot, sensitive: false }],
1071
+ },
1072
+ },
1073
+ }),
1074
+ ),
1075
+ Effect.provide(NodeServices.layer),
1076
+ ),
1077
+ ).pipe(
1078
Layer.provide(
1079
Layer.mergeAll(
1080
layerClaudeAgentSdkReplay(transcript, options),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+62
-3
@@ -1,4 +1,5 @@
1
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
2
+import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
3
import {
4
dynamicToolTitle,
5
formatReadToolLabel,
@@ -2233,9 +2234,11 @@ function claudeCommandOutputText(output: ClaudeNativeToolOutput): string {
2234
const stdout = Reflect.get(value, "stdout");
2235
const stderr = Reflect.get(value, "stderr");
2236
if (typeof stdout === "string" || typeof stderr === "string") {
2236
- const text = [stdout, stderr]
2237
- .filter((part): part is string => typeof part === "string" && part.trim().length > 0)
2238
- .join("\n");
2237
+ const out = typeof stdout === "string" && stdout.trim().length > 0 ? stdout : "";
2238
+ const err = typeof stderr === "string" && stderr.trim().length > 0 ? stderr : "";
2239
+ // Claude trims each stream's trailing newline, so stderr may need one to start its line.
2240
+ const text =
2241
+ out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;
2242
if (text.length > 0) return text;
2243
return output.type === "structured_tool_use_result" && output.fallbackValue !== undefined
2244
? claudeSubagentResultText({ type: "content_block", value: output.fallbackValue })
@@ -3540,6 +3543,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3543
});
3544
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3545
const activeTurn = yield* Ref.make<ActiveClaudeTurnContext | null>(null);
3546
+ // Foreground Bash calls whose output file is being tailed, by tool_use_id.
3547
+ const taskOutputTails = new Map<
3548
+ string,
3549
+ { readonly fiber: Fiber.Fiber<void>; readonly stop: Deferred.Deferred<void> }
3550
+ >();
3551
+ const taskOutputRoot = claudeTaskOutputRoot(adapterOptions.environment, path);
3552
+ // Waits for the tail's last read so its output lands before the call settles.
3553
+ const stopTaskOutputTail = (toolUseId: string) =>
3554
+ Effect.suspend(() => {
3555
+ const tail = taskOutputTails.get(toolUseId);
3556
+ if (tail === undefined) return Effect.void;
3557
+ taskOutputTails.delete(toolUseId);
3558
+ return Deferred.succeed(tail.stop, undefined).pipe(
3559
+ Effect.andThen(Fiber.await(tail.fiber)),
3560
+ Effect.asVoid,
3561
+ );
3562
+ });
3563
const sdkMessageLock = yield* Semaphore.make(1);
3564
// Survives turn settle: members mostly finish after the launching
3565
// turn has ended, and each transition must be emitted exactly once.
@@ -5856,6 +5876,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5876
readonly completedAt: DateTime.Utc;
5877
}) {
5878
for (const toolCall of input.toolCalls) {
5879
+ yield* stopTaskOutputTail(toolCall.nativeItemId);
5880
yield* emitToolCallArtifacts(
5881
buildToolCallArtifacts({
5882
context: input.context,
@@ -7321,6 +7342,43 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7342
7343
if (message.type === "system" && message.subtype === "task_started") {
7344
if (isClaudeNonSubagentTask(message)) {
7345
+ const tailedCall =
7346
+ message.tool_use_id === undefined
7347
+ ? undefined
7348
+ : findToolCall(context, message.tool_use_id);
7349
+ if (
7350
+ taskOutputRoot !== undefined &&
7351
+ message.task_type === "local_bash" &&
7352
+ // Older Claude Code builds omit the flag on foreground calls.
7353
+ message.is_backgrounded !== true &&
7354
+ tailedCall?.classification.itemType === "command_execution" &&
7355
+ !taskOutputTails.has(tailedCall.nativeItemId)
7356
+ ) {
7357
+ const itemId = idAllocator.derive.turnItemFromProviderItem({
7358
+ driver: CLAUDE_PROVIDER,
7359
+ nativeItemId: tailedCall.nativeItemId,
7360
+ });
7361
+ const stop = yield* Deferred.make<void>();
7362
+ const fiber = yield* tailClaudeTaskOutput({
7363
+ root: taskOutputRoot,
7364
+ sessionId: message.session_id,
7365
+ taskId: message.task_id,
7366
+ stop,
7367
+ onChunk: (chunk) =>
7368
+ emitProviderEvent({
7369
+ type: "command_output.delta",
7370
+ driver: CLAUDE_PROVIDER,
7371
+ threadId: tailedCall.threadId,
7372
+ itemId,
7373
+ chunk,
7374
+ }),
7375
+ }).pipe(
7376
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
7377
+ Effect.provideService(Path.Path, path),
7378
+ Effect.forkIn(sessionScope),
7379
+ );
7380
+ taskOutputTails.set(tailedCall.nativeItemId, { fiber, stop });
7381
+ }
7382
context.ignoredTaskIds.add(message.task_id);
7383
yield* applyBackgroundTaskRosterMessage({
7384
nativeThreadId: liveQuery.nativeThreadId,
@@ -7654,6 +7712,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7712
updatedAt: completedAt,
7713
presentation: toolCall.presentation,
7714
});
7715
+ yield* stopTaskOutputTail(toolCall.nativeItemId);
7716
yield* emitToolCallArtifacts(artifacts);
7717
toolCallsFor(context, toolCall).delete(toolCall.nativeItemId);
7718
// A subagent's task tools must not replace the parent's list.
apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts
new
+126
@@ -0,0 +1,126 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { assert, describe, it } from "@effect/vitest";
3
+import * as Deferred from "effect/Deferred";
4
+import * as Effect from "effect/Effect";
5
+import * as Fiber from "effect/Fiber";
6
+import * as FileSystem from "effect/FileSystem";
7
+import * as Path from "effect/Path";
8
+import * as Queue from "effect/Queue";
9
+
10
+import { tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
11
+
12
+const SESSION_ID = "0c91bb28-9e89-4889-bd22-3de9880233d3";
13
+const TASK_ID = "bk6xreeye";
14
+
15
+// Claude Code's layout: <root>/<project>/<session_id>/tasks/<task_id>.output.
16
+const makeTaskFile = Effect.gen(function* () {
17
+ const fileSystem = yield* FileSystem.FileSystem;
18
+ const path = yield* Path.Path;
19
+ const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-task-output-" });
20
+ const tasks = path.join(root, "-private-tmp-project", SESSION_ID, "tasks");
21
+ return { root, tasks, file: path.join(tasks, `${TASK_ID}.output`) };
22
+});
23
+
24
+// Live clock and a real file: this proves the tail follows the writer, which
25
+// TestClock cannot interleave with filesystem IO.
26
+describe("tailClaudeTaskOutput", () => {
27
+ it.live("follows a file that appears after the task starts, across split characters", () =>
28
+ Effect.scoped(
29
+ Effect.gen(function* () {
30
+ const fileSystem = yield* FileSystem.FileSystem;
31
+ const { root, tasks, file } = yield* makeTaskFile;
32
+ const chunks = yield* Queue.unbounded<string>();
33
+ yield* tailClaudeTaskOutput({
34
+ root,
35
+ sessionId: SESSION_ID,
36
+ taskId: TASK_ID,
37
+ stop: yield* Deferred.make<void>(),
38
+ onChunk: (chunk) => Queue.offer(chunks, chunk),
39
+ }).pipe(Effect.forkScoped);
40
+
41
+ yield* fileSystem.makeDirectory(tasks, { recursive: true });
42
+ // "é" is two bytes; the first write ends between them.
43
+ const encoded = new TextEncoder().encode("café 1\n");
44
+ yield* fileSystem.writeFile(file, encoded.subarray(0, 4));
45
+ assert.equal(yield* Queue.take(chunks), "caf");
46
+
47
+ yield* fileSystem.writeFile(file, encoded);
48
+ assert.equal(yield* Queue.take(chunks), "é 1\n");
49
+ }),
50
+ ).pipe(Effect.provide(NodeServices.layer)),
51
+ );
52
+
53
+ it.live("skips ahead when the command writes faster than it is read", () =>
54
+ Effect.scoped(
55
+ Effect.gen(function* () {
56
+ const fileSystem = yield* FileSystem.FileSystem;
57
+ const { root, tasks, file } = yield* makeTaskFile;
58
+ yield* fileSystem.makeDirectory(tasks, { recursive: true });
59
+ yield* fileSystem.writeFileString(file, "start\n");
60
+ const chunks = yield* Queue.unbounded<string>();
61
+ yield* tailClaudeTaskOutput({
62
+ root,
63
+ sessionId: SESSION_ID,
64
+ taskId: TASK_ID,
65
+ stop: yield* Deferred.make<void>(),
66
+ onChunk: (chunk) => Queue.offer(chunks, chunk),
67
+ }).pipe(Effect.forkScoped);
68
+ assert.equal(yield* Queue.take(chunks), "start\n");
69
+
70
+ yield* fileSystem.writeFileString(file, `start\n${"y\n".repeat(1_000_000)}end\n`);
71
+ const flooded = yield* Queue.take(chunks);
72
+ assert.isAtMost(flooded.length, 256 * 1024 + 1);
73
+ assert.isTrue(flooded.startsWith("\n"));
74
+ assert.isTrue(flooded.endsWith("y\nend\n"));
75
+ }),
76
+ ).pipe(Effect.provide(NodeServices.layer)),
77
+ );
78
+
79
+ it.live("reads what was written last when the tool result stops it", () =>
80
+ Effect.scoped(
81
+ Effect.gen(function* () {
82
+ const fileSystem = yield* FileSystem.FileSystem;
83
+ const { root, tasks, file } = yield* makeTaskFile;
84
+ yield* fileSystem.makeDirectory(tasks, { recursive: true });
85
+ yield* fileSystem.writeFileString(file, "one\n");
86
+ const chunks: Array<string> = [];
87
+ const stop = yield* Deferred.make<void>();
88
+ const first = yield* Deferred.make<void>();
89
+ const fiber = yield* tailClaudeTaskOutput({
90
+ root,
91
+ sessionId: SESSION_ID,
92
+ taskId: TASK_ID,
93
+ stop,
94
+ onChunk: (chunk) =>
95
+ Effect.sync(() => chunks.push(chunk)).pipe(
96
+ Effect.andThen(Deferred.succeed(first, undefined)),
97
+ ),
98
+ }).pipe(Effect.forkScoped);
99
+ yield* Deferred.await(first);
100
+ // Written right before the command exits, then the result arrives.
101
+ yield* fileSystem.writeFileString(file, "one\ntwo\n");
102
+ yield* Deferred.succeed(stop, undefined);
103
+ yield* Fiber.join(fiber);
104
+ assert.deepEqual(chunks, ["one\n", "two\n"]);
105
+ }).pipe(Effect.provide(NodeServices.layer)),
106
+ ),
107
+ );
108
+
109
+ it.live("ends when stopped even if Claude Code never wrote the file", () =>
110
+ Effect.scoped(
111
+ Effect.gen(function* () {
112
+ const { root } = yield* makeTaskFile;
113
+ const stop = yield* Deferred.make<void>();
114
+ const fiber = yield* tailClaudeTaskOutput({
115
+ root,
116
+ sessionId: SESSION_ID,
117
+ taskId: TASK_ID,
118
+ stop,
119
+ onChunk: () => Effect.die("no file, no output"),
120
+ }).pipe(Effect.forkScoped);
121
+ yield* Deferred.succeed(stop, undefined);
122
+ yield* Fiber.join(fiber);
123
+ }).pipe(Effect.provide(NodeServices.layer)),
124
+ ),
125
+ );
126
+});
apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts
new
+123
@@ -0,0 +1,123 @@
1
+import * as Deferred from "effect/Deferred";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+import * as Option from "effect/Option";
5
+import * as Path from "effect/Path";
6
+
7
+/**
8
+ * Live output for a foreground Claude Bash call.
9
+ *
10
+ * The Agent SDK sends no stdout until the tool result. Claude Code does write
11
+ * each running command's combined output to
12
+ * `<tmp>/claude-<uid>/<project>/<session_id>/tasks/<task_id>.output`, naming
13
+ * the task in its `task_started` frame (`task_type: "local_bash"`). This path is
14
+ * Claude Code's private layout, not SDK API, so every step degrades to "no live
15
+ * output": the row still gets its full output from the tool result.
16
+ */
17
+
18
+/** How often the file is checked while its command runs. */
19
+const CLAUDE_TASK_OUTPUT_POLL_MS = 250;
20
+/** Give up looking for a file Claude Code never wrote (a newer layout, or Windows). */
21
+const MAX_LOCATE_ATTEMPTS = 40;
22
+/** Bytes read per poll. A faster writer skips ahead: only the tail is shown anyway. */
23
+const MAX_READ_BYTES = 256 * 1024;
24
+
25
+/** Claude Code's per-user temp root, or none where it has no uid (Windows). */
26
+export function claudeTaskOutputRoot(
27
+ environment: Readonly<Record<string, string | undefined>> | undefined,
28
+ path: Path.Path,
29
+): string | undefined {
30
+ const uid = process.getuid?.();
31
+ if (uid === undefined) return undefined;
32
+ const base = environment?.CLAUDE_CODE_TMPDIR?.trim() || "/tmp";
33
+ return path.join(base, `claude-${uid}`);
34
+}
35
+
36
+const locate = Effect.fn("ClaudeTaskOutputTail.locate")(function* (input: {
37
+ readonly root: string;
38
+ readonly sessionId: string;
39
+ readonly taskId: string;
40
+}) {
41
+ const fileSystem = yield* FileSystem.FileSystem;
42
+ const path = yield* Path.Path;
43
+ const projects = yield* fileSystem.readDirectory(input.root).pipe(Effect.orElseSucceed(() => []));
44
+ for (const project of projects) {
45
+ const candidate = path.join(
46
+ input.root,
47
+ project,
48
+ input.sessionId,
49
+ "tasks",
50
+ `${input.taskId}.output`,
51
+ );
52
+ if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
53
+ return Option.some(candidate);
54
+ }
55
+ }
56
+ return Option.none<string>();
57
+});
58
+
59
+/**
60
+ * Reads appended output until `stop` completes, then reads once more so the
61
+ * last bytes written before the command exited still reach live viewers. The
62
+ * caller completes `stop` when the tool result arrives or the turn ends, and
63
+ * awaits the returned effect.
64
+ */
65
+export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(function* (input: {
66
+ readonly root: string;
67
+ readonly sessionId: string;
68
+ readonly taskId: string;
69
+ readonly stop: Deferred.Deferred<void>;
70
+ readonly onChunk: (chunk: string) => Effect.Effect<void>;
71
+}) {
72
+ const fileSystem = yield* FileSystem.FileSystem;
73
+ // True once stopped: the next read is the last.
74
+ const pause = Effect.raceFirst(
75
+ Effect.sleep(CLAUDE_TASK_OUTPUT_POLL_MS).pipe(Effect.as(false)),
76
+ Deferred.await(input.stop).pipe(Effect.as(true)),
77
+ );
78
+ let file = Option.none<string>();
79
+ for (let attempt = 0; Option.isNone(file); attempt += 1) {
80
+ file = yield* locate(input);
81
+ if (Option.isSome(file)) break;
82
+ if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return;
83
+ }
84
+ const filePath = file.value;
85
+ // `stream: true` keeps a multi-byte character split across reads intact;
86
+ // invalid bytes become U+FFFD.
87
+ let decoder = new TextDecoder("utf-8", { fatal: false });
88
+ let offset = 0;
89
+ let last = yield* Deferred.isDone(input.stop);
90
+ while (true) {
91
+ const size = yield* fileSystem.stat(filePath).pipe(
92
+ Effect.map((info) => Number(info.size)),
93
+ Effect.orElseSucceed(() => offset),
94
+ );
95
+ if (size < offset) offset = 0;
96
+ if (size > offset) {
97
+ const start = size - offset > MAX_READ_BYTES ? size - MAX_READ_BYTES : offset;
98
+ const bytes = yield* Effect.scoped(
99
+ Effect.gen(function* () {
100
+ const handle = yield* fileSystem.open(filePath, { flag: "r" });
101
+ yield* handle.seek(BigInt(start), "start");
102
+ return yield* handle.readAlloc(size - start);
103
+ }),
104
+ ).pipe(Effect.orElseSucceed(() => Option.none<Uint8Array>()));
105
+ if (Option.isSome(bytes)) {
106
+ // Skipped output must not splice two unrelated lines together.
107
+ const skipped = start > offset;
108
+ // Bytes held from before the gap belong to a character we never finished reading.
109
+ if (skipped) decoder = new TextDecoder("utf-8", { fatal: false });
110
+ offset = start + bytes.value.byteLength;
111
+ const text = (skipped ? "\n" : "") + decoder.decode(bytes.value, { stream: true });
112
+ if (text.length > 0) yield* input.onChunk(text);
113
+ }
114
+ }
115
+ if (last) {
116
+ // A command that ended mid-character still shows a replacement character.
117
+ const rest = decoder.decode();
118
+ if (rest.length > 0) yield* input.onChunk(rest);
119
+ return;
120
+ }
121
+ last = yield* pause;
122
+ }
123
+});
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+21
@@ -4324,6 +4324,27 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
4324
}),
4325
);
4326
4327
+ yield* client.handleServerNotification("item/commandExecution/outputDelta", (payload) =>
4328
+ Effect.gen(function* () {
4329
+ // A delta always follows its item/started, so the turn is already
4330
+ // known; background commands keep printing after it settles.
4331
+ const context =
4332
+ (yield* Ref.get(activeTurns)).get(payload.turnId) ??
4333
+ (yield* Ref.get(settledTurns)).get(payload.turnId);
4334
+ if (context === undefined) return;
4335
+ yield* emitProviderEvent({
4336
+ type: "command_output.delta",
4337
+ driver: CODEX_PROVIDER,
4338
+ threadId: context.projectionThreadId,
4339
+ itemId: idAllocator.derive.turnItemFromProviderItem({
4340
+ driver: CODEX_PROVIDER,
4341
+ nativeItemId: payload.itemId,
4342
+ }),
4343
+ chunk: payload.delta,
4344
+ });
4345
+ }),
4346
+ );
4347
+
4348
yield* client.handleServerNotification("item/reasoning/summaryTextDelta", (payload) =>
4349
appendReasoning(payload, "summary", payload.summaryIndex),
4350
);
apps/server/src/orchestration-v2/CommandOutputHub.test.ts
new
+461
@@ -0,0 +1,461 @@
1
+import { assert, it } from "@effect/vitest";
2
+import {
3
+ type ModelSelection,
4
+ type OrchestrationV2AppThread,
5
+ type OrchestrationV2CommandOutputFrame,
6
+ type OrchestrationV2TurnItem,
7
+ ProviderDriverKind,
8
+ ProviderInstanceId,
9
+ type ThreadId,
10
+ TurnItemId,
11
+} from "@t3tools/contracts";
12
+import {
13
+ appendTerminalOutput,
14
+ EMPTY_TERMINAL_OUTPUT,
15
+ normalizeTerminalOutput,
16
+ TERMINAL_OUTPUT_TAIL_CHARS,
17
+ type TerminalOutputState,
18
+} from "@t3tools/shared/terminalOutput";
19
+import * as Clock from "effect/Clock";
20
+import * as DateTime from "effect/DateTime";
21
+import * as Effect from "effect/Effect";
22
+import * as Layer from "effect/Layer";
23
+import * as Queue from "effect/Queue";
24
+import * as Stream from "effect/Stream";
25
+import * as TestClock from "effect/testing/TestClock";
26
+
27
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
28
+import * as CommandOutputHub from "./CommandOutputHub.ts";
29
+import * as EventSink from "./EventSink.ts";
30
+import * as EventStore from "./EventStore.ts";
31
+import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
32
+import * as ProjectionStore from "./ProjectionStore.ts";
33
+
34
+const layerTestDatabase = SqlitePersistence.layerMemory;
35
+const layerTestStores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
36
+ Layer.provide(layerTestDatabase),
37
+);
38
+const layerTestEventSink = EventSink.layer.pipe(
39
+ Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
40
+);
41
+const layerTest = Layer.mergeAll(
42
+ layerTestEventSink,
43
+ IdAllocator.layer,
44
+ CommandOutputHub.layer.pipe(Layer.provide(Layer.merge(layerTestEventSink, layerTestStores))),
45
+);
46
+
47
+const modelSelection = {
48
+ instanceId: ProviderInstanceId.make("codex"),
49
+ model: "gpt-5.4",
50
+} satisfies ModelSelection;
51
+const CODEX_DRIVER = ProviderDriverKind.make("codex");
52
+const ITEM_ID = TurnItemId.make("turn-item:command");
53
+
54
+/** What a client holds after applying frames, using the same shared normalizer. */
55
+function applyFrame(
56
+ state: TerminalOutputState,
57
+ frame: OrchestrationV2CommandOutputFrame,
58
+): TerminalOutputState {
59
+ return frame.kind === "replace"
60
+ ? appendTerminalOutput({ ...EMPTY_TERMINAL_OUTPUT, truncated: frame.truncated }, frame.text)
61
+ : appendTerminalOutput(state, frame.text);
62
+}
63
+
64
+const seedThread = Effect.gen(function* () {
65
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
66
+ const eventSink = yield* EventSink.EventSinkV2;
67
+ const now = yield* DateTime.now;
68
+ const projectId = yield* idAllocator.allocate.project({ fixtureName: "command-output" });
69
+ const threadId = yield* idAllocator.allocate.thread({ fixtureName: "command-output", projectId });
70
+ const thread: OrchestrationV2AppThread = {
71
+ createdBy: "user",
72
+ creationSource: "web",
73
+ id: threadId,
74
+ projectId,
75
+ title: "Command output",
76
+ providerInstanceId: modelSelection.instanceId,
77
+ modelSelection,
78
+ runtimeMode: "full-access",
79
+ interactionMode: "default",
80
+ branch: null,
81
+ worktreePath: null,
82
+ branchPullRequest: null,
83
+ activeOrderKey: null,
84
+ activeProviderThreadId: null,
85
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
86
+ forkedFrom: null,
87
+ createdAt: now,
88
+ updatedAt: now,
89
+ archivedAt: null,
90
+ settledOverride: null,
91
+ settledAt: null,
92
+ lastVisitedAt: null,
93
+ deletedAt: null,
94
+ };
95
+ yield* eventSink.write({
96
+ events: [
97
+ {
98
+ id: yield* idAllocator.allocate.event({ threadId }),
99
+ type: "thread.created",
100
+ threadId,
101
+ occurredAt: now,
102
+ payload: thread,
103
+ },
104
+ ],
105
+ });
106
+ return threadId;
107
+});
108
+
109
+const writeCommandItem = (
110
+ threadId: ThreadId,
111
+ fields: Pick<
112
+ Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
113
+ "status" | "output" | "exitCode"
114
+ >,
115
+) =>
116
+ Effect.gen(function* () {
117
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
118
+ const eventSink = yield* EventSink.EventSinkV2;
119
+ const now = yield* DateTime.now;
120
+ const settled = fields.status !== "running";
121
+ const item: OrchestrationV2TurnItem = {
122
+ id: ITEM_ID,
123
+ threadId,
124
+ runId: null,
125
+ nodeId: null,
126
+ providerThreadId: null,
127
+ providerTurnId: null,
128
+ nativeItemRef: null,
129
+ parentItemId: null,
130
+ ordinal: 1,
131
+ title: null,
132
+ startedAt: now,
133
+ completedAt: settled ? now : null,
134
+ updatedAt: now,
135
+ type: "command_execution",
136
+ input: "yes | head -n 1000000",
137
+ ...fields,
138
+ };
139
+ yield* eventSink.write({
140
+ events: [
141
+ {
142
+ id: yield* idAllocator.allocate.event({ threadId }),
143
+ type: "turn-item.updated",
144
+ threadId,
145
+ driver: CODEX_DRIVER,
146
+ providerInstanceId: modelSelection.instanceId,
147
+ occurredAt: now,
148
+ payload: item,
149
+ },
150
+ ],
151
+ });
152
+ });
153
+
154
+/** Collect frames into a queue so the test takes them one receipt at a time. */
155
+const subscribeFrames = (threadId: ThreadId) =>
156
+ Effect.gen(function* () {
157
+ const hub = yield* CommandOutputHub.CommandOutputHub;
158
+ const frames = yield* Queue.unbounded<OrchestrationV2CommandOutputFrame | "ended">();
159
+ yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
160
+ Stream.runForEach((frame) => Queue.offer(frames, frame)),
161
+ Effect.andThen(Queue.offer(frames, "ended")),
162
+ Effect.forkScoped,
163
+ );
164
+ return frames;
165
+ });
166
+
167
+const takeFrame = (frames: Queue.Queue<OrchestrationV2CommandOutputFrame | "ended">) =>
168
+ Queue.take(frames).pipe(
169
+ Effect.flatMap((frame) =>
170
+ frame === "ended" ? Effect.die("command output stream ended early") : Effect.succeed(frame),
171
+ ),
172
+ );
173
+
174
+const layer = it.layer(layerTest);
175
+
176
+layer("CommandOutputHub", (it) => {
177
+ it.effect(
178
+ "a late subscriber gets the running tail, then live appends, then the final output",
179
+ () =>
180
+ Effect.scoped(
181
+ Effect.gen(function* () {
182
+ const hub = yield* CommandOutputHub.CommandOutputHub;
183
+ const threadId = yield* seedThread;
184
+ yield* writeCommandItem(threadId, { status: "running" });
185
+ // Output that arrived before anyone looked, ending mid-escape and mid-redraw.
186
+ yield* hub.append({
187
+ threadId,
188
+ itemId: ITEM_ID,
189
+ chunk: "\u001b[32mbuilding\u001b[0m\n10%",
190
+ });
191
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });
192
+
193
+ const frames = yield* subscribeFrames(threadId);
194
+ const first = yield* takeFrame(frames);
195
+ assert.equal(first.kind, "replace");
196
+ assert.isTrue(first.running);
197
+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);
198
+ assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");
199
+
200
+ // Chunks that land between frames arrive together in one append.
201
+ yield* TestClock.adjust("1 second");
202
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });
203
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });
204
+ const append = yield* takeFrame(frames);
205
+ assert.equal(append.kind, "append");
206
+ client = applyFrame(client, append);
207
+ assert.equal(
208
+ client.text,
209
+ normalizeTerminalOutput(
210
+ "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",
211
+ ).text,
212
+ );
213
+
214
+ // The persisted item settles the row; its output is what the client keeps.
215
+ yield* TestClock.adjust("1 second");
216
+ yield* writeCommandItem(threadId, {
217
+ status: "completed",
218
+ exitCode: 0,
219
+ output: "building\n100%\ndone\n",
220
+ });
221
+ const final = yield* takeFrame(frames);
222
+ assert.deepEqual(final, {
223
+ kind: "replace",
224
+ text: "building\n100%\ndone\n",
225
+ truncated: false,
226
+ running: false,
227
+ });
228
+ assert.equal(yield* Queue.take(frames), "ended");
229
+ }),
230
+ ),
231
+ );
232
+
233
+ it.effect("a row that is not a known command fails instead of waiting forever", () =>
234
+ Effect.gen(function* () {
235
+ const hub = yield* CommandOutputHub.CommandOutputHub;
236
+ const threadId = yield* seedThread;
237
+ const error = yield* hub
238
+ .subscribe({ threadId, itemId: ITEM_ID })
239
+ .pipe(Stream.runDrain, Effect.flip);
240
+ assert.equal(error._tag, "OrchestrationV2CommandOutputError");
241
+ assert.equal(error.message, "No such command.");
242
+ }),
243
+ );
244
+
245
+ it.effect("a viewer whose command was evicted for newer ones is resynced, not appended to", () =>
246
+ Effect.scoped(
247
+ Effect.gen(function* () {
248
+ const hub = yield* CommandOutputHub.CommandOutputHub;
249
+ const threadId = yield* seedThread;
250
+ yield* writeCommandItem(threadId, { status: "running" });
251
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
252
+ const frames = yield* subscribeFrames(threadId);
253
+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
254
+ assert.equal(client.text, "abc");
255
+ // 64 newer commands push this one's tail out of the hub.
256
+ for (let index = 0; index < 64; index += 1) {
257
+ yield* hub.append({
258
+ threadId,
259
+ itemId: TurnItemId.make(`turn-item:other-${index}`),
260
+ chunk: "x",
261
+ });
262
+ }
263
+ yield* TestClock.adjust("1 second");
264
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
265
+ const next = yield* takeFrame(frames);
266
+ assert.equal(next.kind, "replace");
267
+ client = applyFrame(client, next);
268
+ assert.equal(client.text, "X");
269
+ }),
270
+ ),
271
+ );
272
+
273
+ it.effect("every viewer of one command reconstructs the same text", () =>
274
+ Effect.scoped(
275
+ Effect.gen(function* () {
276
+ const hub = yield* CommandOutputHub.CommandOutputHub;
277
+ const threadId = yield* seedThread;
278
+ yield* writeCommandItem(threadId, { status: "running" });
279
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "first\n" });
280
+ const viewers = [yield* subscribeFrames(threadId), yield* subscribeFrames(threadId)];
281
+ const states = [EMPTY_TERMINAL_OUTPUT, EMPTY_TERMINAL_OUTPUT];
282
+ for (const [index, frames] of viewers.entries()) {
283
+ states[index] = applyFrame(states[index]!, yield* takeFrame(frames));
284
+ }
285
+ yield* TestClock.adjust("1 second");
286
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "second\r\nthird" });
287
+ for (const [index, frames] of viewers.entries()) {
288
+ states[index] = applyFrame(states[index]!, yield* takeFrame(frames));
289
+ }
290
+ assert.equal(states[0]!.text, "first\nsecond\nthird");
291
+ assert.equal(states[1]!.text, states[0]!.text);
292
+ }),
293
+ ),
294
+ );
295
+
296
+ it.effect("a flood is sent as bounded tails at a slower rate, not as every chunk", () =>
297
+ Effect.scoped(
298
+ Effect.gen(function* () {
299
+ const hub = yield* CommandOutputHub.CommandOutputHub;
300
+ const threadId = yield* seedThread;
301
+ yield* writeCommandItem(threadId, { status: "running" });
302
+ const stamped = yield* Queue.unbounded<{
303
+ readonly frame: OrchestrationV2CommandOutputFrame;
304
+ readonly at: number;
305
+ }>();
306
+ yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(
307
+ Stream.runForEach((frame) =>
308
+ Clock.currentTimeMillis.pipe(
309
+ Effect.flatMap((at) => Queue.offer(stamped, { frame, at })),
310
+ ),
311
+ ),
312
+ Effect.forkScoped,
313
+ );
314
+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, (yield* Queue.take(stamped)).frame);
315
+ yield* TestClock.adjust("1 second");
316
+
317
+ // `yes | head -n 1000000`: 2 MB in 4 KB chunks, 64 KB every 100 ms.
318
+ const chunk = "y\n".repeat(2_048);
319
+ const sent: Array<{
320
+ readonly frame: OrchestrationV2CommandOutputFrame;
321
+ readonly at: number;
322
+ }> = [];
323
+ const drain = Effect.gen(function* () {
324
+ for (const entry of yield* Queue.clear(stamped)) {
325
+ sent.push(entry);
326
+ client = applyFrame(client, entry.frame);
327
+ }
328
+ });
329
+ for (let tick = 0; tick < 32; tick += 1) {
330
+ for (let index = 0; index < 16; index += 1) {
331
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk });
332
+ }
333
+ yield* TestClock.adjust(CommandOutputHub.COMMAND_OUTPUT_FRAME_INTERVAL_MS);
334
+ yield* drain;
335
+ }
336
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "tail\n" });
337
+ yield* TestClock.adjust("1 second");
338
+ yield* drain;
339
+
340
+ const bytes = sent.reduce((total, { frame }) => total + frame.text.length, 0);
341
+ // 3.2 s of flooding: a frame per chunk would be 512 frames and 2 MB.
342
+ assert.isAtMost(sent.length, 10);
343
+ assert.isAtMost(bytes, 10 * TERMINAL_OUTPUT_TAIL_CHARS);
344
+ for (const { frame } of sent) {
345
+ assert.isAtMost(frame.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
346
+ }
347
+ for (let index = 1; index < sent.length; index += 1) {
348
+ if (sent[index - 1]!.frame.kind === "replace") {
349
+ assert.isAtLeast(
350
+ sent[index]!.at - sent[index - 1]!.at,
351
+ CommandOutputHub.COMMAND_OUTPUT_REPLACE_INTERVAL_MS,
352
+ );
353
+ }
354
+ }
355
+ assert.isTrue(client.truncated);
356
+ assert.isTrue(client.text.endsWith("y\ny\ntail\n"));
357
+ assert.isAtMost(client.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
358
+ }),
359
+ ),
360
+ );
361
+
362
+ it.effect("a finished command sends only its bounded final output", () =>
363
+ Effect.scoped(
364
+ Effect.gen(function* () {
365
+ const threadId = yield* seedThread;
366
+ const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");
367
+ yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });
368
+ const frames = yield* subscribeFrames(threadId);
369
+ const final = yield* takeFrame(frames);
370
+ assert.equal(final.kind, "replace");
371
+ assert.isFalse(final.running);
372
+ assert.isTrue(final.truncated);
373
+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
374
+ assert.isTrue(final.text.endsWith("line 399999"));
375
+ assert.equal(yield* Queue.take(frames), "ended");
376
+ }),
377
+ ),
378
+ );
379
+
380
+ it.effect("a finished command whose output is one huge line still shows its tail", () =>
381
+ Effect.scoped(
382
+ Effect.gen(function* () {
383
+ const threadId = yield* seedThread;
384
+ const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);
385
+ yield* writeCommandItem(threadId, {
386
+ status: "completed",
387
+ exitCode: 0,
388
+ output: `${line}\n`,
389
+ });
390
+ const frames = yield* subscribeFrames(threadId);
391
+ const final = yield* takeFrame(frames);
392
+ assert.equal(final.kind, "replace");
393
+ assert.isTrue(final.truncated);
394
+ assert.isTrue(final.text.includes("xxxx"));
395
+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
396
+ }),
397
+ ),
398
+ );
399
+
400
+ it.effect("an old Claude row's raw Bash result shows as its stdout and stderr", () =>
401
+ Effect.scoped(
402
+ Effect.gen(function* () {
403
+ const threadId = yield* seedThread;
404
+ yield* writeCommandItem(threadId, {
405
+ status: "completed",
406
+ exitCode: 0,
407
+ output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
408
+ });
409
+ const frames = yield* subscribeFrames(threadId);
410
+ const final = yield* takeFrame(frames);
411
+ assert.equal(final.text, "built\n1 warning");
412
+ }),
413
+ ),
414
+ );
415
+
416
+ it.effect("providers that only report output in item snapshots still stream", () =>
417
+ Effect.scoped(
418
+ Effect.gen(function* () {
419
+ const threadId = yield* seedThread;
420
+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
421
+ const frames = yield* subscribeFrames(threadId);
422
+ assert.equal((yield* takeFrame(frames)).text, "step 1\n");
423
+ yield* TestClock.adjust("1 second");
424
+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
425
+ const update = yield* takeFrame(frames);
426
+ assert.deepEqual(update, {
427
+ kind: "replace",
428
+ text: "step 1\nstep 2\n",
429
+ truncated: false,
430
+ running: true,
431
+ });
432
+ }),
433
+ ),
434
+ );
435
+
436
+ it.effect("an interrupted command ends the stream with the output it printed", () =>
437
+ Effect.scoped(
438
+ Effect.gen(function* () {
439
+ const hub = yield* CommandOutputHub.CommandOutputHub;
440
+ const threadId = yield* seedThread;
441
+ yield* writeCommandItem(threadId, { status: "running" });
442
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
443
+ const frames = yield* subscribeFrames(threadId);
444
+ yield* takeFrame(frames);
445
+ yield* TestClock.adjust("1 second");
446
+ // Some providers stop a command without reporting its output. The session
447
+ // manager releases the live tail before the settled item is persisted.
448
+ yield* hub.finish({ threadId, itemId: ITEM_ID });
449
+ yield* writeCommandItem(threadId, { status: "interrupted" });
450
+ const final = yield* takeFrame(frames);
451
+ assert.deepEqual(final, {
452
+ kind: "replace",
453
+ text: "waiting for server\n",
454
+ truncated: false,
455
+ running: false,
456
+ });
457
+ assert.equal(yield* Queue.take(frames), "ended");
458
+ }),
459
+ ),
460
+ );
461
+});
apps/server/src/orchestration-v2/CommandOutputHub.ts
new
+342
@@ -0,0 +1,342 @@
1
+import {
2
+ isOrchestrationV2WorkActive,
3
+ OrchestrationV2CommandOutputError,
4
+ type OrchestrationV2CommandOutputFrame,
5
+ type OrchestrationV2SubscribeCommandOutputInput,
6
+ type OrchestrationV2TurnItem,
7
+} from "@t3tools/contracts";
8
+import {
9
+ appendTerminalOutput,
10
+ EMPTY_TERMINAL_OUTPUT,
11
+ normalizeTerminalOutput,
12
+ type TerminalOutputState,
13
+ TERMINAL_OUTPUT_TAIL_CHARS,
14
+ terminalOutputResumeText,
15
+} from "@t3tools/shared/terminalOutput";
16
+import * as Cause from "effect/Cause";
17
+import * as Clock from "effect/Clock";
18
+import * as Context from "effect/Context";
19
+import * as Effect from "effect/Effect";
20
+import * as Layer from "effect/Layer";
21
+import * as Option from "effect/Option";
22
+import * as Queue from "effect/Queue";
23
+import * as Schema from "effect/Schema";
24
+import * as Stream from "effect/Stream";
25
+
26
+import * as EventSink from "./EventSink.ts";
27
+import * as ProjectionStore from "./ProjectionStore.ts";
28
+
29
+/**
30
+ * Live command output.
31
+ *
32
+ * Output never becomes an orchestration event. Adapters push raw chunks here
33
+ * (through the session manager), the hub keeps a bounded, normalized tail per
34
+ * running command, and `subscribe` serves one expanded row: the current tail,
35
+ * then coalesced appends, then the persisted final output. Memory is bounded
36
+ * per command and in count, and a client that is not showing the row receives nothing.
37
+ */
38
+
39
+/** Fastest a subscriber receives frames while output flows. */
40
+export const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100;
41
+/** After a subscriber falls behind and is sent the whole tail, it waits this long. */
42
+export const COMMAND_OUTPUT_REPLACE_INTERVAL_MS = 500;
43
+/** Raw text a subscriber may accumulate before it is sent the tail instead. */
44
+const COMMAND_OUTPUT_MAX_APPEND_CHARS = 16 * 1024;
45
+/** Running commands tracked at once; the least recently written is dropped beyond this. */
46
+const MAX_LIVE_COMMANDS = 64;
47
+/** Finished tails kept for a settle that reports no output of its own (an interrupt). */
48
+const MAX_FINISHED_COMMANDS = 16;
49
+/** Final output read from persistence is normalized from at most this many trailing chars. */
50
+const MAX_FINAL_SOURCE_CHARS = TERMINAL_OUTPUT_TAIL_CHARS * 4;
51
+
52
+interface Subscriber {
53
+ pendingAppend: string;
54
+ /** The next frame must carry the whole tail. */
55
+ needsReplace: boolean;
56
+ /** `needsReplace` was caused by the subscriber falling behind. */
57
+ overflowed: boolean;
58
+ readonly wake: Queue.Queue<void>;
59
+}
60
+
61
+export type CommandOutputTarget = OrchestrationV2SubscribeCommandOutputInput;
62
+
63
+export interface CommandOutputHubShape {
64
+ /** Add raw output for a running command. Called for every provider chunk. */
65
+ readonly append: (input: CommandOutputTarget & { readonly chunk: string }) => Effect.Effect<void>;
66
+ /**
67
+ * The command settled. Its tail is kept briefly for a settle that carries no
68
+ * output (an interrupt); otherwise the persisted output is what rows show.
69
+ */
70
+ readonly finish: (input: CommandOutputTarget) => Effect.Effect<void>;
71
+ /** Frames for one row until its command settles; see `OrchestrationV2CommandOutputFrame`. */
72
+ readonly subscribe: (
73
+ input: CommandOutputTarget,
74
+ ) => Stream.Stream<OrchestrationV2CommandOutputFrame, OrchestrationV2CommandOutputError>;
75
+}
76
+
77
+export class CommandOutputHub extends Context.Service<CommandOutputHub, CommandOutputHubShape>()(
78
+ "t3/orchestration-v2/CommandOutputHub",
79
+) {}
80
+
81
+const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);
82
+
83
+function commandKey(target: CommandOutputTarget): string {
84
+ return `${target.threadId}\u0000${target.itemId}`;
85
+}
86
+
87
+/** Claude Bash rows stored before #15505 hold the raw `{ stdout, stderr, interrupted, ... }` result. */
88
+const decodeLegacyClaudeBashResult = Schema.decodeUnknownOption(
89
+ Schema.fromJsonString(
90
+ Schema.Struct({ stdout: Schema.String, stderr: Schema.String, interrupted: Schema.Boolean }),
91
+ ),
92
+);
93
+
94
+function legacyClaudeBashOutput(output: string): string {
95
+ if (!output.trimStart().startsWith('{"stdout"')) return output;
96
+ const parsed = decodeLegacyClaudeBashResult(output);
97
+ if (Option.isNone(parsed)) return output;
98
+ const out = parsed.value.stdout.trim().length > 0 ? parsed.value.stdout : "";
99
+ const err = parsed.value.stderr.trim().length > 0 ? parsed.value.stderr : "";
100
+ return out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;
101
+}
102
+
103
+/** The output a row shows from a persisted item, bounded before normalization. */
104
+function persistedCommandOutput(output: string | undefined): {
105
+ readonly text: string;
106
+ readonly truncated: boolean;
107
+} {
108
+ if (output === undefined) return { text: "", truncated: false };
109
+ let source = output;
110
+ if (output.length > MAX_FINAL_SOURCE_CHARS) {
111
+ // Start on a fresh line, so the cut can't land inside an escape sequence.
112
+ source = output.slice(output.length - MAX_FINAL_SOURCE_CHARS);
113
+ const newline = source.indexOf("\n");
114
+ if (newline !== -1 && newline + 1 < source.length) source = source.slice(newline + 1);
115
+ }
116
+ const normalized = normalizeTerminalOutput(source);
117
+ return {
118
+ text: normalized.text,
119
+ truncated: normalized.truncated || source.length !== output.length,
120
+ };
121
+}
122
+
123
+/** Sets `key` as the newest entry of `map`, dropping the oldest beyond `max`. */
124
+function setBounded<V>(
125
+ map: Map<string, V>,
126
+ key: string,
127
+ value: V,
128
+ max: number,
129
+ onEvict?: (key: string) => void,
130
+): void {
131
+ map.delete(key);
132
+ map.set(key, value);
133
+ if (map.size <= max) return;
134
+ const oldest = map.keys().next().value!;
135
+ map.delete(oldest);
136
+ onEvict?.(oldest);
137
+}
138
+
139
+export const make = Effect.gen(function* () {
140
+ const eventSink = yield* EventSink.EventSinkV2;
141
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
142
+ // Insertion order doubles as recency: every write re-inserts its entry.
143
+ const tails = new Map<string, TerminalOutputState>();
144
+ const finished = new Map<string, TerminalOutputState>();
145
+ const subscribers = new Map<string, Set<Subscriber>>();
146
+
147
+ const wakeAll = (key: string, chunk: string) =>
148
+ Effect.forEach(
149
+ subscribers.get(key) ?? [],
150
+ (subscriber) => {
151
+ if (!subscriber.needsReplace) {
152
+ subscriber.pendingAppend += chunk;
153
+ if (subscriber.pendingAppend.length > COMMAND_OUTPUT_MAX_APPEND_CHARS) {
154
+ subscriber.needsReplace = true;
155
+ subscriber.overflowed = true;
156
+ subscriber.pendingAppend = "";
157
+ }
158
+ }
159
+ return Queue.offer(subscriber.wake, undefined);
160
+ },
161
+ { discard: true },
162
+ );
163
+
164
+ const append: CommandOutputHubShape["append"] = ({ chunk, ...target }) =>
165
+ Effect.suspend(() => {
166
+ if (chunk.length === 0) return Effect.void;
167
+ const key = commandKey(target);
168
+ const tail = appendTerminalOutput(tails.get(key) ?? EMPTY_TERMINAL_OUTPUT, chunk);
169
+ setBounded(tails, key, tail, MAX_LIVE_COMMANDS, (oldest) => {
170
+ // Its viewers no longer share the hub's state; resync them on the next frame.
171
+ for (const subscriber of subscribers.get(oldest) ?? []) {
172
+ subscriber.needsReplace = true;
173
+ subscriber.pendingAppend = "";
174
+ }
175
+ });
176
+ return wakeAll(key, chunk);
177
+ });
178
+
179
+ const finish: CommandOutputHubShape["finish"] = (target) =>
180
+ Effect.sync(() => {
181
+ const key = commandKey(target);
182
+ const tail = tails.get(key);
183
+ if (tail === undefined) return;
184
+ tails.delete(key);
185
+ setBounded(finished, key, tail, MAX_FINISHED_COMMANDS);
186
+ });
187
+
188
+ const subscribe: CommandOutputHubShape["subscribe"] = (target) =>
189
+ Stream.unwrap(
190
+ Effect.gen(function* () {
191
+ const key = commandKey(target);
192
+ const wake = yield* Queue.sliding<void>(1);
193
+ const subscriber: Subscriber = {
194
+ pendingAppend: "",
195
+ needsReplace: true,
196
+ overflowed: false,
197
+ wake,
198
+ };
199
+ // Attach before reading anything, so no chunk falls between a read and the attach.
200
+ const keySubscribers = subscribers.get(key) ?? new Set<Subscriber>();
201
+ keySubscribers.add(subscriber);
202
+ subscribers.set(key, keySubscribers);
203
+ yield* Effect.addFinalizer(() =>
204
+ Effect.sync(() => {
205
+ keySubscribers.delete(subscriber);
206
+ if (keySubscribers.size === 0 && subscribers.get(key) === keySubscribers) {
207
+ subscribers.delete(key);
208
+ }
209
+ }),
210
+ );
211
+
212
+ // The persisted item says when the command is done and what it finally printed.
213
+ // Providers that report output only in item snapshots (ACP, Pi) stream through here too.
214
+ let snapshotOutput: string | undefined;
215
+ let lost: Cause.Cause<unknown> | undefined;
216
+ let settled: Extract<OrchestrationV2TurnItem, { type: "command_execution" }> | undefined;
217
+ const observe = (item: OrchestrationV2TurnItem | undefined) =>
218
+ Effect.suspend(() => {
219
+ if (item === undefined || item.type !== "command_execution") return Effect.void;
220
+ if (!isOrchestrationV2WorkActive(item.status)) {
221
+ settled = item;
222
+ } else if (item.output !== undefined && item.output !== snapshotOutput) {
223
+ snapshotOutput = item.output;
224
+ } else {
225
+ return Effect.void;
226
+ }
227
+ subscriber.needsReplace = true;
228
+ return Queue.offer(wake, undefined);
229
+ });
230
+ const fromSequence = yield* eventSink.latestSequence({ threadId: target.threadId });
231
+ yield* eventSink
232
+ .stream({
233
+ threadId: target.threadId,
234
+ afterSequence: fromSequence,
235
+ eventType: "turn-item.updated",
236
+ })
237
+ .pipe(
238
+ Stream.runForEach((stored) =>
239
+ stored.event.type === "turn-item.updated" && stored.event.payload.id === target.itemId
240
+ ? observe(stored.event.payload)
241
+ : Effect.void,
242
+ ),
243
+ // Without its event stream the row can never settle: end with an error
244
+ // instead of waiting forever.
245
+ Effect.catchCause((cause) =>
246
+ Effect.sync(() => {
247
+ lost = cause;
248
+ }).pipe(Effect.andThen(Queue.offer(wake, undefined))),
249
+ ),
250
+ Effect.forkScoped,
251
+ );
252
+ const item = yield* projections.getTurnItem(target);
253
+ // Only command rows have output; anything else would hold a subscription open forever.
254
+ if (item === null || item.type !== "command_execution") {
255
+ return yield* new OrchestrationV2CommandOutputError({
256
+ threadId: target.threadId,
257
+ message: "No such command.",
258
+ });
259
+ }
260
+ yield* observe(item);
261
+ yield* Queue.offer(wake, undefined);
262
+
263
+ let lastFrameAt: number | undefined;
264
+ let throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;
265
+ const nextFrame = Effect.gen(function* (): Effect.fn.Return<
266
+ OrchestrationV2CommandOutputFrame,
267
+ OrchestrationV2CommandOutputError
268
+ > {
269
+ yield* Queue.take(wake);
270
+ if (lost !== undefined) {
271
+ return yield* new OrchestrationV2CommandOutputError({
272
+ threadId: target.threadId,
273
+ message: "Lost the thread's event stream.",
274
+ cause: Cause.squash(lost),
275
+ });
276
+ }
277
+ const now = yield* Clock.currentTimeMillis;
278
+ if (lastFrameAt !== undefined && now - lastFrameAt < throttle) {
279
+ yield* Effect.sleep(throttle - (now - lastFrameAt));
280
+ }
281
+ lastFrameAt = yield* Clock.currentTimeMillis;
282
+ throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;
283
+ // A finished tail still shows until the settled item arrives.
284
+ const tail = tails.get(key) ?? finished.get(key);
285
+ if (settled !== undefined) {
286
+ if (settled.output === undefined && tail !== undefined) {
287
+ return {
288
+ kind: "replace",
289
+ text: tail.text,
290
+ truncated: tail.truncated,
291
+ running: false,
292
+ };
293
+ }
294
+ const output = settled.output && legacyClaudeBashOutput(settled.output);
295
+ return { kind: "replace", ...persistedCommandOutput(output), running: false };
296
+ }
297
+ if (subscriber.needsReplace || tail === undefined) {
298
+ if (subscriber.overflowed) throttle = COMMAND_OUTPUT_REPLACE_INTERVAL_MS;
299
+ subscriber.needsReplace = false;
300
+ subscriber.overflowed = false;
301
+ subscriber.pendingAppend = "";
302
+ if (tail === undefined) {
303
+ return { kind: "replace", ...persistedCommandOutput(snapshotOutput), running: true };
304
+ }
305
+ // The cursor, style and any unfinished escape ride along so the client
306
+ // applies later appends exactly as the hub does.
307
+ return {
308
+ kind: "replace",
309
+ text: terminalOutputResumeText(tail),
310
+ truncated: tail.truncated,
311
+ running: true,
312
+ };
313
+ }
314
+ const text = subscriber.pendingAppend;
315
+ subscriber.pendingAppend = "";
316
+ return { kind: "append", text, truncated: tail.truncated, running: true };
317
+ });
318
+ return Stream.fromEffectRepeat(nextFrame).pipe(
319
+ Stream.filter((frame) => frame.kind !== "append" || frame.text.length > 0),
320
+ Stream.takeUntil((frame) => !frame.running),
321
+ );
322
+ }).pipe(
323
+ Effect.mapError((cause) =>
324
+ isCommandOutputError(cause)
325
+ ? cause
326
+ : new OrchestrationV2CommandOutputError({
327
+ threadId: target.threadId,
328
+ message: "Failed to read command output.",
329
+ cause,
330
+ }),
331
+ ),
332
+ ),
333
+ );
334
+
335
+ return CommandOutputHub.of({ append, finish, subscribe });
336
+});
337
+
338
+export const layer: Layer.Layer<
339
+ CommandOutputHub,
340
+ never,
341
+ EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2
342
+> = Layer.effect(CommandOutputHub, make);
apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+3
@@ -690,6 +690,9 @@ export const layer: Layer.Layer<
690
}),
691
];
692
}
693
+ case "command_output.delta":
694
+ // Live output is routed to the command output hub before ingestion.
695
+ return [];
696
case "turn.terminal":
697
const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);
698
if (input.event.status !== "failed") {
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+4
@@ -50,6 +50,7 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
50
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
51
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
52
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
53
+import * as CommandOutputHub from "./CommandOutputHub.ts";
54
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
55
56
const layerTestDatabase = SqlitePersistence.layerMemory;
@@ -560,6 +561,9 @@ function layerTest(input: {
561
Layer.provide(
562
Layer.mergeAll(
563
layerRegistry.pipe(Layer.provideMerge(McpProviderSessions.layer)),
564
+ CommandOutputHub.layer.pipe(
565
+ Layer.provide(Layer.merge(layerConfiguredEventSink, layerTestStores)),
566
+ ),
567
layerConfiguredEventSink,
568
IdAllocator.layer,
569
layerProviderEventIngestorTest,
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+20
@@ -2,6 +2,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";
2
import * as KeyedLock from "@t3tools/shared/KeyedLock";
3
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
4
import {
5
+ isOrchestrationV2WorkActive,
6
ModelSelection,
7
OrchestrationV2DomainEvent,
8
OrchestrationV2ProviderSession,
@@ -45,6 +46,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
46
import * as ServerSettings from "../serverSettings.ts";
47
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
48
import * as EventSink from "./EventSink.ts";
49
+import * as CommandOutputHub from "./CommandOutputHub.ts";
50
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
51
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
52
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -331,6 +333,7 @@ export const layerWithOptions = (
333
): Layer.Layer<
334
ProviderSessionManagerV2,
335
never,
336
+ | CommandOutputHub.CommandOutputHub
337
| EventSink.EventSinkV2
338
| FileSystem.FileSystem
339
| IdAllocator.IdAllocatorV2
@@ -358,6 +361,7 @@ export const layerWithOptions = (
361
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
362
const projectService = yield* Effect.serviceOption(ProjectService.ProjectService);
363
const eventSink = yield* EventSink.EventSinkV2;
364
+ const commandOutput = yield* CommandOutputHub.CommandOutputHub;
365
const idAllocator = yield* IdAllocator.IdAllocatorV2;
366
const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
367
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
@@ -2021,6 +2025,21 @@ export const layerWithOptions = (
2025
return entry.runtime.events.pipe(
2026
Stream.runForEach((event) => {
2027
if (shutdownSignal.received) return Effect.void;
2028
+ // Live output skips run subscribers and ingestion entirely: it is
2029
+ // never persisted, and a flood of it must not queue ahead of real events.
2030
+ if (event.type === "command_output.delta") {
2031
+ return commandOutput.append(event);
2032
+ }
2033
+ // A settled item carries its final output, so its live tail can go.
2034
+ const releaseLiveOutput =
2035
+ event.type === "turn_item.updated" &&
2036
+ event.turnItem.type === "command_execution" &&
2037
+ !isOrchestrationV2WorkActive(event.turnItem.status)
2038
+ ? commandOutput.finish({
2039
+ threadId: event.turnItem.threadId,
2040
+ itemId: event.turnItem.id,
2041
+ })
2042
+ : Effect.void;
2043
if (
2044
event.type === "provider_session.updated" &&
2045
event.providerSession.status === "stopped"
@@ -2076,6 +2095,7 @@ export const layerWithOptions = (
2095
return;
2096
}
2097
yield* publishToSubscribers(entry.eventSubscribers, { type: "event", event });
2098
+ yield* releaseLiveOutput;
2099
}),
2100
),
2101
);
apps/server/src/orchestration-v2/RunExecutionService.ts
+3
@@ -475,6 +475,9 @@ export function routeProviderEvent(
475
state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
476
state,
477
];
478
+ case "command_output.delta":
479
+ // The session manager hands live output to the command output hub; runs never see it.
480
+ return [false, state];
481
case "turn.terminal":
482
return event.providerTurnId === state.rootProviderTurnId
483
? [true, { ...state, rootTurnEnded: true }]
apps/server/src/orchestration-v2/runtimeLayer.ts
+7
@@ -36,6 +36,7 @@ import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationServic
36
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
37
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
38
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
39
+import * as CommandOutputHub from "./CommandOutputHub.ts";
40
import * as ProviderRuntimeRecoveryService from "./ProviderRuntimeRecoveryService.ts";
41
import * as ProviderSwitchService from "./ProviderSwitchService.ts";
42
import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
@@ -124,9 +125,14 @@ const layerProviderSwitchServiceProvided = ProviderSwitchService.layer.pipe(
125
Layer.provide(layerProviderAdapterRegistryProvided),
126
);
127
128
+const layerCommandOutputHubProvided = CommandOutputHub.layer.pipe(
129
+ Layer.provide(Layer.merge(layerEventSinkProvided, ProjectionStore.layer)),
130
+);
131
+
132
const layerProviderSessionManagerProvided = ProviderSessionManager.layer.pipe(
133
Layer.provide(
134
Layer.mergeAll(
135
+ layerCommandOutputHubProvided,
136
layerProviderAdapterRegistryProvided,
137
layerEventSinkProvided,
138
IdAllocator.layer,
@@ -337,6 +343,7 @@ const layerMcpAppRequestsProvided = McpAppRequests.layer.pipe(
343
);
344
345
export const layer = Layer.mergeAll(
346
+ layerCommandOutputHubProvided,
347
layerOrchestratorProvided,
348
layerMcpAppRequestsProvided,
349
layerThreadManagementProvided,
apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts
+13
@@ -246,6 +246,19 @@ const scenarioExpectations = {
246
turnCompletedCount: 1,
247
approvalRequestCount: 0,
248
},
249
+ command_output_streaming: {
250
+ outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
251
+ incoming: [
252
+ "turn/started",
253
+ "item/started",
254
+ "item/commandExecution/outputDelta",
255
+ "item/completed",
256
+ "turn/completed",
257
+ ],
258
+ turnStartCount: 1,
259
+ turnCompletedCount: 1,
260
+ approvalRequestCount: 0,
261
+ },
262
turn_interrupt_mid_tool: {
263
outgoing: [
264
"initialize",
apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts
new
+55
@@ -0,0 +1,55 @@
1
+import type { TurnItemId } from "@t3tools/contracts";
2
+import {
3
+ appendTerminalOutput,
4
+ EMPTY_TERMINAL_OUTPUT,
5
+ type TerminalOutputState,
6
+} from "@t3tools/shared/terminalOutput";
7
+import * as Context from "effect/Context";
8
+import * as Effect from "effect/Effect";
9
+import * as Layer from "effect/Layer";
10
+
11
+import * as CommandOutputHub from "../CommandOutputHub.ts";
12
+import type * as EventSink from "../EventSink.ts";
13
+import type * as ProjectionStore from "../ProjectionStore.ts";
14
+
15
+/** What one command streamed through the hub during a replay. */
16
+export interface RecordedCommandOutput {
17
+ readonly chunks: number;
18
+ /** The live tail as a viewer would have seen it. */
19
+ readonly output: TerminalOutputState;
20
+}
21
+
22
+export class CommandOutputRecorder extends Context.Service<
23
+ CommandOutputRecorder,
24
+ { readonly snapshot: Effect.Effect<ReadonlyMap<TurnItemId, RecordedCommandOutput>> }
25
+>()("t3/orchestration-v2/testkit/CommandOutputRecorder") {}
26
+
27
+/** The real hub, plus a record of every chunk it was given, keyed by turn item. */
28
+export const layer: Layer.Layer<
29
+ CommandOutputHub.CommandOutputHub | CommandOutputRecorder,
30
+ never,
31
+ EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2
32
+> = Layer.effectContext(
33
+ Effect.gen(function* () {
34
+ const hub = yield* CommandOutputHub.make;
35
+ const recorded = new Map<TurnItemId, RecordedCommandOutput>();
36
+ return Context.make(
37
+ CommandOutputHub.CommandOutputHub,
38
+ CommandOutputHub.CommandOutputHub.of({
39
+ ...hub,
40
+ append: (input) =>
41
+ Effect.sync(() => {
42
+ const previous = recorded.get(input.itemId);
43
+ recorded.set(input.itemId, {
44
+ chunks: (previous?.chunks ?? 0) + 1,
45
+ output: appendTerminalOutput(previous?.output ?? EMPTY_TERMINAL_OUTPUT, input.chunk),
46
+ });
47
+ }).pipe(Effect.andThen(hub.append(input))),
48
+ }),
49
+ ).pipe(
50
+ Context.add(CommandOutputRecorder, {
51
+ snapshot: Effect.sync(() => new Map(recorded)),
52
+ }),
53
+ );
54
+ }),
55
+);
apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
+60
@@ -329,6 +329,66 @@ describe("orchestrator replay fixtures", () => {
329
const rest = entries.filter((_, index) => index !== toolIndex);
330
return [...rest.slice(0, resultIndex), toolEntry, ...rest.slice(resultIndex)];
331
};
332
+ // A subagent's foreground Bash run during the root's turn is tailed like a
333
+ // root call's, so the child's command row streams live.
334
+ const SUBAGENT_BASH_ID = "toolu_01JMN3SSQCHzUTNua9AWdkiH";
335
+ it.effect("streams a subagent's foreground Bash output live during the root turn", () =>
336
+ runFixtureProviderWithRegisteredHarness({
337
+ fixtureName: afterRootFixture.name,
338
+ buildInput: afterRootFixture.buildInput,
339
+ driver: {
340
+ ...afterRootProvider,
341
+ assertOutput: (result) => {
342
+ const childThreadId = projectionFor(result, afterRootFixture.name).subagents[0]
343
+ ?.childThreadId;
344
+ assert.exists(childThreadId);
345
+ const command = result.projections
346
+ .get(childThreadId)
347
+ ?.turnItems.find(
348
+ (item) =>
349
+ item.type === "command_execution" &&
350
+ JSON.stringify(item.input).includes("SUB_DONE_1"),
351
+ );
352
+ assert.exists(command);
353
+ const streamed = result.commandOutput?.get(command.id);
354
+ assert.exists(streamed, "the subagent's command must stream its output");
355
+ assert.include(streamed.output.text, "SUB_DONE_1");
356
+ },
357
+ },
358
+ transformTranscript: (transcript) => {
359
+ const isBashFrame = (entry: ProviderReplayEntry) => {
360
+ if (entry.type !== "emit_inbound") return false;
361
+ const frame = entry.frame as Record<string, any>;
362
+ return (
363
+ frame.message?.content?.[0]?.id === SUBAGENT_BASH_ID ||
364
+ frame.message?.content?.[0]?.tool_use_id === SUBAGENT_BASH_ID ||
365
+ (frame.type === "system" && frame.tool_use_id === SUBAGENT_BASH_ID)
366
+ );
367
+ };
368
+ // Recorded without the structured result the replay writes output files from.
369
+ const bashFrames = transcript.entries.filter(isBashFrame).map((entry) => {
370
+ const frame = (entry as { readonly frame: Record<string, any> }).frame;
371
+ return frame.type === "user"
372
+ ? {
373
+ ...entry,
374
+ frame: { ...frame, tool_use_result: { stdout: "SUB_DONE_1\n", stderr: "" } },
375
+ }
376
+ : entry;
377
+ });
378
+ const rest = transcript.entries.filter((entry) => !isBashFrame(entry));
379
+ const resultIndex = rest.findIndex(
380
+ (entry) => entry.type === "emit_inbound" && entry.label === "result",
381
+ );
382
+ assert.lengthOf(bashFrames, 4, "transcript shape changed");
383
+ assert.isAtLeast(resultIndex, 0, "transcript shape changed");
384
+ return {
385
+ ...transcript,
386
+ entries: [...rest.slice(0, resultIndex), ...bashFrames, ...rest.slice(resultIndex)],
387
+ };
388
+ },
389
+ }),
390
+ );
391
+
392
it.effect.each(
393
(["WebFetch", "Write"] as const).flatMap((tool) =>
394
(["before root settles", "while root is idle"] as const).flatMap((opens) =>
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+4
@@ -11,6 +11,7 @@ import type {
11
ProviderUserInputAnswers,
12
CommandId,
13
ThreadId,
14
+ TurnItemId,
15
} from "@t3tools/contracts";
16
import * as Clock from "effect/Clock";
17
import * as Duration from "effect/Duration";
@@ -23,6 +24,7 @@ import * as Stream from "effect/Stream";
24
import { TestClock } from "effect/testing";
25
26
import * as Orchestrator from "../Orchestrator.ts";
27
+import type { RecordedCommandOutput } from "./CommandOutputRecorder.ts";
28
import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";
29
30
export type OrchestratorV2ScenarioStep =
@@ -117,6 +119,8 @@ export interface OrchestratorV2ScenarioResult {
119
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
120
readonly shellSnapshot: OrchestrationV2ThreadShellSnapshot;
121
readonly capturedShellSnapshots: ReadonlyMap<string, OrchestrationV2ThreadShellSnapshot>;
122
+ /** Live output each command streamed (never persisted). Provider replays fill it in. */
123
+ readonly commandOutput?: ReadonlyMap<TurnItemId, RecordedCommandOutput>;
124
}
125
126
export class OrchestratorV2ScenarioStepError extends Schema.TaggedError<OrchestratorV2ScenarioStepError>()(
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+15
-2
@@ -41,6 +41,7 @@ import * as ProviderContinuationService from "../ProviderContinuationService.ts"
41
import * as ProviderEventIngestor from "../ProviderEventIngestor.ts";
42
import * as ProviderRuntimeRecoveryService from "../ProviderRuntimeRecoveryService.ts";
43
import * as ProviderSessionManager from "../ProviderSessionManager.ts";
44
+import * as CommandOutputRecorder from "./CommandOutputRecorder.ts";
45
import * as ProviderSwitchService from "../ProviderSwitchService.ts";
46
import * as ProviderTurnControlService from "../ProviderTurnControlService.ts";
47
import * as ProviderTurnStartService from "../ProviderTurnStartService.ts";
@@ -220,7 +221,11 @@ export function runOrchestratorV2ProviderReplayScenario<
221
replayGate,
222
});
223
223
- return runOrchestratorV2Scenario(scenario, { replayGate }).pipe(Effect.provide(layer));
224
+ return Effect.gen(function* () {
225
+ const result = yield* runOrchestratorV2Scenario(scenario, { replayGate });
226
+ const recorder = yield* CommandOutputRecorder.CommandOutputRecorder;
227
+ return { ...result, commandOutput: yield* recorder.snapshot };
228
+ }).pipe(Effect.provide(layer));
229
}
230
231
export function layerProviderReplay<Transcript extends ProviderReplayTranscript, Error>(
@@ -245,6 +250,7 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,
250
| Orchestrator.OrchestratorV2
251
| EffectWorker.OrchestrationEffectWorkerV2
252
| EventSink.EventSinkV2
253
+ | CommandOutputRecorder.CommandOutputRecorder
254
| ProviderSessionManager.ProviderSessionManagerV2,
255
Error | MigrationError | PlatformError.PlatformError | SqlError
256
> {
@@ -280,7 +286,8 @@ export function layerWithRegistry<Error>(
286
| Orchestrator.OrchestratorV2
287
| EffectWorker.OrchestrationEffectWorkerV2
288
| EventSink.EventSinkV2
283
- | ProviderSessionManager.ProviderSessionManagerV2,
289
+ | ProviderSessionManager.ProviderSessionManagerV2
290
+ | CommandOutputRecorder.CommandOutputRecorder,
291
Error | MigrationError | PlatformError.PlatformError | SqlError
292
> {
293
const layerServerConfig = Layer.effect(
@@ -353,11 +360,16 @@ export function layerWithRegistry<Error>(
360
IdAllocator.layer,
361
layerProviderEventIngestorProvided,
362
);
363
+ // The real hub, recording what each command streamed so fixtures can assert it.
364
+ const layerCommandOutputHubProvided = CommandOutputRecorder.layer.pipe(
365
+ Layer.provide(Layer.merge(layerEventSinkProvided, layerStores)),
366
+ );
367
const layerProviderSessionManagerProvided = ProviderSessionManager.layerWithOptions({
368
configureMcp: false,
369
}).pipe(
370
Layer.provide(
371
Layer.mergeAll(
372
+ layerCommandOutputHubProvided,
373
layerProvidedRegistry,
374
layerEventSinkProvided,
375
IdAllocator.layer,
@@ -503,6 +515,7 @@ export function layerWithRegistry<Error>(
515
layerEffectWorkerProvided,
516
layerEventSinkProvided,
517
layerContinuationWorkerProvided,
518
+ layerCommandOutputHubProvided,
519
).pipe(Layer.provide(ProviderTurnStartServiceTestkit.layer), Layer.provide(NodeServices.layer));
520
521
// Build the daemon from the exact worker instance exposed alongside the
apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/claude_transcript.ndjson
new
+77
@@ -0,0 +1,77 @@
1
+{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"command_output_streaming","metadata":{"prompts":["Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete"],"model":"claude-sonnet-4-6","nativeSessionId":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}
2
+{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","settings":{"showThinkingSummaries":true},"allowDangerouslySkipPermissions":true,"sessionId":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}}
3
+{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete"},"parent_tool_use_id":null,"uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}}
4
+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","state":"queued","uuid":"6fe0d477-fdc3-47dc-8ff1-3ccc54d469b4","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
5
+{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"08a52454-78a5-452f-9bb8-e88ed4059728","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
6
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"commands_changed","commands":[],"uuid":"c8217962-8361-44e9-bb14-3af863bc1120","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
7
+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","state":"started","uuid":"97a54d83-3bcd-4777-a5cf-2bdc595582a9","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
8
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.282","cwd":"/tmp/claude-replay-command_output_streaming","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"6248439e-cbe2-4414-9c47-a9961bd454c9","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
9
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"status","status":"requesting","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1323609c-6e72-4fbf-b08e-8c17d9f048c4"}}
10
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"14c64722-b32e-4b2c-84f1-023bfbf450dd","ttft_ms":2404,"user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"]}}
11
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"0762a100-bc7a-4557-a875-e37071475656"}}
12
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"20278113-d72a-4a92-a4d3-f48347bcb130","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
13
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"02859d8a-a956-4b0e-95c5-9537c5bd781e"}}
14
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":13,"estimated_tokens_delta":11,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"0cc23935-3171-427f-a238-46528dcfecdc","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
15
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" wants me to run a specific shell command","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"bd7870f4-f4aa-4edf-bc7f-dfe221b3d537"}}
16
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":22,"estimated_tokens_delta":9,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"76c1c5d1-147a-4b51-bd88-8431586bea3a","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
17
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" in the foreground and wait for it","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"1d725fd5-c0d4-4004-b077-4beb6117cc68"}}
18
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1158a602-d8ae-48d0-aba0-3404106a2dfc","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
19
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" to finish,","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"b951aa7f-7bcd-44e3-967c-fa0b8aa75e5f"}}
20
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":30,"estimated_tokens_delta":5,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"c220c092-c175-428f-b03d-387d39a4bf1e","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
21
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" then respond with a","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"6b796b6f-ded8-4600-9581-f777d9d724e2"}}
22
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":33,"estimated_tokens_delta":3,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"b6a5e466-cf90-4b90-a26c-476f6512e9af","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
23
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" specific","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"30b7dcc3-2343-4a82-b963-b9fa4d24986b"}}
24
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":35,"estimated_tokens_delta":2,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"d0cda494-8525-4cd5-89d5-163ae364929b","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
25
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" message","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"97d5635f-12f7-4e57-b7b4-f42326f83c36"}}
26
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":36,"estimated_tokens_delta":1,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"62158fd5-a0ac-433f-8beb-ae2ae37ff9f1","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
27
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":".","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7e08edaa-a314-4d6d-9344-1877c66066ad"}}
28
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":108,"estimated_tokens_delta":72,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"a645e3ae-7e68-41b6-a062-cc6a160a3876","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}
29
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"EqkDCsABCBIYAipA2mzY654tInaSF6DeGkvp3gfkITqOPZhhqF8GT6ZkzgeQ15s7+XBSfSQ5waInilWZR6l+T/1k8YSW/kl1gNLy2TIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJGFmOTIzNWNiLWRjNTItNDViMC05MTI2LTNmZTBkZmJmNzNkY3IQOUPUj6Q5Zqq7Ny6ZW11Rk4gBAZoBEwoRY2xhdWRlLXNvbm5ldC00LTaoAeiIgtYGsAECEgyJBKaNGwE4Bq7bVUAaDK7KTwkdSFhS109YaCIwwQY7/tQ9YthmKPKGQi6d7IN4+9F66tIrCAVIFJCm+PPT55S9uF86eX7hsdezKmtRKpUB81ib01do6Pc5sBsDW11G42sz8a3Vj3bwgXSnmOzsGy2MThUkQMwjiK0goinTRyDI4CM+M8891vUuMH6rNz7tUEla394ITlWCKynXRPRB4M0K/ap4SQKgq7TXOXtbWZd32nSkA7tKL+z4dERb4jwuWmFr6MGUS3IIanrtkdCwUR5dfsLjr8cG2YQjK0H1gUxQSfSwT04YAQ=="}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"bcffb6f7-03d6-42aa-a5d5-fb1dfe835408"}}
30
+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific shell command in the foreground and wait for it to finish, then respond with a specific message.","signature":"EqkDCsABCBIYAipA2mzY654tInaSF6DeGkvp3gfkITqOPZhhqF8GT6ZkzgeQ15s7+XBSfSQ5waInilWZR6l+T/1k8YSW/kl1gNLy2TIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJGFmOTIzNWNiLWRjNTItNDViMC05MTI2LTNmZTBkZmJmNzNkY3IQOUPUj6Q5Zqq7Ny6ZW11Rk4gBAZoBEwoRY2xhdWRlLXNvbm5ldC00LTaoAeiIgtYGsAECEgyJBKaNGwE4Bq7bVUAaDK7KTwkdSFhS109YaCIwwQY7/tQ9YthmKPKGQi6d7IN4+9F66tIrCAVIFJCm+PPT55S9uF86eX7hsdezKmtRKpUB81ib01do6Pc5sBsDW11G42sz8a3Vj3bwgXSnmOzsGy2MThUkQMwjiK0goinTRyDI4CM+M8891vUuMH6rNz7tUEla394ITlWCKynXRPRB4M0K/ap4SQKgq7TXOXtbWZd32nSkA7tKL+z4dERb4jwuWmFr6MGUS3IIanrtkdCwUR5dfsLjr8cG2YQjK0H1gUxQSfSwT04YAQ=="}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"9bdb9448-9eec-4d7f-9596-7c2bb88a520e","timestamp":"2026-10-03T04:28:24.096Z","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"]}}
31
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5b1c3d6b-54da-4169-ba99-0d44d6b0676b"}}
32
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"09c1e8b7-dd45-4109-aa49-854bc20fd260"}}
33
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Running"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"289bbc2e-7af9-4776-b417-8425e8da5e1f"}}
34
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":" the specified"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"19b641ae-50c2-43e2-ad0e-50e18956404b"}}
35
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":" command now."}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a63755c5-4ac7-4b69-b76b-29a27198c05e"}}
36
+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"text","text":"Running the specified command now."}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"21c52985-f6d0-4bce-a041-9a14335cbe4c","timestamp":"2026-10-03T04:28:24.667Z"}}
37
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":1},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"155f9033-d2f5-4bb2-8bbe-99eb910a7eab"}}
38
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","name":"Bash","input":{},"caller":{"type":"direct"}}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5f52cf4d-782c-4365-b9e8-39de7da83b04"}}
39
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"2a952797-fdcd-4d07-89b0-d08a7da2e4c4"}}
40
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"comma"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7c365772-6e18-4e21-ac82-1b610115eebd"}}
41
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"nd\": \"f"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a57acdd1-dc29-4b9e-b324-7825012d7238"}}
42
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"or i in"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"526ce67e-3518-43c6-a6fa-757466973f6e"}}
43
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":" 1 2 3 "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"68228de6-f113-4cfa-b850-fa283e2df465"}}
44
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"4; do p"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5dd7b26c-4058-40c0-bb8f-ec6529608e3c"}}
45
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"rintf '"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"3da221cd-debd-4b28-9995-d9e29817a8b6"}}
46
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\\\\033[3"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"0cd8e2d7-defd-4d81-9707-3d2a7b925788"}}
47
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"2mstrea"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"751d286c-526b-404b-9e58-03d63ded03b6"}}
48
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"m line "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4634f627-4af6-4479-9bc0-3c20dcf85bef"}}
49
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"%s\\\\033"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4975e7ac-dd15-48b5-96df-4b5f870bed94"}}
50
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"[0m\\\\n'"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4e42af58-4532-4228-9bbc-2a34571f1dcf"}}
51
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":" $i; sl"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4dbaff2d-53b1-40fd-af40-1565e3bd6412"}}
52
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"eep 1; "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7869dd97-9bc2-4a96-982e-ff95245344d8"}}
53
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"done; p"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"ba427143-74fa-4926-bec9-588519a38563"}}
54
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"rintf '"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f2b8b20a-dcec-4254-a5b7-c42ddf90965e"}}
55
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"progres"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5ab8b845-c735-4951-ad72-2b91598d3c54"}}
56
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"s 50%%\\"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"c2ae622a-a328-4547-91a0-fcea5a1b8f1c"}}
57
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\\rprogr"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a55100e6-a2c4-4240-bf1f-cc3528e0dd6e"}}
58
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"ess 100"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"9dbf6788-2d4c-4bb8-853a-48d75d96b1da"}}
59
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"%%\\\\n'\"}"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"01f00aea-874b-48b1-af4b-a6f21171ca8a"}}
60
+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","name":"Bash","input":{"command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"},"caller":{"type":"direct"}}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"459b10f0-5940-4da5-b476-58a8e2d1a1f5","timestamp":"2026-10-03T04:28:25.208Z","wire_tool_inputs":{"toolu_01CJnQSvsvh3iZtmvSWQVVvg":{"command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}}}}
61
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":2},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"717ffcb1-64d9-406a-ae9b-bf5ea86b067e"}}
62
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"output_tokens":168,"output_tokens_details":{"thinking_tokens":40},"iterations":[{"input_tokens":3,"output_tokens":168,"cache_read_input_tokens":121265,"cache_creation_input_tokens":13590,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4e7b88bb-8780-4fa2-9180-9d0100709db2"}}
63
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_stop"},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5c4f50f3-448a-4769-9e18-19fef01623e0"}}
64
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_started","task_id":"bmjeipgqr","tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","description":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'","is_backgrounded":false,"task_type":"local_bash","uuid":"6d2c30a6-ae01-4f1e-b461-a788611fbb27","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
65
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"bmjeipgqr","tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","status":"completed","output_file":"","summary":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'","uuid":"bc93586f-9042-46d7-bb2d-bef6306dae41","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}
66
+{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","type":"tool_result","content":"\u001b[32mstream line 1\u001b[0m\n\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%","is_error":false}]},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1e330b27-e5ec-4efd-a1e8-f3210856a354","timestamp":"2026-10-03T04:28:29.316Z","tool_use_result":{"stdout":"\u001b[32mstream line 1\u001b[0m\n\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false}}}
67
+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"status","status":"requesting","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"4b915a96-3ef5-45bb-bedd-316a6225ff28"}}
68
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefyTbebJFTYTaoceKGP","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"025b50aa-f18e-44e0-a3ad-824463157e25","ttft_ms":1793}}
69
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f89c4bd0-d960-4f8f-ba37-8bcf20bba907"}}
70
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"command"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"544181d2-af8e-4b44-bdfb-1a4b62448555"}}
71
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" output fixture complete"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"39ce0edf-4f40-4486-a31d-0e64ed05f4e3"}}
72
+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefyTbebJFTYTaoceKGP","type":"message","role":"assistant","content":[{"type":"text","text":"command output fixture complete"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"a2e4190b-50b6-4d97-9402-64912e5cd213","timestamp":"2026-10-03T04:28:31.124Z"}}
73
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f028526e-63ab-422d-9891-afaf0e23240b"}}
74
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"output_tokens":7,"output_tokens_details":{"thinking_tokens":0},"iterations":[{"input_tokens":1,"output_tokens":7,"cache_read_input_tokens":134855,"cache_creation_input_tokens":233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5090dc1b-46e7-4b61-8f8b-f9d2fb385124"}}
75
+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_stop"},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"c2ec1520-26b6-4735-8318-64cac0040303"}}
76
+{"type":"emit_inbound","label":"result","frame":{"duration_api_ms":6707,"stop_reason":"end_turn","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","total_cost_usd":0.16666124999999998,"usage":{"input_tokens":4,"cache_creation_input_tokens":13823,"cache_read_input_tokens":256120,"output_tokens":175,"output_tokens_details":{"thinking_tokens":40},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":13823,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":1,"output_tokens":7,"cache_read_input_tokens":134855,"cache_creation_input_tokens":233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":7,"outputTokens":186,"cacheReadInputTokens":256120,"cacheCreationInputTokens":14910,"webSearchRequests":0,"costUSD":0.16666124999999998,"contextWindow":200000,"maxOutputTokens":32000,"thinkingTokens":40,"canonicalModel":"claude-sonnet-4-6","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"command output fixture complete","ttft_ms":2938,"type":"result","duration_ms":9977,"uuid":"3e15a737-b7dc-4213-9895-92757055d07e","ttft_stream_ms":2442,"time_to_request_ms":39,"first_content_frame_ms":2512,"user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"],"request_sent_wall_ms":1791001701197,"queued_turn_count":0,"result_index":0}}
77
+{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson
new
+65
@@ -0,0 +1,65 @@
1
+{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.157.0","scenario":"command_output_streaming","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"command_output_streaming.ndjson","description":"One command prints over several seconds, so Codex streams its output deltas.","model":"gpt-6-luna"}}
2
+{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.45"}}}}
3
+{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"T3 Code/0.157.0 (Mac OS 27.0.0; arm64) unknown (T3 Code; 0.0.45)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}}
4
+{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
5
+{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"<workspace>","model":"gpt-6-luna"}}}
6
+{"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1791001627148}}
7
+{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":{"id":":read-only","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}}
8
+{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"detailed","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6"}}}
9
+{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1791001627410}}
10
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}
11
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}
12
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"firecrawl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}
13
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}
14
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}
15
+{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1791001627437}}
16
+{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
17
+{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1791001627550}}
18
+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1791001627553}}
19
+{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1791001627,"completedAt":null,"durationMs":null}},"emittedAtMs":1791001627553}}
20
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001627558}}
21
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001627758}}
22
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001628542}}
23
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"firecrawl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629447}}
24
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}
25
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}
26
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}
27
+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}
28
+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a10004-1683-7d83-9525-bcae2f675340","clientId":null,"content":[{"type":"text","text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","text_elements":[]}]},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001630341},"emittedAtMs":1791001630342}}
29
+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a10004-1683-7d83-9525-bcae2f675340","clientId":null,"content":[{"type":"text","text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","text_elements":[]}]},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001630342},"emittedAtMs":1791001630347}}
30
+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","text":"","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001632408},"emittedAtMs":1791001632408}}
31
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"I"},"emittedAtMs":1791001632408}}
32
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"’ll"},"emittedAtMs":1791001632408}}
33
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" run"},"emittedAtMs":1791001632408}}
34
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" the"},"emittedAtMs":1791001632584}}
35
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" command"},"emittedAtMs":1791001632584}}
36
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" in"},"emittedAtMs":1791001632584}}
37
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" the"},"emittedAtMs":1791001632584}}
38
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" foreground"},"emittedAtMs":1791001632584}}
39
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" and"},"emittedAtMs":1791001632584}}
40
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" wait"},"emittedAtMs":1791001632585}}
41
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" for"},"emittedAtMs":1791001632585}}
42
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" it"},"emittedAtMs":1791001632585}}
43
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" to"},"emittedAtMs":1791001632666}}
44
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" finish"},"emittedAtMs":1791001632666}}
45
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"."},"emittedAtMs":1791001632667}}
46
+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","text":"I’ll run the command in the foreground and wait for it to finish.","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001633018},"emittedAtMs":1791001633021}}
47
+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc \"for i in 1 2 3 4; do printf '\\\\033[32mstream line %s\\\\033[0m\\\\n' \"'$i; sleep 1; done; printf '\"'progress 50%%\\\\rprogress 100%%\\\\n'\"","cwd":"/home/replay-user/t3code/apps/server","processId":"44027","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001635941},"emittedAtMs":1791001635947}}
48
+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 2\u001b[0m\n"},"emittedAtMs":1791001636825}}
49
+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 3\u001b[0m\n"},"emittedAtMs":1791001637829}}
50
+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 4\u001b[0m\n"},"emittedAtMs":1791001638840}}
51
+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"progress 50%\rprogress 100%\n"},"emittedAtMs":1791001639845}}
52
+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc \"for i in 1 2 3 4; do printf '\\\\033[32mstream line %s\\\\033[0m\\\\n' \"'$i; sleep 1; done; printf '\"'progress 50%%\\\\rprogress 100%%\\\\n'\"","cwd":"/home/replay-user/t3code/apps/server","processId":"44027","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"unknown","command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}],"aggregatedOutput":"\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%\n","exitCode":0,"durationMs":3903},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001639846},"emittedAtMs":1791001639848}}
53
+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","tokenUsage":{"total":{"totalTokens":17795,"inputTokens":17653,"cachedInputTokens":3840,"cacheWriteInputTokens":0,"outputTokens":142,"reasoningOutputTokens":0},"last":{"totalTokens":17795,"inputTokens":17653,"cachedInputTokens":3840,"cacheWriteInputTokens":0,"outputTokens":142,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1791001639853}}
54
+{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1791001639853}}
55
+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001642659},"emittedAtMs":1791001642660}}
56
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":"command"},"emittedAtMs":1791001642660}}
57
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" output"},"emittedAtMs":1791001642660}}
58
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" fixture"},"emittedAtMs":1791001642660}}
59
+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" complete"},"emittedAtMs":1791001642870}}
60
+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"command output fixture complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001642938},"emittedAtMs":1791001642940}}
61
+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","tokenUsage":{"total":{"totalTokens":35682,"inputTokens":35532,"cachedInputTokens":20992,"cacheWriteInputTokens":0,"outputTokens":150,"reasoningOutputTokens":0},"last":{"totalTokens":17887,"inputTokens":17879,"cachedInputTokens":17152,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1791001642955}}
62
+{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1791001642955}}
63
+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"idle"}},"emittedAtMs":1791001642982}}
64
+{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"command output fixture complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1791001627,"completedAt":1791001642,"durationMs":15546}},"emittedAtMs":1791001642982}}
65
+{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/input.ts
new
+7
@@ -0,0 +1,7 @@
1
+import { COMMAND_OUTPUT_STREAMING_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
2
+
3
+export function commandOutputStreamingInput(): OrchestratorFixtureInput {
4
+ return {
5
+ steps: [{ type: "message", text: COMMAND_OUTPUT_STREAMING_PROMPT }],
6
+ };
7
+}
apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/output.ts
new
+69
@@ -0,0 +1,69 @@
1
+import { assert } from "@effect/vitest";
2
+import type { ProviderReplayTranscript } from "@t3tools/contracts";
3
+import { normalizeTerminalOutput, terminalOutputPlainText } from "@t3tools/shared/terminalOutput";
4
+
5
+import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
6
+import {
7
+ assertBaseProjection,
8
+ assertSemanticProjectionIntegrity,
9
+ assertUserMessagesInclude,
10
+ assertVisibleTurnItemsMirrorLocalTurnItems,
11
+ COMMAND_OUTPUT_STREAMING_PROMPT,
12
+ projectionFor,
13
+} from "../shared.ts";
14
+
15
+/**
16
+ * A command that prints for a few seconds streams its output live, and that
17
+ * output never becomes an orchestration event: the command item is persisted
18
+ * while running with no output, then once with its final output.
19
+ */
20
+export function assertCommandOutputStreamingOutput(
21
+ result: OrchestratorV2ScenarioResult,
22
+ transcript: ProviderReplayTranscript,
23
+) {
24
+ assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
25
+ const projection = projectionFor(result, transcript.scenario);
26
+ assertSemanticProjectionIntegrity(projection);
27
+ assertVisibleTurnItemsMirrorLocalTurnItems(projection);
28
+ assertUserMessagesInclude(projection, [COMMAND_OUTPUT_STREAMING_PROMPT]);
29
+
30
+ const command = projection.turnItems.find((item) => item.type === "command_execution");
31
+ assert.isDefined(command);
32
+ assert.equal(command?.type, "command_execution");
33
+ if (command?.type !== "command_execution") return;
34
+ assert.equal(command.status, "completed");
35
+ assert.include(command.output ?? "", "progress 100%");
36
+
37
+ // Live output reached the hub, cleaned of escapes and the progress redraw.
38
+ const streamed = result.commandOutput?.get(command.id);
39
+ assert.isDefined(streamed, "the running command must stream its output");
40
+ assert.isAbove(streamed?.chunks ?? 0, 0);
41
+ const liveText = streamed?.output.text ?? "";
42
+ const live = terminalOutputPlainText(liveText);
43
+ // Codex never streams what a command prints before its first yield (the recorded
44
+ // session has no delta, and no aggregatedOutput, for line 1), so it is not asserted.
45
+ for (const line of ["stream line 2", "stream line 3", "stream line 4", "progress 100%"]) {
46
+ assert.include(live, line);
47
+ }
48
+ // The command's green survives as a canonical colour code; nothing else does.
49
+ assert.include(liveText, "\u001b[0;32mstream line 2\u001b[0m");
50
+ assert.notInclude(live, "\u001b");
51
+ assert.notInclude(live, "progress 50%");
52
+ // What viewers watched is the end of what the row keeps once it settles.
53
+ const final = terminalOutputPlainText(normalizeTerminalOutput(command.output ?? "").text);
54
+ assert.isTrue(
55
+ final.trimEnd().endsWith(live.trimEnd()),
56
+ `the live tail must agree with the persisted final output: ${JSON.stringify({ final, live })}`,
57
+ );
58
+ // The row shows what the command printed, not a serialized tool result.
59
+ assert.notInclude(final, '"stdout"');
60
+
61
+ // Never persisted while running: no event carries partial command output.
62
+ const commandEvents = result.domainEvents.flatMap((event) =>
63
+ event.type === "turn-item.updated" && event.payload.id === command.id ? [event.payload] : [],
64
+ );
65
+ for (const item of commandEvents) {
66
+ if (item.type !== "command_execution" || item.status === "completed") continue;
67
+ assert.isUndefined(item.output, "a running command item must not persist live output");
68
+ }
69
+}
apps/server/src/orchestration-v2/testkit/fixtures/index.ts
+27
@@ -186,6 +186,8 @@ import { assertToolCallWorkspaceNeverClaudeOutput } from "./tool_call_workspace_
186
import { assertToolCallWorkspaceNeverOutput } from "./tool_call_workspace_never/codex_output.ts";
187
import { toolCallWorkspaceNeverInput } from "./tool_call_workspace_never/input.ts";
188
import { assertTurnInterruptClaudeOutput } from "./turn_interrupt/claude_output.ts";
189
+import { assertCommandOutputStreamingOutput } from "./command_output_streaming/output.ts";
190
+import { commandOutputStreamingInput } from "./command_output_streaming/input.ts";
191
import { assertTurnInterruptOutput } from "./turn_interrupt/codex_output.ts";
192
import { turnInterruptInput } from "./turn_interrupt/input.ts";
193
import { assertTurnInterruptMidToolClaudeOutput } from "./turn_interrupt_mid_tool/claude_output.ts";
@@ -1567,6 +1569,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
1569
},
1570
],
1571
},
1572
+ {
1573
+ name: "command_output_streaming",
1574
+ buildInput: commandOutputStreamingInput,
1575
+ providers: [
1576
+ {
1577
+ driver: ProviderDriverKind.make("codex"),
1578
+ transcriptFile: new URL(
1579
+ "./command_output_streaming/codex_transcript.ndjson",
1580
+ import.meta.url,
1581
+ ),
1582
+ modelSelection: CODEX_MODEL_SELECTION,
1583
+ runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
1584
+ assertOutput: assertCommandOutputStreamingOutput,
1585
+ },
1586
+ {
1587
+ driver: ProviderDriverKind.make("claudeAgent"),
1588
+ transcriptFile: new URL(
1589
+ "./command_output_streaming/claude_transcript.ndjson",
1590
+ import.meta.url,
1591
+ ),
1592
+ modelSelection: CLAUDE_MODEL_SELECTION,
1593
+ assertOutput: assertCommandOutputStreamingOutput,
1594
+ },
1595
+ ],
1596
+ },
1597
{
1598
name: "turn_interrupt_mid_tool",
1599
buildInput: turnInterruptMidToolInput,
apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
+4
@@ -102,6 +102,10 @@ export const TURN_INTERRUPT_PROMPT =
102
"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.";
103
export const TURN_INTERRUPT_MID_TOOL_PROMPT =
104
"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.";
105
+/** A command that prints over a few seconds, with colour and a carriage-return redraw. */
106
+const COMMAND_OUTPUT_STREAMING_COMMAND =
107
+ "for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'";
108
+export const COMMAND_OUTPUT_STREAMING_PROMPT = `Run this exact shell command in the foreground and wait for it to finish: \`${COMMAND_OUTPUT_STREAMING_COMMAND}\`. Then respond exactly: command output fixture complete`;
109
export const TURN_INTERRUPT_RECOVERY_PROMPT =
110
"Respond with exactly: interrupt recovery fixture complete";
111
export const MESSAGE_STEERING_STEER_PROMPT =
apps/server/src/ws.ts
+8
@@ -117,6 +117,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";
117
import * as Keybindings from "./keybindings.ts";
118
import * as ExternalLauncher from "./process/externalLauncher.ts";
119
import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts";
120
+import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";
121
import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
122
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
123
import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
@@ -1239,6 +1240,7 @@ const layerWsRpc = (
1240
}
1241
};
1242
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
1243
+ const commandOutputHub = yield* CommandOutputHub.CommandOutputHub;
1244
const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1245
const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;
1246
const secretRequests = yield* SecretRequests.SecretRequests;
@@ -2068,6 +2070,12 @@ const layerWsRpc = (
2070
Effect.andThen(subscribeOrchestrationV2Thread(input)),
2071
),
2072
),
2073
+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) =>
2074
+ Stream.unwrap(
2075
+ Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2076
+ Effect.as(commandOutputHub.subscribe(input)),
2077
+ ),
2078
+ ),
2079
[WS_METHODS.scheduledTasksList]: (_input) =>
2080
scheduledTasks.list().pipe(Effect.map(withVisibleWebhookUrls)),
2081
[WS_METHODS.scheduledTasksSubscribe]: (_input) =>
apps/web/src/components/chat/CommandOutputPanel.tsx
new
+85
@@ -0,0 +1,85 @@
1
+import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
2
+import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";
3
+import { useLayoutEffect, useMemo, useRef } from "react";
4
+
5
+import { useTheme } from "../../hooks/useTheme";
6
+import { useServerConfigs } from "../../state/entities";
7
+import { orchestrationEnvironment } from "../../state/orchestration";
8
+import { useEnvironmentQuery } from "../../state/query";
9
+
10
+// Within this many pixels of the end still counts as following the output.
11
+const FOLLOW_SLACK_PX = 8;
12
+
13
+/** True when the environment streams command output; older servers only return final output. */
14
+export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean {
15
+ return (
16
+ useServerConfigs().get(environmentId)?.environment.capabilities.commandOutputStreaming === true
17
+ );
18
+}
19
+
20
+/**
21
+ * Output of one expanded command row: streams while the command runs, then
22
+ * shows its final output. Mount it only when `useCommandOutputStreaming` holds.
23
+ * It subscribes only while mounted, so collapsed rows and other threads receive nothing.
24
+ */
25
+export function CommandOutputPanel(props: {
26
+ readonly environmentId: EnvironmentId;
27
+ readonly threadId: ThreadId;
28
+ readonly itemId: TurnItemId;
29
+}) {
30
+ const { data, error } = useEnvironmentQuery(
31
+ orchestrationEnvironment.v2.commandOutput({
32
+ environmentId: props.environmentId,
33
+ input: { threadId: props.threadId, itemId: props.itemId },
34
+ }),
35
+ );
36
+ const scrollRef = useRef<HTMLDivElement>(null);
37
+ // Follow new output until the reader scrolls up; scrolling back down resumes.
38
+ const followRef = useRef(true);
39
+ const text = data?.output.text ?? "";
40
+ const { resolvedTheme } = useTheme();
41
+ const spans = useMemo(
42
+ () => terminalOutputSpans(text, TERMINAL_PALETTES[resolvedTheme]),
43
+ [text, resolvedTheme],
44
+ );
45
+
46
+ // This panel only re-renders when its output changes, so keep the end in view after each.
47
+ useLayoutEffect(() => {
48
+ const element = scrollRef.current;
49
+ if (element && followRef.current) element.scrollTop = element.scrollHeight;
50
+ });
51
+
52
+ if (text.length === 0) {
53
+ if (error) return <div className="text-destructive">Couldn't load output: {error}</div>;
54
+ if (data === null) return <div className="text-muted-foreground italic">Loading output…</div>;
55
+ return data.running ? null : <div className="text-muted-foreground italic">No output.</div>;
56
+ }
57
+ return (
58
+ <div>
59
+ {data?.output.truncated ? (
60
+ <div className="text-muted-foreground italic">Earlier output not shown</div>
61
+ ) : null}
62
+ <div
63
+ ref={scrollRef}
64
+ onScroll={(event) => {
65
+ const element = event.currentTarget;
66
+ followRef.current =
67
+ element.scrollHeight - element.scrollTop - element.clientHeight <= FOLLOW_SLACK_PX;
68
+ }}
69
+ className="max-h-80 overflow-auto text-muted-foreground"
70
+ >
71
+ {spans.map((span, index) =>
72
+ span.style === null ? (
73
+ span.text
74
+ ) : (
75
+ // Spans are rebuilt from scratch on every update and never reorder.
76
+ // oxlint-disable-next-line react/no-array-index-key
77
+ <span key={index} style={span.style}>
78
+ {span.text}
79
+ </span>
80
+ ),
81
+ )}
82
+ </div>
83
+ </div>
84
+ );
85
+}
apps/web/src/components/chat/V2ItemInspector.tsx
+21
-4
@@ -14,7 +14,7 @@ import {
14
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
15
import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity";
16
import { ExternalLinkIcon, GitBranchIcon, RotateCcwIcon } from "lucide-react";
17
-import { memo, Suspense, use, useMemo } from "react";
17
+import { memo, type ReactNode, Suspense, use, useMemo } from "react";
18
19
import { useTheme } from "../../hooks/useTheme";
20
import { cn } from "../../lib/utils";
@@ -26,6 +26,7 @@ import { formatWorkspaceRelativePath } from "../../filePathDisplay";
26
import { Button } from "../ui/button";
27
import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
28
import { RenderErrorBoundary } from "../RenderErrorBoundary";
29
+import { CommandOutputPanel, useCommandOutputStreaming } from "./CommandOutputPanel";
30
import { resolveExternalWebLinkHref } from "./externalLinkContextMenu";
31
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
32
import { ShellCommandBlock } from "./ShellCommandBlock";
@@ -116,9 +117,10 @@ function StructuredValue({
117
function useFetchedTurnItem(
118
projectedItem: OrchestrationV2ProjectedTurnItem,
119
environmentId: EnvironmentId,
120
+ skip = false,
121
) {
122
const wireItem = projectedItem.item;
121
- const fetches = turnItemNeedsDetailFetch(wireItem);
123
+ const fetches = !skip && turnItemNeedsDetailFetch(wireItem);
124
const detail = useTurnItemDetail(
125
fetches
126
? {
@@ -208,6 +210,8 @@ function ToolCallBody(
210
readonly args?: unknown;
211
readonly toolName?: string | null;
212
readonly exitCode?: number | undefined;
213
+ /** Replaces the fetched output, e.g. with a command's live output. */
214
+ readonly outputSlot?: ReactNode;
215
},
216
) {
217
const call = toolCallLines({ command: props.command, args: props.args });
@@ -229,7 +233,7 @@ function ToolCallBody(
233
</div>
234
) : null}
235
{call.argsText ? <StructuredValue value={call.argsText} highlightJson /> : null}
232
- <ToolOutput {...props} />
236
+ {props.outputSlot ?? <ToolOutput {...props} />}
237
{props.exitCode !== undefined && props.exitCode !== 0 ? (
238
<div className="text-destructive">exit {props.exitCode}</div>
239
) : null}
@@ -238,7 +242,11 @@ function ToolCallBody(
242
}
243
244
export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {
241
- const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId);
245
+ // Command rows stream their output, including the final output, from the server.
246
+ const streamsOutput =
247
+ useCommandOutputStreaming(props.environmentId) &&
248
+ props.projectedItem.item.type === "command_execution";
249
+ const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId, streamsOutput);
250
const item = fetched.item;
251
const outputState = fetched.output;
252
const support = useV2ItemSupport({
@@ -268,6 +276,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
276
exitCode={item.exitCode}
277
{...outputState}
278
onImageExpand={props.onImageExpand}
279
+ outputSlot={
280
+ streamsOutput ? (
281
+ <CommandOutputPanel
282
+ environmentId={props.environmentId}
283
+ threadId={props.projectedItem.sourceThreadId}
284
+ itemId={props.projectedItem.sourceItemId}
285
+ />
286
+ ) : undefined
287
+ }
288
/>
289
) : null}
290
docs/internals/performance-regressions.md
+7
@@ -34,6 +34,13 @@ The v2 checks pin these invariants:
34
Explicit cross-environment transcript exports preserve full tool bodies so the destination
35
agent can read the context. The export rejects timeline JSON above the file attachment limit
36
before sending it; the client still applies its attachment limit to the complete file.
37
+- Live command output reaches a client only through `orchestration.subscribeCommandOutput`, which
38
+ an expanded command row opens and closes with itself. Raw output deltas are never orchestration
39
+ events: adapters send them to the
40
+ [command output hub](../../apps/server/src/orchestration-v2/CommandOutputHub.ts) ahead of
41
+ ingestion, which keeps one bounded tail per running command and throttles each subscriber. Do not
42
+ route output deltas through `turn_item.updated`: a busy command would flood the event store and
43
+ block ingestion for every other thread.
44
- The initial shell contains active navigation rows only. Archived rows use the dedicated archive
45
query, and transcript message bodies stay in thread detail regardless of message size.
46
- Shell resume sends deltas plus compact repository-enrichment metadata, not another full project
docs/user/activity-log.md
+3
-2
@@ -1,8 +1,9 @@
1
# Activity log
2
3
On web and desktop, consecutive tool calls appear as an expandable summary. Open it to inspect
4
-commands, tool inputs, status, and exit codes. Raw command output and tool-result bodies are not
5
-shown. Use **Open diff** on a file change to review its contents.
4
+commands, tool inputs, status, and exit codes. Expand a tool call to see its output. A running
5
+command's output updates live, and long output shows only its most recent part. Use **Open diff** on
6
+a file change to review its contents.
7
8
T3 Orchestrator summaries describe the actions taken, such as **Ran 2 commands and sent messages
9
to 3 threads**. Repeated messages to the same destinations show both counts: **Sent 5 messages to
packages/client-runtime/package.json
+4
@@ -163,6 +163,10 @@
163
"types": "./src/state/git.ts",
164
"default": "./src/state/git.ts"
165
},
166
+ "./state/command-output": {
167
+ "types": "./src/state/commandOutput.ts",
168
+ "default": "./src/state/commandOutput.ts"
169
+ },
170
"./state/item-support": {
171
"types": "./src/state/itemSupport.ts",
172
"default": "./src/state/itemSupport.ts"
packages/client-runtime/src/rpc/client.ts
+1
@@ -53,6 +53,7 @@ export type EnvironmentSubscriptionRpcTag =
53
| typeof WS_METHODS.providerInstallSubscribe
54
| typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell
55
| typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread
56
+ | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput
57
| typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream
58
| typeof WS_METHODS.subscribeAuthAccess
59
| typeof WS_METHODS.subscribeServerConfig
packages/client-runtime/src/state/commandOutput.test.ts
new
+53
@@ -0,0 +1,53 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";
4
+
5
+describe("applyCommandOutputFrame", () => {
6
+ it("continues an escape and a redraw split across appends", () => {
7
+ let view = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {
8
+ kind: "replace",
9
+ text: "install\n12%\u001b[3",
10
+ truncated: false,
11
+ running: true,
12
+ });
13
+ expect(view.output.text).toBe("install\n12%");
14
+ view = applyCommandOutputFrame(view, {
15
+ kind: "append",
16
+ text: "2m\r100%\u001b[0m\n",
17
+ truncated: false,
18
+ running: true,
19
+ });
20
+ // The colour opened before the redraw survives it.
21
+ expect(view.output.text).toBe("install\n\u001b[0;32m100%\u001b[0m\n");
22
+ expect(view.running).toBe(true);
23
+ });
24
+
25
+ it("starts over from the tail a reconnect sends, keeping only that", () => {
26
+ const stale = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {
27
+ kind: "replace",
28
+ text: "line 1\n",
29
+ truncated: false,
30
+ running: true,
31
+ });
32
+ const resumed = applyCommandOutputFrame(stale, {
33
+ kind: "replace",
34
+ text: "line 7\nline 8\n",
35
+ truncated: true,
36
+ running: true,
37
+ });
38
+ expect(resumed.output.text).toBe("line 7\nline 8\n");
39
+ expect(resumed.output.truncated).toBe(true);
40
+ });
41
+
42
+ it("marks the output final when the command settles", () => {
43
+ const view = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {
44
+ kind: "replace",
45
+ text: "done\n",
46
+ truncated: false,
47
+ running: false,
48
+ });
49
+ expect(view.output.text).toBe("done\n");
50
+ expect(view.output.truncated).toBe(false);
51
+ expect(view.running).toBe(false);
52
+ });
53
+});
packages/client-runtime/src/state/commandOutput.ts
new
+37
@@ -0,0 +1,37 @@
1
+import type { OrchestrationV2CommandOutputFrame } from "@t3tools/contracts";
2
+import {
3
+ appendTerminalOutput,
4
+ EMPTY_TERMINAL_OUTPUT,
5
+ type TerminalOutputState,
6
+} from "@t3tools/shared/terminalOutput";
7
+
8
+/** One command row's output as a client holds it. */
9
+export interface CommandOutputView {
10
+ readonly output: TerminalOutputState;
11
+ /** False once the command settled and `output` is final. */
12
+ readonly running: boolean;
13
+}
14
+
15
+export const EMPTY_COMMAND_OUTPUT: CommandOutputView = {
16
+ output: EMPTY_TERMINAL_OUTPUT,
17
+ running: true,
18
+};
19
+
20
+/**
21
+ * Applies one server frame. A `replace` carries the whole bounded tail (the
22
+ * first frame, a viewer that fell behind, or the final output); an `append`
23
+ * is raw terminal text normalized with the same rules the server uses.
24
+ */
25
+export function applyCommandOutputFrame(
26
+ view: CommandOutputView,
27
+ frame: OrchestrationV2CommandOutputFrame,
28
+): CommandOutputView {
29
+ const base = frame.kind === "replace" ? EMPTY_TERMINAL_OUTPUT : view.output;
30
+ return {
31
+ output: appendTerminalOutput(
32
+ { ...base, truncated: base.truncated || frame.truncated },
33
+ frame.text,
34
+ ),
35
+ running: frame.running,
36
+ };
37
+}
packages/client-runtime/src/state/orchestration.ts
+16
@@ -1,10 +1,13 @@
1
import { ORCHESTRATION_V2_WS_METHODS, type ThreadId } from "@t3tools/contracts";
2
import * as Effect from "effect/Effect";
3
import * as Option from "effect/Option";
4
+import * as Stream from "effect/Stream";
5
import * as SubscriptionRef from "effect/SubscriptionRef";
6
import type { HttpClient } from "effect/http";
7
import { Atom } from "effect/reactivity";
8
9
+import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";
10
+
11
import {
12
createEnvironmentRpcCommand,
13
createEnvironmentRpcQueryAtomFamily,
@@ -64,6 +67,19 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
67
tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread,
68
idleTtlMs: 0,
69
}),
70
+ // One expanded command row's output. Mounted only while the row is open,
71
+ // and released as soon as it closes, so hidden rows receive nothing.
72
+ commandOutput: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
73
+ label: "environment-data:orchestration-v2:command-output",
74
+ tag: ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,
75
+ idleTtlMs: 0,
76
+ // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.
77
+ transform: (frames) =>
78
+ frames.pipe(
79
+ Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),
80
+ Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),
81
+ ),
82
+ }),
83
},
84
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
85
label: "environment-data:orchestration:turn-diff",
packages/contracts/src/environment.ts
+3
@@ -221,6 +221,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
221
desktop servers whose app predates the remote trigger, where clients
222
must keep telling the user to update the app on that machine. */
223
desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
224
+ /** Server answers orchestration.subscribeCommandOutput. Absent on older servers,
225
+ which never send command output, so clients must not subscribe. */
226
+ commandOutputStreaming: Schema.optionalKey(Schema.Boolean),
227
/** Server hosts preview tabs in its own headless Chromium (`runtime:
228
"server"`) and streams them over `/api/preview-stream`. Clients
229
without a local browser runtime open server tabs here. */
packages/contracts/src/orchestrationV2.ts
+40
@@ -3283,8 +3283,44 @@ export const ORCHESTRATION_V2_WS_METHODS = {
3283
subscribeArchivedShell: "orchestration.subscribeArchivedShell",
3284
subscribeShell: "orchestration.subscribeShell",
3285
subscribeThread: "orchestration.subscribeThread",
3286
+ subscribeCommandOutput: "orchestration.subscribeCommandOutput",
3287
} as const;
3288
3289
+export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({
3290
+ threadId: ThreadId,
3291
+ itemId: TurnItemId,
3292
+});
3293
+export type OrchestrationV2SubscribeCommandOutputInput =
3294
+ typeof OrchestrationV2SubscribeCommandOutputInput.Type;
3295
+
3296
+/**
3297
+ * Output of one command row, separate from the thread stream so it is never
3298
+ * persisted as events and only reaches clients that show the row expanded.
3299
+ * `replace` carries the whole bounded tail (first frame, or after the client
3300
+ * fell behind); `append` extends it. Text is terminal output, not display
3301
+ * text: `replace` carries the cleaned tail plus the cursor and style escapes
3302
+ * needed to resume, and `append` carries raw chunks. Clients must feed both
3303
+ * through `appendTerminalOutput` from `@t3tools/shared/terminalOutput`.
3304
+ * The stream ends after a frame with `running: false`.
3305
+ */
3306
+export const OrchestrationV2CommandOutputFrame = Schema.Struct({
3307
+ kind: Schema.Literals(["replace", "append"]),
3308
+ text: Schema.String,
3309
+ /** Earlier output was dropped to keep the tail bounded. */
3310
+ truncated: Schema.Boolean,
3311
+ running: Schema.Boolean,
3312
+});
3313
+export type OrchestrationV2CommandOutputFrame = typeof OrchestrationV2CommandOutputFrame.Type;
3314
+
3315
+export class OrchestrationV2CommandOutputError extends Schema.TaggedError<OrchestrationV2CommandOutputError>()(
3316
+ "OrchestrationV2CommandOutputError",
3317
+ {
3318
+ threadId: ThreadId,
3319
+ message: Schema.String,
3320
+ cause: Schema.optional(Schema.Defect()),
3321
+ },
3322
+) {}
3323
+
3324
export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({
3325
schemaVersion: PositiveInt,
3326
snapshotSequence: NonNegativeInt,
@@ -3817,6 +3853,10 @@ export const OrchestrationV2RpcSchemas = {
3853
input: OrchestrationV2SubscribeThreadInput,
3854
output: OrchestrationV2ThreadStreamItem,
3855
},
3856
+ subscribeCommandOutput: {
3857
+ input: OrchestrationV2SubscribeCommandOutputInput,
3858
+ output: OrchestrationV2CommandOutputFrame,
3859
+ },
3860
} as const;
3861
3862
export const ProviderReplayEntry = Schema.Union([
packages/contracts/src/rpc.ts
+12
@@ -212,6 +212,7 @@ import {
212
OrchestrationV2StopWorkflowError,
213
OrchestrationV2DispatchCommandError,
214
OrchestrationV2GetShellSnapshotError,
215
+ OrchestrationV2CommandOutputError,
216
OrchestrationV2GetThreadProjectionError,
217
OrchestrationV2RpcSchemas,
218
OrchestrationV2ThreadLaunchError,
@@ -1738,6 +1739,16 @@ const WsOrchestrationV2SubscribeThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS
1739
stream: true,
1740
});
1741
1742
+const WsOrchestrationV2SubscribeCommandOutputRpc = Rpc.make(
1743
+ ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,
1744
+ {
1745
+ payload: OrchestrationV2RpcSchemas.subscribeCommandOutput.input,
1746
+ success: OrchestrationV2RpcSchemas.subscribeCommandOutput.output,
1747
+ error: Schema.Union([OrchestrationV2CommandOutputError, EnvironmentAuthorizationError]),
1748
+ stream: true,
1749
+ },
1750
+);
1751
+
1752
const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, {
1753
payload: Schema.Struct({}),
1754
success: TerminalEvent,
@@ -2079,4 +2090,5 @@ export const WsRpcGroup = RpcGroup.make(
2090
WsOrchestrationV2SubscribeArchivedShellRpc,
2091
WsOrchestrationV2SubscribeShellRpc,
2092
WsOrchestrationV2SubscribeThreadRpc,
2093
+ WsOrchestrationV2SubscribeCommandOutputRpc,
2094
).middleware(RpcScopeAuthorization);
packages/provider-core/src/server/ProviderAdapter.ts
+13
@@ -32,6 +32,7 @@ import {
32
RunAttemptId,
33
RunId,
34
ThreadId,
35
+ TurnItemId,
36
} from "@t3tools/contracts";
37
import * as Context from "effect/Context";
38
import * as Schema from "effect/Schema";
@@ -124,6 +125,18 @@ export const ProviderAdapterV2Event = Schema.Union([
125
driver: ProviderDriverKind,
126
turnItem: OrchestrationV2TurnItem,
127
}),
128
+ /**
129
+ * Raw output from a running command. Never persisted: the session manager
130
+ * hands it to the command output hub, which only clients showing the row see.
131
+ * The item's final output still arrives in its `turn_item.updated`.
132
+ */
133
+ Schema.Struct({
134
+ type: Schema.Literal("command_output.delta"),
135
+ driver: ProviderDriverKind,
136
+ threadId: ThreadId,
137
+ itemId: TurnItemId,
138
+ chunk: Schema.String,
139
+ }),
140
Schema.Struct({
141
type: Schema.Literal("runtime_request.updated"),
142
driver: ProviderDriverKind,
packages/provider-cursor/src/server/adapter.ts
+22
-2
@@ -788,6 +788,10 @@ interface CursorProjectionTarget {
788
readonly providerTurnId: OrchestrationV2ProviderTurn["id"] | null;
789
}
790
791
+// Fallback final output when Cursor's result carries none. The persisted row only
792
+// ever shows a bounded tail, so keep a little more than that.
793
+const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024;
794
+
795
interface ActiveCursorToolCall {
796
readonly callId: string;
797
toolCall: ToolCall;
@@ -1922,8 +1926,24 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
1926
if (shell === undefined) {
1927
return;
1928
}
1925
- shell.streamedOutput += shellOutputText(update.event);
1926
- yield* emitToolArtifacts({ active: shell, completed: false });
1929
+ const chunk = shellOutputText(update.event);
1930
+ if (chunk.length === 0) return;
1931
+ // The completed call persists the final output once. Re-emitting the
1932
+ // whole accumulated output on every delta grew the event store
1933
+ // quadratically; live output goes to the command output hub instead.
1934
+ shell.streamedOutput = (shell.streamedOutput + chunk).slice(
1935
+ -MAX_CURSOR_STREAMED_OUTPUT_CHARS,
1936
+ );
1937
+ yield* emitProviderEvent({
1938
+ type: "command_output.delta",
1939
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
1940
+ threadId: shell.target.threadId,
1941
+ itemId: idAllocator.derive.turnItemFromProviderItem({
1942
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
1943
+ nativeItemId: shell.callId,
1944
+ }),
1945
+ chunk,
1946
+ });
1947
return;
1948
}
1949
default:
packages/shared/package.json
+4
@@ -119,6 +119,10 @@
119
"types": "./src/toolActivity.ts",
120
"import": "./src/toolActivity.ts"
121
},
122
+ "./terminalOutput": {
123
+ "types": "./src/terminalOutput.ts",
124
+ "import": "./src/terminalOutput.ts"
125
+ },
126
"./toolOutput": {
127
"types": "./src/toolOutput.ts",
128
"import": "./src/toolOutput.ts"
packages/shared/src/terminalOutput.test.ts
new
+279
@@ -0,0 +1,279 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ appendTerminalOutput,
5
+ EMPTY_TERMINAL_OUTPUT,
6
+ normalizeTerminalOutput,
7
+ TERMINAL_PALETTES,
8
+ terminalOutputPlainText,
9
+ terminalOutputResumeText,
10
+ terminalOutputSpans,
11
+ terminalOutputTail,
12
+ type TerminalOutputState,
13
+} from "./terminalOutput.ts";
14
+
15
+function feed(chunks: ReadonlyArray<string>, maxChars?: number): TerminalOutputState {
16
+ return chunks.reduce(
17
+ (state, chunk) => appendTerminalOutput(state, chunk, maxChars),
18
+ EMPTY_TERMINAL_OUTPUT,
19
+ );
20
+}
21
+
22
+const plain = (input: string) => terminalOutputPlainText(normalizeTerminalOutput(input).text);
23
+
24
+describe("appendTerminalOutput", () => {
25
+ it("keeps colours as canonical codes that reset at each line end", () => {
26
+ expect(normalizeTerminalOutput("\u001b[1;32mPASS\u001b[0m ok\u001b]0;title\u0007\n").text).toBe(
27
+ "\u001b[0;1;32mPASS\u001b[0m ok\n",
28
+ );
29
+ // A colour left on across a newline is restated on the next line.
30
+ expect(normalizeTerminalOutput("\u001b[31mone\ntwo").text).toBe(
31
+ "\u001b[0;31mone\u001b[0m\n\u001b[0;31mtwo\u001b[0m",
32
+ );
33
+ });
34
+
35
+ it("keeps only the latest frame of a carriage-return progress bar", () => {
36
+ expect(feed(["[1/3]", "\r[2/3]", "\r[3/3] done\nnext"]).text).toBe("[3/3] done\nnext");
37
+ });
38
+
39
+ it("redraws several lines in place when the cursor moves up", () => {
40
+ // docker pull / pnpm style: print two bars, move up two lines, redraw both.
41
+ const frames = [
42
+ "layer a: 10%\nlayer b: 10%\n",
43
+ "\u001b[2A\u001b[2Klayer a: 60%\n\u001b[2Klayer b: 40%\n",
44
+ "\u001b[2A\u001b[2Klayer a: done\n\u001b[2Klayer b: done\n",
45
+ ];
46
+ expect(feed(frames).text).toBe("layer a: done\nlayer b: done\n");
47
+ });
48
+
49
+ it("erases from the cursor to the end of the screen", () => {
50
+ // log-update style: move up, clear everything below, print the new frame.
51
+ expect(plain("status 1\ndetail 1\n\u001b[2A\u001b[Jstatus 2\n")).toBe("status 2\n");
52
+ });
53
+
54
+ it("overwrites in place like a terminal: carriage return, backspace, columns", () => {
55
+ expect(plain("progress 100%\rdone\u001b[K")).toBe("done");
56
+ expect(plain("abc\b\bX")).toBe("aXc");
57
+ expect(plain("12345\u001b[3GX")).toBe("12X45");
58
+ });
59
+
60
+ it("treats CRLF as one newline even when the pair is split across chunks", () => {
61
+ const state = feed(["one\r", "\ntwo\r\n"]);
62
+ expect(state.text).toBe("one\ntwo\n");
63
+ expect(state.pending).toBe("");
64
+ });
65
+
66
+ it("holds an escape sequence split across chunks until it finishes", () => {
67
+ const first = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, "red: \u001b[3");
68
+ expect(first.text).toBe("red: ");
69
+ expect(feed(["red: \u001b[3", "1mR\u001b[0m"]).text).toBe("red: \u001b[0;31mR\u001b[0m");
70
+ });
71
+
72
+ it("drops binary control bytes but keeps tabs and replacement characters", () => {
73
+ expect(normalizeTerminalOutput("a\u0000b\u0007\tc�\u0090d").text).toBe("ab\tc�d");
74
+ });
75
+
76
+ it("keeps a bounded tail that starts on a fresh line", () => {
77
+ const lines = Array.from({ length: 2_000 }, (_, index) => `line ${index}`).join("\n");
78
+ const state = feed([lines], 1_000);
79
+ expect(state.truncated).toBe(true);
80
+ expect(state.text.length).toBeLessThanOrEqual(1_000);
81
+ expect(state.text.startsWith("line ")).toBe(true);
82
+ expect(state.text.endsWith("line 1999")).toBe(true);
83
+ });
84
+
85
+ it("stays bounded across many appends of huge output, including one endless line", () => {
86
+ let state = EMPTY_TERMINAL_OUTPUT;
87
+ for (let index = 0; index < 5_000; index += 1) {
88
+ state = appendTerminalOutput(state, "y\n".repeat(200), 4_096);
89
+ }
90
+ expect(state.text.length).toBeLessThanOrEqual(4_096);
91
+ expect(state.truncated).toBe(true);
92
+ for (let index = 0; index < 1_000; index += 1) {
93
+ state = appendTerminalOutput(state, ".".repeat(100), 4_096);
94
+ }
95
+ expect(state.text.length).toBeLessThanOrEqual(4_096);
96
+ expect(state.text.endsWith(".")).toBe(true);
97
+ });
98
+
99
+ it("hides a long string sequence's payload however it is split into chunks", () => {
100
+ const input = `a\u001b]0;${"t".repeat(100)}\u0007b`;
101
+ expect(feed([input]).text).toBe("ab");
102
+ expect(feed(["a\u001b]0;", "t".repeat(100), "\u0007b"]).text).toBe("ab");
103
+ expect(feed([`a\u001b]0;${"t".repeat(80)}`, "\u001b", "\\b"]).text).toBe("ab");
104
+ });
105
+
106
+ it("hides an SOS string sequence and its payload", () => {
107
+ expect(normalizeTerminalOutput("a\u001bXhidden \u001b\\b").text).toBe("ab");
108
+ });
109
+
110
+ it("drops an escape sequence that never terminates and resumes after it", () => {
111
+ expect(feed(["ok\u001b]", "x".repeat(200), "\nafter"]).text).toBe("ok\nafter");
112
+ });
113
+});
114
+
115
+describe("appendTerminalOutput edge cases from review", () => {
116
+ it("reads colon-form true colour with or without a colour-space id", () => {
117
+ const red = normalizeTerminalOutput("\u001b[38:2::255:0:0mR").text;
118
+ expect(red).toBe("\u001b[0;38;2;255;0;0mR\u001b[0m");
119
+ expect(normalizeTerminalOutput("\u001b[38:2:0:255:0:0mR").text).toBe(red);
120
+ });
121
+
122
+ it("clears only scrollback on ESC[3J", () => {
123
+ const lines = Array.from({ length: 70 }, (_, index) => `line ${index}`).join("\n");
124
+ const state = feed([lines, "\u001b[3J"]);
125
+ expect(state.text.startsWith("line 6\n")).toBe(true);
126
+ expect(state.text.endsWith("line 69")).toBe(true);
127
+ expect(state.truncated).toBe(true);
128
+ });
129
+
130
+ it("keeps the whole window within the tail when every line is long", () => {
131
+ const long = `${"x".repeat(900)}\n`;
132
+ const state = feed([long.repeat(64)], 4_096);
133
+ const windowChars = state.screen.lines.reduce(
134
+ (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),
135
+ 0,
136
+ );
137
+ expect(windowChars).toBeLessThanOrEqual(4_096);
138
+ expect(state.text.length).toBeLessThanOrEqual(4_096);
139
+ });
140
+
141
+ it("bounds long lines below a cursor that moved up", () => {
142
+ const long = `${"x".repeat(900)}\n`;
143
+ const state = feed([long.repeat(63), "\u001b[63A"], 4_096);
144
+ const windowChars = state.screen.lines.reduce(
145
+ (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),
146
+ 0,
147
+ );
148
+ expect(windowChars).toBeLessThanOrEqual(2 * 4_096);
149
+ });
150
+});
151
+
152
+describe("appendTerminalOutput under adversarial output", () => {
153
+ it("gives the same result however the output is split into chunks", () => {
154
+ const input = "abcdef\rX\u001b[31mred\u001b[0m\nnext line\r\u001b[2Kdone\n";
155
+ const whole = feed([input], 3).text;
156
+ for (let cut = 1; cut < input.length; cut += 1) {
157
+ expect(feed([input.slice(0, cut), input.slice(cut)], 3).text).toBe(whole);
158
+ }
159
+ expect(feed(["abcdef", "\rX"], 3).text).toBe(feed(["abcdef\rX"], 3).text);
160
+ });
161
+
162
+ it("handles a colour change on every character in linear time", () => {
163
+ const chunk = Array.from({ length: 200_000 }, (_, index) =>
164
+ index % 2 === 0 ? "\u001b[31mx" : "\u001b[32my",
165
+ ).join("");
166
+ const started = performance.now();
167
+ const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, chunk);
168
+ expect(performance.now() - started).toBeLessThan(2_000);
169
+ expect(terminalOutputPlainText(state.text).length).toBeLessThanOrEqual(64 * 1024);
170
+ });
171
+
172
+ it("keeps scrollback bounded while a single huge chunk scrolls", () => {
173
+ const state = appendTerminalOutput(
174
+ EMPTY_TERMINAL_OUTPUT,
175
+ "line of log output\n".repeat(200_000),
176
+ 4_096,
177
+ );
178
+ expect(state.screen.settled.length).toBeLessThanOrEqual(2 * 4_096);
179
+ expect(state.truncated).toBe(true);
180
+ });
181
+});
182
+
183
+describe("terminalOutputResumeText", () => {
184
+ it("lets a viewer that starts from it apply later chunks exactly as the source does", () => {
185
+ // Mid-redraw: cursor two lines up, a colour on, and half an escape pending.
186
+ const chunks = [
187
+ "a: 1%\nb: 1%\n",
188
+ "\u001b[2A\u001b[2K\u001b[33ma: 5",
189
+ "0%\u001b[0",
190
+ "m\n\u001b[2Kb: 50%\n",
191
+ ];
192
+ const source = feed(chunks.slice(0, 3));
193
+ const viewer = appendTerminalOutput(
194
+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
195
+ chunks[3]!,
196
+ );
197
+ expect(viewer.text).toBe(feed(chunks).text);
198
+ expect(terminalOutputPlainText(viewer.text)).toBe("a: 50%\nb: 50%\n");
199
+ });
200
+});
201
+
202
+describe("terminalOutputResumeText with a saved cursor or trimmed output", () => {
203
+ it("restores a cursor saved before the resync", () => {
204
+ const source = feed(["abc\u001b7def"]);
205
+ const viewer = appendTerminalOutput(
206
+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
207
+ "\u001b8X",
208
+ );
209
+ expect(viewer.text).toBe("abcXef");
210
+ });
211
+
212
+ it("stays on the right line when early output was trimmed away", () => {
213
+ const lines = Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n");
214
+ const source = feed([lines, "\u001b[1A\rLINE"], 120);
215
+ const viewer = appendTerminalOutput(
216
+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source), 120),
217
+ " edited",
218
+ 120,
219
+ );
220
+ expect(viewer.text).toBe(appendTerminalOutput(source, " edited", 120).text);
221
+ });
222
+
223
+ it("survives a huge cursor move without throwing", () => {
224
+ expect(() => normalizeTerminalOutput("a\u001b[999999999999Cb")).not.toThrow();
225
+ });
226
+});
227
+
228
+describe("terminalOutputTail", () => {
229
+ it("never begins on a lone low surrogate", () => {
230
+ const text = `${"a".repeat(10)}😀${"b".repeat(4)}`;
231
+ const tail = terminalOutputTail(text, 5);
232
+ expect(tail.text).toBe("bbbb");
233
+ });
234
+
235
+ it("never splits a colour code and keeps the colour in force when cutting a line", () => {
236
+ const text = `\u001b[0;32m${"g".repeat(100)}\u001b[0m`;
237
+ const cut = terminalOutputTail(text, 10).text;
238
+ expect(cut.startsWith("\u001b[0;32m")).toBe(true);
239
+ expect(terminalOutputPlainText(cut)).toMatch(/^g+$/u);
240
+ });
241
+});
242
+
243
+describe("terminalOutputSpans", () => {
244
+ it("resolves standard, 256-colour and true-colour codes against the palette", () => {
245
+ const text = normalizeTerminalOutput(
246
+ "\u001b[31mred\u001b[0m \u001b[1;38;5;196mhot\u001b[0m \u001b[38;2;1;2;3mrgb\u001b[0m",
247
+ ).text;
248
+ expect(terminalOutputSpans(text, TERMINAL_PALETTES.dark)).toEqual([
249
+ { text: "red", style: { color: TERMINAL_PALETTES.dark[1] } },
250
+ { text: " ", style: null },
251
+ { text: "hot", style: { color: "rgb(255,0,0)", fontWeight: "600" } },
252
+ { text: " ", style: null },
253
+ { text: "rgb", style: { color: "rgb(1,2,3)" } },
254
+ ]);
255
+ });
256
+
257
+ it("keeps text on a coloured background readable on either palette", () => {
258
+ // "PASS" badge: black on green; "FAIL" badge: grey-white on red.
259
+ const text = normalizeTerminalOutput(
260
+ "\u001b[30;42m PASS \u001b[0m\u001b[1;37;41m FAIL \u001b[0m",
261
+ ).text;
262
+ for (const palette of [TERMINAL_PALETTES.light, TERMINAL_PALETTES.dark]) {
263
+ for (const span of terminalOutputSpans(text, palette)) {
264
+ expect(span.style?.color === undefined).toBe(false);
265
+ }
266
+ }
267
+ const [pass, fail] = terminalOutputSpans(text, TERMINAL_PALETTES.light);
268
+ expect(pass?.style?.color).toBe("#ffffff");
269
+ expect(fail?.style?.color).toBe("#ffffff");
270
+ });
271
+
272
+ it("collapses the rest into plain text past the span limit", () => {
273
+ const text = normalizeTerminalOutput("\u001b[31mx\u001b[32my".repeat(50)).text;
274
+ const spans = terminalOutputSpans(text, TERMINAL_PALETTES.light, 10);
275
+ expect(spans.length).toBe(11);
276
+ expect(spans.at(-1)?.style).toBeNull();
277
+ expect(spans.map((span) => span.text).join("")).toBe("xy".repeat(50));
278
+ });
279
+});
packages/shared/src/terminalOutput.ts
new
+872
@@ -0,0 +1,872 @@
1
+/**
2
+ * Turns raw terminal bytes (already decoded to text) into a bounded tail that
3
+ * a timeline can show. Runs on the server before output crosses the wire, and
4
+ * again on clients when they splice appends onto what they hold, so both sides
5
+ * must reach the same state from the same input.
6
+ *
7
+ * It models a small terminal: the last `LIVE_LINES` lines form a window that
8
+ * cursor movement can rewrite, so `\r` progress bars and multi-line redraws
9
+ * (docker pull, pnpm, test reporters) keep only their latest frame. Older lines
10
+ * are fixed text. The model has no width, so lines never wrap.
11
+ *
12
+ * - Colours and text attributes (SGR) survive as canonical `ESC[0;…m` codes.
13
+ * Every line starts from the default style and resets at its end, so any line
14
+ * boundary is a safe place to cut. `terminalOutputSpans` reads them back.
15
+ * - Cursor moves, line and screen erases, and save/restore are applied. Other
16
+ * escape sequences (titles, modes) and control characters are dropped.
17
+ * - Only the last `maxChars` survive, cut at a line boundary when possible.
18
+ *
19
+ * Chunks can split an escape sequence, so the unfinished fragment is carried in
20
+ * `pending` until the next chunk arrives.
21
+ */
22
+export interface TerminalOutputState {
23
+ /** What to show: fixed lines, then the window. Contains only SGR escapes. */
24
+ readonly text: string;
25
+ /** True once anything was dropped from the front. */
26
+ readonly truncated: boolean;
27
+ /** An unfinished escape sequence awaiting the next chunk. */
28
+ readonly pending: string;
29
+ readonly screen: TerminalScreen;
30
+}
31
+
32
+/** A styled stretch of one line. `pen` is canonical SGR parameters, "" for default. */
33
+interface Run {
34
+ readonly pen: string;
35
+ readonly text: string;
36
+}
37
+type Line = ReadonlyArray<Run>;
38
+
39
+interface TerminalScreen {
40
+ /** Serialized lines, each ending in `\n`, that scrolled out of the window. */
41
+ readonly settled: string;
42
+ /** The live window; never empty. */
43
+ readonly lines: ReadonlyArray<Line>;
44
+ readonly row: number;
45
+ readonly col: number;
46
+ readonly pen: string;
47
+ readonly saved: { readonly row: number; readonly col: number } | null;
48
+}
49
+
50
+export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {
51
+ text: "",
52
+ truncated: false,
53
+ pending: "",
54
+ screen: { settled: "", lines: [[]], row: 0, col: 0, pen: "", saved: null },
55
+};
56
+
57
+/** The default tail kept for one running command, in UTF-16 code units. */
58
+export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;
59
+
60
+/** Lines that cursor movement can still reach; older output is fixed. */
61
+const LIVE_LINES = 64;
62
+
63
+// Longest fragment we will hold waiting for an escape sequence to finish.
64
+const MAX_PENDING_ESCAPE = 64;
65
+
66
+const ESC = "\u001b";
67
+
68
+function sgr(pen: string): string {
69
+ return pen === "" ? `${ESC}[0m` : `${ESC}[0;${pen}m`;
70
+}
71
+
72
+// Lengths of lines already measured. Lines are never mutated once a feed ends.
73
+const lineLengths = new WeakMap<Line, number>();
74
+
75
+function lineLength(line: Line): number {
76
+ const cached = lineLengths.get(line);
77
+ if (cached !== undefined) return cached;
78
+ let length = 0;
79
+ for (const run of line) length += run.text.length;
80
+ lineLengths.set(line, length);
81
+ return length;
82
+}
83
+
84
+// Past this many style changes, a line's oldest runs lose their style. Rendering
85
+// already caps spans, and it keeps per-write work bounded on colour-per-character output.
86
+const MAX_LINE_RUNS = 2_048;
87
+
88
+/** Runs covering columns [start, end) of `line`. */
89
+function sliceLine(line: Line, start: number, end: number): Array<Run> {
90
+ const out: Array<Run> = [];
91
+ let offset = 0;
92
+ for (const run of line) {
93
+ const runEnd = offset + run.text.length;
94
+ if (runEnd > start && offset < end) {
95
+ out.push({
96
+ pen: run.pen,
97
+ text: run.text.slice(Math.max(0, start - offset), Math.min(run.text.length, end - offset)),
98
+ });
99
+ }
100
+ offset = runEnd;
101
+ if (offset >= end) break;
102
+ }
103
+ return out;
104
+}
105
+
106
+function pushRun(runs: Array<Run>, run: Run): void {
107
+ if (run.text.length === 0) return;
108
+ const last = runs.at(-1);
109
+ if (last !== undefined && last.pen === run.pen) {
110
+ runs[runs.length - 1] = { pen: last.pen, text: last.text + run.text };
111
+ } else {
112
+ runs.push(run);
113
+ }
114
+}
115
+
116
+/** Drops the first `count` columns of a line this feed owns, in place. */
117
+function trimLineStart(runs: Array<Run>, count: number): void {
118
+ let dropped = 0;
119
+ let remaining = count;
120
+ while (remaining > 0 && dropped < runs.length) {
121
+ const run = runs[dropped]!;
122
+ if (run.text.length <= remaining) {
123
+ remaining -= run.text.length;
124
+ dropped += 1;
125
+ } else {
126
+ runs[dropped] = { pen: run.pen, text: run.text.slice(remaining) };
127
+ remaining = 0;
128
+ }
129
+ }
130
+ if (dropped > 0) runs.splice(0, dropped);
131
+}
132
+
133
+/** `line` with `text` written over it from `col`, as a terminal overwrites. */
134
+function writeLine(line: Line, col: number, text: string, pen: string): Line {
135
+ const length = lineLength(line);
136
+ if (col === length) {
137
+ // The common case: printing at the end of the line.
138
+ const runs = line.slice();
139
+ pushRun(runs, { pen, text });
140
+ return runs;
141
+ }
142
+ const runs: Array<Run> = [];
143
+ for (const run of sliceLine(line, 0, Math.min(col, length))) pushRun(runs, run);
144
+ if (col > length) pushRun(runs, { pen: "", text: " ".repeat(col - length) });
145
+ pushRun(runs, { pen, text });
146
+ for (const run of sliceLine(line, col + text.length, length)) pushRun(runs, run);
147
+ return runs;
148
+}
149
+
150
+/** Erase in line: 0 cursor to end, 1 start to cursor, 2 whole line. */
151
+function eraseLine(line: Line, col: number, mode: number): Line {
152
+ const length = lineLength(line);
153
+ if (mode === 0) return sliceLine(line, 0, col);
154
+ if (mode === 1) {
155
+ const runs: Array<Run> = [];
156
+ pushRun(runs, { pen: "", text: " ".repeat(Math.min(col + 1, length)) });
157
+ for (const run of sliceLine(line, col + 1, length)) pushRun(runs, run);
158
+ return runs;
159
+ }
160
+ return [];
161
+}
162
+
163
+function serializeLine(line: Line): string {
164
+ let out = "";
165
+ let current = "";
166
+ for (const run of line) {
167
+ if (run.pen !== current) {
168
+ out += sgr(run.pen);
169
+ current = run.pen;
170
+ }
171
+ out += run.text;
172
+ }
173
+ return current === "" ? out : out + sgr("");
174
+}
175
+
176
+interface Attributes {
177
+ bold: boolean;
178
+ dim: boolean;
179
+ italic: boolean;
180
+ underline: boolean;
181
+ strike: boolean;
182
+ inverse: boolean;
183
+ fg: string;
184
+ bg: string;
185
+}
186
+
187
+function parsePen(pen: string): Attributes {
188
+ const attributes: Attributes = {
189
+ bold: false,
190
+ dim: false,
191
+ italic: false,
192
+ underline: false,
193
+ strike: false,
194
+ inverse: false,
195
+ fg: "",
196
+ bg: "",
197
+ };
198
+ if (pen !== "") applySgr(attributes, pen.split(";").map(Number));
199
+ return attributes;
200
+}
201
+
202
+function formatPen(attributes: Attributes): string {
203
+ const parts: Array<string> = [];
204
+ if (attributes.bold) parts.push("1");
205
+ if (attributes.dim) parts.push("2");
206
+ if (attributes.italic) parts.push("3");
207
+ if (attributes.underline) parts.push("4");
208
+ if (attributes.inverse) parts.push("7");
209
+ if (attributes.strike) parts.push("9");
210
+ if (attributes.fg !== "") parts.push(attributes.fg);
211
+ if (attributes.bg !== "") parts.push(attributes.bg);
212
+ return parts.join(";");
213
+}
214
+
215
+/** Reads an extended colour (`5;n` or `2;r;g;b`) starting at `index`; returns the code and next index. */
216
+function extendedColor(
217
+ code: number,
218
+ params: ReadonlyArray<number>,
219
+ index: number,
220
+): [string | undefined, number] {
221
+ const mode = params[index + 1];
222
+ if (mode === 5) {
223
+ const value = params[index + 2];
224
+ return value === undefined || value > 255
225
+ ? [undefined, index + 3]
226
+ : [`${code};5;${value}`, index + 3];
227
+ }
228
+ if (mode === 2) {
229
+ const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]];
230
+ if (r === undefined || g === undefined || b === undefined) return [undefined, index + 5];
231
+ return [`${code};2;${r & 255};${g & 255};${b & 255}`, index + 5];
232
+ }
233
+ return [undefined, index + 2];
234
+}
235
+
236
+function applySgr(attributes: Attributes, params: ReadonlyArray<number>): void {
237
+ if (params.length === 0) params = [0];
238
+ for (let index = 0; index < params.length;) {
239
+ const code = params[index]!;
240
+ if (code === 0 || Number.isNaN(code)) {
241
+ Object.assign(attributes, parsePen(""));
242
+ } else if (code === 1) attributes.bold = true;
243
+ else if (code === 2) attributes.dim = true;
244
+ else if (code === 3) attributes.italic = true;
245
+ else if (code === 4) attributes.underline = true;
246
+ else if (code === 7) attributes.inverse = true;
247
+ else if (code === 9) attributes.strike = true;
248
+ else if (code === 22) attributes.bold = attributes.dim = false;
249
+ else if (code === 23) attributes.italic = false;
250
+ else if (code === 24) attributes.underline = false;
251
+ else if (code === 27) attributes.inverse = false;
252
+ else if (code === 29) attributes.strike = false;
253
+ else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) attributes.fg = String(code);
254
+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
255
+ attributes.bg = String(code);
256
+ else if (code === 39) attributes.fg = "";
257
+ else if (code === 49) attributes.bg = "";
258
+ else if (code === 38 || code === 48) {
259
+ const [color, next] = extendedColor(code, params, index);
260
+ if (color !== undefined) attributes[code === 38 ? "fg" : "bg"] = color;
261
+ index = next;
262
+ continue;
263
+ }
264
+ index += 1;
265
+ }
266
+}
267
+
268
+const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]);
269
+
270
+/** Length of a complete escape sequence starting at `index` (an ESC), or -1 if unfinished. */
271
+function escapeLength(input: string, index: number): number {
272
+ const next = input[index + 1];
273
+ if (next === undefined) return -1;
274
+ if (next === "[") {
275
+ // CSI: parameters/intermediates, then a final byte in @-~.
276
+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {
277
+ const code = input.charCodeAt(cursor);
278
+ if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;
279
+ }
280
+ return -1;
281
+ }
282
+ if (STRING_SEQUENCE_INTRODUCERS.has(next)) {
283
+ // OSC/DCS/SOS/APC/PM end at BEL or ST (ESC \). A newline also ends one (and is
284
+ // kept), so a stray introducer in binary output can't hide everything after it.
285
+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {
286
+ if (input[cursor] === "\u0007") return cursor - index + 1;
287
+ if (input[cursor] === "\n") return cursor - index;
288
+ if (input[cursor] === ESC) {
289
+ if (cursor + 1 >= input.length) return -1;
290
+ if (input[cursor + 1] === "\\") return cursor - index + 2;
291
+ }
292
+ }
293
+ return -1;
294
+ }
295
+ // Charset designation (ESC ( B) takes three; other two-byte sequences (ESC 7) two.
296
+ if (next === "(" || next === ")" || next === "*" || next === "+") {
297
+ return index + 2 < input.length ? 3 : -1;
298
+ }
299
+ return 2;
300
+}
301
+
302
+const penTransitions = new Map<string, string>();
303
+
304
+/** CSI parameters as numbers. Colon sub-parameters (`38:2::r:g:b`) carry an optional
305
+ colour-space id that the semicolon form (`38;2;r;g;b`) has no slot for. */
306
+function csiParams(params: string): Array<number> {
307
+ const numbers: Array<number> = [];
308
+ for (const part of params.split(";")) {
309
+ if (!part.includes(":")) {
310
+ numbers.push(Number(part));
311
+ continue;
312
+ }
313
+ const sub = part.split(":").map(Number);
314
+ if ((sub[0] === 38 || sub[0] === 48) && sub[1] === 2 && sub.length >= 6) sub.splice(2, 1);
315
+ numbers.push(...sub);
316
+ }
317
+ return numbers;
318
+}
319
+
320
+/** A mutable copy of the screen, for applying one chunk. */
321
+class Terminal {
322
+ settled: string;
323
+ lines: Array<Line>;
324
+ row: number;
325
+ col: number;
326
+ pen: string;
327
+ saved: { row: number; col: number } | null;
328
+ /** Output was discarded on purpose (scrollback cleared or window over budget). */
329
+ dropped = false;
330
+ readonly maxChars: number;
331
+ /** Lines created during this feed, which it may extend in place. */
332
+ private readonly owned = new WeakSet<Line>();
333
+
334
+ constructor(screen: TerminalScreen, maxChars: number) {
335
+ this.maxChars = maxChars;
336
+ this.settled = screen.settled;
337
+ this.lines = screen.lines.slice();
338
+ this.row = screen.row;
339
+ this.col = screen.col;
340
+ this.pen = screen.pen;
341
+ this.saved = screen.saved;
342
+ }
343
+
344
+ write(text: string): void {
345
+ let line = this.lines[this.row]!;
346
+ const length = lineLength(line);
347
+ if (this.col === length && this.owned.has(line)) {
348
+ // Printing at the end of a line this feed already copied: extend it in place.
349
+ pushRun(line as Array<Run>, { pen: this.pen, text });
350
+ lineLengths.set(line, length + text.length);
351
+ } else {
352
+ line = writeLine(line, this.col, text, this.pen);
353
+ this.owned.add(line);
354
+ }
355
+ this.col += text.length;
356
+ if (line.length > MAX_LINE_RUNS) {
357
+ // Fold all but the newest runs into one plain run, so trimming below eats it cheaply.
358
+ const keep = line.length - MAX_LINE_RUNS / 8;
359
+ const plain = line
360
+ .slice(0, keep)
361
+ .map((run) => run.text)
362
+ .join("");
363
+ line = [{ pen: "", text: plain }, ...line.slice(keep)];
364
+ this.owned.add(line);
365
+ }
366
+ // A line keeps only its last `maxChars` columns, trimmed on every write so the
367
+ // result never depends on how the output was split into chunks.
368
+ let current = lineLength(line);
369
+ if (current > this.maxChars) {
370
+ let removed = current - this.maxChars;
371
+ if (!this.owned.has(line)) {
372
+ line = line.slice();
373
+ this.owned.add(line);
374
+ }
375
+ trimLineStart(line as Array<Run>, removed);
376
+ // Never start on a lone low surrogate.
377
+ const first = line[0]?.text.charCodeAt(0) ?? 0;
378
+ if (first >= 0xdc00 && first <= 0xdfff) {
379
+ trimLineStart(line as Array<Run>, 1);
380
+ removed += 1;
381
+ }
382
+ current -= removed;
383
+ this.dropped = true;
384
+ this.col = Math.max(0, this.col - removed);
385
+ if (this.saved !== null && this.saved.row === this.row) {
386
+ this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) };
387
+ }
388
+ }
389
+ lineLengths.set(line, current);
390
+ this.lines[this.row] = line;
391
+ }
392
+
393
+ newline(): void {
394
+ this.row += 1;
395
+ this.col = 0;
396
+ if (this.row === this.lines.length) this.lines.push([]);
397
+ while (this.lines.length > LIVE_LINES) this.scrollOut();
398
+ }
399
+
400
+ /** Moves the top line out of the window into scrollback; returns its length. */
401
+ scrollOut(): number {
402
+ const line = this.lines.shift()!;
403
+ this.settle(line);
404
+ this.row -= 1;
405
+ if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };
406
+ return lineLength(line);
407
+ }
408
+
409
+ /** Fixes a line that left the window, keeping scrollback near the tail size as it grows. */
410
+ settle(line: Line): void {
411
+ this.settled += `${serializeLine(line)}\n`;
412
+ if (this.settled.length > 2 * this.maxChars) {
413
+ this.settled = terminalOutputTail(this.settled, this.maxChars).text;
414
+ this.dropped = true;
415
+ }
416
+ }
417
+
418
+ moveTo(row: number, col: number): void {
419
+ this.row = Math.max(0, Math.min(this.lines.length - 1, row));
420
+ // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.
421
+ this.col = Math.max(0, Math.min(TERMINAL_OUTPUT_TAIL_CHARS, col));
422
+ }
423
+
424
+ csi(params: string, final: string): void {
425
+ if (/^[?>=]/u.test(params)) return; // Mode switches (cursor visibility, bracketed paste).
426
+ const numbers = params === "" ? [] : csiParams(params);
427
+ const count = Math.max(1, numbers[0] || 1);
428
+ switch (final) {
429
+ case "m": {
430
+ // Colourful output repeats a handful of transitions, so they are cached.
431
+ const key = `${this.pen}|${params}`;
432
+ let pen = penTransitions.get(key);
433
+ if (pen === undefined) {
434
+ const attributes = parsePen(this.pen);
435
+ applySgr(attributes, numbers);
436
+ pen = formatPen(attributes);
437
+ if (penTransitions.size >= 512) penTransitions.clear();
438
+ penTransitions.set(key, pen);
439
+ }
440
+ this.pen = pen;
441
+ return;
442
+ }
443
+ case "A":
444
+ return this.moveTo(this.row - count, this.col);
445
+ case "B":
446
+ return this.moveTo(this.row + count, this.col);
447
+ case "C":
448
+ return this.moveTo(this.row, this.col + count);
449
+ case "D":
450
+ return this.moveTo(this.row, this.col - count);
451
+ case "E":
452
+ return this.moveTo(this.row + count, 0);
453
+ case "F":
454
+ return this.moveTo(this.row - count, 0);
455
+ case "G":
456
+ return this.moveTo(this.row, count - 1);
457
+ case "H":
458
+ case "f":
459
+ // Rows count from the top of the window: there is no fixed screen height.
460
+ return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);
461
+ case "K":
462
+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);
463
+ return;
464
+ case "J": {
465
+ const mode = numbers[0] ?? 0;
466
+ if (mode === 0) {
467
+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);
468
+ this.lines.length = this.row + 1;
469
+ } else if (mode === 1) {
470
+ for (let row = 0; row < this.row; row += 1) this.lines[row] = [];
471
+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);
472
+ } else if (mode === 3) {
473
+ // Clear scrollback: what already scrolled out goes, the window stays.
474
+ if (this.settled !== "") this.dropped = true;
475
+ this.settled = "";
476
+ } else {
477
+ // A cleared screen starts the window over; what scrolled out stays.
478
+ this.lines = [[]];
479
+ this.row = 0;
480
+ this.col = 0;
481
+ }
482
+ return;
483
+ }
484
+ case "s":
485
+ this.saved = { row: this.row, col: this.col };
486
+ return;
487
+ case "u":
488
+ if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
489
+ return;
490
+ default:
491
+ }
492
+ }
493
+
494
+ escape(sequence: string): void {
495
+ if (sequence[1] === "[") {
496
+ this.csi(sequence.slice(2, -1), sequence.at(-1)!);
497
+ } else if (sequence === `${ESC}7`) {
498
+ this.saved = { row: this.row, col: this.col };
499
+ } else if (sequence === `${ESC}8`) {
500
+ if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
501
+ } else if (sequence === `${ESC}M`) {
502
+ this.moveTo(this.row - 1, this.col); // Reverse line feed.
503
+ }
504
+ }
505
+
506
+ /** Applies `input`; returns the unfinished escape left at its end. */
507
+ feed(input: string): string {
508
+ let printable = 0;
509
+ const flush = (end: number) => {
510
+ if (end > printable) this.write(input.slice(printable, end));
511
+ };
512
+ for (let index = 0; index < input.length; index += 1) {
513
+ const code = input.charCodeAt(index);
514
+ // Printable text, including tabs, is batched into one write.
515
+ if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {
516
+ continue;
517
+ }
518
+ flush(index);
519
+ printable = index + 1;
520
+ if (code === 0x0a) this.newline();
521
+ else if (code === 0x0d) this.col = 0;
522
+ else if (code === 0x08) this.col = Math.max(0, this.col - 1);
523
+ else if (code === 0x1b) {
524
+ const length = escapeLength(input, index);
525
+ if (length === -1) {
526
+ const fragment = input.slice(index);
527
+ if (fragment.length <= MAX_PENDING_ESCAPE) return fragment;
528
+ // A long string sequence keeps only its introducer (and a trailing ESC that
529
+ // may start its ST), so the payload stays hidden until it ends.
530
+ if (STRING_SEQUENCE_INTRODUCERS.has(fragment[1]!)) {
531
+ return fragment.slice(0, 2) + (fragment.endsWith(ESC) ? ESC : "");
532
+ }
533
+ // Any other runaway sequence is noise; drop it instead of waiting forever.
534
+ return "";
535
+ }
536
+ this.escape(input.slice(index, index + length));
537
+ index += length - 1;
538
+ printable = index + 1;
539
+ }
540
+ // Other C0, DEL and C1 controls carry no visible text.
541
+ }
542
+ flush(input.length);
543
+ return "";
544
+ }
545
+}
546
+
547
+/** The active style at `index` of `text` and where a cut there may safely start. */
548
+function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {
549
+ const lineStart = text.lastIndexOf("\n", index - 1) + 1;
550
+ let prefix = "";
551
+ let cursor = lineStart;
552
+ while (cursor < index) {
553
+ const found = text.indexOf(`${ESC}[`, cursor);
554
+ if (found === -1 || found >= index) break;
555
+ const end = text.indexOf("m", found);
556
+ if (end === -1) break;
557
+ if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };
558
+ prefix = text.slice(found, end + 1);
559
+ cursor = end + 1;
560
+ }
561
+ return { start: index, prefix: prefix === sgr("") ? "" : prefix };
562
+}
563
+
564
+/** Keeps the last `maxChars`, preferring to start on a fresh line. */
565
+export function terminalOutputTail(
566
+ text: string,
567
+ maxChars: number,
568
+): { readonly text: string; readonly truncated: boolean } {
569
+ if (text.length <= maxChars) return { text, truncated: false };
570
+ let start = text.length - maxChars;
571
+ const newline = text.indexOf("\n", start);
572
+ // Drop the partial first line unless that would discard most of the tail.
573
+ if (newline !== -1 && newline - start < maxChars / 4) {
574
+ return { text: text.slice(newline + 1), truncated: true };
575
+ }
576
+ // Cutting inside a line: never split an escape, and keep the colour in force.
577
+ const style = styleAt(text, start);
578
+ start = style.start;
579
+ // Never start on a lone low surrogate.
580
+ const first = text.charCodeAt(start);
581
+ if (first >= 0xdc00 && first <= 0xdfff) start += 1;
582
+ return { text: style.prefix + text.slice(start), truncated: true };
583
+}
584
+
585
+/** Appends one decoded chunk and returns the new bounded state. */
586
+export function appendTerminalOutput(
587
+ state: TerminalOutputState,
588
+ chunk: string,
589
+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
590
+): TerminalOutputState {
591
+ const input = state.pending + chunk;
592
+ if (input.length === 0) return state;
593
+ const terminal = new Terminal(state.screen, maxChars);
594
+ const pending = terminal.feed(input);
595
+ let truncated = state.truncated;
596
+ // The window as a whole stays within the tail too: oldest lines scroll out early.
597
+ let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);
598
+ while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();
599
+ // Lines below a cursor that moved up can't scroll out; they keep only their ends.
600
+ if (windowChars > maxChars) {
601
+ let budget = maxChars;
602
+ for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);
603
+ for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {
604
+ const line = terminal.lines[row]!;
605
+ const length = lineLength(line);
606
+ const keep = Math.max(0, Math.min(length, budget));
607
+ if (keep < length) {
608
+ truncated = true;
609
+ terminal.lines[row] = sliceLine(line, length - keep, length);
610
+ if (terminal.saved !== null && terminal.saved.row === row) {
611
+ terminal.saved = {
612
+ ...terminal.saved,
613
+ col: Math.max(0, terminal.saved.col - (length - keep)),
614
+ };
615
+ }
616
+ }
617
+ budget -= keep;
618
+ }
619
+ }
620
+ if (terminal.dropped) truncated = true;
621
+ const settled = terminalOutputTail(terminal.settled, maxChars);
622
+ const window = terminal.lines.map(serializeLine).join("\n");
623
+ const tail = terminalOutputTail(settled.text + window, maxChars);
624
+ return {
625
+ text: tail.text,
626
+ truncated: truncated || settled.truncated || tail.truncated,
627
+ pending,
628
+ screen: {
629
+ settled: settled.text,
630
+ lines: terminal.lines,
631
+ row: terminal.row,
632
+ col: terminal.col,
633
+ pen: terminal.pen,
634
+ saved: terminal.saved,
635
+ },
636
+ };
637
+}
638
+
639
+/**
640
+ * Text that rebuilds `state` when fed to an empty state: the output, then the
641
+ * cursor, style and any unfinished escape. A viewer that starts from it (or
642
+ * resyncs to it) applies later raw chunks exactly as the server does.
643
+ */
644
+export function terminalOutputResumeText(state: TerminalOutputState): string {
645
+ const { screen } = state;
646
+ const lastRow = screen.lines.length - 1;
647
+ // Moves are relative to the last line, and a viewer only holds the lines in `text`.
648
+ const shownLines = state.text.split("\n").length;
649
+ const reachable = Math.min(LIVE_LINES, shownLines) - 1;
650
+ const up = (row: number) => Math.min(lastRow - row, reachable);
651
+ const goTo = (row: number, col: number) =>
652
+ (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;
653
+ let suffix = "";
654
+ if (screen.saved !== null) {
655
+ suffix += `${goTo(screen.saved.row, screen.saved.col)}${ESC}7`;
656
+ if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;
657
+ }
658
+ if (
659
+ screen.saved !== null ||
660
+ screen.row < lastRow ||
661
+ screen.col !== lineLength(screen.lines[screen.row]!)
662
+ ) {
663
+ suffix += goTo(screen.row, screen.col);
664
+ }
665
+ if (screen.pen !== "") suffix += sgr(screen.pen);
666
+ return state.text + suffix + state.pending;
667
+}
668
+
669
+/** Normalizes a complete output string in one pass. */
670
+export function normalizeTerminalOutput(
671
+ text: string,
672
+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
673
+): { readonly text: string; readonly truncated: boolean } {
674
+ const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);
675
+ return { text: state.text, truncated: state.truncated };
676
+}
677
+
678
+/** A stretch of shown output with one style. */
679
+export interface TerminalSpan {
680
+ readonly text: string;
681
+ readonly style: TerminalSpanStyle | null;
682
+}
683
+
684
+/** A span's style, usable as-is by a web or React Native `style` prop. */
685
+export interface TerminalSpanStyle {
686
+ /** CSS colours, already resolved against the palette. */
687
+ readonly color?: string;
688
+ readonly backgroundColor?: string;
689
+ readonly fontWeight?: "600";
690
+ readonly opacity?: number;
691
+ readonly fontStyle?: "italic";
692
+ readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";
693
+}
694
+
695
+/** The 16 standard terminal colours, chosen to stay readable on each app theme. */
696
+export const TERMINAL_PALETTES = {
697
+ dark: [
698
+ "#3b4048",
699
+ "#f47067",
700
+ "#57ab5a",
701
+ "#c69026",
702
+ "#539bf5",
703
+ "#b083f0",
704
+ "#39c5cf",
705
+ "#adbac7",
706
+ "#768390",
707
+ "#ff938a",
708
+ "#6bc46d",
709
+ "#daaa3f",
710
+ "#6cb6ff",
711
+ "#dcbdfb",
712
+ "#56d4dd",
713
+ "#cdd9e5",
714
+ ],
715
+ light: [
716
+ "#24292f",
717
+ "#cf222e",
718
+ "#116329",
719
+ "#7d4e00",
720
+ "#0550ae",
721
+ "#8250df",
722
+ "#1b7c83",
723
+ "#6e7781",
724
+ "#57606a",
725
+ "#a40e26",
726
+ "#1a7f37",
727
+ "#633c01",
728
+ "#0969da",
729
+ "#6639ba",
730
+ "#3192aa",
731
+ "#8c959f",
732
+ ],
733
+} as const;
734
+
735
+function xtermColor(index: number, palette: ReadonlyArray<string>): string {
736
+ if (index < 16) return palette[index]!;
737
+ if (index >= 232) {
738
+ const level = 8 + (index - 232) * 10;
739
+ return `rgb(${level},${level},${level})`;
740
+ }
741
+ const cube = index - 16;
742
+ const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);
743
+ return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;
744
+}
745
+
746
+function resolveColor(
747
+ code: string,
748
+ base: number,
749
+ palette: ReadonlyArray<string>,
750
+): string | undefined {
751
+ const parts = code.split(";").map(Number);
752
+ const head = parts[0]!;
753
+ if (head === base + 8) {
754
+ if (parts[1] === 5) return xtermColor(parts[2]!, palette);
755
+ return `rgb(${parts[2]},${parts[3]},${parts[4]})`;
756
+ }
757
+ if (head >= base && head <= base + 7) return palette[head - base];
758
+ if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];
759
+ return undefined;
760
+}
761
+
762
+type Rgb = readonly [number, number, number];
763
+
764
+/** Reads the `#rrggbb` and `rgb(r,g,b)` colours this module produces. */
765
+function parseCssColor(color: string): Rgb | undefined {
766
+ if (color.startsWith("#") && color.length === 7) {
767
+ return [1, 3, 5].map((offset) =>
768
+ Number.parseInt(color.slice(offset, offset + 2), 16),
769
+ ) as unknown as Rgb;
770
+ }
771
+ const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);
772
+ return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
773
+}
774
+
775
+function luminance([r, g, b]: Rgb): number {
776
+ const channel = (value: number) => {
777
+ const scaled = value / 255;
778
+ return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
779
+ };
780
+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
781
+}
782
+
783
+function contrastRatio(a: Rgb, b: Rgb): number {
784
+ const [first, second] = [luminance(a), luminance(b)];
785
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
786
+}
787
+
788
+function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {
789
+ if (pen === "") return null;
790
+ const attributes = parsePen(pen);
791
+ let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);
792
+ let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);
793
+ if (attributes.inverse) {
794
+ [color, backgroundColor] = [backgroundColor, color ?? palette[7]];
795
+ }
796
+ // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.
797
+ if (backgroundColor !== undefined) {
798
+ const background = parseCssColor(backgroundColor);
799
+ const foreground = color === undefined ? undefined : parseCssColor(color);
800
+ if (
801
+ background !== undefined &&
802
+ (foreground === undefined || contrastRatio(foreground, background) < 3)
803
+ ) {
804
+ color = luminance(background) > 0.35 ? "#1f2328" : "#ffffff";
805
+ }
806
+ }
807
+ const textDecorationLine = attributes.underline
808
+ ? attributes.strike
809
+ ? "underline line-through"
810
+ : "underline"
811
+ : attributes.strike
812
+ ? "line-through"
813
+ : undefined;
814
+ return {
815
+ ...(color === undefined ? {} : { color }),
816
+ ...(backgroundColor === undefined ? {} : { backgroundColor }),
817
+ ...(attributes.bold ? { fontWeight: "600" } : {}),
818
+ ...(attributes.dim ? { opacity: 0.65 } : {}),
819
+ ...(attributes.italic ? { fontStyle: "italic" } : {}),
820
+ ...(textDecorationLine === undefined ? {} : { textDecorationLine }),
821
+ };
822
+}
823
+
824
+/**
825
+ * Splits shown output into styled spans for rendering. Past `maxSpans` the rest
826
+ * is one plain span, so a pathological stream of colour changes cannot turn
827
+ * into tens of thousands of DOM or native nodes.
828
+ */
829
+export function terminalOutputSpans(
830
+ text: string,
831
+ palette: ReadonlyArray<string>,
832
+ maxSpans = 2_000,
833
+): ReadonlyArray<TerminalSpan> {
834
+ const spans: Array<TerminalSpan> = [];
835
+ const styles = new Map<string, TerminalSpanStyle | null>();
836
+ let pen = "";
837
+ let cursor = 0;
838
+ const push = (end: number) => {
839
+ if (end <= cursor) return;
840
+ let style = styles.get(pen);
841
+ if (style === undefined) {
842
+ style = spanStyle(pen, palette);
843
+ styles.set(pen, style);
844
+ }
845
+ spans.push({ text: text.slice(cursor, end), style });
846
+ };
847
+ while (cursor < text.length) {
848
+ const escape = text.indexOf(`${ESC}[`, cursor);
849
+ if (escape === -1 || spans.length >= maxSpans) break;
850
+ push(escape);
851
+ const end = text.indexOf("m", escape);
852
+ if (end === -1) break;
853
+ const params = text.slice(escape + 2, end);
854
+ pen = params === "0" ? "" : params.replace(/^0;/u, "");
855
+ cursor = end + 1;
856
+ }
857
+ if (cursor < text.length) {
858
+ if (spans.length >= maxSpans) {
859
+ spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });
860
+ } else {
861
+ push(text.length);
862
+ }
863
+ }
864
+ return spans;
865
+}
866
+
867
+const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;]*m`, "gu");
868
+
869
+/** Shown output without its colour codes. */
870
+export function terminalOutputPlainText(text: string): string {
871
+ return text.replace(SGR_PATTERN, "");
872
+}