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

AcpRuntimeModel.ts

582 lines16.5 KB

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