Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - realpath containment must use Node's fs/path directly.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import {
7 WorkflowInspectionError,
8 type WorkflowReadAgentTranscriptInput,
9 type WorkflowReadAgentTranscriptResult,
10 type WorkflowReadJournalInput,
11 type WorkflowReadJournalResult,
12 type WorkflowReadScriptInput,
13 type WorkflowReadScriptResult,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19
20/**
21 * Read-only inspection of Claude Agent SDK workflow-run artifacts on local
22 * disk. Clients echo server-local paths back over RPC, so every path is
23 * validated structurally (absolute + realpath-contained inside the projects
24 * root) before any disk access — the service must never become an
25 * arbitrary-file-read oracle.
26 */
27
28/** `readScript`: clip source text past this many characters. */
29const SCRIPT_MAX_CHARS = 512 * 1024;
30/** `readJournal`: clip each serialized result past this many characters. */
31const JOURNAL_RESULT_MAX_CHARS = 32 * 1024;
32/** `readJournal`: cap the number of distinct agents reported. */
33const JOURNAL_MAX_ENTRIES = 512;
34/** `readAgentTranscript`: cap the number of lines returned per page. */
35const TRANSCRIPT_MAX_LINES = 400;
36/** `readAgentTranscript`: stop a page once accumulated chars exceed this. */
37const TRANSCRIPT_MAX_CHARS = 768 * 1024;
38
39/** Only these agent id shapes are accepted before touching the filesystem. */
40const AGENT_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
41
42/** Mutable while parsing the journal; frozen into the readonly contract shape. */
43interface MutableJournalEntry {
44 agentId: string;
45 hasResult: boolean;
46 resultJson?: string;
47 resultTruncated?: boolean;
48}
49
50/** Parse one JSONL line defensively; unparseable lines return `undefined`. */
51const parseJsonLine = (text: string): unknown => {
52 try {
53 return JSON.parse(text) as unknown;
54 } catch {
55 return undefined;
56 }
57};
58
59const isEnoent = (cause: unknown): boolean =>
60 typeof cause === "object" &&
61 cause !== null &&
62 "code" in cause &&
63 (cause as { code?: unknown }).code === "ENOENT";
64
65const isNotFoundPlatformError = (cause: unknown): boolean =>
66 typeof cause === "object" &&
67 cause !== null &&
68 "reason" in cause &&
69 typeof (cause as { reason?: unknown }).reason === "object" &&
70 (cause as { reason: { _tag?: unknown } }).reason !== null &&
71 (cause as { reason: { _tag?: unknown } }).reason._tag === "NotFound";
72
73export class WorkflowInspectionService extends Context.Service<
74 WorkflowInspectionService,
75 {
76 readonly readScript: (
77 input: WorkflowReadScriptInput,
78 ) => Effect.Effect<WorkflowReadScriptResult, WorkflowInspectionError>;
79 readonly readJournal: (
80 input: WorkflowReadJournalInput,
81 ) => Effect.Effect<WorkflowReadJournalResult, WorkflowInspectionError>;
82 readonly readAgentTranscript: (
83 input: WorkflowReadAgentTranscriptInput,
84 ) => Effect.Effect<WorkflowReadAgentTranscriptResult, WorkflowInspectionError>;
85 }
86>()("t3/workflow/WorkflowInspectionService") {}
87
88export const make = (options?: { readonly projectsRoot?: string }) =>
89 Effect.gen(function* () {
90 const fs = yield* FileSystem.FileSystem;
91 const projectsRoot =
92 options?.projectsRoot ?? NodePath.join(NodeOS.homedir(), ".claude", "projects");
93
94 /**
95 * Resolve the real path of `target` and prove it is contained within the
96 * real projects root using a path-segment-safe prefix comparison. ENOENT
97 * during either realpath maps to `not-found`; escape maps to
98 * `invalid-path`.
99 */
100 const resolveContained = Effect.fn("WorkflowInspectionService.resolveContained")(function* (
101 operation: string,
102 target: string,
103 ) {
104 if (!NodePath.isAbsolute(target)) {
105 return yield* new WorkflowInspectionError({
106 operation,
107 reason: "invalid-path",
108 detail: "Path must be absolute.",
109 });
110 }
111
112 const realRoot = yield* Effect.tryPromise({
113 try: () => NodeFSP.realpath(projectsRoot),
114 catch: (cause) =>
115 new WorkflowInspectionError({
116 operation,
117 reason: isEnoent(cause) ? "not-found" : "read-failed",
118 detail: "Failed to resolve the workflow projects root.",
119 cause,
120 }),
121 });
122
123 const realTarget = yield* Effect.tryPromise({
124 try: () => NodeFSP.realpath(target),
125 catch: (cause) =>
126 new WorkflowInspectionError({
127 operation,
128 reason: isEnoent(cause) ? "not-found" : "read-failed",
129 detail: "Failed to resolve the requested path.",
130 cause,
131 }),
132 });
133
134 if (realTarget !== realRoot && !realTarget.startsWith(realRoot + NodePath.sep)) {
135 return yield* new WorkflowInspectionError({
136 operation,
137 reason: "invalid-path",
138 detail: "Path escapes the workflow projects root.",
139 });
140 }
141
142 return realTarget;
143 });
144
145 const readScript = Effect.fn("WorkflowInspectionService.readScript")(function* (
146 input: WorkflowReadScriptInput,
147 ) {
148 const operation = "WorkflowInspectionService.readScript";
149 if (!input.scriptPath.endsWith(".js") && !input.scriptPath.endsWith(".mjs")) {
150 return yield* new WorkflowInspectionError({
151 operation,
152 reason: "invalid-path",
153 detail: "Script path must end with .js or .mjs.",
154 });
155 }
156
157 const realPath = yield* resolveContained(operation, input.scriptPath);
158 const source = yield* fs.readFileString(realPath).pipe(
159 Effect.mapError(
160 (cause) =>
161 new WorkflowInspectionError({
162 operation,
163 reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
164 detail: "Failed to read the workflow script.",
165 cause,
166 }),
167 ),
168 );
169
170 const truncated = source.length > SCRIPT_MAX_CHARS;
171 return {
172 source: truncated ? source.slice(0, SCRIPT_MAX_CHARS) : source,
173 truncated,
174 } satisfies WorkflowReadScriptResult;
175 });
176
177 const readJournal = Effect.fn("WorkflowInspectionService.readJournal")(function* (
178 input: WorkflowReadJournalInput,
179 ) {
180 const operation = "WorkflowInspectionService.readJournal";
181 const realDir = yield* resolveContained(operation, input.transcriptDir);
182 // Re-contain the joined leaf: a symlink named journal.jsonl inside a
183 // valid directory must not escape the projects root.
184 const journalPath = yield* resolveContained(
185 operation,
186 NodePath.join(realDir, "journal.jsonl"),
187 );
188 const raw = yield* fs.readFileString(journalPath).pipe(
189 Effect.mapError(
190 (cause) =>
191 new WorkflowInspectionError({
192 operation,
193 reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
194 detail: "Failed to read the workflow journal.",
195 cause,
196 }),
197 ),
198 );
199
200 // Preserve first-seen agent order via an insertion-ordered Map.
201 const entries = new Map<string, MutableJournalEntry>();
202 let truncated = false;
203
204 const ensureEntry = (agentId: string): MutableJournalEntry | undefined => {
205 const existing = entries.get(agentId);
206 if (existing !== undefined) return existing;
207 if (entries.size >= JOURNAL_MAX_ENTRIES) {
208 truncated = true;
209 return undefined;
210 }
211 const created: MutableJournalEntry = { agentId, hasResult: false };
212 entries.set(agentId, created);
213 return created;
214 };
215
216 for (const line of raw.split("\n")) {
217 const text = line.trim();
218 if (text.length === 0) continue;
219 const record = parseJsonLine(text);
220 if (record === undefined) continue;
221 if (typeof record !== "object" || record === null) continue;
222 const parsed = record as {
223 type?: unknown;
224 agentId?: unknown;
225 result?: unknown;
226 };
227 if (typeof parsed.agentId !== "string" || parsed.agentId.length === 0) continue;
228
229 if (parsed.type === "started") {
230 ensureEntry(parsed.agentId);
231 continue;
232 }
233 if (parsed.type === "result") {
234 const entry = ensureEntry(parsed.agentId);
235 if (entry === undefined) continue;
236 entry.hasResult = true;
237 // @effect-diagnostics-next-line preferSchemaOverJson:off - result is arbitrary JSON re-serialized verbatim.
238 const serialized = JSON.stringify(parsed.result);
239 if (serialized !== undefined) {
240 const resultTruncated = serialized.length > JOURNAL_RESULT_MAX_CHARS;
241 entry.resultJson = resultTruncated
242 ? serialized.slice(0, JOURNAL_RESULT_MAX_CHARS)
243 : serialized;
244 if (resultTruncated) entry.resultTruncated = true;
245 }
246 }
247 }
248
249 return {
250 entries: Array.from(entries.values()),
251 truncated,
252 } satisfies WorkflowReadJournalResult;
253 });
254
255 const readAgentTranscript = Effect.fn("WorkflowInspectionService.readAgentTranscript")(
256 function* (input: WorkflowReadAgentTranscriptInput) {
257 const operation = "WorkflowInspectionService.readAgentTranscript";
258 if (!AGENT_ID_PATTERN.test(input.agentId)) {
259 return yield* new WorkflowInspectionError({
260 operation,
261 reason: "invalid-path",
262 detail: "Agent id contains unsupported characters.",
263 });
264 }
265
266 const realDir = yield* resolveContained(operation, input.transcriptDir);
267 // Re-contain the joined leaf: a symlink named agent-<id>.jsonl inside
268 // a valid directory must not escape the projects root.
269 const transcriptPath = yield* resolveContained(
270 operation,
271 NodePath.join(realDir, `agent-${input.agentId}.jsonl`),
272 );
273 // v1 reads the whole file per page; acceptable for current transcript
274 // sizes. Revisit with a streaming/seek reader if transcripts grow large.
275 const raw = yield* fs.readFileString(transcriptPath).pipe(
276 Effect.mapError(
277 (cause) =>
278 new WorkflowInspectionError({
279 operation,
280 reason: isNotFoundPlatformError(cause) ? "not-found" : "read-failed",
281 detail: "Failed to read the agent transcript.",
282 cause,
283 }),
284 ),
285 );
286
287 const allLines = raw.split("\n");
288 if (allLines.length > 0 && allLines[allLines.length - 1] === "") {
289 allLines.pop();
290 }
291 const total = allLines.length;
292 const afterLine = Math.max(0, input.afterLine ?? 0);
293
294 const lines: string[] = [];
295 let accumulated = 0;
296 for (let index = afterLine; index < total && lines.length < TRANSCRIPT_MAX_LINES; index++) {
297 const current = allLines[index] ?? "";
298 lines.push(current);
299 accumulated += current.length;
300 if (accumulated > TRANSCRIPT_MAX_CHARS) break;
301 }
302
303 const nextLine = afterLine + lines.length;
304 return {
305 lines,
306 nextLine,
307 complete: nextLine >= total,
308 } satisfies WorkflowReadAgentTranscriptResult;
309 },
310 );
311
312 return WorkflowInspectionService.of({
313 readScript,
314 readJournal,
315 readAgentTranscript,
316 });
317 });
318
319export const layer = Layer.effect(WorkflowInspectionService, make());