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

CommandOutputHub.ts

342 lines13.6 KB

1import {
2 isOrchestrationV2WorkActive,
3 OrchestrationV2CommandOutputError,
4 type OrchestrationV2CommandOutputFrame,
5 type OrchestrationV2SubscribeCommandOutputInput,
6 type OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8import {
9 appendTerminalOutput,
10 EMPTY_TERMINAL_OUTPUT,
11 normalizeTerminalOutput,
12 type TerminalOutputState,
13 TERMINAL_OUTPUT_TAIL_CHARS,
14 terminalOutputResumeText,
15} from "@t3tools/shared/terminalOutput";
16import * as Cause from "effect/Cause";
17import * as Clock from "effect/Clock";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25​
26import * as EventSink from "./EventSink.ts";
27import * 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. */
40export const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100;
41/** After a subscriber falls behind and is sent the whole tail, it waits this long. */
42export const COMMAND_OUTPUT_REPLACE_INTERVAL_MS = 500;
43/** Raw text a subscriber may accumulate before it is sent the tail instead. */
44const COMMAND_OUTPUT_MAX_APPEND_CHARS = 16 * 1024;
45/** Running commands tracked at once; the least recently written is dropped beyond this. */
46const MAX_LIVE_COMMANDS = 64;
47/** Finished tails kept for a settle that reports no output of its own (an interrupt). */
48const MAX_FINISHED_COMMANDS = 16;
49/** Final output read from persistence is normalized from at most this many trailing chars. */
50const MAX_FINAL_SOURCE_CHARS = TERMINAL_OUTPUT_TAIL_CHARS * 4;
51​
52interface 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>;
60​
61export type CommandOutputTarget = OrchestrationV2SubscribeCommandOutputInput;
62​
63export 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>;
76​
77export class CommandOutputHub extends Context.Service<CommandOutputHub, CommandOutputHubShape>()(
78 "t3/orchestration-v2/CommandOutputHub",
79) {}
80​
81const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);
82​
83function commandKey(target: CommandOutputTarget): string {
84 return `${target.threadId}\u0000${target.itemId}`;
86​
87/** Claude Bash rows stored before #15505 hold the raw `{ stdout, stderr, interrupted, ... }` result. */
88const decodeLegacyClaudeBashResult = Schema.decodeUnknownOption(
89 Schema.fromJsonString(
90 Schema.Struct({ stdout: Schema.String, stderr: Schema.String, interrupted: Schema.Boolean }),
91 ),
92);
93​
94function 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;
102​
103/** The output a row shows from a persisted item, bounded before normalization. */
104function 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 };
122​
123/** Sets `key` as the newest entry of `map`, dropping the oldest beyond `max`. */
124function 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);
138​
139export 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​
338export const layer: Layer.Layer<
339 CommandOutputHub,
340 never,
341 EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2
342> = Layer.effect(CommandOutputHub, make);