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

AcpRuntimeModel.ts

491 lines13.5 KB

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;
14​
15export interface AcpSessionModeState {
16 readonly currentModeId: string;
17 readonly availableModes: ReadonlyArray<AcpSessionMode>;
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>;
29​
30export interface AcpPlanUpdate {
31 readonly explanation?: string | null;
32 readonly plan: ReadonlyArray<{
33 readonly step: string;
34 readonly status: "pending" | "inProgress" | "completed";
35 }>;
37​
38export interface AcpPermissionRequest {
39 readonly kind: string | "unknown";
40 readonly detail?: string;
41 readonly toolCall?: AcpToolCallState;
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;
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);
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 );
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: Array<AcpSessionMode> = [];
130 for (const mode of modes.availableModes) {
131 const id = mode.id.trim();
132 const name = mode.name.trim();
133 if (!id || !name) {
134 continue;
135 }
136 const description = mode.description?.trim() || undefined;
137 availableModes.push(
138 description !== undefined
139 ? ({ id, name, description } satisfies AcpSessionMode)
140 : ({ id, name } satisfies AcpSessionMode),
141 );
142 }
143 if (availableModes.length === 0) {
144 return undefined;
145 }
146 return {
147 currentModeId,
148 availableModes,
149 };
151​
152function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" {
153 switch (raw) {
154 case "completed":
155 return "completed";
156 case "in_progress":
157 case "inProgress":
158 return "inProgress";
159 default:
160 return "pending";
161 }
163​
164function normalizeToolCallStatus(
165 raw: unknown,
166 fallback?: "pending" | "inProgress" | "completed" | "failed",
167): "pending" | "inProgress" | "completed" | "failed" | undefined {
168 switch (raw) {
169 case "pending":
170 return "pending";
171 case "in_progress":
172 case "inProgress":
173 return "inProgress";
174 case "completed":
175 return "completed";
176 case "failed":
177 return "failed";
178 default:
179 return fallback;
180 }
182​
183function normalizeCommandValue(value: unknown): string | undefined {
184 if (typeof value === "string" && value.trim().length > 0) {
185 return value.trim();
186 }
187 if (!Array.isArray(value)) {
188 return undefined;
189 }
190 const parts: Array<string> = [];
191 for (const entry of value) {
192 if (typeof entry === "string") {
193 const part = entry.trim();
194 if (part.length > 0) {
195 parts.push(part);
196 }
197 }
198 }
199 return parts.length > 0 ? parts.join(" ") : undefined;
201​
202function extractCommandFromTitle(title: string | undefined): string | undefined {
203 if (!title) {
204 return undefined;
205 }
206 const match = /`([^`]+)`/.exec(title);
207 return match?.[1]?.trim() || undefined;
209​
210function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {
211 if (isRecord(rawInput)) {
212 const directCommand = normalizeCommandValue(rawInput.command);
213 if (directCommand) {
214 return directCommand;
215 }
216 const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : "";
217 const args = normalizeCommandValue(rawInput.args);
218 if (executable && args) {
219 return `${executable} ${args}`;
220 }
221 if (executable) {
222 return executable;
223 }
224 }
225 return extractCommandFromTitle(title);
227​
228function extractTextContentFromToolCallContent(
229 content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
230): string | undefined {
231 if (!content) return undefined;
232 const chunks: Array<string> = [];
233 for (const entry of content) {
234 if (entry.type !== "content") {
235 continue;
236 }
237 const nestedContent = entry.content;
238 if (nestedContent.type !== "text") {
239 continue;
240 }
241 const text = nestedContent.text.trim();
242 if (text.length > 0) {
243 chunks.push(text);
244 }
245 }
246 return chunks.length > 0 ? chunks.join("\n") : undefined;
248​
249function normalizeToolKind(kind: unknown): string | undefined {
250 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
252​
253function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
254 switch (kind) {
255 case "execute":
256 return "command_execution";
257 case "edit":
258 case "delete":
259 case "move":
260 return "file_change";
261 case "search":
262 case "fetch":
263 return "web_search";
264 default:
265 return "dynamic_tool_call";
266 }
268​
269function makeToolCallState(
270 input: {
271 readonly toolCallId: string;
272 readonly title?: string | null | undefined;
273 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
274 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
275 readonly rawInput?: unknown;
276 readonly rawOutput?: unknown;
277 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
278 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
279 },
280 options?: {
281 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
282 },
283): AcpToolCallState | undefined {
284 const toolCallId = input.toolCallId.trim();
285 if (!toolCallId) {
286 return undefined;
287 }
288 const title = input.title?.trim() || undefined;
289 const command = extractToolCallCommand(input.rawInput, title);
290 const textContent = extractTextContentFromToolCallContent(input.content);
291 const normalizedTitle =
292 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
293 ? title
294 : undefined;
295 const data: Record<string, unknown> = { toolCallId };
296 const kind = normalizeToolKind(input.kind);
297 if (kind) {
298 data.kind = kind;
299 }
300 if (command) {
301 data.command = command;
302 }
303 if (input.rawInput !== undefined) {
304 data.rawInput = input.rawInput;
305 }
306 if (input.rawOutput !== undefined) {
307 data.rawOutput = input.rawOutput;
308 }
309 if (input.content !== undefined) {
310 data.content = input.content;
311 }
312 if (input.locations !== undefined) {
313 data.locations = input.locations;
314 }
315 const fallbackDetail = command ?? normalizedTitle ?? textContent;
316 const hasPresentationSeed =
317 title !== undefined ||
318 kind !== undefined ||
319 command !== undefined ||
320 normalizedTitle !== undefined ||
321 textContent !== undefined;
322 const presentation = hasPresentationSeed
323 ? deriveToolActivityPresentation({
324 itemType: canonicalItemTypeFromAcpToolKind(kind),
325 title,
326 detail: fallbackDetail,
327 data,
328 fallbackSummary: title ?? "Tool",
329 })
330 : undefined;
331 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
332 return {
333 toolCallId,
334 ...(kind ? { kind } : {}),
335 ...(presentation?.summary ? { title: presentation.summary } : {}),
336 ...(status ? { status } : {}),
337 ...(command ? { command } : {}),
338 ...(presentation?.detail ? { detail: presentation.detail } : {}),
339 data,
340 };
342​
343function parseTypedToolCallState(
344 event: AcpToolCallUpdate,
345 options?: {
346 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
347 },
348): AcpToolCallState | undefined {
349 return makeToolCallState(
350 {
351 toolCallId: event.toolCallId,
352 title: event.title,
353 kind: event.kind,
354 status: event.status,
355 rawInput: event.rawInput,
356 rawOutput: event.rawOutput,
357 content: event.content,
358 locations: event.locations,
359 },
360 options,
361 );
363​
364export function mergeToolCallState(
365 previous: AcpToolCallState | undefined,
366 next: AcpToolCallState,
367): AcpToolCallState {
368 const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
369 const kind = nextKind ?? previous?.kind;
370 const title = next.title ?? previous?.title;
371 const status = next.status ?? previous?.status;
372 const command = next.command ?? previous?.command;
373 const detail = next.detail ?? previous?.detail;
374 return {
375 toolCallId: next.toolCallId,
376 ...(kind ? { kind } : {}),
377 ...(title ? { title } : {}),
378 ...(status ? { status } : {}),
379 ...(command ? { command } : {}),
380 ...(detail ? { detail } : {}),
381 data: {
382 ...previous?.data,
383 ...next.data,
384 },
385 };
387​
388export function parsePermissionRequest(
389 params: EffectAcpSchema.RequestPermissionRequest,
390): AcpPermissionRequest {
391 const toolCall = makeToolCallState(
392 {
393 toolCallId: params.toolCall.toolCallId,
394 title: params.toolCall.title,
395 kind: params.toolCall.kind,
396 status: params.toolCall.status,
397 rawInput: params.toolCall.rawInput,
398 rawOutput: params.toolCall.rawOutput,
399 content: params.toolCall.content,
400 locations: params.toolCall.locations,
401 },
402 { fallbackStatus: "pending" },
403 );
404 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
405 const detail =
406 toolCall?.command ??
407 toolCall?.title ??
408 toolCall?.detail ??
409 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
410 return {
411 kind,
412 ...(detail ? { detail } : {}),
413 ...(toolCall ? { toolCall } : {}),
414 };
416​
417export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
418 readonly modeId?: string;
419 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
420} {
421 const upd = params.update;
422 const events: Array<AcpParsedSessionEvent> = [];
423 let modeId: string | undefined;
424​
425 switch (upd.sessionUpdate) {
426 case "current_mode_update": {
427 modeId = upd.currentModeId.trim();
428 if (modeId) {
429 events.push({
430 _tag: "ModeChanged",
431 modeId,
432 });
433 }
434 break;
435 }
436 case "plan": {
437 const plan = upd.entries.map((entry, index) => ({
438 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
439 status: normalizePlanStepStatus(entry.status),
440 }));
441 if (plan.length > 0) {
442 events.push({
443 _tag: "PlanUpdated",
444 payload: {
445 plan,
446 },
447 rawPayload: params,
448 });
449 }
450 break;
451 }
452 case "tool_call": {
453 const toolCall = parseTypedToolCallState(upd, {
454 fallbackStatus: "pending",
455 });
456 if (toolCall) {
457 events.push({
458 _tag: "ToolCallUpdated",
459 toolCall,
460 rawPayload: params,
461 });
462 }
463 break;
464 }
465 case "tool_call_update": {
466 const toolCall = parseTypedToolCallState(upd);
467 if (toolCall) {
468 events.push({
469 _tag: "ToolCallUpdated",
470 toolCall,
471 rawPayload: params,
472 });
473 }
474 break;
475 }
476 case "agent_message_chunk": {
477 if (upd.content.type === "text" && upd.content.text.length > 0) {
478 events.push({
479 _tag: "ContentDelta",
480 text: upd.content.text,
481 rawPayload: params,
482 });
483 }
484 break;
485 }
486 default:
487 break;
488 }
489​
490 return { ...(modeId !== undefined ? { modeId } : {}), events };