Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeTaskOutputTail.ts

105 lines4.0 KB

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/** The SDK withholds stdout until tool results; tail task_started files for live output.
8 * The private Claude layout can change; failures omit live output and retain the final result. */
9​
10const CLAUDE_TASK_OUTPUT_POLL_MS = 250;
11/** Bound discovery when Claude never writes the file. */
12const MAX_LOCATE_ATTEMPTS = 40;
13/** Skip ahead of fast writers; only the tail is displayed. */
14const MAX_READ_BYTES = 256 * 1024;
15​
16/** Claude Code's per-user temp root, or none where it has no uid (Windows). */
17export function claudeTaskOutputRoot(
18 environment: Readonly<Record<string, string | undefined>> | undefined,
19 path: Path.Path,
20): string | undefined {
21 const uid = process.getuid?.();
22 if (uid === undefined) return undefined;
23 const base = environment?.CLAUDE_CODE_TMPDIR?.trim() || "/tmp";
24 return path.join(base, `claude-${uid}`);
26​
27const locate = Effect.fn("ClaudeTaskOutputTail.locate")(function* (input: {
28 readonly root: string;
29 readonly sessionId: string;
30 readonly taskId: string;
31}) {
32 const fileSystem = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const projects = yield* fileSystem.readDirectory(input.root).pipe(Effect.orElseSucceed(() => []));
35 for (const project of projects) {
36 const candidate = path.join(
37 input.root,
38 project,
39 input.sessionId,
40 "tasks",
41 `${input.taskId}.output`,
42 );
43 if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
44 return Option.some(candidate);
45 }
46 }
47 return Option.none<string>();
48});
49​
50/** Complete stop on tool result or turn end, then await the effect; it performs a final read before returning. */
51export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(function* (input: {
52 readonly root: string;
53 readonly sessionId: string;
54 readonly taskId: string;
55 readonly stop: Deferred.Deferred<void>;
56 readonly onChunk: (chunk: string) => Effect.Effect<void>;
57}) {
58 const fileSystem = yield* FileSystem.FileSystem;
59 const pause = Effect.raceFirst(
60 Effect.sleep(CLAUDE_TASK_OUTPUT_POLL_MS).pipe(Effect.as(false)),
61 Deferred.await(input.stop).pipe(Effect.as(true)),
62 );
63 let file = Option.none<string>();
64 for (let attempt = 0; Option.isNone(file); attempt += 1) {
65 file = yield* locate(input);
66 if (Option.isSome(file)) break;
67 if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return;
68 }
69 const filePath = file.value;
70 let decoder = new TextDecoder("utf-8", { fatal: false });
71 let offset = 0;
72 let last = yield* Deferred.isDone(input.stop);
73 while (true) {
74 const size = yield* fileSystem.stat(filePath).pipe(
75 Effect.map((info) => Number(info.size)),
76 Effect.orElseSucceed(() => offset),
77 );
78 if (size < offset) offset = 0;
79 if (size > offset) {
80 const start = size - offset > MAX_READ_BYTES ? size - MAX_READ_BYTES : offset;
81 const bytes = yield* Effect.scoped(
82 Effect.gen(function* () {
83 const handle = yield* fileSystem.open(filePath, { flag: "r" });
84 yield* handle.seek(BigInt(start), "start");
85 return yield* handle.readAlloc(size - start);
86 }),
87 ).pipe(Effect.orElseSucceed(() => Option.none<Uint8Array>()));
88 if (Option.isSome(bytes)) {
89 // Skipped output must not splice two unrelated lines together.
90 const skipped = start > offset;
91 // Reset partial UTF-8 bytes when skipping output.
92 if (skipped) decoder = new TextDecoder("utf-8", { fatal: false });
93 offset = start + bytes.value.byteLength;
94 const text = (skipped ? "\n" : "") + decoder.decode(bytes.value, { stream: true });
95 if (text.length > 0) yield* input.onChunk(text);
96 }
97 }
98 if (last) {
99 const rest = decoder.decode();
100 if (rest.length > 0) yield* input.onChunk(rest);
101 return;
102 }
103 last = yield* pause;
104 }
105});