Open History to see the last commit
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 { commandItemOutput } from "@t3tools/shared/commandOutput";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
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/** Output bypasses orchestration events; expanded rows receive tails, coalesced appends, then persisted output. */
30
31/** Fastest a subscriber receives frames while output flows. */
32const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100;
33/** After a subscriber falls behind and is sent the whole tail, it waits this long. */
34const COMMAND_OUTPUT_REPLACE_INTERVAL_MS = 500;
35/** Raw text a subscriber may accumulate before it is sent the tail instead. */
36const COMMAND_OUTPUT_MAX_APPEND_CHARS = 16 * 1024;
37/** Evict the least recently written command beyond this limit. */
38const MAX_LIVE_COMMANDS = 64;
39/** Retain finished tails for settlements that omit output. */
40const MAX_FINISHED_COMMANDS = 16;
41const MAX_FINAL_SOURCE_CHARS = TERMINAL_OUTPUT_TAIL_CHARS * 4;
42
43interface Subscriber {
44 pendingAppend: string;
45 needsReplace: boolean;
46 /** `needsReplace` was caused by the subscriber falling behind. */
47 overflowed: boolean;
48 readonly wake: Queue.Queue<void>;
49}
50
51export type CommandOutputTarget = OrchestrationV2SubscribeCommandOutputInput;
52
53export interface CommandOutputHubShape {
54 readonly append: (input: CommandOutputTarget & { readonly chunk: string }) => Effect.Effect<void>;
55 /** Retains the tail briefly for settlements without output; otherwise rows use persisted output. */
56 readonly finish: (input: CommandOutputTarget) => Effect.Effect<void>;
57 readonly subscribe: (
58 input: CommandOutputTarget,
59 ) => Stream.Stream<OrchestrationV2CommandOutputFrame, OrchestrationV2CommandOutputError>;
60}
61
62export class CommandOutputHub extends Context.Service<CommandOutputHub, CommandOutputHubShape>()(
63 "t3/orchestration-v2/CommandOutputHub",
64) {}
65
66const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);
67
68function commandKey(target: CommandOutputTarget): string {
69 return `${target.threadId}\u0000${target.itemId}`;
70}
71
72function persistedCommandOutput(output: string | undefined): {
73 readonly text: string;
74 readonly truncated: boolean;
75} {
76 if (output === undefined) return { text: "", truncated: false };
77 let source = output;
78 if (output.length > MAX_FINAL_SOURCE_CHARS) {
79 // Cut at a newline to avoid splitting escape sequences.
80 source = output.slice(output.length - MAX_FINAL_SOURCE_CHARS);
81 const newline = source.indexOf("\n");
82 if (newline !== -1 && source.length - (newline + 1) >= TERMINAL_OUTPUT_TAIL_CHARS) {
83 source = source.slice(newline + 1);
84 }
85 }
86 const normalized = normalizeTerminalOutput(source);
87 return {
88 text: normalized.text,
89 truncated: normalized.truncated || source.length !== output.length,
90 };
91}
92
93function setBounded<V>(
94 map: Map<string, V>,
95 key: string,
96 value: V,
97 max: number,
98 onEvict?: (key: string) => void,
99): void {
100 map.delete(key);
101 map.set(key, value);
102 if (map.size <= max) return;
103 const oldest = map.keys().next().value!;
104 map.delete(oldest);
105 onEvict?.(oldest);
106}
107
108export const make = Effect.gen(function* () {
109 const eventSink = yield* EventSink.EventSinkV2;
110 const projections = yield* ProjectionStore.ProjectionStoreV2;
111 const tails = new Map<string, TerminalOutputState>();
112 const finished = new Map<string, TerminalOutputState>();
113 const subscribers = new Map<string, Set<Subscriber>>();
114
115 const wakeAll = (key: string, chunk: string) =>
116 Effect.forEach(
117 subscribers.get(key) ?? [],
118 (subscriber) => {
119 if (!subscriber.needsReplace) {
120 subscriber.pendingAppend += chunk;
121 if (subscriber.pendingAppend.length > COMMAND_OUTPUT_MAX_APPEND_CHARS) {
122 subscriber.needsReplace = true;
123 subscriber.overflowed = true;
124 subscriber.pendingAppend = "";
125 }
126 }
127 return Queue.offer(subscriber.wake, undefined);
128 },
129 { discard: true },
130 );
131
132 const append: CommandOutputHubShape["append"] = ({ chunk, ...target }) =>
133 Effect.suspend(() => {
134 if (chunk.length === 0) return Effect.void;
135 const key = commandKey(target);
136 const tail = appendTerminalOutput(tails.get(key) ?? EMPTY_TERMINAL_OUTPUT, chunk);
137 setBounded(tails, key, tail, MAX_LIVE_COMMANDS, (oldest) => {
138 // Eviction invalidates viewers' state; resync on their next frame.
139 for (const subscriber of subscribers.get(oldest) ?? []) {
140 subscriber.needsReplace = true;
141 subscriber.pendingAppend = "";
142 }
143 });
144 return wakeAll(key, chunk);
145 });
146
147 const finish: CommandOutputHubShape["finish"] = (target) =>
148 Effect.sync(() => {
149 const key = commandKey(target);
150 const tail = tails.get(key);
151 if (tail === undefined) return;
152 tails.delete(key);
153 setBounded(finished, key, tail, MAX_FINISHED_COMMANDS);
154 });
155
156 const subscribe: CommandOutputHubShape["subscribe"] = (target) =>
157 Stream.unwrap(
158 Effect.gen(function* () {
159 const key = commandKey(target);
160 const wake = yield* Queue.sliding<void>(1);
161 const subscriber: Subscriber = {
162 pendingAppend: "",
163 needsReplace: true,
164 overflowed: false,
165 wake,
166 };
167 // Subscribe before reading to avoid losing intervening chunks.
168 const keySubscribers = subscribers.get(key) ?? new Set<Subscriber>();
169 keySubscribers.add(subscriber);
170 subscribers.set(key, keySubscribers);
171 yield* Effect.addFinalizer(() =>
172 Effect.sync(() => {
173 keySubscribers.delete(subscriber);
174 if (keySubscribers.size === 0 && subscribers.get(key) === keySubscribers) {
175 subscribers.delete(key);
176 }
177 }),
178 );
179
180 // Persisted items provide settlement and final output; snapshot-only providers (ACP, Pi) also stream here.
181 let snapshotOutput: string | undefined;
182 let lost: Cause.Cause<unknown> | undefined;
183 let settled: Extract<OrchestrationV2TurnItem, { type: "command_execution" }> | undefined;
184 const observe = (item: OrchestrationV2TurnItem | undefined) =>
185 Effect.suspend(() => {
186 if (item === undefined || item.type !== "command_execution") return Effect.void;
187 if (!isOrchestrationV2WorkActive(item.status)) {
188 settled = item;
189 } else if (item.output !== undefined && item.output !== snapshotOutput) {
190 snapshotOutput = item.output;
191 } else {
192 return Effect.void;
193 }
194 subscriber.needsReplace = true;
195 return Queue.offer(wake, undefined);
196 });
197 const fromSequence = yield* eventSink.latestSequence({ threadId: target.threadId });
198 yield* eventSink
199 .stream({
200 threadId: target.threadId,
201 afterSequence: fromSequence,
202 eventType: "turn-item.updated",
203 })
204 .pipe(
205 Stream.runForEach((stored) =>
206 stored.event.type === "turn-item.updated" && stored.event.payload.id === target.itemId
207 ? observe(stored.event.payload)
208 : Effect.void,
209 ),
210 // A lost event stream cannot settle the row; end with an error.
211 Effect.catchCause((cause) =>
212 Effect.sync(() => {
213 lost = cause;
214 }).pipe(Effect.andThen(Queue.offer(wake, undefined))),
215 ),
216 Effect.forkScoped,
217 );
218 const item = yield* projections.getTurnItem(target);
219 // Non-command rows would hold output subscriptions open forever.
220 if (item === null || item.type !== "command_execution") {
221 return yield* new OrchestrationV2CommandOutputError({
222 threadId: target.threadId,
223 message: "No such command.",
224 });
225 }
226 yield* observe(item);
227 yield* Queue.offer(wake, undefined);
228
229 let lastFrameAt: number | undefined;
230 let throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;
231 const nextFrame = Effect.gen(function* (): Effect.fn.Return<
232 OrchestrationV2CommandOutputFrame,
233 OrchestrationV2CommandOutputError
234 > {
235 yield* Queue.take(wake);
236 if (lost !== undefined) {
237 return yield* new OrchestrationV2CommandOutputError({
238 threadId: target.threadId,
239 message: "Lost the thread's event stream.",
240 cause: Cause.squash(lost),
241 });
242 }
243 const now = yield* Clock.currentTimeMillis;
244 if (lastFrameAt !== undefined && now - lastFrameAt < throttle) {
245 yield* Effect.sleep(throttle - (now - lastFrameAt));
246 }
247 lastFrameAt = yield* Clock.currentTimeMillis;
248 throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;
249 const tail = tails.get(key) ?? finished.get(key);
250 if (settled !== undefined) {
251 if (settled.output === undefined && tail !== undefined) {
252 return {
253 kind: "replace",
254 text: tail.text,
255 truncated: tail.truncated,
256 running: false,
257 };
258 }
259 return {
260 kind: "replace",
261 ...persistedCommandOutput(commandItemOutput(settled)),
262 running: false,
263 };
264 }
265 if (subscriber.needsReplace || tail === undefined) {
266 if (subscriber.overflowed) throttle = COMMAND_OUTPUT_REPLACE_INTERVAL_MS;
267 subscriber.needsReplace = false;
268 subscriber.overflowed = false;
269 subscriber.pendingAppend = "";
270 if (tail === undefined) {
271 return { kind: "replace", ...persistedCommandOutput(snapshotOutput), running: true };
272 }
273 // Include terminal state so clients interpret later appends identically.
274 return {
275 kind: "replace",
276 text: terminalOutputResumeText(tail),
277 truncated: tail.truncated,
278 running: true,
279 };
280 }
281 const text = subscriber.pendingAppend;
282 subscriber.pendingAppend = "";
283 return { kind: "append", text, truncated: tail.truncated, running: true };
284 });
285 return Stream.fromEffectRepeat(nextFrame).pipe(
286 Stream.filter((frame) => frame.kind !== "append" || frame.text.length > 0),
287 Stream.takeUntil((frame) => !frame.running),
288 );
289 }).pipe(
290 Effect.mapError((cause) =>
291 isCommandOutputError(cause)
292 ? cause
293 : new OrchestrationV2CommandOutputError({
294 threadId: target.threadId,
295 message: "Failed to read command output.",
296 cause,
297 }),
298 ),
299 ),
300 );
301
302 return CommandOutputHub.of({ append, finish, subscribe });
303});
304
305export const layer: Layer.Layer<
306 CommandOutputHub,
307 never,
308 EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2
309> = Layer.effect(CommandOutputHub, make);