Open History to see the last commit
1import type * as EffectAcpSchema from "effect-acp/schema";
2import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
3import type { ToolLifecycleItemType } from "@t3tools/contracts";
4
5function isRecord(value: unknown): value is Record<string, unknown> {
6 return typeof value === "object" && value !== null && !Array.isArray(value);
7}
8
9export interface AcpSessionMode {
10 readonly id: string;
11 readonly name: string;
12 readonly description?: string;
13}
14
15export interface AcpSessionModeState {
16 readonly currentModeId: string;
17 readonly availableModes: ReadonlyArray<AcpSessionMode>;
18}
19
20export interface AcpToolCallState {
21 readonly toolCallId: string;
22 readonly kind?: string;
23 readonly title?: string;
24 readonly status?: "pending" | "inProgress" | "completed" | "failed";
25 readonly command?: string;
26 readonly detail?: string;
27 readonly data: Record<string, unknown>;
28}
29
30export interface AcpPlanUpdate {
31 readonly explanation?: string | null;
32 readonly plan: ReadonlyArray<{
33 readonly step: string;
34 readonly status: "pending" | "inProgress" | "completed";
35 }>;
36}
37
38export interface AcpPermissionRequest {
39 readonly kind: string | "unknown";
40 readonly detail?: string;
41 readonly toolCall?: AcpToolCallState;
42}
43
44export type AcpParsedSessionEvent =
45 | {
46 readonly _tag: "ModeChanged";
47 readonly modeId: string;
48 }
49 | {
50 readonly _tag: "AssistantItemStarted";
51 readonly itemId: string;
52 }
53 | {
54 readonly _tag: "AssistantItemCompleted";
55 readonly itemId: string;
56 }
57 | {
58 readonly _tag: "PlanUpdated";
59 readonly payload: AcpPlanUpdate;
60 readonly rawPayload: unknown;
61 }
62 | {
63 readonly _tag: "ToolCallUpdated";
64 readonly toolCall: AcpToolCallState;
65 readonly rawPayload: unknown;
66 }
67 | {
68 readonly _tag: "ContentDelta";
69 readonly itemId?: string;
70 readonly text: string;
71 readonly rawPayload: unknown;
72 };
73
74type AcpSessionSetupResponse =
75 | EffectAcpSchema.LoadSessionResponse
76 | EffectAcpSchema.NewSessionResponse
77 | EffectAcpSchema.ResumeSessionResponse;
78
79type AcpToolCallUpdate = Extract<
80 EffectAcpSchema.SessionNotification["update"],
81 { readonly sessionUpdate: "tool_call" | "tool_call_update" }
82>;
83
84export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
85 const configOptions = sessionResponse.configOptions;
86 if (!configOptions) return undefined;
87 for (const opt of configOptions) {
88 if (opt.category === "model" && opt.id.trim().length > 0) {
89 return opt.id.trim();
90 }
91 }
92 return undefined;
93}
94
95export function findSessionConfigOption(
96 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
97 configId: string,
98): EffectAcpSchema.SessionConfigOption | undefined {
99 if (!configOptions) {
100 return undefined;
101 }
102 const normalizedConfigId = configId.trim();
103 if (!normalizedConfigId) {
104 return undefined;
105 }
106 return configOptions.find((option) => option.id.trim() === normalizedConfigId);
107}
108
109export function collectSessionConfigOptionValues(
110 configOption: EffectAcpSchema.SessionConfigOption,
111): ReadonlyArray<string> {
112 if (configOption.type !== "select") {
113 return [];
114 }
115 return configOption.options.flatMap((entry) =>
116 "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
117 );
118}
119
120export function parseSessionModeState(
121 sessionResponse: AcpSessionSetupResponse,
122): AcpSessionModeState | undefined {
123 const modes = sessionResponse.modes;
124 if (!modes) return undefined;
125 const currentModeId = modes.currentModeId.trim();
126 if (!currentModeId) {
127 return undefined;
128 }
129 const availableModes = modes.availableModes
130 .map((mode) => {
131 const id = mode.id.trim();
132 const name = mode.name.trim();
133 if (!id || !name) {
134 return undefined;
135 }
136 const description = mode.description?.trim() || undefined;
137 return description !== undefined
138 ? ({ id, name, description } satisfies AcpSessionMode)
139 : ({ id, name } satisfies AcpSessionMode);
140 })
141 .filter((mode): mode is AcpSessionMode => mode !== undefined);
142 if (availableModes.length === 0) {
143 return undefined;
144 }
145 return {
146 currentModeId,
147 availableModes,
148 };
149}
150
151function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" {
152 switch (raw) {
153 case "completed":
154 return "completed";
155 case "in_progress":
156 case "inProgress":
157 return "inProgress";
158 default:
159 return "pending";
160 }
161}
162
163function normalizeToolCallStatus(
164 raw: unknown,
165 fallback?: "pending" | "inProgress" | "completed" | "failed",
166): "pending" | "inProgress" | "completed" | "failed" | undefined {
167 switch (raw) {
168 case "pending":
169 return "pending";
170 case "in_progress":
171 case "inProgress":
172 return "inProgress";
173 case "completed":
174 return "completed";
175 case "failed":
176 return "failed";
177 default:
178 return fallback;
179 }
180}
181
182function normalizeCommandValue(value: unknown): string | undefined {
183 if (typeof value === "string" && value.trim().length > 0) {
184 return value.trim();
185 }
186 if (!Array.isArray(value)) {
187 return undefined;
188 }
189 const parts = value
190 .map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : null))
191 .filter((entry): entry is string => entry !== null);
192 return parts.length > 0 ? parts.join(" ") : undefined;
193}
194
195function extractCommandFromTitle(title: string | undefined): string | undefined {
196 if (!title) {
197 return undefined;
198 }
199 const match = /`([^`]+)`/.exec(title);
200 return match?.[1]?.trim() || undefined;
201}
202
203function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {
204 if (isRecord(rawInput)) {
205 const directCommand = normalizeCommandValue(rawInput.command);
206 if (directCommand) {
207 return directCommand;
208 }
209 const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : "";
210 const args = normalizeCommandValue(rawInput.args);
211 if (executable && args) {
212 return `${executable} ${args}`;
213 }
214 if (executable) {
215 return executable;
216 }
217 }
218 return extractCommandFromTitle(title);
219}
220
221function extractTextContentFromToolCallContent(
222 content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
223): string | undefined {
224 if (!content) return undefined;
225 const chunks = content
226 .map((entry) => {
227 if (entry.type !== "content") {
228 return undefined;
229 }
230 const nestedContent = entry.content;
231 if (nestedContent.type !== "text") {
232 return undefined;
233 }
234 return nestedContent.text.trim().length > 0 ? nestedContent.text.trim() : undefined;
235 })
236 .filter((entry): entry is string => entry !== undefined);
237 return chunks.length > 0 ? chunks.join("\n") : undefined;
238}
239
240function normalizeToolKind(kind: unknown): string | undefined {
241 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
242}
243
244function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
245 switch (kind) {
246 case "execute":
247 return "command_execution";
248 case "edit":
249 case "delete":
250 case "move":
251 return "file_change";
252 case "search":
253 case "fetch":
254 return "web_search";
255 default:
256 return "dynamic_tool_call";
257 }
258}
259
260function makeToolCallState(
261 input: {
262 readonly toolCallId: string;
263 readonly title?: string | null | undefined;
264 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
265 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
266 readonly rawInput?: unknown;
267 readonly rawOutput?: unknown;
268 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
269 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
270 },
271 options?: {
272 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
273 },
274): AcpToolCallState | undefined {
275 const toolCallId = input.toolCallId.trim();
276 if (!toolCallId) {
277 return undefined;
278 }
279 const title = input.title?.trim() || undefined;
280 const command = extractToolCallCommand(input.rawInput, title);
281 const textContent = extractTextContentFromToolCallContent(input.content);
282 const normalizedTitle =
283 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
284 ? title
285 : undefined;
286 const data: Record<string, unknown> = { toolCallId };
287 const kind = normalizeToolKind(input.kind);
288 if (kind) {
289 data.kind = kind;
290 }
291 if (command) {
292 data.command = command;
293 }
294 if (input.rawInput !== undefined) {
295 data.rawInput = input.rawInput;
296 }
297 if (input.rawOutput !== undefined) {
298 data.rawOutput = input.rawOutput;
299 }
300 if (input.content !== undefined) {
301 data.content = input.content;
302 }
303 if (input.locations !== undefined) {
304 data.locations = input.locations;
305 }
306 const fallbackDetail = command ?? normalizedTitle ?? textContent;
307 const hasPresentationSeed =
308 title !== undefined ||
309 kind !== undefined ||
310 command !== undefined ||
311 normalizedTitle !== undefined ||
312 textContent !== undefined;
313 const presentation = hasPresentationSeed
314 ? deriveToolActivityPresentation({
315 itemType: canonicalItemTypeFromAcpToolKind(kind),
316 title,
317 detail: fallbackDetail,
318 data,
319 fallbackSummary: title ?? "Tool",
320 })
321 : undefined;
322 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
323 return {
324 toolCallId,
325 ...(kind ? { kind } : {}),
326 ...(presentation?.summary ? { title: presentation.summary } : {}),
327 ...(status ? { status } : {}),
328 ...(command ? { command } : {}),
329 ...(presentation?.detail ? { detail: presentation.detail } : {}),
330 data,
331 };
332}
333
334function parseTypedToolCallState(
335 event: AcpToolCallUpdate,
336 options?: {
337 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
338 },
339): AcpToolCallState | undefined {
340 return makeToolCallState(
341 {
342 toolCallId: event.toolCallId,
343 title: event.title,
344 kind: event.kind,
345 status: event.status,
346 rawInput: event.rawInput,
347 rawOutput: event.rawOutput,
348 content: event.content,
349 locations: event.locations,
350 },
351 options,
352 );
353}
354
355export function mergeToolCallState(
356 previous: AcpToolCallState | undefined,
357 next: AcpToolCallState,
358): AcpToolCallState {
359 const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
360 const kind = nextKind ?? previous?.kind;
361 const title = next.title ?? previous?.title;
362 const status = next.status ?? previous?.status;
363 const command = next.command ?? previous?.command;
364 const detail = next.detail ?? previous?.detail;
365 return {
366 toolCallId: next.toolCallId,
367 ...(kind ? { kind } : {}),
368 ...(title ? { title } : {}),
369 ...(status ? { status } : {}),
370 ...(command ? { command } : {}),
371 ...(detail ? { detail } : {}),
372 data: {
373 ...previous?.data,
374 ...next.data,
375 },
376 };
377}
378
379export function parsePermissionRequest(
380 params: EffectAcpSchema.RequestPermissionRequest,
381): AcpPermissionRequest {
382 const toolCall = makeToolCallState(
383 {
384 toolCallId: params.toolCall.toolCallId,
385 title: params.toolCall.title,
386 kind: params.toolCall.kind,
387 status: params.toolCall.status,
388 rawInput: params.toolCall.rawInput,
389 rawOutput: params.toolCall.rawOutput,
390 content: params.toolCall.content,
391 locations: params.toolCall.locations,
392 },
393 { fallbackStatus: "pending" },
394 );
395 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
396 const detail =
397 toolCall?.command ??
398 toolCall?.title ??
399 toolCall?.detail ??
400 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
401 return {
402 kind,
403 ...(detail ? { detail } : {}),
404 ...(toolCall ? { toolCall } : {}),
405 };
406}
407
408export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
409 readonly modeId?: string;
410 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
411} {
412 const upd = params.update;
413 const events: Array<AcpParsedSessionEvent> = [];
414 let modeId: string | undefined;
415
416 switch (upd.sessionUpdate) {
417 case "current_mode_update": {
418 modeId = upd.currentModeId.trim();
419 if (modeId) {
420 events.push({
421 _tag: "ModeChanged",
422 modeId,
423 });
424 }
425 break;
426 }
427 case "plan": {
428 const plan = upd.entries.map((entry, index) => ({
429 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
430 status: normalizePlanStepStatus(entry.status),
431 }));
432 if (plan.length > 0) {
433 events.push({
434 _tag: "PlanUpdated",
435 payload: {
436 plan,
437 },
438 rawPayload: params,
439 });
440 }
441 break;
442 }
443 case "tool_call": {
444 const toolCall = parseTypedToolCallState(upd, {
445 fallbackStatus: "pending",
446 });
447 if (toolCall) {
448 events.push({
449 _tag: "ToolCallUpdated",
450 toolCall,
451 rawPayload: params,
452 });
453 }
454 break;
455 }
456 case "tool_call_update": {
457 const toolCall = parseTypedToolCallState(upd);
458 if (toolCall) {
459 events.push({
460 _tag: "ToolCallUpdated",
461 toolCall,
462 rawPayload: params,
463 });
464 }
465 break;
466 }
467 case "agent_message_chunk": {
468 if (upd.content.type === "text" && upd.content.text.length > 0) {
469 events.push({
470 _tag: "ContentDelta",
471 text: upd.content.text,
472 rawPayload: params,
473 });
474 }
475 break;
476 }
477 default:
478 break;
479 }
480
481 return { ...(modeId !== undefined ? { modeId } : {}), events };
482}