Open History to see the last commit
1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * 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. */
19const CLAUDE_TASK_OUTPUT_POLL_MS = 250;
20/** Give up looking for a file Claude Code never wrote (a newer layout, or Windows). */
21const MAX_LOCATE_ATTEMPTS = 40;
22/** Bytes read per poll. A faster writer skips ahead: only the tail is shown anyway. */
23const MAX_READ_BYTES = 256 * 1024;
24
25/** Claude Code's per-user temp root, or none where it has no uid (Windows). */
26export 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
36const 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 */
65export 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});