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